{"text": "function delay=delayest_3point(u2,u1,method,estimator,parameter);\n%delay=delayest_3point(u2,u1,method,estimator,parameter);\n%Estimates delay of u2 wrt u1 by interpolating the peak of the cross correlatio\n%using a three-point peak interpolation\n%method may be 'parabola','Gaussian','modGaussian','cosine'.\n%estimator may be 'xcorr','ASDF','AMDF' (AMDF is very slow).\n%if using modGaussian, parameter is a bias (always used if >=0, only used\n%for xc<0 for parameter < 0)\n\nif nargin<3\n method='parabola';\nend\n\nif nargin<4\n estimator='xcorr';\nend\n\nif nargin<5\n switch method\n case {'modGaussian','modgaussian'}\n parameter=1;\n end\nend\n\n\nN_p=numel(u2);%number of elements\n\n\n\nswitch estimator\n case {'xcorr','xc','xcorr_fft'}%cross correlation\n U1=fft(u1);\n U2=fft(u2);\n xc=ifft(U2.*conj(U1));%circular xcorr\n [tmp idx]=max(xc);\n case {'ASDF'}%average squared difference function\n xc = (-2*ifft(fft(u2).*conj(fft(u1))) + sum(u1.^2) + sum(u2.^2))/N_p;%ADSF\n [tmp idx]=min(xc);\n case {'AMDF'}%average magnitude difference function (this is a lot slower for large N_p)\n xc=sum(abs(repmat(u1',1,N_p)-hankel(u2',[u2(end)'; u2(1:(end-1))'])))/N_p;%AMDF\n [tmp idx]=min(xc);\nend\n\n\nR=zeros(1,3);%three points to use for interpolation\nR(2)=xc(idx);%peak\n\n%find neighbors, assuming periodic\nif idx==1\n R(1)=xc(end);\n R(3)=xc(2);\nelseif idx==numel(xc)\n R(1)=xc(end-1);\n R(3)=xc(1);\nelse\n R(1)=xc(idx-1);\n R(3)=xc(idx+1);\nend\n\n\nswitch method\n case {'Gaussian','gaussian'}\n %a=exp(log(R(2))+(log(R(3))-log(R(1)))^2/(16*log(R(2))-8*log(R(1))-8*log(R(3))));%peak value\n %b=(2*log(R(2))-log(R(1))-log(R(3)))/2;%width\n c=(log(R(3))-log(R(1)))/(4*log(R(2))-2*log(R(1))-2*log(R(3)));\n case {'parabola','parabolic'}\n \t%A=inv([1 -1 1;0 0 1;1 1 1])*R';\n %c=-A(2)/(2*A(1));\n %a=-1/4*A(2)^2/A(1)+A(3);%peak value\n c=(R(3)-R(1))/(2*(2*R(2)-R(1)-R(3)));\n case {'modGaussian','modgaussian'}\n if parameter>=0%always add bias\n R=R-min(R)+parameter*R(2);\n else%only add bias if R has a negative value\n if any(R<=0)\n R=R-min(R)-parameter*R(2);\n end\n end\n %a=exp(log(R(2))+(log(R(3))-log(R(1)))^2/(16*log(R(2))-8*log(R(1))-8*log(R(3))));\n %b=(2*log(R(2))-log(R(1))-log(R(3)))/2;\n c=(log(R(3))-log(R(1)))/(4*log(R(2))-2*log(R(1))-2*log(R(3)));\n case {'cosine'}\n omega=acos((R(1)+R(3))/(2*R(2)));\n theta=atan((R(1)-R(3))/(2*R(2)*sin(omega)));\n %A=R(2)/cos(theta);\n c=-theta/omega;\n otherwise\n error('unknown method')\nend\n\nlag=mod(idx-1+floor(N_p/2),N_p)-floor(N_p/2);%integer part\ndelay=lag+c;%delay estimate\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/25210-subsample-delay-estimation/delay_estimation_6_03/delayest_3point.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7499632401444675}} {"text": "function p = predictOneVsAll(all_theta, X)\n%PREDICT Predict the label for a trained one-vs-all classifier. The labels \n%are in the range 1..K, where K = size(all_theta, 1). \n% p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions\n% for each example in the matrix X. Note that X contains the examples in\n% rows. all_theta is a matrix where the i-th row is a trained logistic\n% regression theta vector for the i-th class. You should set p to a vector\n% of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2\n% for 4 examples) \n\nm = size(X, 1);\nnum_labels = size(all_theta, 1);\n\n% You need to return the following variables correctly \np = zeros(size(X, 1), 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters (one-vs-all).\n% You should set p to a vector of predictions (from 1 to\n% num_labels).\n%\n% Hint: This code can be done all vectorized using the max function.\n% In particular, the max function can also return the index of the \n% max element, for more information see 'help max'. If your examples \n% are in rows, then, you can use max(A, [], 2) to obtain the max \n% for each row.\n% \n\n\nall_preds = all_theta * X';\n[max_vals, max_ndxs] = max(all_preds);\np = max_ndxs';\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "khanhnamle1994", "repo": "machine-learning", "sha": "fa391eb9429187a295c15a14ba24f4416667e5c1", "save_path": "github-repos/MATLAB/khanhnamle1994-machine-learning", "path": "github-repos/MATLAB/khanhnamle1994-machine-learning/machine-learning-fa391eb9429187a295c15a14ba24f4416667e5c1/machine-learning-ex3/ex3/predictOneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8723473813156294, "lm_q1q2_score": 0.749925415296403}} {"text": "function r=rmse(data,estimate)\n% Function to calculate root mean square error from a data vector or matrix \n% and the corresponding estimates.\n% Usage: r=rmse(data,estimate)\n% Note: data and estimates have to be of same size\n% Example: r=rmse(randn(100,100),randn(100,100));\n\n% delete records with NaNs in both datasets first\nI = ~isnan(data) & ~isnan(estimate); \ndata = data(I); estimate = estimate(I);\n\nr=sqrt(sum((data(:)-estimate(:)).^2)/numel(data));", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21383-rmse/rmse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.749913111366888}} {"text": "clear all\n% explicit euler\n% m = 1; %adjust value of m\n% y(1) = 1;%input your initial condition\n% dt = 0.2; %adjust your step size\n% T = 0:dt:15; %set up your time domain, here I have [0,5]\n% for i = 2:length(T) %construct a 'for' loop\n% y(i) = y(i-1) + m*dt*(-3*(i-2)/(i-1))*y(i-1)+m*dt*(2*(1+(i-2)^3))*exp(-(i-2));\n% end\n% plot(T,y)\n% \n% Implicit euler\n% n = 1; %adjust value of m\n% w(1) = 1;%input your initial condition\n% dtt = 0.2; %adjust your step size\n% T1 = 0:dtt:15; %set up your time domain, here I have [0,5]\n% for j = 2:length(T1) %construct a 'for' loop\n% w(j) = (w(j-1)+ dtt*(2*(j^3))*exp(-j+1))/(1+3*dtt*(j-1)/j) ;\n% end\n% plot(T1,w)\n% \n% \n% Crank-Nicolson\nm = 1; %adjust value of m\ny(1) = 1;%input your initial condition\ndt = 0.2; %adjust your step size\nT = 0:dt:15; %set up your time domain, here I have [0,5]\nfor i = 2:length(T) %construct a 'for' loop\n y(i)=(dt*i^3*exp(-i+1)+dt*(i-1)^3*exp(-i+2)+...\n y(i-1)*(1-0.5*dt*(-3*i-6/(i-1))))/(1+0.5*dt*(3*i+3/i));\nend\nplot(T,y)\n\n\n\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/Coupled/time.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067211996142, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7499131002361356}} {"text": "function [ l, u ] = vand2_lu ( n, x )\n\n%*****************************************************************************80\n%\n%% VAND2_LU returns the LU factors of the VAND2 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Halil Oruc, George Phillips,\n% Explicit factorization of the Vandermonde matrix,\n% Linear Algebra and its Applications,\n% Volume 315, Number 1-3, 15 August 2000, pages 113-123.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real X(N), the values that define the matrix.\n%\n% Output, real L(N,N), U(N,N), the LU factors of the matrix.\n%\n l = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : i\n l(i,j) = 1.0;\n for k = 1 : j - 1\n l(i,j) = l(i,j) * ( x(i) - x(k) ) / ( x(j) - x(k) );\n end\n end \n end\n\n u = zeros ( n, n );\n\n for i = 1 : n\n for j = i : n\n u(i,j) = complete_symmetric_poly ( i, j - i, x );\n for k = 1 : i - 1\n u(i,j) = u(i,j) * ( x(i) - x(k) );\n end\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/test_mat/vand2_lu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7498999407757476}} {"text": "function pp = splinefit(varargin)\n%SPLINEFIT Fit a spline to noisy data.\n% PP = SPLINEFIT(X,Y,BREAKS) fits a piecewise cubic spline with breaks\n% (knots) BREAKS to the noisy data (X,Y). X is a vector and Y is a vector\n% or an ND array. If Y is an ND array, then X(j) and Y(:,...,:,j) are\n% matched. Use PPVAL to evaluate PP.\n%\n% PP = SPLINEFIT(X,Y,P) where P is a positive integer interpolates the\n% breaks linearly from the sorted locations of X. P is the number of\n% spline pieces and P+1 is the number of breaks.\n%\n% OPTIONAL INPUT\n% Argument places 4 to 8 are reserved for optional input.\n% These optional arguments can be given in any order:\n%\n% PP = SPLINEFIT(...,'p') applies periodic boundary conditions to\n% the spline. The period length is MAX(BREAKS)-MIN(BREAKS).\n%\n% PP = SPLINEFIT(...,'r') uses robust fitting to reduce the influence\n% from outlying data points. Three iterations of weighted least squares\n% are performed. Weights are computed from previous residuals.\n%\n% PP = SPLINEFIT(...,BETA), where 0 < BETA < 1, sets the robust fitting\n% parameter BETA and activates robust fitting ('r' can be omitted).\n% Default is BETA = 1/2. BETA close to 0 gives all data equal weighting.\n% Increase BETA to reduce the influence from outlying data. BETA close\n% to 1 may cause instability or rank deficiency.\n%\n% PP = SPLINEFIT(...,N) sets the spline order to N. Default is a cubic\n% spline with order N = 4. A spline with P pieces has P+N-1 degrees of\n% freedom. With periodic boundary conditions the degrees of freedom are\n% reduced to P.\n%\n% PP = SPLINEFIT(...,CON) applies linear constraints to the spline.\n% CON is a structure with fields 'xc', 'yc' and 'cc':\n% 'xc', x-locations (vector)\n% 'yc', y-values (vector or ND array)\n% 'cc', coefficients (matrix).\n%\n% Constraints are linear combinations of derivatives of order 0 to N-2\n% according to\n%\n% cc(1,j)*y(x) + cc(2,j)*y'(x) + ... = yc(:,...,:,j), x = xc(j).\n%\n% The maximum number of rows for 'cc' is N-1. If omitted or empty 'cc'\n% defaults to a single row of ones. Default for 'yc' is a zero array.\n%\n% EXAMPLES\n%\n% % Noisy data\n% x = linspace(0,2*pi,100);\n% y = sin(x) + 0.1*randn(size(x));\n% % Breaks\n% breaks = [0:5,2*pi];\n%\n% % Fit a spline of order 5\n% pp = splinefit(x,y,breaks,5);\n%\n% % Fit a spline of order 3 with periodic boundary conditions\n% pp = splinefit(x,y,breaks,3,'p');\n%\n% % Constraints: y(0) = 0, y'(0) = 1 and y(3) + y\"(3) = 0\n% xc = [0 0 3];\n% yc = [0 1 0];\n% cc = [1 0 1; 0 1 0; 0 0 1];\n% con = struct('xc',xc,'yc',yc,'cc',cc);\n%\n% % Fit a cubic spline with 8 pieces and constraints\n% pp = splinefit(x,y,8,con);\n%\n% % Fit a spline of order 6 with constraints and periodicity\n% pp = splinefit(x,y,breaks,con,6,'p');\n%\n% See also SPLINE, PPVAL, PPDIFF, PPINT\n\n% Author: Jonas Lundgren 2010\n\n% 2009-05-06 Original SPLINEFIT.\n% 2010-06-23 New version of SPLINEFIT based on B-splines.\n% 2010-09-01 Robust fitting scheme added.\n% 2010-09-01 Support for data containing NaNs.\n% 2011-07-01 Robust fitting parameter added.\n\n% Copyright (c) 2010, Jonas Lundgren\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% Check number of arguments\nerror(nargchk(3,7,nargin));\n\n% Check arguments\n[x,y,dim,breaks,n,periodic,beta,constr] = arguments(varargin{:});\n\n% Evaluate B-splines\nbase = splinebase(breaks,n);\npieces = base.pieces;\nA = ppval(base,x);\n\n% Bin data\n[junk,ibin] = histc(x,[-inf,breaks(2:end-1),inf]); %#ok\n\n% Sparse system matrix\nmx = numel(x);\nii = [ibin; ones(n-1,mx)];\nii = cumsum(ii,1);\njj = repmat(1:mx,n,1);\nif periodic\n ii = mod(ii-1,pieces) + 1;\n A = sparse(ii,jj,A,pieces,mx);\nelse\n A = sparse(ii,jj,A,pieces+n-1,mx);\nend\n\n% Don't use the sparse solver for small problems\nif pieces < 20*n/log(1.7*n)\n A = full(A);\nend\n\n% Solve\nif isempty(constr)\n % Solve Min norm(u*A-y)\n u = lsqsolve(A,y,beta);\nelse\n % Evaluate constraints\n B = evalcon(base,constr,periodic);\n % Solve constraints\n [Z,u0] = solvecon(B,constr);\n % Solve Min norm(u*A-y), subject to u*B = yc\n y = y - u0*A;\n A = Z*A;\n v = lsqsolve(A,y,beta);\n u = u0 + v*Z;\nend\n\n% Periodic expansion of solution\nif periodic\n jj = mod(0:pieces+n-2,pieces) + 1;\n u = u(:,jj);\nend\n\n% Compute polynomial coefficients\nii = [repmat(1:pieces,1,n); ones(n-1,n*pieces)];\nii = cumsum(ii,1);\njj = repmat(1:n*pieces,n,1);\nC = sparse(ii,jj,base.coefs,pieces+n-1,n*pieces);\ncoefs = u*C;\ncoefs = reshape(coefs,[],n);\n\n% Make piecewise polynomial\npp = mkpp(breaks,coefs,dim);\n\n\n%--------------------------------------------------------------------------\nfunction [x,y,dim,breaks,n,periodic,beta,constr] = arguments(varargin)\n%ARGUMENTS Lengthy input checking\n% x Noisy data x-locations (1 x mx)\n% y Noisy data y-values (prod(dim) x mx)\n% dim Leading dimensions of y\n% breaks Breaks (1 x (pieces+1))\n% n Spline order\n% periodic True if periodic boundary conditions\n% beta Robust fitting parameter, no robust fitting if beta = 0\n% constr Constraint structure\n% constr.xc x-locations (1 x nx)\n% constr.yc y-values (prod(dim) x nx)\n% constr.cc Coefficients (?? x nx)\n\n% Reshape x-data\nx = varargin{1};\nmx = numel(x);\nx = reshape(x,1,mx);\n\n% Remove trailing singleton dimensions from y\ny = varargin{2};\ndim = size(y);\nwhile numel(dim) > 1 && dim(end) == 1\n dim(end) = [];\nend\nmy = dim(end);\n\n% Leading dimensions of y\nif numel(dim) > 1\n dim(end) = [];\nelse\n dim = 1;\nend\n\n% Reshape y-data\npdim = prod(dim);\ny = reshape(y,pdim,my);\n\n% Check data size\nif mx ~= my\n mess = 'Last dimension of array y must equal length of vector x.';\n error('arguments:datasize',mess)\nend\n\n% Treat NaNs in x-data\ninan = find(isnan(x));\nif ~isempty(inan)\n x(inan) = [];\n y(:,inan) = [];\n mess = 'All data points with NaN as x-location will be ignored.';\n warning('arguments:nanx',mess)\nend\n\n% Treat NaNs in y-data\ninan = find(any(isnan(y),1));\nif ~isempty(inan)\n x(inan) = [];\n y(:,inan) = [];\n mess = 'All data points with NaN in their y-value will be ignored.';\n warning('arguments:nany',mess)\nend\n\n% Check number of data points\nmx = numel(x);\nif mx == 0\n error('arguments:nodata','There must be at least one data point.')\nend\n\n% Sort data\nif any(diff(x) < 0)\n [x,isort] = sort(x);\n y = y(:,isort);\nend\n\n% Breaks\nif isscalar(varargin{3})\n % Number of pieces\n p = varargin{3};\n if ~isreal(p) || ~isfinite(p) || p < 1 || fix(p) < p\n mess = 'Argument #3 must be a vector or a positive integer.';\n error('arguments:breaks1',mess)\n end\n if x(1) < x(end)\n % Interpolate breaks linearly from x-data\n dx = diff(x);\n ibreaks = linspace(1,mx,p+1);\n [junk,ibin] = histc(ibreaks,[0,2:mx-1,mx+1]); %#ok\n breaks = x(ibin) + dx(ibin).*(ibreaks-ibin);\n else\n breaks = x(1) + linspace(0,1,p+1);\n end\nelse\n % Vector of breaks\n breaks = reshape(varargin{3},1,[]);\n if isempty(breaks) || min(breaks) == max(breaks)\n mess = 'At least two unique breaks are required.';\n error('arguments:breaks2',mess);\n end\nend\n\n% Unique breaks\nif any(diff(breaks) <= 0)\n breaks = unique(breaks);\nend\n\n% Optional input defaults\nn = 4; % Cubic splines\nperiodic = false; % No periodic boundaries\nrobust = false; % No robust fitting scheme\nbeta = 0.5; % Robust fitting parameter\nconstr = []; % No constraints\n\n% Loop over optional arguments\nfor k = 4:nargin\n a = varargin{k};\n if ischar(a) && isscalar(a) && lower(a) == 'p'\n % Periodic conditions\n periodic = true;\n elseif ischar(a) && isscalar(a) && lower(a) == 'r'\n % Robust fitting scheme\n robust = true;\n elseif isreal(a) && isscalar(a) && isfinite(a) && a > 0 && a < 1\n % Robust fitting parameter\n beta = a;\n robust = true;\n elseif isreal(a) && isscalar(a) && isfinite(a) && a > 0 && fix(a) == a\n % Spline order\n n = a;\n elseif isstruct(a) && isscalar(a)\n % Constraint structure\n constr = a;\n else\n error('arguments:nonsense','Failed to interpret argument #%d.',k)\n end\nend\n\n% No robust fitting\nif ~robust\n beta = 0;\nend\n\n% Check exterior data\nh = diff(breaks);\nxlim1 = breaks(1) - 0.01*h(1);\nxlim2 = breaks(end) + 0.01*h(end);\nif x(1) < xlim1 || x(end) > xlim2\n if periodic\n % Move data inside domain\n P = breaks(end) - breaks(1);\n x = mod(x-breaks(1),P) + breaks(1);\n % Sort\n [x,isort] = sort(x);\n y = y(:,isort);\n else\n mess = 'Some data points are outside the spline domain.';\n warning('arguments:exteriordata',mess)\n end\nend\n\n% Return\nif isempty(constr)\n return\nend\n\n% Unpack constraints\nxc = [];\nyc = [];\ncc = [];\nnames = fieldnames(constr);\nfor k = 1:numel(names)\n switch names{k}\n case {'xc'}\n xc = constr.xc;\n case {'yc'}\n yc = constr.yc;\n case {'cc'}\n cc = constr.cc;\n otherwise\n mess = 'Unknown field ''%s'' in constraint structure.';\n warning('arguments:unknownfield',mess,names{k})\n end\nend\n\n% Check xc\nif isempty(xc)\n mess = 'Constraints contains no x-locations.';\n error('arguments:emptyxc',mess)\nelse\n nx = numel(xc);\n xc = reshape(xc,1,nx);\nend\n\n% Check yc\nif isempty(yc)\n % Zero array\n yc = zeros(pdim,nx);\nelseif numel(yc) == 1\n % Constant array\n yc = zeros(pdim,nx) + yc;\nelseif numel(yc) ~= pdim*nx\n % Malformed array\n error('arguments:ycsize','Cannot reshape yc to size %dx%d.',pdim,nx)\nelse\n % Reshape array\n yc = reshape(yc,pdim,nx);\nend\n\n% Check cc\nif isempty(cc)\n cc = ones(size(xc));\nelseif numel(size(cc)) ~= 2\n error('arguments:ccsize1','Constraint coefficients cc must be 2D.')\nelseif size(cc,2) ~= nx\n mess = 'Last dimension of cc must equal length of xc.';\n error('arguments:ccsize2',mess)\nend\n\n% Check high order derivatives\nif size(cc,1) >= n\n if any(any(cc(n:end,:)))\n mess = 'Constraints involve derivatives of order %d or larger.';\n error('arguments:difforder',mess,n-1)\n end\n cc = cc(1:n-1,:);\nend\n\n% Check exterior constraints\nif min(xc) < xlim1 || max(xc) > xlim2\n if periodic\n % Move constraints inside domain\n P = breaks(end) - breaks(1);\n xc = mod(xc-breaks(1),P) + breaks(1);\n else\n mess = 'Some constraints are outside the spline domain.';\n warning('arguments:exteriorconstr',mess)\n end\nend\n\n% Pack constraints\nconstr = struct('xc',xc,'yc',yc,'cc',cc);\n\n\n%--------------------------------------------------------------------------\nfunction pp = splinebase(breaks,n)\n%SPLINEBASE Generate B-spline base PP of order N for breaks BREAKS\n\nbreaks = breaks(:); % Breaks\nbreaks0 = breaks'; % Initial breaks\nh = diff(breaks); % Spacing\npieces = numel(h); % Number of pieces\ndeg = n - 1; % Polynomial degree\n\n% Extend breaks periodically\nif deg > 0\n if deg <= pieces\n hcopy = h;\n else\n hcopy = repmat(h,ceil(deg/pieces),1);\n end\n % to the left\n hl = hcopy(end:-1:end-deg+1);\n bl = breaks(1) - cumsum(hl);\n % and to the right\n hr = hcopy(1:deg);\n br = breaks(end) + cumsum(hr);\n % Add breaks\n breaks = [bl(deg:-1:1); breaks; br];\n h = diff(breaks);\n pieces = numel(h);\nend\n\n% Initiate polynomial coefficients\ncoefs = zeros(n*pieces,n);\ncoefs(1:n:end,1) = 1;\n\n% Expand h\nii = [1:pieces; ones(deg,pieces)];\nii = cumsum(ii,1);\nii = min(ii,pieces);\nH = h(ii(:));\n\n% Recursive generation of B-splines\nfor k = 2:n\n % Antiderivatives of splines\n for j = 1:k-1\n coefs(:,j) = coefs(:,j).*H/(k-j);\n end\n Q = sum(coefs,2);\n Q = reshape(Q,n,pieces);\n Q = cumsum(Q,1);\n c0 = [zeros(1,pieces); Q(1:deg,:)];\n coefs(:,k) = c0(:);\n % Normalize antiderivatives by max value\n fmax = repmat(Q(n,:),n,1);\n fmax = fmax(:);\n for j = 1:k\n coefs(:,j) = coefs(:,j)./fmax;\n end\n % Diff of adjacent antiderivatives\n coefs(1:end-deg,1:k) = coefs(1:end-deg,1:k) - coefs(n:end,1:k);\n coefs(1:n:end,k) = 0;\nend\n\n% Scale coefficients\nscale = ones(size(H));\nfor k = 1:n-1\n scale = scale./H;\n coefs(:,n-k) = scale.*coefs(:,n-k);\nend\n\n% Reduce number of pieces\npieces = pieces - 2*deg;\n\n% Sort coefficients by interval number\nii = [n*(1:pieces); deg*ones(deg,pieces)];\nii = cumsum(ii,1);\ncoefs = coefs(ii(:),:);\n\n% Make piecewise polynomial\npp = mkpp(breaks0,coefs,n);\n\n\n%--------------------------------------------------------------------------\nfunction B = evalcon(base,constr,periodic)\n%EVALCON Evaluate linear constraints\n\n% Unpack structures\nbreaks = base.breaks;\npieces = base.pieces;\nn = base.order;\nxc = constr.xc;\ncc = constr.cc;\n\n% Bin data\n[junk,ibin] = histc(xc,[-inf,breaks(2:end-1),inf]); %#ok\n\n% Evaluate constraints\nnx = numel(xc);\nB0 = zeros(n,nx);\nfor k = 1:size(cc,1)\n if any(cc(k,:))\n B0 = B0 + repmat(cc(k,:),n,1).*ppval(base,xc);\n end\n % Differentiate base\n coefs = base.coefs(:,1:n-k);\n for j = 1:n-k-1\n coefs(:,j) = (n-k-j+1)*coefs(:,j);\n end\n base.coefs = coefs;\n base.order = n-k;\nend\n\n% Sparse output\nii = [ibin; ones(n-1,nx)];\nii = cumsum(ii,1);\njj = repmat(1:nx,n,1);\nif periodic\n ii = mod(ii-1,pieces) + 1;\n B = sparse(ii,jj,B0,pieces,nx);\nelse\n B = sparse(ii,jj,B0,pieces+n-1,nx);\nend\n\n\n%--------------------------------------------------------------------------\nfunction [Z,u0] = solvecon(B,constr)\n%SOLVECON Find a particular solution u0 and null space Z (Z*B = 0)\n% for constraint equation u*B = yc.\n\nyc = constr.yc;\ntol = 1000*eps;\n\n% Remove blank rows\nii = any(B,2);\nB2 = full(B(ii,:));\n\n% Null space of B2\nif isempty(B2)\n Z2 = [];\nelse\n % QR decomposition with column permutation\n [Q,R,dummy] = qr(B2); %#ok\n R = abs(R);\n jj = all(R < R(1)*tol, 2);\n Z2 = Q(:,jj)';\nend\n\n% Sizes\n[m,ncon] = size(B);\nm2 = size(B2,1);\nnz = size(Z2,1);\n\n% Sparse null space of B\nZ = sparse(nz+1:nz+m-m2,find(~ii),1,nz+m-m2,m);\nZ(1:nz,ii) = Z2;\n\n% Warning rank deficient\nif nz + ncon > m2\n\tmess = 'Rank deficient constraints, rank = %d.';\n\twarning('solvecon:deficient',mess,m2-nz);\nend\n\n% Particular solution\nu0 = zeros(size(yc,1),m);\nif any(yc(:))\n % Non-homogeneous case\n\tu0(:,ii) = yc/B2;\n % Check solution\n\tif norm(u0*B - yc,'fro') > norm(yc,'fro')*tol\n mess = 'Inconsistent constraints. No solution within tolerance.';\n error('solvecon:inconsistent',mess)\n\tend\nend\n\n\n%--------------------------------------------------------------------------\nfunction u = lsqsolve(A,y,beta)\n%LSQSOLVE Solve Min norm(u*A-y)\n\n% Avoid sparse-complex limitations\nif issparse(A) && ~isreal(y)\n A = full(A);\nend\n\n% Solution\nu = y/A;\n\n% Robust fitting\nif beta > 0\n [m,n] = size(y);\n alpha = 0.5*beta/(1-beta)/m;\n for k = 1:3\n % Residual\n r = u*A - y;\n rr = r.*conj(r);\n rrmean = sum(rr,2)/n;\n rrmean(~rrmean) = 1;\n rrhat = (alpha./rrmean)'*rr;\n % Weights\n w = exp(-rrhat);\n spw = spdiags(w',0,n,n);\n % Solve weighted problem\n u = (y*spw)/(A*spw);\n end\nend\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/K-wave/k-Wave/private/splinefit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715774, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7498999386448053}} {"text": "function value = monomial_value ( dim_num, point_num, x, expon )\n\n%*****************************************************************************80\n%\n%% MONOMIAL_VALUE evaluates a monomial.\n%\n% Discussion:\n%\n% This routine evaluates a monomial of the form\n%\n% product ( 1 <= dim <= dim_num ) x(dim)^expon(dim)\n%\n% where the exponents are nonnegative integers. Note that\n% if the combination 0^0 is encountered, it should be treated\n% as 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 05 May 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer POINT_NUM, the number of points at which the\n% monomial is to be evaluated.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the point coordinates.\n%\n% Input, integer EXPON(DIM_NUM), the exponents.\n%\n% Output, real VALUE(POINT_NUM), the value of the monomial.\n%\n value(1:point_num) = 1.0;\n\n for dim = 1 : dim_num\n if ( 0 ~= expon(dim) )\n value(1:point_num) = value(1:point_num) .* x(dim,1:point_num).^expon(dim);\n end\n end\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/stroud/monomial_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7497555812031753}} {"text": "function [ ntree, itree, seed ] = tree_rooted_random ( nnode, seed )\n\n%*****************************************************************************80\n%\n%% TREE_ROOTED_RANDOM selects a random unlabeled rooted tree.\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% Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.\n% FORTRAN90 version by John Burkardt.\n%\n% Reference:\n%\n% Albert Nijenhuis, Herbert Wilf,\n% Combinatorial Algorithms,\n% Academic Press, 1978, second edition,\n% ISBN 0-12-519260-6.\n%\n% Parameters:\n%\n% Input, integer NNODE, the number of nodes.\n%\n% Input/output, integer SEED, a seed for the random \n% number generator.\n%\n% Output, integer NTREE(NNODE). NTREE(I) is the number of \n% rooted, unlabeled trees on I nodes, for I = 1, 2, ... NNODE.\n%\n% Output, integer ITREE(NNODE). (I,ITREE(I)) is the I-th edge\n% of the output tree for I = 2,NNODE. ITREE(1)=0.\n%\n if ( nnode <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TREE_ROOTED_RANDOM - Fatal error!\\n' );\n fprintf ( 1, ' NNODE = %d\\n', nnode );\n fprintf ( 1, ' but NNODE must be at least 1.\\n' );\n error ( 'TREE_ROOTED_RANDOM - Fatal error!' );\n end\n%\n% Compute a table of the number of such trees for a given number of nodes.\n%\n ntree = tree_rooted_enum ( nnode );\n%\n% Now select one such tree at random.\n%\n l = 0;\n\n nval = nnode;\n is1 = 0;\n is2 = 0;\n \n while ( 1 )\n\n while ( 2 < nval )\n \n [ r, seed ] = r8_uniform_01 ( seed );\n\n iz = floor ( ( nval - 1 ) * ntree(nval) * r );\n\n id = 0;\n \n id = id + 1;\n itd = id * ntree(id);\n m = nval;\n j = 0;\n \n while ( 1 )\n \n j = j + 1;\n m = m - id;\n\n if ( m < 1 )\n id = id + 1;\n itd = id * ntree(id);\n m = nval;\n j = 0;\n continue\n end\n\n iz = iz - ntree(m) * itd;\n\n if ( iz < 0 )\n break\n end\n\n end\n\n is1 = is1 + 1;\n stack(1,is1) = j;\n stack(2,is1) = id;\n nval = m;\n \n end\n \n itree(is2+1) = l;\n l = is2 + 1;\n is2 = is2 + nval;\n\n if ( 1 < nval )\n itree(is2) = is2 - 1;\n end\n \n while ( 1 )\n \n nval = stack(2,is1);\n \n if ( nval ~= 0 )\n stack(2,is1) = 0;\n break\n end\n \n j = stack(1,is1);\n is1 = is1 - 1;\n m = is2 - l + 1;\n ll = itree(l);\n ls = l + ( j - 1 ) * m - 1;\n \n if ( j ~= 1 )\n for i = l : ls\n itree(i+m) = itree(i) + m;\n if ( mod(i-l,m) == 0 )\n itree(i+m) = ll;\n end\n end\n end\n \n is2 = ls + m;\n \n if ( is2 == nnode )\n return\n end\n\n l = ll;\n \n end\n\n end\n \n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/treepack/tree_rooted_random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648676, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.7497555768004522}} {"text": "function h = p12_h ( n, x )\n\n%*****************************************************************************80\n%\n%% P12_H evaluates the Hessian for problem 12.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 March 2000\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real H(N,N), the N by N Hessian matrix.\n%\n h = zeros ( n, n );\n\n d1 = 2.0 / 3.0;\n\n for i = 1 : 99\n\n arg = i / 100.0;\n r = ( - 50.0 * log ( arg ) )^d1 + 25.0 - x(2);\n t1 = abs ( r )^x(3) / x(1);\n t2 = exp ( - t1 );\n t3 = t1 * t2 * ( t1 * t2 + ( t1 - 1.0 ) * ( t2 - arg ) );\n t = t1 * t2 * ( t2 - arg );\n logr = log ( abs ( r ) );\n\n h(1,1) = h(1,1) + 2.0 * t3 - 2.0 * t;\n h(1,2) = h(1,2) + 2.0 * t3 / r;\n h(1,3) = h(1,3) - 2.0 * t3 * logr;\n\n h(2,1) = h(2,1) + 2.0 * t3 / r;\n h(2,2) = h(2,2) + 2.0 * ( t + x(3) * t3 ) / r / r;\n h(2,3) = h(2,3) + 2.0 * ( t - x(3) * t3 * logr ) / r;\n\n h(3,1) = h(3,1) - 2.0 * t3 * logr;\n h(3,2) = h(3,2) + 2.0 * ( t - x(3) * t3 * logr ) / r;\n h(3,3) = h(3,3) + 2.0 * t3 * logr * logr;\n\n end\n\n h(1,1) = ( h(1,1) / x(1) ) / x(1);\n h(1,2) = h(1,2) * x(3) / x(1);\n h(1,3) = h(1,3) / x(1);\n\n h(2,1) = h(2,1) * x(3) / x(1);\n h(2,2) = h(2,2) * x(3);\n\n h(3,1) = h(3,1) / x(1);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_opt/p12_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7497224684792905}} {"text": "function [eef_transform,J]=directKinematics_1(q,TefTool,dh)\n%% Calculates the direct kinematics of a robotic manipulator \n\n% Syntax:\n% [eef_transform,J]=directKinematics(q,TefTool,dh)\n\n% Arreguments:\n% q: angles of the joints of the robot.\n% TefTool: transfomr matrix from the tool frame to the flange frame of the\n% robot.\n% dh: is a structure with the Denavit-Hartenberg parameters of the robot.\n\n\n% Return value:\n% eef_transform: transfomration matrix from end-effector to tool\n% J: jacobean at the tool center point (TCP) of the end-effector EEF.\n\n% Copyright:\n% Mohammad SAFEEA\n% 16th-Aug-2017\n% updated: 22nd-June-2018\n\n%% DH PARAMETERS FOR THE ROBOT\nalfa=dh.alfa;\nd=dh.d;\na=dh.a;\n\n%% Calculating the direct Kinematics\nT=zeros(4,4,7);\ni=1;\nT(:,:,i)=getDHMatrix(alfa{i},q(i),d{i},a{i});\n for i=2:7\n T(:,:,i)=T(:,:,i-1)*getDHMatrix(alfa{i},q(i),d{i},a{i});\n T(:,:,i)=normalizeColumns(T(:,:,i));\n end\n T(:,:,7)=T(:,:,7)*TefTool;\n T(:,:,7)=normalizeColumns(T(:,:,7));\n \n pef=T(1:3,4,7);\n for i=1:7\n k=T(1:3,3,i);\n pij=pef-T(1:3,4,i);\n J(1:3,i)=cross(k,pij);\n J(4:6,i)=k;\n end\n%% End effector transform\neef_transform=T(:,:,7);\nend\n\nfunction T=getDHMatrix(alfa,theta,d,a)\nT=zeros(4,4);\n\ncalpha=cos(alfa);\nsinalpha=sin(alfa);\ncoshteta=cos(theta);\nsintheta=sin(theta);\n\nT(1,1)=coshteta;\nT(2,1)=sintheta*calpha;\nT(3,1)=sintheta*sinalpha;\t\t\t\t\n\nT(1,2)=-sintheta;\nT(2,2)=coshteta*calpha;\nT(3,2)=coshteta*sinalpha;\n\nT(2,3)=-sinalpha;\nT(3,3)=calpha;\n\nT(1,4)=a;\nT(2,4)=-sinalpha*d;\nT(3,4)=calpha*d;\nT(4,4)=1;\n\nend\n\nfunction normalizedT=normalizeColumns(T)\n%% This function is used to normalize the columns of a rotation matrix with \n% some numerical errors resulting from matrix multiplication problems\nr=zeros(4,3); % corrected rotatio matrix, with zero badding row at the end\nfor j=1:3\n r(1:3,j)=T(1:3,j)/norm(T(1:3,j));\nend\nnormalizedT=[r,T(:,4)];\nend\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/Matlab_client/directKinematics_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7497224620180603}} {"text": "function X = matrandcong(m,n,gamma)\n%MATRANDCONG Create a random matrix with a fixed congruence.\n%\n% X = MATRANDCONG(M,N,GAMMA) creates a matrix X of size M x N such\n% that each column of X has norm 1 and any two columns of X have an inner\n% product equal to GAMMA.\n%\n% Based on code from Evrim Acar and the paper G. Tomasi and R. Bro, A\n% comparison of algorithms for fitting the PARAFAC model, Computational\n% Statistics & Data Analysis, 50: 1700-1734, 2006.\n%\n% See also MATRANDORTH, MATRANDNORM, CREATE_PROBLEM, CREATE_GUESS.\n%\n%MATLAB Tensor Toolbox.\n%Copyright 2015, Sandia Corporation.\n\n% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.\n% http://www.sandia.gov/~tgkolda/TensorToolbox.\n% Copyright (2015) Sandia Corporation. Under the terms of Contract\n% DE-AC04-94AL85000, there is a non-exclusive license for use of this\n% work by or on behalf of the U.S. Government. Export of this data may\n% require a license from the United States Government.\n% The full license terms can be found in the file LICENSE.txt\n\nCG = gamma * ones(n,n) + (1-gamma) * eye(n);\nCGR = chol(CG);\nX = randn(m,n);\n[Q,~] = qr(X,0);\nX = Q * CGR;\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/分类算法/DEEP-TENSOR-FACTORIZATION-FOR-HYPERSPECTRAL-IMAGE-CLASSIFICATION-master/code/tensor_toolbox_2.6/matrandcong.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7497071747275998}} {"text": "% GAUSSIAN_DLOGPDF - The log pdf of a multivariate normal distribution.\n%\n% Computes the logarithm of the multivariate normal probability density\n% function N(Y|MU,COV), where Y is the random variable, MU is the mean\n% and COV is the covariance.\n%\n% The function is called as:\n%\n% L = GAUSSIAN_LOGPDF(Y_INVCOV_Y, Y_INVCOV_MU, MU_INVCOV_MU, LOGDET_COV, D)\n%\n% where\n%\n% Y_INVCOV_Y : Y'*INV(COV)*Y\n% Y_INVCOV_MU : Y'*INV(COV)*MU\n% MU_INVCOV_MU : MU'*INV(COV)*MU\n% LOGDET_COV : LOG(DET(COV))\n% D : the dimensionality of the distribution\n%\n% However, these terms should be computed more efficiently than using INV\n% and LOG(DET(..)).\n%\n% Letting the user to compute the terms allows greater efficiency and\n% flexibility.\n%\n% Also note that the function is linear with respect to its arguments. Thus,\n% some efficiency may be obtained for a large set of pdfs by summing the\n% terms and calling this function only once with scalar arguments.\n%\n% Usage:\n%\n% X = GAUSSIAN_DLOGPDF(Y, MU, L)\n%\n% X = GAUSSIAN_DLOGPDF(INVCOV_Y, INVCOV_MU)\n%\n% X = GAUSSIAN_DLOGPDF(D_Y_INVCOV_Y, D_Y_INVCOV_MU, D_MU_INVCOV_MU, ...\n% D_LOGDET_COV)\n\n% Last modified 2011-02-09\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)\n\nfunction dx = gaussian_dlogpdf(p1, p2, p3, p4)\n\nif nargin == 3\n\n y = p1;\n mu = p2;\n L = p3;\n\n dx = -linsolve_lchol(L,y-mu);\n\nelseif nargin == 2\n \n invCov_y = p1;\n invCov_mu = p2;\n\n dx = invCov_mu - invCov_y;\n \nelseif nargin == 4\n \n dx = -0.5*(p1-2*p2+p3) - 0.5*p4;\n\nend\n\n\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/distributions/gaussian_dlogpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.74970716961842}} {"text": "function y = pinvNx2(x)\n\n% PINVNX2 computes a pseudo-inverse of the slices of an Nx2xM real-valued matrix.\n% Output has dimensionality 2xNxM. This implementation is generally faster\n% than calling pinv in a for-loop, once M > 2 \n\nsiz = [size(x) 1];\nxtx = zeros([2,2,siz(3:end)]);\nxtx(1,1,:,:) = sum(x(:,1,:,:).^2,1);\nxtx(2,2,:,:) = sum(x(:,2,:,:).^2,1);\ntmp = sum(x(:,1,:,:).*x(:,2,:,:),1);\nxtx(1,2,:,:) = tmp;\nxtx(2,1,:,:) = tmp;\nixtx = inv2x2(xtx);\ny = mtimes2xN(ixtx, permute(x, [2 1 3:ndims(x)]));\n\nfunction [d] = inv2x2(x)\n\n% INV2X2 computes inverse of matrix x, where x = 2x2xN, using explicit analytic definition\n\nadjx = [x(2,2,:,:) -x(1,2,:,:); -x(2,1,:,:) x(1,1,:,:)];\ndenom = x(1,1,:,:).*x(2,2,:,:) - x(1,2,:,:).*x(2,1,:,:);\nd = adjx./denom([1 1],[1 1],:,:);\n\nfunction [z] = mtimes2xN(x, y)\n\n% MTIMES2XN computes x*y where x = 2x2xM and y = 2xNxM\n% and output dimensionatity is 2xNxM \n\nsiz = size(y);\nz = zeros(siz);\n\nfor k = 1:siz(2)\n z(1,k,:,:) = x(1,1,:,:).*y(1,k,:,:) + x(1,2,:,:).*y(2,k,:,:);\n z(2,k,:,:) = x(2,1,:,:).*y(1,k,:,:) + x(2,2,:,:).*y(2,k,:,:);\nend\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/utilities/private/pinvNx2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.8031737892899221, "lm_q1q2_score": 0.7497071615345274}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% split1.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% function z = split1(x1,x2,f1,f2)\n% Input: points x1 and x2, x1 < x2, and corresponding function values f1\n% and f2\n% splits the interval [x1,x2] according to the golden section rule\n% the part containing the better point gets the larger fraction of the \n% interval\n\nfunction z = split1(x1,x2,f1,f2)\nif f1 <= f2\n z = x1 + 0.5*(-1 + sqrt(5))*(x2 - x1);\nelse\n z = x1 + 0.5*(3 - sqrt(5))*(x2 - x1);\nend\n", "meta": {"author": "lacerbi", "repo": "optimviz", "sha": "2cc41c19ffeaaa9a23239f53d80691cf3599357d", "save_path": "github-repos/MATLAB/lacerbi-optimviz", "path": "github-repos/MATLAB/lacerbi-optimviz/optimviz-2cc41c19ffeaaa9a23239f53d80691cf3599357d/utils/mcs/private/split1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850093037731, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.749675927537779}} {"text": "function p=gaussian(x,m,C);\n% p=gaussian(x,m,C);\n%\n% Evaluate the multi-variate density with mean vector m and covariance\n% matrix C for the input vector x.\n% \n% p=gaussian(X,m,C);\n% \n% Vectorized version: Here X is a matrix of column vectors, and p is \n% a vector of probabilities for each vector.\n% Jianbo Shi, 1997\nd=length(m);\n\nif size(x,1)~=d\n x=x';\nend\nN=size(x,2);\n\ndetC = det(C);\nif rcond(C)N),\n error('t0 must be between 1 and N.');\nelse\n if h <= 0 \n f = (1/N:1/N:0.5-1/N) ;\n y = zeros(1,N/2);\n y(2:N/2) = (f.^(-1-h)).*exp(-i*2*pi*f.*(t0-1));\n x = real(ifft(y,N)) ;\n x = x./max(x); \n x = x.' - sign(min(x))*abs(min(x)) ;\n else\n t = 1:N;\n x = abs(t-t0).^h;\n x = max(x)-x.' ;\n end\nend\n\nx=hilbert(x);", "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/anasing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.749625108781788}} {"text": "function y = wprctile(x, p, w)\n%WPRCTILE Percentiles of a weighted sample.\n%\n% Description\n% Y = PRCTILE(X, P, W) returns percentiles of the values in X\n% (along the first dimension). P is a scalar or a vector of percent\n% values. W is a vector of unnormalized weights for samples. Length\n% of W has to be same as length of X. X need to be a a vector. Y is\n% the same size as P, and Y(i) contains the P(i)-th percentile.\n%\n% Example\n% y = prctile(x,50,w); % the median of x given sample weights w\n%\n% See also wmean, prctile\n%\n% Copyright (c) 2000-2013 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\nx=sort(x,1);\np=p./100;\ny=zeros(length(p),size(x,2));\nww=cumsum(w);ww=ww./ww(end);\nfor j=1:length(p)\n wi=min(find(ww>=p(j)));\n if wi==1\n y(j,:)=x(1,:);\n else\n w1=ww(wi-1);x1=x(wi-1,:);\n y(j,:)=x1+(x(wi,:)-x1).*(p(j)-w1)./(ww(wi)-w1);\n end\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/misc/wprctile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7496251062856728}} {"text": "function [ r ] = EffRank(s, thresh)\n%[ r ] = EffRank(s, thresh)\n% get the effective rank of an singular value array\n% s: the singular values in descending order\n% thresh: the total variance to preserve\n% author: Liang Xiong (lxiong@cs.cmu.edu)\n\nif nargin < 2; thresh = 0.99; end\nassert(all(s > 0), 'not a proper singular value array');\n\ns = sort(s.^2,'descend');\ncs = cumsum(s);\nif cs(end) < 1e-10\n error('EffRank has encounted a zero matrix');\nelse\n r = sum(cs./cs(end) <= thresh) + 1;\n r = min(length(s), r);\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/nmf/DRMF/EffRank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.749625095634901}} {"text": " function output = ir_radon_zwart_powell(theta, rr)\n%function output = ir_radon_zwart_powell(theta, yr)\n%|\n%| Compute analytic 2D Radon transform of Zwart-Powell box spline.\n%|\n%| in\n%| theta\tray angle in radian\n%| rr\tdistance between the point and the ray (normalized by the pixel size)\n%| output: radon transform of the Zwart-Powell box spline element\n%|\n%| This is the modified version of the code written by [1]\n%| to avoid symbolic math operation.\n%| Code written by Seongjin Yoon, Univ. of Michigan, Jan 2015\n%|\n%| Reference\n%| [1] A. Entezari, M. Nilchian, and M. Unser, \"A box spline calculus\n%| for the discretization of computed tomography reconstruction problems,\"\n%| IEEE Trans. Med. Imaging, vol. 31, no. 8, pp. 1532–1541, 2012.\n%|\n%| 2015-08-10 Jeff Fessler, added self test and parallelized\n\nif nargin == 1 && streq(theta, 'test'), ir_radon_zwart_powell_test, return, end\nif nargin < 2, ir_usage, end\n\ndim = size(theta);\ntheta = theta(:);\n\nzeta = zeros(numel(theta), 4);\nzeta(:,1) = cos(theta);\nzeta(:,2) = sin(theta);\nzeta(:,3) = zeta(:,1) + zeta(:,2);\nzeta(:,4) = zeta(:,1) - zeta(:,2);\n\ncond = abs(zeta) >= eps('single');\nN = sum(cond,2);\n\noutput = BoxSp4(rr(:), zeta, cond, N) ./ factorial(N-1);\noutput = reshape(output, dim);\n\n\nfunction output = BoxSp0(y, N)\n%output = heaviside(y) .* y.^(N-1);\nif any(size(y) ~= size(N)), keyboard, end\noutput = (y >= 0) .* y.^(N-1);\n\n\nfunction output = BoxSp1(y, zeta, cond, N)\ngood = cond(:,1);\noutput = (BoxSp0(y+0.5*zeta(:,1), N) ...\n\t- BoxSp0(y-0.5*zeta(:,1), N)) ./ zeta(:,1);\noutput(~good) = BoxSp0(y(~good), N(~good));\n\n\nfunction output = BoxSp2(y, zeta, cond, N)\ngood = cond(:,2);\noutput = (BoxSp1(y+0.5*zeta(:,2), zeta, cond, N) ...\n\t- BoxSp1(y-0.5*zeta(:,2), zeta, cond, N)) ./ zeta(:,2);\noutput(~good) = BoxSp1(y(~good), zeta(~good,:), cond(~good,:), N(~good));\n\n\nfunction output = BoxSp3(y, zeta, cond, N)\ngood = cond(:,3);\noutput = (BoxSp2(y+0.5*zeta(:,3), zeta, cond, N) ...\n\t- BoxSp2(y-0.5*zeta(:,3), zeta, cond, N)) ./ zeta(:,3);\noutput(~good) = BoxSp2(y(~good), zeta(~good,:), cond(~good,:), N(~good));\n\n\nfunction output = BoxSp4(y, zeta, cond, N)\ngood = cond(:,4);\noutput = (BoxSp3(y+0.5*zeta(:,4), zeta, cond, N) ...\n\t- BoxSp3(y-0.5*zeta(:,4), zeta, cond, N)) ./ zeta(:,4);\noutput(~good) = BoxSp3(y(~good), zeta(~good,:), cond(~good,:), N(~good));\n\n\n% ir_radon_zwart_powell_test()\nfunction ir_radon_zwart_powell_test\ntheta = linspace(0,pi,181);\nr = linspace(-1,1,101) * 2;\n[tt rr] = ndgrid(theta, r);\nsino = ir_radon_zwart_powell(tt, rr);\nim('colorneg', r, theta, sino'), cbar\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/fbp/ir_radon_zwart_powell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7496071127440984}} {"text": "function L = compute_point_laplacian(pts, type, rings, options)\n\n% compute_point_laplacian - compute a laplacian matrix L, L = -(Laplacian operator).\n%\n% L = compute_point_laplacian(pts, type, rings, options)\n%\n% If options.symmetrize=1 and options.normalize=0 then \n% L = D-W\n% If options.symmetrize=1 and options.normalize=1 then \n% L = eye(n)-D^{-1/2}*W*D^{-1/2}\n% If options.symmetrize=0 and options.normalize=1 then \n% L = eye(n)-D^{-1}*W.\n% where D=diag(sum(W,2)) and W is the unormalized weight matrix \n% (see compute_mesh_weight).\n%\n% type can 'combinatorial', 'distance', 'conformal'.\n%\n% See also compute_point_weight.\n%\n% Changed default value for symmetrize from 1 to 0 (JJCAO)\n% Copyright (c) 2009 jjcao\n\noptions.null = 0;\nnormalize = getoptions(options, 'normalize', 0);\nsymmetrize = getoptions(options, 'symmetrize', 1);\n\nW = compute_point_weight(pts, type, rings, options);\nn = size(W,1);\n \nif symmetrize==1 && normalize==0\n L = diag(sum(W,2)) - W;\nelseif symmetrize==1 && normalize==1\n L = speye(n) - diag(sum(W,2).^(-1/2)) * W * diag(sum(W,2).^(-1/2));\nelseif symmetrize==0 && normalize==1\n L = speye(n) - diag(sum(W,2).^(-1)) * W;\nelse\n error('Does not work with symmetrize=0 and normalize=0'); \nend\n", "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_laplacian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545289551957, "lm_q2_score": 0.7905303211371899, "lm_q1q2_score": 0.7495449042626319}} {"text": "function [degree, node] = grNodeDegree(node, edges)\n%GRNODEDEGREE Degree of a node in a (undirected) graph.\n%\n% DEGREE = grNodeDegree(NODE_INDEX, EDGES);\n% return the degree of a node in the given edge list, that is the number\n% of edges connected to it.\n% NODE_INDEX is the index of the node, and EDGES is a liste of couples of\n% indices (origin and destination node). \n% This degree is the sum of inner degree (number of edges arriving on the\n% node) and the outer degree (number of emanating edges).\n% \n% Note: Also works when NODE_INDEX is a vector of indices\n%\n% DEGREE = grNodeDegree(EDGES);\n% Return the degree of each node references by the array EDGES. DEGREE is\n% a column vector with as many rows as the number of nodes referenced by\n% edges.\n%\n% [DEG, INDS] = grNodeDegree(EDGES);\n% Also returns the indices of the nodes that were referenced.\n% \n% Example\n% edges = [1 2;1 3;2 3;2 4;3 4];\n% grNodeDegree(2, edges)\n% ans =\n% 3\n% grNodeDegree(edges)'\n% ans =\n% 2 3 3 2\n%\n% See also grNodeInnerDegree, grNodeOuterDegree\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2003-08-13\n% Copyright 2003-2022 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas)\n\n% If only edge array is given, assume we want the degree of each node\nif nargin == 1\n edges = node;\n node = unique(edges(:));\nend\n\n% allocate array for result\ndegree = zeros(size(node));\n\n% for each node ID, count the number of edges containing it\nfor i = 1:length(node(:))\n degree(i) = sum(edges(:,1) == node(i)) + sum(edges(:,2) == node(i));\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/graphs/grNodeDegree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7495433029109088}} {"text": "function pass = test_battery(pref)\n% A large battery of functions. \n\nif ( nargin < 1 ) \n pref = chebfunpref; \nend \ntol = 1e8 * pref.cheb3Prefs.chebfun3eps;\n\nBattery = {@(x,y,z) cos(pi*x.*y.*z),... % 1\n @(x,y,z) cos(2*pi*x.*y.*z),... % 2\n @(x,y,z) cos(3*pi*x.*y.*z),... % 3\n @(x,y,z) cos(4*pi*x.*y.*z),... % 4\n @(x,y,z) cos(5*pi*x.*y.*z),... % 5\n @(x,y,z) cos(6*pi*x.*y.*z),... % 6\n @(x,y,z) cos(7*pi*x.*y.*z),... % 7\n @(x,y,z) sin(pi*x.*y.*z),... % 8\n @(x,y,z) sin(8*pi*x.*(1-x).*y.*(1-y).*z.*(1-z)),... % 9\n @(x,y,z) sin(8*pi*x.*(1-x).*y.*(1-y).*z.*(1-z).*(x-y-z).^2),... % 10\n @(x,y,z) cos(0*pi*(x-y-z).^2),... % 11\n @(x,y,z) cos(pi*(x-y-z).^2),... % 12\n @(x,y,z) cos(2*pi*(x-y-z).^2),... % 13\n @(x,y,z) exp(sin(4*pi./(1+x)).*sin(4*pi./(1+y)).*sin(4*pi./(1+z))),... % 14\n @(x,y,z) log(1+x.*y.*z),... % 15\n @(x,y,z) cos(pi*x.*sin(pi*y)) + cos(pi*y.*z.*sin(pi*x.*z)),... % 16\n @(x,y,z) cos(2*pi*x.*sin(pi*y).*cos(pi*z)) + cos(2*pi*y.*sin(pi*x)),... % 17\n @(x,y,z) (1-x.*y.*z)./(1+x.^2+y.^2),... % 18\n @(x,y,z) cos(pi*x.*y.^2.*z.^3).*cos(pi*z.*y.^2.*x.^3),... % 19\n @(x,y,z) cos(2*pi*x.*y.^2.*z.^3).*cos(2*pi*y.*x.^2.*z.^3),... % 20\n @(x,y,z) cos(3*pi*x.*y.^2.*(1+z)).*cos(3*pi*y.*x.^2.*(1+z)),... % 21 \n @(x,y,z) (x-y)./(3-x.^2+z.^2),... % 22 \n @(x,y,z) exp(-y.*x.^2.*z) + exp(-x.*y.^2.*z),... % 23\n @(x,y,z) exp((1-x.^2.*z)./(1+y.^2.*z)) + exp((1-y.^2.*z)./(1+x.^2.*z)),... % 24\n @(x,y,z) 10.^(-x.*y.*z),... % 25\n @(x,y,z) 10.^(-10*x.*y.*z),... % 26\n @(x,y,z) sin(x+y+z),... % 27\n @(x,y,z) exp(x+y+z).*cos(x+y+z),... % 28\n @(x,y,z) cos(pi/4+x+y+z),... % 29\n @(x,y,z) cos(pi/3+5*x+5*y+5*z),... % 30\n @(x,y,z) (x+y+z).^12,... % 31\n @(x,y,z) exp(x.^2.*y.^2.*z.^2).*cos(x+y+z),... % 32\n @(x,y,z) sin(x.*y.*z)+x+y+z,... % 33\n @(x,y,z) cos(100*x)-cos(100*y)-cos(100*z),... % 34\n @(x,y,z) x-y+z,... % 35\n @(x,y,z) -sin(x).*(sin(x.^2/pi).^2 - sin(y).*sin(y.^2/pi).^2) - sin(z).*sin(z.^2/pi).^2,... % 36\n @(x,y,z) -x.*sin(sqrt(abs(0.2+x))) - y.*sin(sqrt(abs(0.3+y))) - z.*sin(sqrt(abs(0.1+z))),... % 37 \n @(x,y,z) (x.^2+y.^2+z.^2)/4000 - cos(x).*cos(y/sqrt(2)) .* cos(z/sqrt(3))+1,... % 38\n @(x,y,z) exp(1./(1+(((x+1)/2).*((y+1)/2).*(z+1)/2).^2)),... % 39\n @(x,y,z) 2*exp(exp((x+1)/2)),... % 40\n };\n\n% Exact values for definite integrals computed with MATLAB's symbolic\n% toolbox.\nexact = [\n 0.8461106227350253, ...\n 0.6052157118483288, ...\n 0.4697661749231274, ...\n 0.3886397051915788, ...\n 0.3330920107414529, ...\n 0.2928314960173565, ...\n 0.2619772790103158, ...\n 0.3226674912855009, ...\n 0.1153949594968427, ...\n 0.0463743346003271, ...\n 1.0, ...\n 0.3854484437166375, ...\n 0.2595975105701650, ...\n 1.0700418045865364, ...\n 0.1103040719136995, ...\n 1.1941278093664705, ...\n 0.4916086077355209, ...\n 0.5741043338997425, ...\n 0.9381453489074456, ...\n 0.8830048694732021, ...\n 0.3411136775418946, ...\n 0.0101828389788635, ...\n 1.8529116285910792, ...\n 4.2715143503929390, ...\n 0.7859343211742496, ...\n 0.3352208605577725, ...\n 0.8793549306454008, ...\n -0.801590008944990, ...\n -0.577703137905825, ...\n -0.008766419956637, ...\n 5220.0021978021978, ...\n 0.0366931467095498, ...\n 1.6224340287967378, ...\n 0.0050636564110975, ...\n 0.5, ...\n -0.022434416365347, ...\n -1.181086511303566, ...\n 0.2694080277004217, ...\n 2.3340368233541618, ...\n 17.816513659679896, ...\n ];\n\ndom = [0 1 0 1 0 1];\nfor jj=1:1:length(Battery)\n % Test construction from the function handle:\n g = chebfun3(Battery{jj}, dom);\n pass(5*jj-4) = abs(sum3(g) - exact(jj)) < tol;\n \n % Test construction from the Chebfun3 object:\n % 1: Without specifying the variable to be separated in Phase 1:\n h = chebfun3(@(x,y,z) g(x,y,z), dom);\n pass(5*jj-3) = abs(sum3(h) - exact(jj)) < tol;\n \n % 2: Different variables specified to be separated in Phase 1. The\n % goal is to check that constructor has no issues with any choice of\n % variable chosen for the first separation.\n h1 = chebfun3(@(x,y,z) g(x,y,z), dom, 'fiberDim', 1);\n pass(5*jj-2) = abs(sum3(h1) - exact(jj)) < tol;\n \n h2 = chebfun3(@(x,y,z) g(x,y,z), dom, 'fiberDim', 2);\n pass(5*jj-1) = abs(sum3(h2) - exact(jj)) < tol;\n \n h3 = chebfun3(@(x,y,z) g(x,y,z), dom, 'fiberDim', 3);\n pass(5*jj) = abs(sum3(h3) - exact(jj)) < tol;\n \nend\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebfun3/test_battery.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7495172040889322}} {"text": "function [ ival, pint ] = plane_normal_line_exp_int_3d ( pp, normal, p1, p2 )\n\n%*****************************************************************************80\n%\n%% PLANE_NORMAL_LINE_EXP_INT_3D: intersection of plane and line in 3D.\n%\n% Discussion:\n%\n% The normal form of a plane in 3D is:\n%\n% PP is a point on the plane,\n% N is a normal vector to the plane.\n%\n% The explicit form of a line in 3D is:\n%\n% P1, P2 are two points on the line.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real PP(3), a point on the plane.\n%\n% Input, real NORMAL(3), a normal vector to the plane.\n%\n% Input, real P1(3), P2(3), two distinct points on the line.\n%\n% Output, integer IVAL, the kind of intersection;\n% 0, the line and plane seem to be parallel and separate;\n% 1, the line and plane intersect at a single point;\n% 2, the line and plane seem to be parallel and joined.\n%\n% Output, real PINT(3), the coordinates of a\n% common point of the plane and line, when IVAL is 1 or 2.\n%\n dim_num = 3;\n%\n% Make sure the line is not degenerate.\n%\n if ( line_exp_is_degenerate_nd ( dim_num, p1, p2 ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PLANE_NORMAL_LINE_EXP_INT_3D - Fatal error!\\n' );\n fprintf ( 1, ' The line is degenerate.\\n' );\n error ( 'PLANE_NORMAL_LINE_EXP_INT_3D - Fatal error!' );\n end\n%\n% Make sure the plane normal vector is a unit vector.\n%\n temp = sqrt ( sum ( normal(1:dim_num).^2 ) );\n\n if ( temp == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PLANE_NORMAL_LINE_EXP_INT_3D - Fatal error!\\n' );\n fprintf ( 1, ' The normal vector of the plane is degenerate.\\n' );\n error ( 'PLANE_NORMAL_LINE_EXP_INT_3D - Fatal error!' );\n end\n\n normal(1:dim_num) = normal(1:dim_num) / temp;\n%\n% Determine the unit direction vector of the line.\n%\n direction(1:dim_num) = p2(1:dim_num) - p1(1:dim_num);\n temp = sqrt ( sum ( direction(1:dim_num).^2 ) );\n direction(1:dim_num) = direction(1:dim_num) / temp;\n%\n% If the normal and direction vectors are orthogonal, then\n% we have a special case to deal with.\n%\n if ( normal(1:dim_num) * direction(1:dim_num)' == 0.0 )\n\n temp = normal(1:dim_num) * ( p1(1:dim_num) - pp(1:dim_num) )';\n\n if ( temp == 0.0 )\n ival = 2;\n pint(1:dim_num) = p1(1:dim_num);\n else\n ival = 0;\n pint(1:dim_num) = Inf;\n end\n\n return\n end\n%\n% Determine the distance along the direction vector to the intersection point.\n%\n temp = ( ( pp(1:dim_num) - p1(1:dim_num) ) * normal(1:dim_num)' )...\n / ( direction(1:dim_num) * normal(1:dim_num)' );\n\n ival = 1;\n pint(1:dim_num) = p1(1:dim_num) + temp * direction(1:dim_num);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/plane_normal_line_exp_int_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7494935257649011}} {"text": "% Calculate head direction.\n%\n% Calculates the head direction for each position sample pair. Direction\n% is defined as east = 0 degrees, north = 90 degrees, west = 180 degrees,\n% south = 270 degrees. Direction is set to NaN for missing samples.\n% Position matrix contains information about front and back LED. Head\n% direction is the counter-clockwise direction from back LED to the front.\n%\n% USAGE\n% hd = calcHeadDirection(positions)\n%\n% positions Animal's position data, Nx5. Position data should\n% contain timestamps (1 column), X/Y coordinates of\n% first LED (2 and 3 columns correspondingly), X/Y\n% coordinates of the second LED (4 and 5 columns\n% correspondingly).\n% it is assumed that positions(:, 2:3) correspond to\n% front LED, and positions(:, 4:5) to the back LED.\n% The resulting hd is the directon from back LED to\n% the front LED.\n% hd Vector of head directions in degrees.\n%\nfunction hd = calcHeadDirection(positions)\n\n if size(positions, 2) < 5\n error('Position data should be 2D (type ''help analyses.calcHeadDirection'' for details).');\n end\n % 1 column contains timestamps\n x1 = positions(:, 2);\n y1 = positions(:, 3);\n x2 = positions(:, 4);\n y2 = positions(:, 5);\n\n hd = rem(atan2d(y2-y1, x2-x1) + 180, 360);\nend\n", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Analysis/+analyses/calcHeadDirection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947117065458, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7494809343132174}} {"text": "function Y=hooklaw(X, td, E, ni);\n\n%Y=hooklaw(X, td, E, ni)\n%\n%This function calculates the strain or stress according to Hook's Law.\n%Transform direction determine the input variable td.\n%The proper values of td variable:\n%td='stress_strain' - if input variable X is a stress tensor\n%td='strain_stress' - if input variable X is a strain tensor\n%\n%But, for the purpose of computations we use the vector representation\n%of a tensor X(ij), so that:\n%X - is a vector representation of a tensor X(ij)\n% with the components in the following order:\n%\n%X=[Xxx Xyy Xzz Xxy Xxz Xzx Xyx Xyz Xxz]\n%or\n%X=[Xxx Xyy Xzz Xxy Xxz Xyz]\n%or\n%X=[Xxx Xyy Xzz]\n%\n%Dimension of X can be [m n]\n%where: m - represents the number of tensors to calculate\n% n = 9, 6 or 3 (see above)\n%\n%E - Young's modulus\n%ni - Poisson's coefficient\n%\n% Copyright (c) 2001 by Aleksander Karolczuk.\n% $Revision: 1.2 $ $Date: 2004/02/13\n\n\n\nerror(nargchk(4,4,nargin))\n\n[m n]=size(X);\n\nif n==3\n I=[1 1 1];\nelseif n==6\n I=[1 1 1 0 0 0];\nelseif n==9\n I=[1 1 1 0 0 0 0 0 0];\nelse\n error('Improper matrix dimension')\nend\n\nif lower(td)=='stress_strain'\n Y=((1+ni)/E)*(X-(ni/(1+ni))*(X*I')*I);\n elseif lower(td)=='strain_stress'\n Y=(E/(1+ni))*(X+(ni/(1-2*ni))*(X*I')*I);\n else\n error('Improper name of transform direction')\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/24711-stress2strain/hooklaw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.7494809179922656}} {"text": "function [X, sigma2, W] = ppcaEmbed(Y, dims)\n\n% PPCAEMBED Embed data set with probabilistic PCA.\n% FORMAT\n% DESC returns latent positions for a given data set via probabilistic\n% PCA.\n% ARG Y : the data set which you want the latent positions for.\n% ARG dims : the dimensionality of the latent space.\n% RETURN X : the latent positions.\n% RETURN sigma2 : the variance not explained by the latent positions.\n% RETURN W : the matrix required to invert the transformation, Y=X*W'.\n%\n% COPYRIGHT : Neil D. Lawrence, 2006\n%\n% SEEALSO : lleEmbed, isomapEmbed\n\n% MLTOOLS\n\nif ~any(any(isnan(Y)))\n if size(Y, 1)30000\n % Bug in MATLAB 7.0 means you have to do this.\n innerY = zeros(size(Ycentre, 1));\n for i = 1:size(Ycentre, 1)\n innerY(i, :) = Ycentre(i, :)*Ycentre';\n end\n else\n innerY = Ycentre*Ycentre';\n end\n [v, u] = eigdec(innerY, dims); \n v(find(v<0))=0;\n X = u(:, 1:dims)*sqrt(size(Y, 1));\n v = v/sqrt(size(Y, 1));\n sigma2 = (trace(innerY) - sum(v))/(size(Y, 2)-dims);\n W = X'*Ycentre;\n\n else\n [v, u] = pca(Y);\n v(find(v<0))=0;\n Ymean = mean(Y);\n Ycentre = zeros(size(Y));\n for i = 1:size(Y, 2);\n Ycentre(:, i) = Y(:, i) - Ymean(i);\n end\n X = Ycentre*u(:, 1:dims)*diag(1./sqrt(v(1:dims)));\n sigma2 = mean(v(dims+1:end));\n W = X'*Ycentre;\n end\nelse\n % Hacky implementation of Probabilistic PCA for when there is missing data.\n iters = 100;\n % Initialise W randomly\n d = size(Y, 2);\n q = dims;\n N = size(Y, 1);\n W = randn(d, q)*1e-3;\n sigma2 = 1;\n mu = zeros(d, 1);\n for i = 1:d\n obs = find(~isnan(Y(:, i)));\n if length(obs)>0\n mu(i) = mean(Y(obs, i));\n else\n mu(i) = 0;\n end\n end\n numObs = sum(sum(~isnan(Y)));\n for i = 1:iters\n M = W'*W + sigma2*eye(q);\n invM = inv(M);\n exp_xxT = zeros(q);\n exp_x = zeros(N, q);\n for n = 1:N\n obs = find(~isnan(Y(n, :)));\n exp_x(n, :) = (invM*W(obs, :)'*(Y(n, obs)' - mu(obs)))';\n end\n exp_xxT = N*sigma2*invM + exp_x'*exp_x;\n s = zeros(d, q);\n s2 = 0;\n for n = 1:N\n obs = find(~isnan(Y(n, :)));\n subY = zeros(size(Y(n, :)))';\n subY(obs) = Y(n, obs)' - mu(obs);\n s = s + (subY)*exp_x(n, :);\n s2 = s2 + sum((Y(n, obs)' - mu(obs)).^2) - 2*exp_x(n, :)*W(obs, :)'*(Y(n, obs)' - mu(obs));\n end\n W = s*inv(exp_xxT);\n sigma2 = 1/(numObs)*(s2 + trace(exp_xxT*W'*W));\n end\n \n X = exp_x;\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/mltools/ppcaEmbed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7494001385652752}} {"text": "function dz = rollingCartPoleDynamics(~,z,P) \n%DZ = ROLLINGCARTPOLEDYNAMICS(T,Z,P)\n% \n%FUNCTION: This function computes the dynamics of a rolling\n% cart-pole, and is designed to be called from ode45.\n% \n%INPUTS: \n% t = time. Dummy input for ode45. Not used.\n% z = [4xn] matrix of states.\n% P = struct of parameters\n%OUTPUTS: \n% dz = [4xn] matrix of state derivatives\n% \n%NOTES:\n% This file was automatically generated by writeRollingCartPoleDynamics\n\nm1 = P.m1; %disk mass\nm2 = P.m2; %bob mass\nI = P.I; %disk moment of inertia\ng = P.g ; %gravity\nl = P.l; %pendulum length\nr = P.r; %disk radius\n\nphi = z(1,:); %link one absolute angle\nth = z(2,:); %link one angular rate\ndphi = z(3,:); %link two absolute angle\ndth = z(4,:); %link two angular rate\n\nf1 = - m2.*r.*sin(th).*(dth.^2.*l + g.*cos(th)) - dth.^2.*l.*m1.*r.*sin(th);\nf2 = -g.*m2.*sin(th);\n\nM11 = - I - m1.*r.^2 - m2.*r.^2.*sin(th).^2;\nM12 = l.*m1.*r.*cos(th);\nM21 = m2.*r.*cos(th);\nM22 = -l.*m2;\n\nD = M11.*M22 - M12.*M21;\n\nddphi = (f2.*M12 - f1.*M22)./D;\nddth = -(f2.*M11 - f1.*M21)./D;\n\ndz = [...\n dphi; %derivative of link one absolute angle\n dth; %derivative of link one angular rate\n ddphi; %derivative of link two absolute angle\n ddth; %derivative of link two angular rate\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/rollingCartPole/rollingCartPoleDynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7494001347317903}} {"text": "function y = frunge ( x )\n\n%*****************************************************************************80\n%\n%% FRUNGE sets the Runge data values.\n%\n% Discussion:\n%\n% Interpolation of the Runge function at evenly spaced points\n% in [-1,1] is a common test.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 January 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument.\n%\n% Output, real FRUNGE, the value of the derivative of the Runge function.\n%\n y = 1.0E+00 ./ ( 1.0E+00 + 25.0E+00 * 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/spline/frunge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8774768002981829, "lm_q1q2_score": 0.7492886236694595}} {"text": "k=1/(2*sqrt(log(2)));\nx=0:30/1999:30; \na1=1.0; t1=5; w1=1.3;\ny1=a1*exp(-((x-t1)/(w1*k)).^2);\na2=1.0; t2=15.0; w2=1.3;\ny2=a2*(1+4*((x-t2)/w2).^2).^(-1);\na3=1.0; t3=25;\ny3=a3*ones(size(x))./(1+exp(-3.0*(x-t3)));\ny=y1+y2+y3;\nnoise=rand(size(y));\ny=y+(noise-0.5)*0.01;\n\nfigure\nsubplot(3,1,1)\nplot(x,y);\ntitle('noisy data');\n\nsubplot(3,1,2)\nplot(x(1:end-1)+(x(2)-x(1)),diff(y)/(x(2)-x(1)));\ntitle('diff function');\n\nsubplot(3,1,3)\nplot(x,filter(-smooth_diff(10),1,y)/(x(2)-x(1)));\ntitle('smoothed differentiation');\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/6170-smooth-differentiation/smooth_diff_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778073288127, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7492254265834561}} {"text": "function logPr = calcLogPrGaussian( X, mu, invSigma)\n% Each row of X is an independent draw from Normal( mu, invSigma )\n\nD = size( invSigma,1);\nLOG_2PI = 1.837877066409345;\n\ncholInvSigma = chol( invSigma );\nlogDetInvSigma = 2*sum( log( diag( cholInvSigma ) ) );\n\nXdiffMu = bsxfun( @minus, X, mu );\nU = XdiffMu'*cholInvSigma';\nlogPr = -0.5*D*LOG_2PI + 0.5*logDetInvSigma - 0.5*sum(U.^2, 2);", "meta": {"author": "michaelchughes", "repo": "NPBayesHMM", "sha": "22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd", "save_path": "github-repos/MATLAB/michaelchughes-NPBayesHMM", "path": "github-repos/MATLAB/michaelchughes-NPBayesHMM/NPBayesHMM-22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd/code/BayesCalc/calcLogPrGaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778000158576, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7492254160070254}} {"text": "function [suspicious_index suspicious_score u] = OD_onlinePCA(A, beta)\n%\n% Outlier detection via over-sampling online PCA\n%\n% This function is used for outlier detection. The main idea is using \n% the variation of the first principal direction detect the outlierness\n% of each instance(event) in the leave one out procedure. Here the \n% over-sampling on target instance is also used for enlarge the \n% outlierness\n%\n%\n% input\n% A: the data matrix, each row represents an instance\n% beta: forgetting factor\n% For example, beta=0.9 means we decrease the influence of previous\n% data by a factor of 0.9\n% output\n% suspicious_score: the suspicious score for each instance\n% suspicious_index: the ranking of instances according to their\n% suspicious score\n% For example, suspicious_index(i)=j means the ith \n% instance is in jth position in the ranking.\n%\n% References\n% Anomaly Detection via Over-Sampling Principal Component Analysis \n% Send your comment and inquiry to Dr. Yi-Ren Yeh (yirenyeh@gmail.com) \n%\n\n[n p]= size(A);\n\nA_m = mean(A);\nd = 0.0001;\nu = ones(p,1);\nfor i = 1:n\n [u d] = Track_w(A(i,:)-A_m, u, d, 1);\nend\nu = u/norm(u);\n\n\nsim_pool = zeros(n,1);\nratio = 1/(n*beta);\nfor i = 1:n\n temp_mu = (A_m+ratio*A(i,:))/(1+ratio);\n x =A(i,:)-temp_mu;\n [w] = Track_w(x, u, d, beta); \n w = w/norm(w);\n sim_pool(i,:) = abs(diag(u'*w));\n if (~mod(i,10000))\n display(['Iteration ',num2str(i)])\n end\nend\n\n[non,suspicious_index]=sort(sim_pool);\nsuspicious_score = 1-sim_pool;\n\n\n%==========================================================================\nfunction [w d] = Track_w(x, w, d, beta)\ny = x*w;\nd = beta*d+y^2;\ne = x'-w*y;\nw = w + (y*e)/d;\n% function [w d] = Track_w(x, w, d, n, ratio)\n% y = x*w;\n% d = (1/n)*d+ratio*y^2;\n% e = x'-w*y;\n% w = w + (y*e)/d;\n", "meta": {"author": "dsmi-lab-ntust", "repo": "AnomalyDetectionToolbox", "sha": "b9385ba405026f56a008f88c0580b1a18e24b355", "save_path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox", "path": "github-repos/MATLAB/dsmi-lab-ntust-AnomalyDetectionToolbox/AnomalyDetectionToolbox-b9385ba405026f56a008f88c0580b1a18e24b355/Algorithms/PCA_based/osPCA/OD_onlinePCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7491932594531083}} {"text": "function value = r8_cosd ( degrees )\n\n%*****************************************************************************80\n%\n%% R8_COSD returns the cosine of an angle given in degrees.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 July 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real DEGREES, the angle in degrees.\n%\n% Output, real VALUE, the cosine of the angle.\n%\n radians = pi * ( degrees / 180.0 );\n\n value = cos ( radians );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8_cosd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8459424450764199, "lm_q1q2_score": 0.7491932441840464}} {"text": "function area = polygonArea3d(poly, varargin)\n%POLYGONAREA3D Area of a 3D polygon.\n%\n% AREA = polygonArea3d(POLY)\n% POLY is given as a N-by-3 array of vertex coordinates. The resulting\n% area is positive.\n% Works also for polygons given as a cell array of polygons.\n%\n% Example\n% % area of a simple 3D square \n% poly = [10 30 20;20 30 20;20 40 20;10 40 20];\n% polygonArea3d(poly)\n% ans =\n% 100\n%\n% % Area of a 3D mesh\n% [v f] = createCubeOctahedron;\n% polygons = meshFacePolygons(v, f);\n% areas = polygonArea3d(polygons);\n% sum(areas)\n% ans =\n% 18.9282\n%\n% See also\n% polygons3d, triangleArea3d, polygonArea, polygonCentroid3d\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2012-02-24, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n% HISTORY\n% 2013-08-20 add support for multiple polygons\n\n% Check multiple polygons\nif iscell(poly) || sum(sum(isnan(poly))) > 0\n % split the polygons into a cell array\n polygons = splitPolygons3d(poly);\n nPolys = length(polygons);\n \n % compute area of each polygon\n area = zeros(nPolys, 1);\n for i = 1:nPolys\n area(i) = polygonArea3d(polygons{i});\n end\n \n return;\nend\n\n% put the first vertex at origin (reducing computation errors for polygons\n% far from origin)\nv0 = poly(1, :);\npoly = bsxfun(@minus, poly, v0);\n\n% indices of next vertices\nN = size(poly, 1);\niNext = [2:N 1];\n\n% compute cross-product of each elementary triangle formed by origin and\n% two consecutive vertices\ncp = cross(poly, poly(iNext,:), 2);\n\n% choose one of the triangles as reference for the normal direction\nvn = vectorNorm3d(cp);\n[tmp, ind] = max(vn); %#ok\ncpRef = cp(ind,:);\n\n% compute the sign of the area of each triangle\n% (need to compute the sign explicitely, as the norm of the cross product\n% does not keep orientation within supporting plane)\nsign_i = sign(dot(cp, repmat(cpRef, N, 1), 2));\n\n% compute area of each triangle, using sign correction\narea_i = vectorNorm3d(cp) .* sign_i;\n\n% sum up individual triangles area\narea = sum(area_i) / 2;\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/polygonArea3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.7491932424117173}} {"text": "%TRNORM Normalize an SO(3) or SE(3) matrix\n%\n% TRNORM(R) is guaranteed to be a proper orthogonal matrix rotation\n% matrix (3x3) which is \"close\" to the input matrix R (3x3). If R\n% = [N,O,A] the O and A vectors are made unit length and the normal vector\n% is formed from N = O x A, and then we ensure that O and A are orthogonal\n% by O = A x N.\n%\n% TRNORM(T) as above but the rotational submatrix of the homogeneous\n% transformation T (4x4) is normalised while the translational part is\n% unchanged.\n%\n% If R (3x3xK) or T (4x4xK) representing a sequence then the normalisation\n% is performed on each of the K planes.\n%\n% Notes::\n% - Only the direction of A (the z-axis) is unchanged.\n% - Used to prevent finite word length arithmetic causing transforms to \n% become `unnormalized'.\n% - There is no Toolbox function for SO(2) or SE(2).\n%\n% See also OA2TR, SO3.trnorm, SE3.trnorm.\n\n%## 3d homogeneous \n\n% Copyright (C) 1993-2019 Peter I. Corke\n%\n% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n% of the Software, and to permit persons to whom the Software is furnished to do\n% so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%\n% https://github.com/petercorke/spatial-math\n\nfunction TR = trnorm(T)\n\n assert(ishomog(T) || isrot(T), 'SMTB:trnorm:badarg', 'expecting 3x3xN or 4x4xN hom xform');\n \n if ndims(T) == 3\n % recurse for transform sequence\n n = size(T);\n TR = zeros(n);\n for i=1:n(3)\n TR(:,:,i) = trnorm(T(:,:,i));\n end\n return\n end\n \n o = T(1:3,2); a = T(1:3,3);\n n = cross(o, a); % N = O x A\n o = cross(a, n); % O = A x N\n R = [unit(n) unit(o) unit(a)];\n \n if ishomog(T)\n TR = rt2tr( R, T(1:3,4) );\n elseif isrot(T)\n TR = R;\n end\n\n", "meta": {"author": "petercorke", "repo": "spatialmath-matlab", "sha": "6eeff4a79f14286705560b84f1fe72e0b7e0e7f7", "save_path": "github-repos/MATLAB/petercorke-spatialmath-matlab", "path": "github-repos/MATLAB/petercorke-spatialmath-matlab/spatialmath-matlab-6eeff4a79f14286705560b84f1fe72e0b7e0e7f7/trnorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7491620495558211}} {"text": "function line = fitLine3d(points)\n%FITLINE3D Fit a 3D line to a set of points.\n%\n% LINE = fitLine3d(PTS)\n%\n% Example\n% pts = randn(300, 3);\n% pts = transformPoint3d(pts, createScaling3d([6 4 2]));\n% pts = transformPoint3d(pts, createRotationOx(pi/6));\n% pts = transformPoint3d(pts, createRotationOy(pi/4));\n% pts = transformPoint3d(pts, createRotationOz(pi/3));\n% pts = transformPoint3d(pts, createTranslation3d([5 4 3]));\n% elli = inertiaEllipsoid(pts);\n% figure; drawPoint3d(pts); axis equal;\n% hold on; drawEllipsoid(elli, ...\n% 'drawEllipses', true, 'EllipseColor', 'b', 'EllipseWidth', 3);\n% line = fitLine3d(pts);\n% drawLine3d(line, 'color', 'm', 'LineWidth', 4);\n%\n% See also\n% lines3d, inertiaEllipsoid, fitPlane\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2012-11-11, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n% number of points\nn = size(points, 1);\n\n% compute centroid\ncenter = mean(points);\n\n% compute the covariance matrix\ncovPts = cov(points)/n;\n\n% perform a principal component analysis with 2 variables, \n% to extract inertia axes\n[U, S] = svd(covPts);\n\n% sort axes from greater to lower\n[dummy, ind] = sort(diag(S), 'descend'); %#ok\n\n% format U to ensure first axis points to positive x direction\nU = U(ind, :);\nif U(1,1) < 0\n U = -U;\n % keep matrix determinant positive\n U(:,3) = -U(:,3);\nend\n\nline = [center U(:,1)'];\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/fitLine3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7491208595246495}} {"text": "function qoi_quad ( )\n\n%*****************************************************************************80\n%\n%% QOI_QUAD seeks the expected value of a quantity of interest.\n%\n% Discussion:\n%\n% Our base value for DELTA_BASE is 0.01.\n%\n% Our quantity of interest Q is the time at which the solution achieves\n% the value 0.99.\n%\n% Our parameter U is uniformly distributed in [-1,+1], and determines\n% our actual value of DELTA by\n%\n% DELTA = 2^U * DELTA_BASE.\n%\n% We seek the expected value of Q, which we define as:\n%\n% E(Q) = Integral ( -1 <= U <= +1 ) Q(Y(DELTA(U))) rho(U) dU\n%\n% where \n%\n% rho(U) = 1/2;\n% DELTA(U) = 2^U * DELTA_BASE;\n% Y(DELTA()) is the solution of the combustion ODE for an initial\n% condition of DELTA;\n% Q(Y) is the (first) time T* at which the solution Y(T*) = 0.99.\n%\n% We approximate the integral using a Clenshaw-Curtis quadrature rule.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n delta_base = 0.01;\n n_max = 12;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QOI_QUAD\\n' );\n fprintf ( 1, ' Use quadrature to estimate the expected value of our\\n' );\n fprintf ( 1, ' quantity of interest Q, the time at which the\\n' );\n fprintf ( 1, ' combustion solution reaches 0.99.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using Clenshaw-Curtis quadrature of orders 1 through %d\\n', n_max );\n%\n% Set up an option to have ODE45 return when the solution reached 0.99.\n%\n options = odeset ( 'EVENTS', @event_function );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N Estimated Q\\n' );\n fprintf ( 1, '\\n' );\n\n for n = 1 : n_max\n\n [ x, w ] = clenshaw_curtis_compute ( n );\n\n f = zeros ( n, 1 );\n\n for j = 1 : n\n%\n% Uniformly select \n% U, the logarithm base 2, between -1 and +1, of\n% F, a factor between 1/2 and 2, which multiplies \n% DELTA_BASE, the base value, which gives us\n% DELTA, the initial size of the flame.\n%\n u = x(j);\n factor = 2^u;\n delta = factor * delta_base;\n%\n% Set the starting point.\n%\n t_start = 0.0;\n y_start(1,1) = delta;\n%\n% Get the stopping point.\n%\n t_stop = 250.0;\n%\n% Call ODE45 to solve the problem, stopping immediately if the event \n% (y=0.99) is observed.\n%\n t_span = [ t_start, t_stop ];\n\n [ t, y ] = ode45 ( @flame_fun, t_span, y_start, options );\n%\n% Our function must be weighted by rho(u), which is uniformly 1/2.\n%\n f(j) = 0.5 * t(end);\n\n end\n%\n% Compute the integral estimate.\n%\n q = w' * f;\n\n fprintf ( 1, ' %2d %12g\\n', n, q );\n\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QOI_QUAD\\n' );\n fprintf ( 1, ' Normal end of execution\\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/flame_ode/qoi_quad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7491173045406316}} {"text": "%% RATE OF CONVERGENCE OF MIXED FINITE ELEMENT METHOD (RT0-P0) FOR POISSON EQUATION\n%\n% This example is to show the rate of convergence of RT0-P0 mixed finite\n% element approximation of the Poisson equation on the unit square with the\n% following boundary conditions:\n%\n% - pure Dirichlet boundary condition.\n% - Pure Neumann boundary condition.\n% - mxied boundary condition.\n%\n% The basis, data structure and numerical test is summarized in Poisson3RT0femrate.\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% Triangular preconditioned GMRES (default solver) and Uzawa preconditioned\n% CG converges uniformly in all cases. Traingular preconditioner is two\n% times faster than PCG although GMRES is used.\n% See also PoissonBDM1mfemrate, Poissonfemrate, Poissonafemrate\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n\n%% Setting\n[node,elem] = cubemesh([0,1,0,1,0,1],0.5);\nmesh = struct('node',node,'elem',elem);\noption.L0 = 1;\noption.maxIt = 3;\noption.printlevel = 1;\noption.elemType = 'RT0';\n% pde = mixedPossiondata;\n\n%% Dirichelt for u and Neumann boundary condition for sigma\noption.solver = 'uzawapcg';\npde = sincosdata3;\nmesh.bdFlag = setboundary3(node,elem,'Dirichlet');\nmfemPoisson3(mesh,pde,option);\n\n%% Neumann for u and Dirichlet boundary condition for sigma.\noption.solver = 'tri';\npde = sincosdata3;\nmesh.bdFlag = setboundary3(node,elem,'Neumann');\nmfemPoisson3(mesh,pde,option);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/fem/mixedPoisson/Poisson3RT0mfemrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8198933447152498, "lm_q1q2_score": 0.7491173007694841}} {"text": "function [x,N] = makesig(SigName,N)\n% [x,N] = makesig(SigName,N) Creates artificial test signal identical to the\n% standard test signals proposed and used by D. Donoho and I. Johnstone\n% in WaveLab (- a matlab toolbox developed by Donoho et al. the statistics\n% department at Stanford University).\n%\n% Input: SigName - Name of the desired signal (Default 'all')\n% 'AllSig' (Returns a matrix with all the signals)\n% 'HeaviSine'\n% 'Bumps'\n% 'Blocks'\n% 'Doppler'\n% 'Ramp'\n% 'Cusp'\n% 'Sing'\n% 'HiSine'\n% 'LoSine'\n% 'LinChirp'\n% 'TwoChirp'\n% 'QuadChirp'\n% 'MishMash'\n% 'WernerSorrows' (Heisenberg)\n% 'Leopold' (Kronecker)\n% N - Length in samples of the desired signal (Default 512)\n%\n% Output: x - vector/matrix of test signals\n% N - length of signal returned\n%\n% See also: \n%\n% References:\n% WaveLab can be accessed at\n% www_url: http://playfair.stanford.edu/~wavelab/\n% Also see various articles by D.L. Donoho et al. at\n% web_url: http://playfair.stanford.edu/\n%\n%Author: Jan Erik Odegard \n%This m-file is a copy of the code provided with WaveLab\n%customized to be consistent with RWT.\n\nif(nargin < 1)\n SigName = 'AllSig';\n N = 512;\nelseif(nargin == 1)\n N = 512;\nend;\nt = (1:N) ./N;\nx = [];\ny = [];\nif(strcmp(SigName,'HeaviSine') | strcmp(SigName,'AllSig')),\n y = 4.*sin(4*pi.*t);\n y = y - sign(t - .3) - sign(.72 - t);\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'Bumps') | strcmp(SigName,'AllSig')),\n pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];\n hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2];\n wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005];\n y = zeros(size(t));\n for j =1:length(pos)\n y = y + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;\n end \nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'Blocks') | strcmp(SigName,'AllSig')),\n pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];\n hgt = [4 (-5) 3 (-4) 5 (-4.2) 2.1 4.3 (-3.1) 2.1 (-4.2)];\n y = zeros(size(t));\n for j=1:length(pos)\n y = y + (1 + sign(t-pos(j))).*(hgt(j)/2) ;\n end\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'Doppler') | strcmp(SigName,'AllSig')),\n y = sqrt(t.*(1-t)).*sin((2*pi*1.05) ./(t+.05));\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'Ramp') | strcmp(SigName,'AllSig')),\n y = t - (t >= .37);\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'Cusp') | strcmp(SigName,'AllSig')),\n y = sqrt(abs(t - .37));\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'Sing') | strcmp(SigName,'AllSig')),\n k = floor(N * .37);\n y = 1 ./abs(t - (k+.5)/N);\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'HiSine') | strcmp(SigName,'AllSig')),\n y = sin( pi * (N * .6902) .* t);\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'LoSine') | strcmp(SigName,'AllSig')),\n y = sin( pi * (N * .3333) .* t);\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'LinChirp') | strcmp(SigName,'AllSig')),\n y = sin(pi .* t .* ((N .* .125) .* t));\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'TwoChirp') | strcmp(SigName,'AllSig')),\n y = sin(pi .* t .* (N .* t)) + sin((pi/3) .* t .* (N .* t));\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'QuadChirp') | strcmp(SigName,'AllSig')),\n y = sin( (pi/3) .* t .* (N .* t.^2));\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'MishMash') | strcmp(SigName,'AllSig')), \n % QuadChirp + LinChirp + HiSine\n y = sin( (pi/3) .* t .* (N .* t.^2)) ;\n y = y + sin( pi * (N * .6902) .* t);\n y = y + sin(pi .* t .* (N .* .125 .* t));\nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'WernerSorrows') | strcmp(SigName,'AllSig')),\n y = sin( pi .* t .* (N/2 .* t.^2)) ;\n y = y + sin( pi * (N * .6902) .* t);\n y = y + sin(pi .* t .* (N .* t));\n pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];\n hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2];\n wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005];\n for j =1:length(pos)\n y = y + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;\n end \nend;\nx = [x;y];\ny = [];\nif(strcmp(SigName,'Leopold') | strcmp(SigName,'AllSig')),\n y = (t == floor(.37 * N)/N); \t\t% Kronecker\nend;\nx = [x;y];\ny = [];\n\n% disp(sprintf('MakeSignal: I don*t recognize << %s>>',SigName))\n% disp('Allowable SigNames are:')\n% disp('AllSig'),\n% disp('HeaviSine'),\n% disp('Bumps'),\n% disp('Blocks'),\n% disp('Doppler'),\n% disp('Ramp'),\n% disp('Cusp'),\n% disp('Crease'),\n% disp('Sing'),\n% disp('HiSine'),\n% disp('LoSine'),\n% disp('LinChirp'),\n% disp('TwoChirp'),\n% disp('QuadChirp'),\n% disp('MishMash'),\n% disp('WernerSorrows'),\n% disp('Leopold'),\n%end\n", "meta": {"author": "ricedsp", "repo": "D-AMP_Toolbox", "sha": "6e597d98c84755697b65554d59485d50a549c01a", "save_path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox", "path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox/D-AMP_Toolbox-6e597d98c84755697b65554d59485d50a549c01a/Packages/rwt/bin/makesig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7489974427093401}} {"text": "function [ SimilarityMatrix ] = similarity_neighbor_grid_further( x, side, types, dist)\n%similarity_neighbor_grid_further Summary of this function goes here\n\n % this assumes that the patch is laid out with first column, then second\n % column, ... final column (column major)\n\n% dist = 2;\n SimilarityMatrix = eye(side*side);\n\n % types - 1 - horizontal, 2 - vertical, 3 - diagonal (bl-tr), 4 -\n % diagonal (br - tl)\n for t=1:numel(types)\n\n if(types(t) == 1)\n \n % for horizontal we want to link both neighbours \n % (which are offset from the points by height)\n i = 1:(side*side-side*dist);\n % create the neighboring links for i\n SimilarityMatrix(sub2ind([side^2, side^2], i, i+side*dist)) = 1;\n SimilarityMatrix(sub2ind([side^2, side^2], i+side*dist, i)) = 1; \n \n end \n if(types(t) == 2)\n \n % for vertical we want to link both neighbours except at edge\n % cases which are mod(y_loc,side) = 0 as they are at the edges\n i = 1:side*side;\n i_to_rem =[];\n for s=1:dist\n i_to_rem = union(i_to_rem, i(mod(i+s-1, side) == 0));\n end\n i_both = setdiff(i, i_to_rem);\n % create the neighboring links for i\n SimilarityMatrix(sub2ind([side^2, side^2], i_both+dist, i_both)) = 1;\n SimilarityMatrix(sub2ind([side^2, side^2], i_both, i_both+dist)) = 1;\n \n end \n if(types(t) == 3)\n \n % for diagonal to top right, and bottom left don't use right most column\n i = 1:(side^2)-dist * side;\n i_to_rem = [];\n for s=1:dist\n i_to_rem = union(i_to_rem,i(mod(i-s, side) == 0));\n end\n i_both = setdiff(i, i_to_rem);\n % create the neighboring links for i\n SimilarityMatrix(sub2ind([side^2, side^2], i_both+dist*side-dist, i_both)) = 1;\n SimilarityMatrix(sub2ind([side^2, side^2], i_both, i_both+dist*side-dist)) = 1; \n end\n if(types(t) == 4)\n \n % for diagonal to top left, and bottom right don't use right most column\n i = 1:(side^2)-dist*side;\n i_to_rem = [];\n for s=1:dist\n i_to_rem = union(i_to_rem, i(mod(i+s-1, side) == 0));\n end\n i_both = setdiff(i, i_to_rem);\n % create the neighboring links for i\n SimilarityMatrix(sub2ind([side^2, side^2], i_both+dist*side+dist, i_both)) = 1;\n SimilarityMatrix(sub2ind([side^2, side^2], i_both, i_both+dist*side+ dist)) = 1; \n \n end\n \n end \n assert(isequal(SimilarityMatrix, SimilarityMatrix'));\nend", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/model_training/CCNF/CCNF/lib/similarity_neighbor_grid_further.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.748992467391635}} {"text": "function [node,face,elem]=meshunitsphere(tsize,maxvol)\n%\n% [node,face,elem]=meshunitsphere(tsize,maxvol)\n%\n% create the surface and/or volumetric mesh of a unit sphere \n% centered at [0 0 0] and radius 1\n%\n% author: Qianqian Fang, \n%\n% input: \n% tsize: maximum size of the surface triangles (from 0 to 1)\n% maxvol: maximum volume of the tetrahedron; if one wants to return\n% elem without specifying maxvol, maxvol=tsize^3\n%\n% output:\n% node: node coordinates, 3 columns for x, y and z respectively\n% face: integer array with dimensions of NB x 3, each row represents\n% a surface mesh face element \n% elem: integer array with dimensions of NE x 4, each row represents\n% a tetrahedron. If ignored, this function only produces the surface\n%\n% example:\n% [node,face]=meshunitsphere(0.05);\n% [node,face,elem]=meshunitsphere(0.05,0.01);\n% plotmesh(node,elem,'x>0'); axis equal;\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n% \n\ndim=60;\nesize=tsize*dim;\nthresh=dim/2-1;\n[xi,yi,zi]=meshgrid(0:0.5:dim,0:0.5:dim,0:0.5:dim);\ndist=thresh-sqrt((xi-30).^2+(yi-30).^2+(zi-30).^2);\ndist(dist<0)=0;\nclear xi yi zi;\n\n% extract a level-set at v=thresh, being a sphere with R=thresh\n% the maximum element size of the surface triangles is tsize*dim\n\n[node,face]=vol2restrictedtri(dist,1,[dim dim dim],dim*dim*dim,30,esize,esize,40000);\nnode=(node-0.5)*0.5;\n\n[node,face]=removeisolatednode(node,face);\n\nnode=(node-30)/28;\nr0=sqrt(sum((node.*node)'));\nnode=node.*repmat(1./r0(:),1,3);\n\nif(nargout==3)\n if(nargin==1)\n maxvol=tsize*tsize*tsize;\n end\n [node,elem,face]=surf2mesh(node,face,[-1 -1 -1]*1.1,[1 1 1]*1.1,1,maxvol,[],[]);\n elem=elem(:,1:4);\nend\n\nface=face(:,1:3);\n", "meta": {"author": "fangq", "repo": "iso2mesh", "sha": "556f4c321467a3ee042d4c559b4edc11e01dc574", "save_path": "github-repos/MATLAB/fangq-iso2mesh", "path": "github-repos/MATLAB/fangq-iso2mesh/iso2mesh-556f4c321467a3ee042d4c559b4edc11e01dc574/meshunitsphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7489924578858338}} {"text": "function prime_plot ( n_max )\n\n%*****************************************************************************80\n%\n%% PRIME_PLOT makes a box plot of primes.\n%\n% Usage:\n%\n% prime_plot ( n_max )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N_MAX, the maximum number to be considered.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRIME_PLOT\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Display primes and composite numbers.\\n' );\n fprintf ( 1, ' If N is composite, Box (N,D) is blue if N is divisible by D.\\n' );\n fprintf ( 1, ' If N is prime, Column (N,:) is red.\\n' );\n%\n% First argument is N_MAX.\n%\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n n_max = input ( ' Enter N, the maximum number to check: ' );\n end\n\n clf\n%\n% Every box starts out WHITE.\n%\n for n = 1 : n_max\n\n for d = 1 : n_max\n\n x1 = n - 0.44;\n x2 = n + 0.44;\n y1 = d - 0.44;\n y2 = d + 0.44;\n\n patch ( [ x1, x2, x2, x1 ], [ y1, y1, y2, y2 ], 'w', 'EdgeColor', 'none' );\n\n end\n \n end\n%\n% By convention, 1 is NOT a prime!\n%\n n = 1;\n d = 1;\n\n x1 = n - 0.44;\n x2 = n + 0.44;\n y1 = d - 0.44;\n y2 = d + 0.44;\n patch ( [ x1, x2, x2, x1 ], [ y1, y1, y2, y2 ], 'b', 'EdgeColor', 'none' );\n\n for n = 2 : n_max\n\n prime = 1;\n\n d = 1;\n\n for d = 2 : min ( n_max, n - 1 )\n\n if ( mod ( n, d ) == 0 )\n x1 = n - 0.44;\n x2 = n + 0.44;\n y1 = d - 0.44;\n y2 = d + 0.44;\n patch ( [ x1, x2, x2, x1 ], [ y1, y1, y2, y2 ], 'b', 'EdgeColor', 'none' );\n prime = 0;\n end\n\n end\n\n d = n;\n\n if ( prime )\n x1 = n - 0.44;\n x2 = n + 0.44;\n y1 = 1 - 0.44;\n y2 = d + 0.44;\n patch ( [ x1, x2, x2, x1 ], [ y1, y1, y2, y2 ], 'r', 'EdgeColor', 'none' ); \n else\n x1 = n - 0.44;\n x2 = n + 0.44;\n y1 = d - 0.44;\n y2 = d + 0.44;\n patch ( [ x1, x2, x2, x1 ], [ y1, y1, y2, y2 ], 'b', 'EdgeColor', 'none' ); \n x1 = n - 0.44;\n x2 = n + 0.44;\n y1 = 1 - 0.44;\n y2 = 1 + 0.44;\n patch ( [ x1, x2, x2, x1 ], [ y1, y1, y2, y2 ], 'b', 'EdgeColor', 'none' ); \n end\n\n end\n\n xlabel ( '<---N--->' )\n ylabel ( '<--Divisors-->' )\n title ( 'Primes are red columns; blue squares are factors.' )\n\n axis ( [ 0.5, n + 0.5, 0.5, n + 0.5 ] );\n axis equal\n axis square\n axis tight\n\n filename = 'prime_plot.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Plot saved in file \"%s\".\\n', filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PRIME_PLOT\\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/prime_plot/prime_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8791467627598857, "lm_q1q2_score": 0.7489915478746542}} {"text": "function [f,str] = constructpolynomialmatrix2d(matrixsize,locs,degree)\n\n% function [f,str] = constructpolynomialmatrix2d(matrixsize,locs,degree)\n%\n% is a 2D matrix size like [100 50]\n% is a row or column vector of indices into that matrix size\n% is the maximum polynomial degree desired.\n% should be no greater than 10.\n% \n% return , a matrix of dimensions length() x N\n% with polynomial basis functions evaluated at in\n% the columns. the polynomial basis functions are evaluated\n% over the range [-1,1] which is presumed to correspond to\n% the beginning and ending element along each of the two dimensions.\n% (if a dimension has only one element, the values are all set to 1.)\n% also, return , the algebraic expression that corresponds to\n% the columns of . 'x' refers to the first matrix dimension; 'y'\n% refers to the second matrix dimension.\n%\n% note that there may be various gain factors on the basis functions\n% (e.g. don't assume that they are all unit-length).\n%\n% also, beware of numerical precision issues for high degrees...\n%\n% see also constructpolynomialmatrix3d.m.\n%\n% history:\n% - 2013/05/23 - hard code the basis expansion to ensure consistent results across platforms.\n% this changes previous behavior.\n%\n% example:\n% [f,str] = constructpolynomialmatrix2d([30 30],find(ones(30,30)),2);\n% str\n% f = reshape(f,30,30,[]);\n% figure; imagesc(makeimagestack(f));\n\n% prep\nx = sym('x');\ny = sym('y');\n\n% do the algebra\n%str = char(expand((x+y+1)^degree));\nswitch degree\ncase 0\n str = '1';\ncase 1\n str = 'x+y+1';\ncase 2\n str = 'x^2+2*x*y+2*x+y^2+2*y+1';\ncase 3\n str = 'x^3+3*x^2*y+3*x^2+3*x*y^2+6*x*y+3*x+y^3+3*y^2+3*y+1';\ncase 4\n str = '1+4*x+4*y+6*x^2+12*x*y+6*y^2+4*x^3*y+6*x^2*y^2+12*x^2*y+4*x*y^3+12*x*y^2+x^4+4*x^3+y^4+4*y^3';\ncase 5\n str = '1+5*x+5*y+10*x^2+20*x*y+10*y^2+20*x^3*y+30*x^2*y^2+30*x^2*y+20*x*y^3+30*x*y^2+5*x^4+10*x^3+5*y^4+10*y^3+y^5+5*x*y^4+10*x^2*y^3+10*x^3*y^2+5*x^4*y+x^5';\ncase 6\n str = '1+6*x+6*y+15*x^2+30*x*y+15*y^2+60*x^3*y+90*x^2*y^2+60*x^2*y+60*x*y^3+60*x*y^2+15*x^4+20*x^3+15*y^4+20*y^3+6*x*y^5+y^6+6*y^5+30*x*y^4+15*x^2*y^4+60*x^2*y^3+60*x^3*y^2+20*x^3*y^3+15*x^4*y^2+30*x^4*y+6*x^5+x^6+6*x^5*y';\ncase 7\n str = '1+7*x+7*y+21*x^2+42*x*y+21*y^2+140*x^3*y+210*x^2*y^2+105*x^2*y+140*x*y^3+105*x*y^2+35*x^4+35*x^3+35*y^4+35*y^3+7*x*y^6+42*x*y^5+7*y^6+21*y^5+y^7+105*x*y^4+105*x^2*y^4+210*x^2*y^3+21*x^2*y^5+210*x^3*y^2+35*x^3*y^4+140*x^3*y^3+105*x^4*y^2+105*x^4*y+21*x^5+7*x^6+x^7+35*x^4*y^3+42*x^5*y+21*x^5*y^2+7*x^6*y';\ncase 8\n str = '1+8*x+8*y+28*x^2+56*x*y+28*y^2+280*x^3*y+420*x^2*y^2+168*x^2*y+280*x*y^3+168*x*y^2+70*x^4+56*x^3+70*y^4+56*y^3+56*x*y^6+168*x*y^5+8*x*y^7+28*y^6+56*y^5+8*y^7+y^8+280*x*y^4+28*x^2*y^6+420*x^2*y^4+560*x^2*y^3+168*x^2*y^5+560*x^3*y^2+280*x^3*y^4+560*x^3*y^3+56*x^3*y^5+420*x^4*y^2+280*x^4*y+56*x^5+28*x^6+8*x^7+x^8+70*x^4*y^4+280*x^4*y^3+168*x^5*y+168*x^5*y^2+56*x^5*y^3+56*x^6*y+28*x^6*y^2+8*x^7*y';\ncase 9\n str = '1+9*x+9*y+36*x^2+72*x*y+36*y^2+504*x^3*y+756*x^2*y^2+252*x^2*y+504*x*y^3+252*x*y^2+126*x^4+84*x^3+126*y^4+84*y^3+252*x*y^6+504*x*y^5+72*x*y^7+84*y^6+126*y^5+36*y^7+9*y^8+630*x*y^4+252*x^2*y^6+1260*x^2*y^4+1260*x^2*y^3+756*x^2*y^5+1260*x^3*y^2+1260*x^3*y^4+1680*x^3*y^3+504*x^3*y^5+1260*x^4*y^2+630*x^4*y+126*x^5+84*x^6+36*x^7+9*x^8+630*x^4*y^4+1260*x^4*y^3+504*x^5*y+756*x^5*y^2+504*x^5*y^3+252*x^6*y+252*x^6*y^2+72*x^7*y+x^9+y^9+9*x^8*y+36*x^7*y^2+84*x^6*y^3+126*x^5*y^4+126*x^4*y^5+84*x^3*y^6+36*x^2*y^7+9*x*y^8';\ncase 10\n str = '1+10*x+10*y+45*x^2+90*x*y+45*y^2+840*x^3*y+1260*x^2*y^2+360*x^2*y+840*x*y^3+360*x*y^2+210*x^4+120*x^3+210*y^4+120*y^3+840*x*y^6+1260*x*y^5+360*x*y^7+210*y^6+252*y^5+120*y^7+45*y^8+1260*x*y^4+1260*x^2*y^6+3150*x^2*y^4+2520*x^2*y^3+2520*x^2*y^5+2520*x^3*y^2+4200*x^3*y^4+4200*x^3*y^3+2520*x^3*y^5+3150*x^4*y^2+1260*x^4*y+252*x^5+210*x^6+120*x^7+45*x^8+3150*x^4*y^4+4200*x^4*y^3+1260*x^5*y+2520*x^5*y^2+2520*x^5*y^3+840*x^6*y+1260*x^6*y^2+360*x^7*y+10*x^9+10*y^9+x^10+90*x^8*y+360*x^7*y^2+840*x^6*y^3+1260*x^5*y^4+1260*x^4*y^5+840*x^3*y^6+360*x^2*y^7+90*x*y^8+10*x^9*y+45*x^8*y^2+y^10+120*x^7*y^3+210*x^6*y^4+252*x^5*y^5+210*x^4*y^6+120*x^3*y^7+45*x^2*y^8+10*x*y^9';\notherwise\n die;\nend\n\n%REMOVE since hard-coded now\n%str = sort(strsplit(str,'+'));%% sort the stuff in between + signs to try to ensure consistent ordering!!!\nstr = strsplit(str,'+');\nstr = cat(1,str,repmat({'+'},[1 length(str)]));\nstr = cat(2,str{:});\nstr = str(1:end-1);\n\n% add a little padding so the 1 step below will work for degree 0\nstr = [' ' str ' '];\n\n% change * to .*\n old = pwd; % THIS IS A TOTAL HACK TO AVOID FUNCTION NAME CONFLICTS!\n cd(fullfile(matlabroot,'toolbox','matlab','funfun'));\nstr = vectorize(str);\n cd(old);\n\n% remove +\nstr(str=='+') = ' ';\n\n% change 1 to ones(size(x),1)\nstr0 = strrep(str,' 1 ',' ones(size(x)) '); assert(length(str0) ~= length(str));\nstr = str0;\n\n% add brackets\nstr = [ '[' str ']' ];\n\n% prep the linear coordinates\n[x,y] = ind2sub(matrixsize,locs(:));\nif matrixsize(1)~=1\n x = normalizerange(x,-1,1,1,matrixsize(1));\nend\nif matrixsize(2)~=1\n y = normalizerange(y,-1,1,1,matrixsize(2));\nend\n\n% do it\nf = eval(str);\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/knkutils/constructpolynomialmatrix2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7489878473195007}} {"text": "% Showing the effect of the POCS partial Fourier reconstruction.\n%\n% Mark a cell (code beginning with \"%%\") and\n% press + to evaluate the cell content only.\n\n\n%% simple example (2D, single coil, no phase errors)\n%\nN = 256;\niter = 30;\npf = 9/16; % a typical large partial fourier factor\np = single(phantom(N));\nkspRef = fftshift(fftshift( fft(fft( fftshift(fftshift( p, 1),2), [],1),[],2), 1),2);\nkspRef = kspRef + 3 * complex( randn(N), randn(N) ); % add noise\nkspPF = kspRef;\nkspPF(:,1:floor((1-pf)*N)) = 0;\n\nimReco = pocs( kspPF, iter, true );\n\nimRef = ifftshift(ifftshift( ifft(ifft( ifftshift(ifftshift( kspRef, 1),2), [],1),[],2), 1),2);\nimDirect = ifftshift(ifftshift( ifft(ifft( ifftshift(ifftshift( kspPF, 1),2), [],1),[],2), 1),2);\n\nfigure,\nimagesc(abs([imRef imReco imDirect]), [0 2*mean(abs(imRef(:)))])\naxis image\ntitle('reference (full dataset) | POCS reco | zero-padded reco')\ncolormap(gray(256))\n\n\n%% multicoil example with phase error\n%\nclear p kspRef kspPF imReco imRef imDirect\nN = 256;\niter = 30;\npf = 9/16;\n% Set up some pseudo coilmaps:\ncmap(1,:,:) = repmat( ( 3./(1:N) .^0.10) .* exp(1i*(1:N) *pi/(N/3)) , N, 1 );\ncmap(2,:,:) = repmat( ( 1./(1:N).'.^0.20) .* exp(1i*(1:N).'*pi/(N/4)) , 1, N );\ncmap(3,:,:) = repmat( fliplr(( 2./(1:N) .^0.04) .* exp(1i*(1:N) *pi/(N/8))), N, 1 );\ncmap(4,:,:) = repmat( flipud(( 2./(1:N).'.^0.15) .* exp(1i*(1:N).'*pi/(N/10))),1, N );\ncmap = single(cmap);\n\nNc = size(cmap,1);\np = reshape( single(phantom(N)), 1, N, N );\nsubs = { 1, 164:181, 187:193 };\np(subs{:}) = 0;\nsubs = { 1, 166:179, 189:191 };\np(subs{:}) = 1 * exp(1i * pi/2);\np = bsxfun( @times, cmap, p );\nkspRef = fftshift(fftshift( fft(fft( fftshift(fftshift( p, 2),3), [],2),[],3), 2),3);\nkspRef = kspRef + 10 * complex( randn(Nc,N,N), randn(Nc,N,N) ); % add noise\nkspPF = kspRef;\nkspPF(:,:,1:floor((1-pf)*N)) = 0;\n\nimReco = pocs( kspPF, iter, true );\n\nimReco = squeeze(sqrt(sum( abs(imReco).^2, 1)));\nimRef = ifftshift(ifftshift( ifft(ifft( ifftshift(ifftshift( kspRef, 2),3), [],2),[],3), 2),3);\nimRef = squeeze(sqrt(sum( abs(imRef).^2, 1)));\nimDirect = ifftshift(ifftshift( ifft(ifft( ifftshift(ifftshift( kspPF, 2),3), [],2),[],3), 2),3);\nimDirect = squeeze(sqrt(sum( abs(imDirect).^2, 1)));\n\nfigure,\nimagesc(abs([imRef imReco imDirect]),[0 2*mean(abs(imRef(:)))])\naxis image\ntitle('reference (full dataset) | POCS reco | zero-padded reco')\ncolormap(gray(256))\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/39350-mri-partial-fourier-reconstruction-with-pocs/pocs_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.748987839502344}} {"text": "function [ t, dtdr, dtds ] = shape_t10 ( r, s )\n\n%*****************************************************************************80\n%\n%% SHAPE_T10 evaluates shape functions for a 10 node reference 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 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real R, S, the reference coordinates of a point.\n%\n% Output, real T(10), the basis functions at the point.\n%\n% Output, real DTDR(10), the R basis derivatives at the point.\n%\n% Output, real DTDS(10), the S basis derivatives at the point.\n%\n a = 1.0 / 3.0;\n b = 2.0 / 3.0;\n c = 1.0;\n\n t(1) = 4.5 * ( a - r - s ) * ( b - r - s ) * ( c - r - s );\n t(2) = 13.5 * r * ( b - r - s ) * ( c - r - s );\n t(3) = - 13.5 * r * ( a - r ) * ( c - r - s );\n t(4) = 4.5 * r * ( a - r ) * ( b - r );\n t(5) = 13.5 * s * ( b - r - s ) * ( c - r - s );\n t(6) = 27.0 * r * s * ( c - r - s );\n t(7) = 13.5 * r * s * ( r - a );\n t(8) = 13.5 * s * ( s - a ) * ( c - r - s );\n t(9) = 13.5 * r * s * ( s - a );\n t(10) = 4.5 * s * ( a - s ) * ( b - s );\n\n dtdr(1) = 4.5 * ( ( a - s ) * ( 2.0 * r - c - b + 2.0 * s ) ...\n - ( s - b ) * ( s - c ) - 2.0 * ( 2.0 * s - b - c ) * r - 3.0 * r * r );\n dtdr(2) = 13.5 * ( ( s - b ) * ( s - c ) + 2.0 * ( 2.0 * s - b - c ) * r ...\n + 3.0 * r * r );\n dtdr(3) = - 13.5 * ( a * ( c - s ) + 2.0 * ( s - a - c ) * r + 3.0 * r * r );\n dtdr(4) = 4.5 * ( a * b - 2.0 * ( a + b ) * r + 3.0 * r * r );\n dtdr(5) = 13.5 * s * ( 2.0 * s - b - c + 2.0 * r );\n dtdr(6) = 27.0 * s * ( c - s - 2.0 * r );\n dtdr(7) = 13.5 * s * ( 2.0 * r - a );\n dtdr(8) = - 13.5 * s * ( s - a );\n dtdr(9) = 13.5 * s * ( s - a);\n dtdr(10) = 0.0;\n\n dtds(1) = 4.5 * ( ( a - r ) * ( 2.0 * s - c - b + 2.0 * r ) ...\n - ( r - b ) * ( r - c ) - 2.0 * ( 2.0 * r - b - c ) * s - 3.0 * s * s );\n dtds(2) = 13.5 * r * ( 2.0 * s + 2.0 * r - b - c );\n dtds(3) = 13.5 * r * ( a - r );\n dtds(4) = 0.0;\n dtds(5) = 13.5 * ( ( r - b ) * ( r - c ) + 2.0 * ( 2.0 * r - b - c ) * s ...\n + 3.0 * s * s );\n dtds(6) = 27.0 * r * ( c - r - 2.0 * s );\n dtds(7) = 13.5 * r * ( r - a );\n dtds(8) = - 13.5 * ( a * ( c - r ) + 2.0 * ( r - c - a ) * s + 3.0 * s * s );\n dtds(9) = 13.5 * r * ( 2.0 * s - a );\n dtds(10) = 4.5 * ( a * b - 2.0 * ( a + b ) * s + 3.0 * s * 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_pack/shape_t10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7489220653807912}} {"text": "function kpn_test ( )\n\n%*****************************************************************************80\n%\n%% KPN_TEST uses the KPN function for 1D quadrature over (-oo,+oo).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 May 2012\n%\n% Author:\n%\n% John Burkardt\n%\n d = 1;\n exact = hermite_integral ( d );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'KPN_TEST:\\n' );\n fprintf ( 1, ' Kronrod-Patterson-Hermite quadrature over (-oo,+oo):\\n' );\n fprintf ( 1, ' Exact integral is %g\\n', exact );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Level Nodes Estimate Error\\n' );\n fprintf ( 1, '\\n' );\n\n for l = 1 : 5\n\n n = kpn_order ( l );\n\n nh = floor ( ( n + 1 ) / 2 );\n\n [ xh, wh ] = kpn ( l );\n\n if ( mod ( n, 2 ) == 1 )\n x = [ -xh(nh:-1:2); xh ];\n w = [ wh(nh:-1:2); wh ];\n else\n x = [ -xh(nh:-1:1); xh ];\n w = [ wh(nh:-1:1); wh ];\n end\n\n fx = hermite_integrand ( d, n, x );\n q = w' * fx;\n e = sqrt ( ( q - exact ).^2 ) / exact;\n\n fprintf( ' %2d %6d %10.5g %10.5g\\n', l, n, q, e )\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_hw/kpn_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7488840336810786}} {"text": "%\n% [idx,netsim,dpsim,expref]=apclusterSparse(s,p)\n%\n% APCLUSTER uses affinity propagation (Frey and Dueck, Science,\n% 2007) to identify data clusters, using a set of real-valued\n% pair-wise data point similarities as input. Each cluster is\n% represented by a data point called a cluster center, and the\n% method searches for clusters so as to maximize a fitness\n% function called net similarity. The method is iterative and\n% stops after maxits iterations (default of 500 - see below for\n% how to change this value) or when the cluster centers stay\n% constant for convits iterations (default of 50). The command\n% apcluster(s,p,'plot') can be used to plot the net similarity\n% during operation of the algorithm.\n%\n% For N data points, there may be as many as N^2-N pair-wise\n% similarities (note that the similarity of data point i to k\n% need not be equal to the similarity of data point k to i).\n% These may be passed to APCLUSTER in an NxN matrix s, where\n% s(i,k) is the similarity of point i to point k. In fact, only\n% a smaller number of relevant similarities are needed for\n% APCLUSTER to work. If only M similarity values are known,\n% where M < N^2-N, they can be passed to APCLUSTER in an Mx3\n% matrix s, where each row of s contains a pair of data point\n% indices and a corresponding similarity value: s(j,3) is the\n% similarity of data point s(j,1) to data point s(j,2).\n%\n% APCLUSTER automatically determines the number of clusters,\n% based on the input p, which is an Nx1 matrix of real numbers\n% called preferences. p(i) indicates the preference that data\n% point i be chosen as a cluster center. A good choice is to \n% set all preference values to the median of the similarity\n% values. The number of identified clusters can be increased or\n% decreased by changing this value accordingly. If p is a\n% scalar, APCLUSTER assumes all preferences are equal to p.\n%\n% The fitness function (net similarity) used to search for\n% solutions equals the sum of the preferences of the the data\n% centers plus the sum of the similarities of the other data\n% points to their data centers.\n%\n% The identified cluster centers and the assignments of other\n% data points to these centers are returned in idx. idx(j) is\n% the index of the data point that is the cluster center for\n% data point j. If idx(j) equals j, then point j is itself a\n% cluster center. The sum of the similarities of the data\n% points to their cluster centers is returned in dpsim, the\n% sum of the preferences of the identified cluster centers is\n% returned in expref and the net similarity (sum of the data\n% point similarities and preferences) is returned in netsim.\n%\n% EXAMPLE\n%\n% N=100; x=rand(N,2); % Create N, 2-D data points\n% M=N*N-N; s=zeros(M,3); % Make ALL N^2-N similarities\n% j=1;\n% for i=1:N\n% for k=[1:i-1,i+1:N]\n% s(j,1)=i; s(j,2)=k; s(j,3)=-sum((x(i,:)-x(k,:)).^2);\n% j=j+1;\n% end;\n% end;\n% p=median(s(:,3)); % Set preference to median similarity\n% [idx,netsim,dpsim,expref]=apclusterSparse(s,p,'plot');\n% fprintf('Number of clusters: %d\\n',length(unique(idx)));\n% fprintf('Fitness (net similarity): %f\\n',netsim);\n% figure; % Make a figures showing the data and the clusters\n% for i=unique(idx)'\n% ii=find(idx==i); h=plot(x(ii,1),x(ii,2),'o'); hold on;\n% col=rand(1,3); set(h,'Color',col,'MarkerFaceColor',col);\n% xi1=x(i,1)*ones(size(ii)); xi2=x(i,2)*ones(size(ii)); \n% line([x(ii,1),xi1]',[x(ii,2),xi2]','Color',col);\n% end;\n% axis equal tight;\n%\n% PARAMETERS\n% \n% [idx,netsim,dpsim,expref]=apclusterSparse(s,p,'NAME',VALUE,...)\n% \n% The following parameters can be set by providing name-value\n% pairs, eg, apcluster(s,p,'maxits',1000):\n%\n% Parameter Value\n% 'maxits' Any positive integer. This specifies the\n% maximum number of iterations performed by\n% affinity propagation. Default: 1000.\n% 'convits' Any positive integer. APCLUSTER decides that\n% the algorithm has converged if the estimated\n% cluster centers stay fixed for convits\n% iterations. Increase this value to apply a\n% more stringent convergence test. Default: 100.\n% 'dampfact' A real number that is less than 1 and\n% greater than or equal to 0.5. This sets the\n% damping level of the message-passing method,\n% where values close to 1 correspond to heavy\n% damping which may be needed if oscillations\n% occur. Default: .9\n% 'plot' No value needed. This creates a figure that\n% plots the net similarity after each iteration\n% of the method. If the net similarity fails to\n% converge, consider increasing the values of\n% dampfact and maxits.\n% 'details' No value needed. This causes idx, netsim,\n% dpsim and expref to be stored after each\n% iteration.\n% 'nonoise' No value needed. Degenerate input similarities\n% (eg, where the similarity of i to k equals the\n% similarity of k to i) can prevent convergence.\n% To avoid this, APCLUSTER adds a small amount\n% of noise to the input similarities. This flag\n% turns off the addition of noise.\n%\n% Copyright (c) Brendan J. Frey and Delbert Dueck (2006). This\n% software may be freely used and distributed for\n% non-commercial purposes.\n\nfunction [idx,netsim,dpsim,expref]=apclusterSparse(s,p,varargin);\n\n% Handle arguments to function\nif nargin<2 error('Too few input arguments');\nelse\n maxits=1000; convits=100; lam=0.9; plt=0; details=0; nonoise=0;\n i=1;\n while i<=length(varargin)\n if strcmp(varargin{i},'plot')\n plt=1; i=i+1;\n elseif strcmp(varargin{i},'details')\n details=1; i=i+1;\n elseif strcmp(varargin{i},'nonoise')\n nonoise=1; i=i+1;\n elseif strcmp(varargin{i},'maxits')\n maxits=varargin{i+1};\n i=i+2;\n if maxits<=0 error('maxits must be a positive integer'); end;\n elseif strcmp(varargin{i},'convits')\n convits=varargin{i+1};\n i=i+2;\n if convits<=0 error('convits must be a positive integer'); end;\n elseif strcmp(varargin{i},'dampfact')\n lam=varargin{i+1};\n i=i+2;\n if (lam<0.5)||(lam>=1)\n error('dampfact must be >= 0.5 and < 1');\n end;\n else i=i+1;\n end;\n end;\nend;\nif lam>0.9\n fprintf('\\n*** Warning: Large damping factor in use. Turn on plotting\\n');\n fprintf(' to monitor the net similarity. The algorithm will\\n');\n fprintf(' change decisions slowly, so consider using a larger value\\n');\n fprintf(' of convits.\\n\\n');\nend;\n\n% Check that standard arguments are consistent in size\nif length(size(s))~=2 error('s should be a 2D matrix');\nelseif length(size(p))>2 error('p should be a vector or a scalar');\nelseif size(s,2)==3\n tmp=max(max(s(:,1)),max(s(:,2)));\n if length(p)==1 N=tmp; else N=length(p); end;\n if tmp>N\n error('data point index exceeds number of data points');\n elseif min(min(s(:,1)),min(s(:,2)))<=0\n error('data point indices must be >= 1');\n end;\nelseif size(s,1)==size(s,2)\n N=size(s,1);\n if (length(p)~=N)&&(length(p)~=1)\n error('p should be scalar or a vector of size N');\n end;\nelse error('s must have 3 columns or be square'); end;\n\n% Make vector of preferences\nif length(p)==1 p=p*ones(N,1); end;\n\n% Append self-similarities (preferences) to s-matrix\ntmps=[repmat([1:N]',[1,2]),p]; s=[s;tmps];\nM=size(s,1);\n\n% In case user did not remove degeneracies from the input similarities,\n% avoid degenerate solutions by adding a small amount of noise to the\n% input similarities\nif ~nonoise\n rns=randn('state'); randn('state',0);\n s(:,3)=s(:,3)+(eps*s(:,3)+realmin*100).*rand(M,1);\n randn('state',rns);\nend;\n\n% Construct indices of neighbors\nind1e=zeros(N,1);\nfor j=1:M k=s(j,1); ind1e(k)=ind1e(k)+1; end;\nind1e=cumsum(ind1e); ind1s=[1;ind1e(1:end-1)+1]; ind1=zeros(M,1); \nfor j=1:M k=s(j,1); ind1(ind1s(k))=j; ind1s(k)=ind1s(k)+1; end;\nind1s=[1;ind1e(1:end-1)+1];\nind2e=zeros(N,1);\nfor j=1:M k=s(j,2); ind2e(k)=ind2e(k)+1; end;\nind2e=cumsum(ind2e); ind2s=[1;ind2e(1:end-1)+1]; ind2=zeros(M,1); \nfor j=1:M k=s(j,2); ind2(ind2s(k))=j; ind2s(k)=ind2s(k)+1; end;\nind2s=[1;ind2e(1:end-1)+1];\n\n% Allocate space for messages, etc\nA=zeros(M,1); R=zeros(M,1); t=1;\nif plt netsim=zeros(1,maxits+1); end;\nif details\n idx=zeros(N,maxits+1);\n netsim=zeros(1,maxits+1); \n dpsim=zeros(1,maxits+1); \n expref=zeros(1,maxits+1); \nend;\n\n% Execute parallel affinity propagation updates\ne=zeros(N,convits); dn=0; i=0;\nwhile ~dn\n i=i+1; \n\n % Compute responsibilities\n for j=1:N\n ss=s(ind1(ind1s(j):ind1e(j)),3);\n as=A(ind1(ind1s(j):ind1e(j)))+ss;\n [Y,I]=max(as); as(I)=-realmax; [Y2,I2]=max(as);\n r=ss-Y; r(I)=ss(I)-Y2;\n R(ind1(ind1s(j):ind1e(j)))=(1-lam)*r+ ...\n lam*R(ind1(ind1s(j):ind1e(j)));\n end;\n\n % Compute availabilities\n for j=1:N\n rp=R(ind2(ind2s(j):ind2e(j)));\n rp(1:end-1)=max(rp(1:end-1),0);\n a=sum(rp)-rp;\n a(1:end-1)=min(a(1:end-1),0);\n A(ind2(ind2s(j):ind2e(j)))=(1-lam)*a+ ...\n lam*A(ind2(ind2s(j):ind2e(j)));\n end;\n\n % Check for convergence\n E=((A(M-N+1:M)+R(M-N+1:M))>0); e(:,mod(i-1,convits)+1)=E; K=sum(E);\n if i>=convits || i>=maxits\n se=sum(e,2);\n unconverged=(sum((se==convits)+(se==0))~=N);\n if (~unconverged&&(K>0))||(i==maxits) dn=1; end;\n end;\n\n % Handle plotting and storage of details, if requested\n if plt||details\n if K==0\n tmpnetsim=nan; tmpdpsim=nan; tmpexpref=nan; tmpidx=nan;\n else\n tmpidx=zeros(N,1); tmpdpsim=0;\n tmpidx(find(E))=find(E); tmpexpref=sum(p(find(E)));\n discon=0;\n for j=find(E==0)'\n ss=s(ind1(ind1s(j):ind1e(j)),3);\n ii=s(ind1(ind1s(j):ind1e(j)),2);\n ee=find(E(ii));\n if length(ee)==0 discon=1;\n else\n [smx imx]=max(ss(ee));\n tmpidx(j)=ii(ee(imx));\n tmpdpsim=tmpdpsim+smx;\n end;\n end;\n if discon\n tmpnetsim=nan; tmpdpsim=nan; tmpexpref=nan; tmpidx=nan;\n else tmpnetsim=tmpdpsim+tmpexpref;\n end;\n end;\n end;\n if details\n netsim(i)=tmpnetsim; dpsim(i)=tmpdpsim; expref(i)=tmpexpref;\n idx(:,i)=tmpidx;\n end;\n if plt\n netsim(i)=tmpnetsim;\n figure(234); \n tmp=1:i; tmpi=find(~isnan(netsim(1:i)));\n plot(tmp(tmpi),netsim(tmpi),'r-');\n xlabel('# Iterations');\n ylabel('Net similarity of quantized intermediate solution');\n drawnow;\n end;\nend;\n% Identify exemplars\nE=((A(M-N+1:M)+R(M-N+1:M))>0); K=sum(E);\nif K>0\n tmpidx=zeros(N,1); tmpidx(find(E))=find(E); % Identify clusters\n for j=find(E==0)'\n ss=s(ind1(ind1s(j):ind1e(j)),3);\n ii=s(ind1(ind1s(j):ind1e(j)),2);\n ee=find(E(ii));\n [smx imx]=max(ss(ee));\n tmpidx(j)=ii(ee(imx));\n end;\n EE=zeros(N,1);\n for j=find(E)'\n jj=find(tmpidx==j); mx=-Inf;\n ns=zeros(N,1); msk=zeros(N,1);\n for m=jj'\n mm=s(ind1(ind1s(m):ind1e(m)),2);\n msk(mm)=msk(mm)+1;\n ns(mm)=ns(mm)+s(ind1(ind1s(m):ind1e(m)),3);\n end;\n ii=jj(find(msk(jj)==length(jj)));\n [smx imx]=max(ns(ii));\n EE(ii(imx))=1;\n end;\n E=EE;\n tmpidx=zeros(N,1); tmpdpsim=0;\n tmpidx(find(E))=find(E); tmpexpref=sum(p(find(E)));\n for j=find(E==0)'\n ss=s(ind1(ind1s(j):ind1e(j)),3);\n ii=s(ind1(ind1s(j):ind1e(j)),2);\n ee=find(E(ii));\n [smx imx]=max(ss(ee));\n tmpidx(j)=ii(ee(imx));\n tmpdpsim=tmpdpsim+smx;\n end;\n tmpnetsim=tmpdpsim+tmpexpref;\nelse\n tmpidx=nan*ones(N,1); tmpnetsim=nan; tmpexpref=nan;\nend;\nif details\n netsim(i+1)=tmpnetsim; netsim=netsim(1:i+1);\n dpsim(i+1)=tmpnetsim-tmpexpref; dpsim=dpsim(1:i+1);\n expref(i+1)=tmpexpref; expref=expref(1:i+1);\n idx(:,i+1)=tmpidx; idx=idx(:,1:i+1);\nelse\n netsim=tmpnetsim; dpsim=tmpnetsim-tmpexpref;\n expref=tmpexpref; idx=tmpidx;\nend;\nif plt||details\n fprintf('\\nNumber of identified clusters: %d\\n',K);\n fprintf('Fitness (net similarity): %f\\n',tmpnetsim);\n fprintf(' Similarities of data points to exemplars: %f\\n',dpsim(end));\n fprintf(' Preferences of selected exemplars: %f\\n',tmpexpref);\n fprintf('Number of iterations: %d\\n\\n',i);\nend;\nif unconverged\n fprintf('\\n*** Warning: Algorithm did not converge. The similarities\\n');\n fprintf(' may contain degeneracies - add noise to the similarities\\n');\n fprintf(' to remove degeneracies. To monitor the net similarity,\\n');\n fprintf(' activate plotting. Also, consider increasing maxits and\\n');\n fprintf(' if necessary dampfact.\\n\\n');\nend;\n", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/algorithm/AP/apclusterSparse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7488840246487916}} {"text": "function [D] = wishart_kl (arg1,arg2,arg3,arg4)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% [D] = wishart_kl (B_q,B_p,alpha_q,alpha_p)\n%\n% computes the divergence \n% /\n% D(q||p) = | q(x)*log(q(x)/p(x)) dx\n% /\n% between two k-dimensional Wishart propability density for C given\n% scale matrix B and shape parameter alpha\n%\n% alpha\n% |B| alpha-(k+1)/2\n% p(x)= ------------- |C| exp (-tr(BC))\n% Gamma (alpha)\n% k\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin == 4\n B_q = arg1; B_p = arg2; alpha_q = arg3; alpha_p = arg4;\nelseif nargin == 2\n B_q = arg1.Gam_rate; alpha_q = arg1.Gam_shape;\n B_p = arg2.Gam_rate; alpha_p = arg2.Gam_shape;\nelse\n error('Incorrect number of input arguments');\nend\n\nif size(B_q)~=size(B_p)\n error('Distributions must have equal dimensions');\nend\n\nK=size(B_p,1);\n\ntry\n Lq = -logdet(B_q,'chol');\n Lp = -logdet(B_p,'chol'); \ncatch \n disp('One of the two covariance matrices (or both) is not positive definite')\n disp('Check for NaNs in the time series. Also, are there enough time points?')\n error('Error computing the inverse of the covariance matrix.')\nend\n\nlZq = log(2) * (alpha_q*K/2) - Lq * (-alpha_q/2) + K*(K-1)/4 * log(pi); \nlZp = log(2) * (alpha_p*K/2) - Lp * (-alpha_p/2) + K*(K-1)/4 * log(pi); \n\nLq = Lq + K * log(2);\nLp = Lp + K * log(2);\n\nfor k = 1:K\n lZq = lZq + gammaln(alpha_q/2+0.5-0.5*k);\n lZp = lZp + gammaln(alpha_p/2+0.5-0.5*k);\n Lq = Lq + psi(alpha_q/2+0.5-0.5*k);\n Lp = Lp + psi(alpha_p/2+0.5-0.5*k);\nend\n\nD = (alpha_q/2-0.5-0.5*K)*Lq - (alpha_p/2-0.5-0.5*K)*Lp ...\n - alpha_q * K / 2 + alpha_q * trace(B_p / B_q) / 2 + lZp - lZq;\n\nreturn;\n\n", "meta": {"author": "OHBA-analysis", "repo": "HMM-MAR", "sha": "bb0433b75482e473980791a2b30afe2012cf6578", "save_path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR", "path": "github-repos/MATLAB/OHBA-analysis-HMM-MAR/HMM-MAR-bb0433b75482e473980791a2b30afe2012cf6578/utils/math/wishart_kl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362486, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7487981958443408}} {"text": "% J. Shi and J. Malik,\n% \"Normalized Cuts and Image Segmentation\",\n% In Proc. IEEE Conf. Computer Vision and Pattern Recognition, \n% pages 731-737, 1997.\n\n% Asad Ali\n% GIK Institute of Engineering Sciences & Technology, Pakistan\n% Email: asad_82@yahoo.com\n\n% CONCEPT: Introduced the use of 2nd generalized eigenvector for clustering\nclear all;\nclose all;\n\n% generate the data\ndata = GenerateData(2);\nfigure,plot(data(:,1), data(:,2),'r+'),title('Original Data Points'); grid on;shg\n\naffinity = CalculateAffinity(data);\nfigure,imshow(affinity,[]), title('Affinity Matrix');\n\n% compute the degree matrix\nfor i=1:size(affinity,1)\n D(i,i) = sum(affinity(i,:));\nend\n\n% compute the unnormalized graph laplacian matrix\nL = D - affinity; \n\n[eigVectors,eigValues] = eig(L);\n\n% plot the eigen vector corresponding to the 2nd largest eigen value\nfigure,plot(eigVectors(:,2),'r*'),title('2nd Largest Eigenvector');\n\n% threshold the eigen vectors\n[xx1,yy1,val1] = find(eigVectors(:,2) > 0.15);\n[xx2,yy2,val2] = find(eigVectors(:,2) > 0 & eigVectors(:,2) < 0.15);\n[xx3,yy3,val3] = find(eigVectors(:,2) < 0);\n\nfigure,\nhold on;\nplot(data(xx1,1),data(xx1,2),'m*');\nplot(data(xx2,1),data(xx2,2),'b*');\nplot(data(xx3,1),data(xx3,2),'g*');\nhold off;\ntitle('Clustering Results using 2nd Generalized Eigen Vector');\ngrid on;shg\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/26354-spectral-clustering-algorithms/Spectral Clustering/Shi_Malik.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7487749284808328}} {"text": "function [a1, b1, c1, a2, b2, c2] = aaa(A, B, C)\n%AAA gives both solutions to the angle-angle-angle problem, in radians.\n%\n% AAA(A, B, C) will result in NaNs if the existence condition \n% |pi - |A|-|B|| <= |C| <= pi - ||A| - |B||\n% is not met. \n%\n% See also AAAD.\n\n% Rody P.S. Oldenhuis\n% Delft University of Technology\n% oldenhuis@gmail.com\n%\n% Created : 23/Feb/2009\n% Last edited: 30/Nov/2012\n \n % first solution \n a1 = acos2( (cos(A) + cos(B).*cos(C)) ./ (sin(B).*sin(C)), A );\n b1 = acos2( (cos(B) + cos(A).*cos(C)) ./ (sin(A).*sin(C)), B );\n c1 = acos2( (cos(C) + cos(A).*cos(B)) ./ (sin(A).*sin(B)), C );\n \n % second solution\n a2 = 2*pi - a1;\n b2 = 2*pi - b1;\n c2 = 2*pi - c1;\n\n % check constraints\n indices = ( ...\n abs(pi - abs(A)-abs(B)) > abs(C) | ...\n abs(C) > pi - abs(abs(A)-abs(B)) );\n a1(indices) = NaN; a2(indices) = NaN;\n b1(indices) = NaN; b2(indices) = NaN;\n c1(indices) = NaN; c2(indices) = NaN;\n \nend", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SphericalTrigToolbox/aaa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7486150768118395}} {"text": "function p = matrix_T_pdf(A, M, V, K, n)\n% MATRIX_T_PDF Evaluate the density of a matrix under a Matrix-T distribution\n% p = matrix_T_pdf(A, M, V, K, n)\n\n% See \"Bayesian Linear Regression\", T. Minka, MIT Tech Report, 2001\n\n[d m] = size(K);\nis = 1:d;\nc1 = prod(gamma((n+1-is)/2)) / prod(gamma((n-m+1-is)/2));\nc2 = det(K)^(d/2) / det(pi*V)^(m/2); %% pi or 2pi?\np = c1 * c2 * det((A-M)'*inv(V)*(A-M)*K + eye(m))^(-n/2);\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/murphy/KPMstats/matrix_T_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750387190131, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7486150726420167}} {"text": "function circle_segment_test11 ( )\n\n%*****************************************************************************80\n%\n%% CIRCLE_SEGMENT_TEST11 demonstrates CIRCLE_SEGMENT_ROTATION_FROM_CHORD.\n%\n% Discussion:\n%\n% We make a table of all pairs of angles that are multiples of pi/12.\n%\n% For each pair, we compute the rotation, that is, the angle of the\n% central radius of the circle segment. We print out the result in\n% terms of multiples of pi/12.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIRCLE_SEGMENT_TEST11:\\n' );\n fprintf ( 1, ' CIRCLE_SEGMENT_ROTATION_FROM_CHORD is given the endpoints\\n' );\n fprintf ( 1, ' of a chord, and is asked to determine the angle of the\\n' );\n fprintf ( 1, ' central radius vector.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' We make a table of all pairs of angles that are multiples\\n' );\n fprintf ( 1, ' of pi/12, determine the corresponding chord endpoints, and\\n' );\n fprintf ( 1, ' compute the rotation angle, also printed as a multiple of pi/12.\\n' );\n\n r = 2.0;\n c = [ 3.0; 5.0 ];\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0\\n' );\n fprintf ( 1, '\\n' );\n for i = 0 : 12\n rho1 = i * pi / 6;\n p1 = c + r * [ cos(rho1); sin(rho1) ];\n fprintf ( 1, ' %2d.0: ', i );\n for j = 0 : 12\n rho2 = j * pi / 6;\n p2 = c + r * [ cos(rho2); sin(rho2) ];\n alpha = circle_segment_rotation_from_chord ( r, c, p1, p2 );\n fprintf ( 1, ' %4.1f', round ( 10 * 6 * alpha / pi ) / 10 );\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/circle_segment/circle_segment_test11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7485274564899956}} {"text": "% P2.7\nclear; clc;\nn1 = 0:20;\nx1 = 0.9.^n1;\nsubplot(3,2,1); stem(n1,x1,'ko'); title('First given sequence x1(n)');\naxis([-20 20 0 1]);\n[x1f,n1f] = sigfold(x1,n1); % obtain x1(-n)\nn2 = -20:0;\nx2 = 0.8.^(-n2);\nsubplot(3,2,2); stem(n2,x2,'ko'); title('Second given sequence x2(n)');\naxis([-20 20 0 1]);\n[x2f,n2f] = sigfold(x2,n2); % obtain x2(-n)\n[r,nr] = conv_m(x1,n1,x1f,n1f); % auto-correlation\nsubplot(3,2,3); stem(nr,r,'ko'); title('Auto-Correlation x1(n)*x1(-n)');\n[r,nr] = conv_m(x2,n2,x2f,n2f); % auto-correlation\nsubplot(3,2,4); stem(nr,r,'ko'); title('Auto-Correlation x2(n)*x2(-n)');\n[r,nr] = conv_m(x1f,n1f,x2,n2); % cross-correlation\nsubplot(3,1,3); stem(nr,r,'ko'); title('Cross-Correlation');", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/16323-ingle-proakis-chapter-2-solutions/P207.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7485156775301236}} {"text": "function [w, dwdx, dwdxx] = Weight(type, para, di, dmI)\n% EVALUATE WEIGHT FUNCTION\n%\n% SYNTAX: [w, dwdr, dwdrr] = GaussWeight(type, para, di, dmi)\n%\n% INPUT PARAMETERS\n% type - Type of weight function\n% para - Weight function parameter\n% di - Distance\n% dmi - Support size\n% OUTPUT PARAMETERS\n% w - Value of weight function at r\n% dwdx - Value of first order derivative of weight function with respect to x at r\n% dwdxx- Value of Second order derivative of weight function with respect to x at r\n%\nr = abs(di) / dmI;\n\nif (di >= 0.0)\n drdx = 1.0/dmI;\nelse\n drdx = -1.0/dmI;\nend\n\n% EVALUATE WEIGHT FUNCTION AND ITS FIRST AND SECOND ORDER OF DERIVATIVES WITH RESPECT r AT r\nif (type == 'GAUSS')\n [w,dwdr,dwdrr] = Gauss(para,r);\nelseif (type == 'CUBIC')\n [w,dwdr,dwdrr] = Cubic(r);\nelseif (type == 'SPLIN')\n [w,dwdr,dwdrr] = Spline(r);\nelseif (type == 'power')\n [w,dwdr,dwdrr] = power_function(para,r); \nelseif (type == 'CSRBF')\n [w,dwdr,dwdrr] = CSRBF2(r);\nelse\n error('Invalid type of weight function.');\nend\n\ndwdx = dwdr * drdx;\ndwdxx = dwdrr * drdx * drdx;\n\n\nfunction [w,dwdr,dwdrr] = Gauss(beta,r)\nif (r>1.0)\n w = 0.0;\n dwdr = 0.0;\n dwdrr = 0.0;\nelse\n b2 = beta*beta;\n r2 = r*r;\n eb2 = exp(-b2);\n\n w = (exp(-b2*r2) - eb2) / (1.0 - eb2);\n dwdr = -2*b2*r*exp(-b2*r2) / (1.0 - eb2);\n dwdrr = -2*b2*exp(-b2*r2)*(1-2*b2*r2) / (1.0 - eb2);\nend\n\nfunction [w,dwdr,dwdrr] = Cubic(r)\nif (r>1.0)\n w = 0.0;\n dwdr = 0.0;\n dwdrr = 0.0;\nelse\n w = 1-6*r^2+8*r^3-3*r^4;\n dwdr = -12*r+24*r^2-12*r^3;\n dwdrr = -12+48*r-36*r^2;\nend\n\nfunction [w,dwdr,dwdrr] = power_function(arfa,r)\nif (r>1.0)\n w = 0.0;\n dwdr = 0.0;\n dwdrr = 0.0;\nelse\n a2 = arfa*arfa;\n r2 = r*r;\n w = exp(-r2/a2);\n dwdr = (-2*r/a2)*exp(-r2/a2);\n dwdrr = (-2/a2+(-2*r/a2).^2)*exp(-r2/a2);\nend\n\nfunction [w,dwdr,dwdrr] = Spline(r)\nif (r>1.0)\n w = 0.0;\n dwdr = 0.0;\n dwdrr = 0.0;\nelseif (r<=0.5)\n w = 2/3 - 4*r^2 + 4*r^3;\n dwdr = -8*r + 12*r^2;\n dwdrr = -8 + 24*r;\nelse\n w = 4/3 - 4*r + 4*r^2 - 4*r^3/3;\n dwdr = -4 + 8*r -4*r^2;\n dwdrr = 8 - 8*r;\nend\n\nfunction [w,dwdr,dwdrr] = CSRBF2(r)\nif (r>1.0)\n w = 0.0;\n dwdr = 0.0;\n dwdrr = 0.0;\nelse\n\tw = (1-r)^6*(6+36*r+82*r^2+72*r^3+30*r^4+5*r^5);\n\tdwdr = 11*r*(r+2)*(5*r^3+15*r^2+18*r+4)*(r-1)^5;\n dwdrr = 22*(25*r^5+100*r^4+142*r^3+68*r^2-16*r-4)*(r-1)^4;\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/34514-moving-least-squaremls1d/Weight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7485156612439311}} {"text": "function [ dmap ] = dataDensity( x, y, width, height, limits, fudge )\n%DATADENSITY Get a data density image of data \n% x, y - two vectors of equal length giving scatterplot x, y co-ords\n% width, height - dimensions of the data density plot, in pixels\n% limits - [xmin xmax ymin ymax] - defaults to data max/min\n% fudge - the amount of smear, defaults to size of pixel diagonal\n%\n% By Malcolm McLean\n%\n if(nargin == 4)\n limits(1) = min(x);\n limits(2) = max(x);\n limits(3) = min(y);\n limits(4) = max(y);\n end\n deltax = (limits(2) - limits(1)) / width;\n deltay = (limits(4) - limits(3)) / height;\n if(nargin < 6)\n fudge = sqrt(deltax^2 + deltay^2);\n end\n dmap = zeros(height, width);\n for ii = 0: height - 1\n yi = limits(3) + ii * deltay + deltay/2;\n for jj = 0 : width - 1\n xi = limits(1) + jj * deltax + deltax/2;\n dd = 0;\n for kk = 1: length(x)\n dist2 = (x(kk) - xi)^2 + (y(kk) - yi)^2;\n dd = dd + 1 / ( dist2 + fudge); \n end\n dmap(ii+1,jj+1) = dd;\n end\n end\n \n\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31726-data-density-plot/DataDensity/dataDensity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7484798362211575}} {"text": "function variance = gamma_variance ( a, b, c )\n\n%*****************************************************************************80\n%\n%% GAMMA_VARIANCE returns the variance of the Gamma PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, C, the parameters of the PDF.\n% 0.0 < B,\n% 0.0 < C.\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n variance = b * b * 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/prob/gamma_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7484690745522438}} {"text": "function [r,normr,nre,s] = reorth(Q,r,normr,index,alpha,method)\n\n%REORTH Reorthogonalize a vector using iterated Gram-Schmidt\n%\n% [R_NEW,NORMR_NEW,NRE] = reorth(Q,R,NORMR,INDEX,ALPHA,METHOD)\n% reorthogonalizes R against the subset of columns of Q given by INDEX. \n% If INDEX==[] then R is reorthogonalized all columns of Q.\n% If the result R_NEW has a small norm, i.e. if norm(R_NEW) < ALPHA*NORMR,\n% then a second reorthogonalization is performed. If the norm of R_NEW\n% is once more decreased by more than a factor of ALPHA then R is \n% numerically in span(Q(:,INDEX)) and a zero-vector is returned for R_NEW.\n%\n% If method==0 then iterated modified Gram-Schmidt is used.\n% If method==1 then iterated classical Gram-Schmidt is used.\n%\n% The default value for ALPHA is 0.5. \n% NRE is the number of reorthogonalizations performed (1 or 2).\n\n% References: \n% Aake Bjorck, \"Numerical Methods for Least Squares Problems\",\n% SIAM, Philadelphia, 1996, pp. 68-69.\n%\n% J.~W. Daniel, W.~B. Gragg, L. Kaufman and G.~W. Stewart, \n% ``Reorthogonalization and Stable Algorithms Updating the\n% Gram-Schmidt QR Factorization'', Math. Comp., 30 (1976), no.\n% 136, pp. 772-795.\n%\n% B. N. Parlett, ``The Symmetric Eigenvalue Problem'', \n% Prentice-Hall, Englewood Cliffs, NJ, 1980. pp. 105-109\n\n% Rasmus Munk Larsen, DAIMI, 1998.\n\n% Check input arguments.\n% warning('PROPACK:NotUsingMex','Using slow matlab code for reorth.')\nif nargin<2\n error('Not enough input arguments.')\nend\n[n k1] = size(Q);\nif nargin<3 | isempty(normr)\n% normr = norm(r);\n normr = sqrt(r'*r);\nend\nif nargin<4 | isempty(index)\n k=k1;\n index = [1:k]';\n simple = 1;\nelse\n k = length(index);\n if k==k1 & index(:)==[1:k]'\n simple = 1;\n else\n simple = 0;\n end\nend\nif nargin<5 | isempty(alpha)\n alpha=0.5; % This choice garanties that \n % || Q^T*r_new - e_{k+1} ||_2 <= 2*eps*||r_new||_2,\n % cf. Kahans ``twice is enough'' statement proved in \n % Parletts book.\nend\nif nargin<6 | isempty(method)\n method = 0;\nend\nif k==0 | n==0\n return\nend\nif nargout>3\n s = zeros(k,1);\nend\n\n\nnormr_old = 0;\nnre = 0;\nwhile normr < alpha*normr_old | nre==0\n if method==1\n if simple\n t = Q'*r;\n r = r - Q*t;\n else\n t = Q(:,index)'*r;\n r = r - Q(:,index)*t;\n end\n else \n for i=index, \n t = Q(:,i)'*r; \n r = r - Q(:,i)*t;\n end\n end\n if nargout>3\n s = s + t;\n end\n normr_old = normr;\n% normr = norm(r);\n normr = sqrt(r'*r);\n nre = nre + 1;\n if nre > 4\n % r is in span(Q) to full accuracy => accept r = 0 as the new vector.\n r = zeros(n,1);\n normr = 0;\n return\n end\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/mc/IALM-MC/utils/reorth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7484209118662796}} {"text": "function [all_theta] = oneVsAll(X, y, num_labels, lambda)\n%ONEVSALL trains multiple logistic regression classifiers and returns all\n%the classifiers in a matrix all_theta, where the i-th row of all_theta \n%corresponds to the classifier for label i\n% [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels\n% logisitc regression classifiers and returns each of these classifiers\n% in a matrix all_theta, where the i-th row of all_theta corresponds \n% to the classifier for label i\n\n% Some useful variables\nm = size(X, 1);\nn = size(X, 2);\n\n% You need to return the following variables correctly \nall_theta = zeros(num_labels, n + 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should complete the following code to train num_labels\n% logistic regression classifiers with regularization\n% parameter lambda. \n%\n% Hint: theta(:) will return a column vector.\n%\n% Hint: You can use y == c to obtain a vector of 1's and 0's that tell use \n% whether the ground truth is true/false for this class.\n%\n% Note: For this assignment, we recommend using fmincg to optimize the cost\n% function. It is okay to use a for-loop (for c = 1:num_labels) to\n% loop over the different classes.\n%\n% fmincg works similarly to fminunc, but is more efficient when we\n% are dealing with large number of parameters.\n%\n% Example Code for fmincg:\n%\n% % Set Initial theta\n% initial_theta = zeros(n + 1, 1);\n% \n% % Set options for fminunc\n% options = optimset('GradObj', 'on', 'MaxIter', 50);\n% \n% % Run fmincg to obtain the optimal theta\n% % This function will return theta and the cost \n% [theta] = ...\n% fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...\n% initial_theta, options);\n%\n\nfor c = 1:num_labels\n options = optimset('GradObj', 'on', 'MaxIter', 50);\n\n all_theta(c, :) = fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...\n zeros(n + 1, 1), options);\n\n% =========================================================================\n\n\nend\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/ex3/oneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7482717665077964}} {"text": "function varargout = createTetrakaidecahedron()\n%CREATETETRAKAIDECAHEDRON Create a 3D mesh representing a tetrakaidecahedron.\n%\n% [V, E, F] = createTetrakaidecahedron;\n% Create a mesh structure representing a tetrakaidecahedron, composed of\n% both square and hexagonal faces. Tetrakaidecahedron can be used to tile\n% the 3D Euclidean space.\n%\n% V is a 24-by-3 array with vertex coordinates,\n% E is a 36-by-2 array containing indices of neighbour vertices,\n% F is a 14-by-1 cell array containing vertex indices array of each face.\n%\n% [V, F] = createTetrakaidecahedron;\n% Returns only the vertices and the face vertex indices.\n%\n% MESH = createTetrakaidecahedron;\n% Returns the data as a mesh structure, with fields 'vertices', 'edges'\n% and 'faces'.\n%\n% Example\n% [n, e, f] = createTetrakaidecahedron;\n% drawMesh(n, f);\n% \n% See also \n% meshes3d, drawMesh\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inra.fr\n% Created: 2005-02-10\n% Copyright 2005-2022 INRA - TPV URPOI - BIA IMASTE\n\nnodes = [...\n 1 0 2;0 1 2;-1 0 2;0 -1 2;...\n 2 0 1;0 2 1;-2 0 1;0 -2 1;...\n 2 1 0;1 2 0;-1 2 0;-2 1 0;-2 -1 0;-1 -2 0;1 -2 0;2 -1 0;...\n 2 0 -1;0 2 -1;-2 0 -1;0 -2 -1;...\n 1 0 -2;0 1 -2;-1 0 -2;0 -1 -2];\n\nedges = [...\n 1 2;1 4;1 5;2 3;2 6;3 4;3 7;4 8;...\n 5 9;5 16;6 10;6 11;7 12;7 13;8 14;8 15;...\n 9 10;9 17;10 18;11 12;11 18;12 19;13 14;13 19;14 20;15 16;15 20;16 17;....\n 17 21;18 22;19 23;20 24;21 22;21 24;22 23;23 24];\n \n \nfaces = {...\n [1 2 3 4], ...\n [1 4 8 15 16 5], [1 5 9 10 6 2], [2 6 11 12 7 3], [3 7 13 14 8 4],...\n [5 16 17 9], [6 10 18 11], [7 12 19 13], [8 14 20 15],...\n [9 17 21 22 18 10], [11 18 22 23 19 12], [13 19 23 24 20 14], [15 20 24 21 17 16], ...\n [21 24 23 22]};\nfaces = faces';\n \n% format output\nvarargout = formatMeshOutput(nargout, nodes, edges, faces);\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/meshes3d/createTetrakaidecahedron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7482703772256608}} {"text": "function xyz = plane_normal_qr_to_xyz ( pp, normal, pq, pr, n, qr )\n\n%*****************************************************************************80\n%\n%% PLANE_NORMAL_QR_TO_XYZ: QR_TO_XYZ coordinates for a normal form plane.\n%\n% Discussion:\n%\n% The normal form of a plane in 3D is:\n%\n% PP is a point on the plane,\n% NORMAL is a normal vector to the plane.\n%\n% Two vectors PQ and PR can be computed with the properties that\n% * NORMAL, PQ and PR are pairwise orthogonal;\n% * PQ and PR have unit length;\n% * every point P in the plane has a \"QR\" representation\n% as P = PP + q * PQ + r * PR.\n%\n% This function is given the QR coordinates of a set of points on the\n% plane, and returns the XYZ coordinates.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real PP(3), a point on the plane.\n%\n% Input, real NORMAL(3), a normal vector N to the plane. The\n% vector must not have zero length, but it is not necessary for N\n% to have unit length.\n%\n% Input, real PQ(3), a vector of unit length,\n% perpendicular to the vector N and the vector PR.\n%\n% Input, real PR(3), a vector of unit length,\n% perpendicular to the vector N and the vector PQ.\n%\n% Input, integer N, the number of points on the plane.\n%\n% Input, real QR(2,N), the QR coordinates of the points.\n%\n% Output, real XYZ(3,N), the XYZ coordinates of the points.\n%\n xyz = repmat ( pp, 1, n ) + [ pq'; pr' ]' * qr(1:2,1:n);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/plane_normal_qr_to_xyz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8376199613065411, "lm_q1q2_score": 0.7482537901340129}} {"text": "function [ a, seed ] = markov_random ( n, key )\n\n%*****************************************************************************80\n%\n%% MARKOV_RANDOM returns a random Markov matrix.\n%\n% Discussion:\n%\n% A Markov matrix, also called a \"stochastic\" matrix, is distinguished\n% by two properties:\n%\n% * All matrix entries are nonnegative;\n% * The sum of the entries in each row is 1.\n%\n% A \"transition matrix\" is the transpose of a Markov matrix, and\n% has column sums equal to 1.\n%\n% Example:\n%\n% N = 4\n%\n% 1/10 2/10 3/10 4/10\n% 1 0 0 0\n% 5/10 2/10 3/10 0\n% 2/10 2/10 2/10 4/10\n%\n% Properties:\n%\n% A is generally not symmetric: A' /= A.\n%\n% 0 <= A(I,J) <= 1.0 for every I and J.\n%\n% The sum of the entries in each row of A is 1.\n%\n% Because it has a constant row sum of 1,\n% A has an eigenvalue of 1, and\n% a (right) eigenvector of ( 1, 1, 1, ..., 1 ).\n%\n% All the eigenvalues of A have modulus no greater than 1.\n%\n% The eigenvalue 1 lies on the boundary of all the Gerschgorin rowsum disks.\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, integer N, the order of A.\n%\n% Input, integer KEY, a positive value that selects the data.\n%\n% Output, real A(N,N), the matrix.\n%\n seed = key;\n\n [ a, seed ] = r8mat_uniform_01 ( n, n, seed );\n\n for i = 1 : n\n\n row_sum = sum ( a(i,1:n) );\n\n a(i,1:n) = a(i,1:n) / row_sum;\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/markov_random.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7482537889967024}} {"text": "function geometry_test007 ( )\n\n%*****************************************************************************80\n%\n%% TEST007 tests BALL_UNIT_SAMPLE_3D.\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 dim_num = 3;\n n_sample = 1000;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST007\\n' );\n fprintf ( 1, ' For the unit ball in 3 dimensions:\\n' );\n fprintf ( 1, ' BALL_UNIT_SAMPLE_3D samples;\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A few sample values:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 5\n [ x, seed ] = ball_unit_sample_3d ( seed );\n fprintf ( 1, ' %10f %10f %10f\\n', x(1:dim_num) );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of sample points = %d\\n', n_sample );\n\n average(1:dim_num) = 0.0;\n\n for i = 1 : n_sample\n [ x, seed ] = ball_unit_sample_3d ( seed );\n average(1:dim_num) = average(1:dim_num) + x(1:dim_num);\n end\n\n average(1:dim_num) = average(1:dim_num) / n_sample;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Now average the points, which should get a value\\n' );\n fprintf ( 1, ' close to zero, and closer as N_SAMPLE increases.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Average: %10f %10f %10f\\n', average(1:dim_num) );\n\n average_r = 0.0;\n\n for i = 1 : n_sample\n [ x, seed ] = ball_unit_sample_3d ( seed );\n r = sqrt ( sum ( x(1:dim_num).^2 ) );\n average_r = average_r + r;\n end\n\n average_r = average_r / n_sample;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Now average the distance of the points from\\n' );\n fprintf ( 1, ' the center, which should be the \\n' );\n fprintf ( 1, ' 1/2**(1/dim_num) = %f\\n', 0.5^( 1.0 / dim_num ) );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Average: %f\\n', average_r );\n\n average_theta = 0.0;\n\n for i = 1 : n_sample\n [ x, seed ] = ball_unit_sample_3d ( seed );\n theta = r8_atan ( x(2), x(1) );\n average_theta = average_theta + theta;\n end\n\n average_theta = average_theta / n_sample;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Now average the angle THETA,\\n' );\n fprintf ( 1, ' which should be PI.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Average: %f\\n', average_theta );\n\n average_phi = 0.0;\n\n for i = 1 : n_sample\n [ x, seed ] = ball_unit_sample_3d ( seed );\n r = sqrt ( sum ( x(1:dim_num).^2 ) );\n phi = acos ( x(3) / r );\n average_phi = average_phi + phi;\n end\n\n average_phi = average_phi / n_sample;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Now average the angle PHI,\\n' );\n fprintf ( 1, ' which should be PI/2.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Average: %f\\n', average_phi );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/geometry_test007.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7481799388115706}} {"text": "function [node,elem] = cuboidmesh(cuboid,h)\n%% CUBEHEXMESH uniform mesh of cuboid\n%\n% [node,elem] = cuboidmesh([x0,x1,y0,y1,z0,z1],h) generates a uniform mesh of the\n% cuboid [x0,x1]*[y0,y1]*[z0,z1] with mesh size h.\n%\n% Example\n%\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details. \n\nx0 = cuboid(1); x1 = cuboid(2); \ny0 = cuboid(3); y1 = cuboid(4);\nz0 = cuboid(5); z1 = cuboid(6);\n\n[x,y,z] = meshgrid(x0:h:x1,y0:h:y1,z0:h:z1);\n\nnode = [x(:),y(:),z(:)];\n\n%% Generate elements\nnx = size(x,1) - 1; % number of cells in x-direction\nny = size(y,2) - 1; % number of cells in y-direction\nnz = size(z,2) - 1; % number of cells in z-direction\n\nelem = zeros(nx*ny*nz,8);\ncellidx = 1:nx*ny*nz;\n\n[i, j, k] = ind2sub([nx ny nz],cellidx); % index of cells in subscript form\n\ns =[ nx+1, ny+1, nz+1];\n\nelem(cellidx,1) = sub2ind3(s,i,j,k);\nelem(cellidx,2) = sub2ind3(s,i,j+1,k);\nelem(cellidx,3) = sub2ind3(s,i+1,j+1,k);\nelem(cellidx,4) = sub2ind3(s,i+1,j,k);\nelem(cellidx,5) = sub2ind3(s,i,j,k+1);\nelem(cellidx,6) = sub2ind3(s,i,j+1,k+1);\nelem(cellidx,7) = sub2ind3(s,i+1,j+1,k+1);\nelem(cellidx,8) = sub2ind3(s,i+1,j,k+1);\n\n function idx = sub2ind3(siz,i,j,k)\n nr = siz(1); nc = siz(2); nv = siz(3);\n if (max(j)>nc) || (max(i)>nr) || (max(k)>nv)\n error(message('MATLAB:mysub2ind:IndexOutOfRange'));\n end\n idx = (k-1)*nr*nc + (j-1)*nr+i;\n end\n\n\n\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/cuboidmesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7481799313703679}} {"text": "function f=ref_idwilt(c,g,a,M)\n%REF_DWILT Reference Inverse Discrete Wilson Transform\n% Usage: f=ref_idwilt(c,g,a,M);\n%\n\n% Setup transformation matrix.\n\nL=size(g,1);\nW=size(c,2);\nN=L/a;\n\nF=zeros(L,M*N);\n\n\n\n% Weight coefficients.\n\nl=(0:L-1).';\n\npif=0;\n\nif 1\n % This version uses sines and cosines to express the basis functions.\n\n for n=0:N/2-1 \n % Do the unmodulated coefficient.\n F(:,2*M*n+1)=circshift(g,2*a*n);\n \n % Setting this to -n*a should produce a time-invariant transform.\n timeinv=0; %-n*a;\n \n % m odd case\n for m=1:2:M-1\n F(:,m+2*M*n+1) = sqrt(2)*sin(pi*m/M*(l+timeinv)+pif).*circshift(g,2*n*a);\n F(:,m+2*M*n+M+1) = sqrt(2)*cos(pi*m/M*(l+timeinv)+pif).*circshift(g,(2*n+1)*a);\n end;\n \n % m even case\n for m=2:2:M-1\n F(:,m+2*M*n+1) = sqrt(2)*cos(pi*m/M*(l+timeinv)+pif).*circshift(g,2*n*a);\n F(:,m+2*M*n+M+1) = sqrt(2)*sin(pi*m/M*(l+timeinv)+pif).*circshift(g,(2*n+1)*a);\n end;\n \n % Most modulated coefficient, Nyquest frequency.\n if mod(M,2)==0\n F(:,M+2*M*n+1)=(-1).^(l+timeinv).*circshift(g,2*n*a);\n else\n F(:,M+2*M*n+1)=(-1).^(l+timeinv).*circshift(g,(2*n+1)*a);\n end;\n end;\n\nelse\n\n % This version uses a cosine, \n\n for n=0:N/2-1 \n % Do the unmodulated coefficient.\n F(:,2*M*n+1)=circshift(g,2*a*n);\n \n timeinv=-n*a;\n \n % m odd case\n for m=1:2:M-1\n F(:,m+2*M*n+1) = sqrt(2)*cos(pi*m/M*(l+timeinv-M/2)+pif).*circshift(g,2*n*a);\n F(:,m+2*M*n+M+1) = sqrt(2)*sin(pi*m/M*(l+timeinv-M/2-a)+pif).*circshift(g,(2*n+1)*a);\n end;\n \n % m even case\n for m=2:2:M-1\n F(:,m+2*M*n+1) = sqrt(2)*cos(pi*m/M*(l+timeinv-M/2)+pif).*circshift(g,2*n*a);\n F(:,m+2*M*n+M+1) = sqrt(2)*sin(pi*m/M*(l+timeinv-M/2-a)+pif).*circshift(g,(2*n+1)*a);\n end;\n \n % Most modulated coefficient, Nyquest frequency.\n if mod(M,2)==0\n F(:,M+2*M*n+1)=(-1).^(l+timeinv).*circshift(g,2*n*a);\n else\n F(:,M+2*M*n+1)=(-1).^(l+timeinv-a).*circshift(g,(2*n+1)*a);\n end;\n end;\n\n\n\nend;\n\nf=F*c;\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_idwilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629193, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7481745805761376}} {"text": "function [ L, D, C, Cinv ] = get_transform_matrices_2d( R, method )\n%UNTITLED4 Summary of this function goes here\n% Detailed explanation goes here\nif method == 1\n % LDL Without the permutation\n [L, D] = ldl(R);\n C = inv(L); \n Cinv = L;\n\nelseif method == 2\n % Eigen Decomp\n [V,D] = eig(R);\n C = V.';\n Cinv = V;\n \nelseif method == 3\n % Cholesky Decomp (Special case of LDL, D=I)\n L = chol(R); % NOTE: this is the UPPER triangular transform\n L = L.';\n C = inv(L);\n Cinv = L;\n D = eye(2,2);\n\nelseif method == 4 %%% ANALYTICAL\n rho = R(1,2);\n L = [1 0; rho 1];\n D = diag([1, 1 - rho^2]);\n C = [1 0; -rho 1]; \n % C = inv(L);\n Cinv = L;\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/CTMC/Diffusion_2D/get_transform_matrices_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7481745801365313}} {"text": "function R = RiemannND(x)\n% Riemann's non-differentiable function, R(x) for rational x = p/q\n\n[p,q] = rat(x);\nR = 0;\nfor k = 1:q-1\n R = R + sin(k^2*p*pi/q)/(sin(k*pi/2/q))^2;\nend\nR = R*pi/4/q/q;\nend", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Test Problems/Development/RiemannND.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7481745801365313}} {"text": " function y = jinc(x)\n%function y = jinc(x)\n% jinc(x) = J_1(pi x) / (2 x),\n% where J_1 is Bessel function of the first kind of order 1.\n% This is the 2D Fourier transform of a disk of diameter 1,\n% so its DC value is the area of that disk which is pi/4.\n% Equivalently it is the Hankel transform of rect = @(r) abs(r) < 1/2;\n% Jeff Fessler, University of Michigan\n\nx = abs(x); % kludge for bessel with negative arguments, perhaps not needed\ny = pi/4 + 0 * x; % jinc(0) = pi/4\nig = x ~= 0;\ny(ig) = besselj(1, pi * x(ig)) ./ (2 * x(ig));\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/jinc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.748115652185407}} {"text": "function Y = symNormalRnd(M, S, sz)\n\n% Generates independent symmetric matrices\n% according to a matrix-variate symmetric normal distribution.\n%\n% Y = symNormalRnd(M, S, sz)\n%\n%\n% Input:\n% M pxp mean symmetric matrix\n% S qxq covariance matrix\n% sz size of the array (e.g. number of samples)\n%\n% Output:\n% Y pxpx[sz] array of random symmetric matrices.\n%\n% Copyright: Armin Schwartzman, 2009\n%\n\n% HISTORY:\n% 2008.12.30 ASH (armins@hsph.harvard.edu) wrote it.\n\n% Check inputs\nif (size(M,1) ~= size(M,2)),\n error('Wrong input format');\nend\nif (size(S,1) ~= size(S,2)),\n error('Wrong input format');\nend\np = size(M,1);\nq = p*(p+1)/2;\nif (size(S,1) ~= q),\n error('Wrong input format');\nend\nif ~exist('sz'),\n sz = 1;\nend\n\n%-----------------------------------------------------------------\n% Generate multivariate normal\nN = prod(sz); % number of samples\nz = mvnrnd(zeros(1,q), S, N); % size Nxq\nz = reshape(z', [q sz]); % size qxN\nY = repmat(M, [1 1 sz]) + vecdinv(z);\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/mrDiffusion/statistics/symNormalRnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7481156481680552}} {"text": "function res = bhp(im,thresh,n)\n\n% inputs\n% im is the fourier transform of the image\n% thresh is the cutoff circle radius\n\n%outputs\n% res is the filtered image\n\n[r,c]=size(im);\nd0=thresh;\n\nd=zeros(r,c);\nh=zeros(r,c);\n\nfor i=1:r\n for j=1:c\n d(i,j)= sqrt( (i-(r/2))^2 + (j-(c/2))^2);\n end\nend\n\nfor i=1:r\n for j=1:c\n h(i,j)= 1 / (1+ (d0/d(i,j))^(2*n) ) ;\n end\nend\n\n\nfor i=1:r\n for j=1:c\n res(i,j)=(h(i,j))*im(i,j);\n\n end\nend\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/40579-frequency-domain-filtering-for-grayscale-images/freqfilters/bhp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.7481003193905759}} {"text": "function value = p27_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P27_F evaluates the integrand for problem 27.\n%\n% Dimension:\n%\n% N arbitrary.\n%\n% Region:\n%\n% 0 <= X(1:DIM_NUM) <= 1\n%\n% Integral Parameters:\n%\n% The integral depends on a parameter R and vector C(1:N).\n%\n% R defaults to 0.3.\n%\n% The reference suggests choosing C at random in [0,1]\n% and then multiplying by the normalizing factor (25/N).\n% C(1:N) defaults to 1/N.\n%\n% To get or set R, call P27_R8.\n% To get or set C, call P27_R8VEC.\n%\n% Integrand:\n%\n% cos ( 2 * pi * R + sum ( c(1:n) * x(1:n) ) )\n%\n% Exact Integral:\n%\n% 2^N * cos ( 2 * pi * R + 0.5 * sum ( c(1:n) ) )\n% * product ( sin ( 0.5 * c(1:n) ) / c(1:n) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Alan Genz,\n% [Integral #1]\n% A Package for Testing Multiple Integration Subroutines,\n% in Numerical Integration: Recent Developments, Software\n% and Applications,\n% edited by Patrick Keast and Graeme Fairweather,\n% D Reidel, 1987, pages 337-340,\n% LC: QA299.3.N38.\n%\n% Thomas Patterson,\n% [Integral #5],\n% On the Construction of a Practical Ermakov-Zolotukhin \n% Multiple Integrator,\n% in Numerical Integration: Recent Developments, Software\n% and Applications,\n% edited by Patrick Keast and Graeme Fairweather,\n% D. Reidel, 1987, pages 269-290,\n% LC: QA299.3.N38.\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 r = 0.0;\n r = p27_r8 ( 'G', 'R', r );\n\n c = [];\n c = p27_r8vec ( 'G', 'C', dim_num, c );\n\n value(1:point_num) = 0.0;\n\n for point = 1 : point_num\n\n arg = 2.0 * pi * r + c(1:dim_num,1)' * x(1:dim_num,point);\n value(point) = cos ( arg );\n\n end\n\n p27_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/p27_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7480799954253174}} {"text": "function y = sigmoidabTransform(x, transform, varargin)\n\n% SIGMOIDABTRANSFORM Constrains a parameter to be between A and B\n% by a scaled logistic sigmoid function.\n%\n% FORMAT\n%\n% DESC contains commands to constrain parameters to be between A\n% and B via the sigmoid function, y=A+(B-A)/(1+exp(-x)).\n%\n% ARG x : input argument.\n%\n% ARG transform : type of transform, 'atox' maps a value into\n% the transformed space (i.e. makes it between A and B). 'xtoa' \n% maps the parameter back from transformed space to the original\n% space. 'gradfact' gives the factor needed to correct gradients\n% with respect to the transformed parameter, that is, it gives\n% the gradient dx/da where x is the transformed parameter and a\n% is the untransformed parameter.\n%\n% ARG transformsettings (first element of varargin): vector [A B] \n% giving the minimum and maximum values A and B for the transformed \n% parameter. If not given, assume A=0 and B=1 as in the function \n% sigmoidTransform.\n%\n% OUTPUT y : return argument.\n% \n% SEEALSO : negLogLogitTransform, expTransform\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006, 2007\n%\n% COPYRIGHT : Jaakko Peltonen, 2011\n%\n% COPYRIGHT : Antti Honkela, 2012\n\n% OPTIMI\n\n\n% Get the transformation settings from the varargin structure\nif ~isempty(varargin),\n transformsettings=varargin{1};\nelse\n transformsettings=[];\nend;\n\n\nidentitymode=0;\nif identitymode==1,\n % DEBUG ONLY, turns transformation to identity!\n fprintf(1,'Using identity mode for transform %s of parameter value %f\\n',transform, x)\n switch transform\n case 'atox'\n y=x;\n case 'xtoa'\n y=x;\n case 'gradfact'\n y=0*x+1;\n end\nelse\n % normal mode, logistic sigmoid between A and B\n \n if isempty(transformsettings),\n warning(sprintf('sigmoidabTransform(%f,%s) called without transformation settings\\n',x,transform));\n A=0; B=1;\n else\n A=transformsettings(1);\n B=transformsettings(2);\n end;\n \n limVal = 36;\n minval_sigmoid=A+(B-A)*eps;\n maxval_sigmoid=A+(B-A)*(1-eps);\n \n y = zeros(size(x));\n switch transform\n case 'atox'\n %x\n %A\n %B\n %fprintf(1,'transforming x %f, A %f, B %f\\n',x,A,B);\n \n I1 = x < -limVal;\n y(I1) = A+(B-A)*eps;\n\n I2 = x > limVal;\n y(I2) = A+(B-A)*(1-eps);\n \n I3 = ~I1 & ~I2;\n y(I3) = A+(B-A)*sigmoid(x(I3));\n \n case 'xtoa'\n % [x A B]\n %fprintf(1,'inverse-transforming x %f, A %f, B %f\\n',x,A,B);\n I1 = x<=minval_sigmoid;\n y(I1) = -limVal;\n \n I2 = x>=maxval_sigmoid;\n y(I2) = limVal;\n\n I3 = ~I1 & ~I2;\n y(I3) = invSigmoid((x(I3)-A)/(B-A));\n \n \n case 'gradfact'\n %fprintf(1,'gradfact-transforming x %f, A %f, B %f\\n',x,A,B);\n %y = (B-A)*x.*(1-x);\n y = (x-A).*(B-x)/(B-A);\n %y=0*x+1; % DEBUG ONLY, turns factors off!\n end\nend;\n\n \n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/optimi/sigmoidabTransform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7480715761443406}} {"text": "function w = ymdf_to_weekday_julian2 ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_WEEKDAY_JULIAN2 returns the weekday of a Julian YMDF date.\n%\n% Discussion:\n%\n% This routine computes the day of the week from the date in\n% the Julian calendar, that is, the calendar in force before the\n% Gregorian calendar, in which every fourth year was a leap year.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Richards,\n% Algorithm A,\n% Mapping Time, The Calendar and Its History,\n% Oxford, 1999, pages 307-308.\n%\n% Parameters:\n%\n% Input, integer Y, M, D, real F, the YMDF date.\n%\n% Output, integer W, the day of the week of the date.\n% The days are numbered from Sunday through Saturday, 1 through 7.\n%\n m_prime = mod ( 9 + m, 12 );\n q = floor ( m_prime / 10 );\n z = floor ( ( 13 * m_prime + 2 ) / 5 );\n t = 28 * m_prime + z + d - 365 * q + 59;\n\n c = i4_wrap ( t, 1, 7 );\n\n y_prime = y - q;\n v = floor ( y / 4 ) - floor ( y_prime / 4 );\n p = y + floor ( y / 4 ) + 4 - v;\n n = 7 - mod ( p, 7 );\n\n w = i4_wrap ( c + 1 - n, 1, 7 );\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_weekday_julian2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7480715628823433}} {"text": "function value = c8_log ( z )\n\n%*****************************************************************************80\n%\n%% C8_LOG evaluates the logarithm of a C8.\n%\n% Discussion:\n%\n% A C8 is a complex value.\n%\n% Here we use the relationship:\n%\n% C8_LOG ( Z ) = LOG ( MAG ( Z ) ) + i * ARG ( Z )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 11 February 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, complex Z, the argument.\n%\n% Output, complex VALUE, the function value.\n%\n arg = c8_arg ( z );\n mag = c8_mag ( z );\n\n value = log ( mag ) + arg * i;\n \n return\nend\n", "meta": {"author": "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_log.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7480715513117682}} {"text": "function KeplerUniversalVsSTK()\n%% Constants\nmu = 398600.4418;\n\n%% Polar GEO Altitude Orbit Propagation Comparison\nload('PolarGEO.mat');\nr0 = repmat(PosVel(1,1:3)',[1 size(PosVel,1)]);\nv0 = repmat(PosVel(1,4:6)',[1 size(PosVel,1)]);\n[r,v] = keplerUniversal(r0,v0,0:60:(size(PosVel,1)-1)*60,mu);\nPlotStateVectorErrors(r,v,PosVel,0:60:(size(PosVel,1)-1)*60,'GEO Altitude, Polar Inclination Propagation');\n\n%% LEO Orbit Propagation Comparison\nload('InclinedLEO.mat');\nr0 = repmat(PosVel(1,1:3)',[1 size(PosVel,1)]);\nv0 = repmat(PosVel(1,4:6)',[1 size(PosVel,1)]);\n[r,v] = keplerUniversal(r0,v0,0:60:(size(PosVel,1)-1)*60,mu);\nPlotStateVectorErrors(r,v,PosVel,0:60:(size(PosVel,1)-1)*60,'LEO Inclined Propagation');\n\n%% Hyperbolic LEO Altitude Orbit Propagtion Comparison\nload('HyperbolicLEO.mat');\nr0 = repmat(PosVel(1,1:3)',[1 size(PosVel,1)]);\nv0 = repmat(PosVel(1,4:6)',[1 size(PosVel,1)]);\n[r,v] = keplerUniversal(r0,v0,0:60:(size(PosVel,1)-1)*60,mu);\nPlotStateVectorErrors(r,v,PosVel,0:60:(size(PosVel,1)-1)*60,'Hyperbolic Orbit Propagation');\n\n%% Parabolic LEO Altitude Orbit Propagation comparison\nload('ParabolicLEO.mat');\nr0 = repmat(PosVel(1,1:3)',[1 size(PosVel,1)]);\nv0 = repmat(PosVel(1,4:6)',[1 size(PosVel,1)]);\n[r,v] = keplerUniversal(r0,v0,0:60:(size(PosVel,1)-1)*60,mu);\nPlotStateVectorErrors(r,v,PosVel,0:60:(size(PosVel,1)-1)*60,'Parabolic Orbit Propagation');\n\nend\n\nfunction PlotStateVectorErrors(r,v,PosVel,t,titleText)\nMaxPositionError = abs(r-PosVel(:,1:3)');\nMaxVelocityError = abs(v-PosVel(:,4:6)');\nfigure('color',[1 1 1]);\nsubplot(4,1,1); plot(t./60,MaxPositionError); title(titleText); ylabel('Pos Err (km)');\nsubplot(4,1,2); plot(t./60,MaxVelocityError); ylabel('Vel Err (km/s)'); \nsubplot(4,1,3); plot(t./60,abs(sqrt(sum(r.^2,1)) - sqrt(sum(PosVel(:,1:3)'.^2,1)))); ylabel('Pos Mag Err (km)'); xlabel('Time (m)');\nsubplot(4,1,4); plot(t./60,abs(sqrt(sum(v.^2,1)) - sqrt(sum(PosVel(:,4:6)'.^2,1)))); ylabel('Vel Mag Err (km/s)'); xlabel('Time (m)');\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/35566-vectorized-analytic-two-body-propagator-kepler-universal-variables/KeplerUniversalVsSTK.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107843878721, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7480692538037461}} {"text": "function eg2OC_BVP\n%EG2OC_BVP Example 2 of optimal control tutorial.\n% This example is from D.E.Kirk's Optimal control theory: an introduction\n% example 6.2-2 on page 338-339\n% The problem is reformulated as a boundary value problem (BVP)\n% and solved with bvp4c solver\n\n% Initial guess for the solution\nsolinit = bvpinit(linspace(0,0.78,50), [0 0 0.5 0.5]);\noptions = bvpset('Stats','on','RelTol',1e-1);\nglobal R;\nR = 0.1;\nsol = bvp4c(@BVP_ode, @BVP_bc, solinit, options);\nt = sol.x;\ny = sol.y;\n\n% Calculate u(t) from x1,x2,p1,p2\nut = (y(3,:).*(y(1,:) + 1/4))/(2*0.1);\nn = length(t);\n% Calculate the cost\nJ = 0.78*(y(1,:)*y(1,:)' + y(2,:)*y(2,:)' + ut*ut'*0.1)/n;\n\nfigure(1);\nplot(t, y(1:2,:)','-');hold on;\nplot(t,ut', 'r:')\ntext(.2,0.08,'x_1(t)');\ntext(.3,-.1,'x_2(t)');\ntext(.2,.4, 'u(t)');\ns = strcat('Final cost is: J=',num2str(J));\ntext(.4,1,s);\nxlabel('time');\nylabel('states');\nhold off;\nprint -djpeg90 -r300 eg2_bvp.jpg\n\n%------------------------------------------------\n% ODE's for states and costates\nfunction dydt = BVP_ode(t,y)\nglobal R;\nt1 = y(1)+.25;\nt2 = y(2)+.5;\nt3 = exp(25*y(1)/(y(2)+2));\nt4 = 50/(y(1)+2)^2;\nu = y(3)*t1/(2*R);\n\ndydt = [-2*t1+t2*t3-t2*u\n 0.5-y(2)-t2*t3\n -2*y(1)+2*y(3)-y(3)*t2*t4*t3+y(3)*u+y(4)*t2*t4*t3\n -2*y(2)-y(3)*t3+y(4)*(1+t3)];\n\n% -----------------------------------------------\n% The boundary conditions:\n% x1(0) = 0.05, x2(0) = 0, tf = 0.78, p1(tf) = 0, p2(tf) = 0;\nfunction res = BVP_bc(ya,yb)\nres = [ ya(1) - 0.05\n ya(2) - 0\n yb(3) - 0\n yb(4) - 0 ];\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/25889-an-optimal-control-tutorial-for-beginners/eg2OC_BVP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7480443835853493}} {"text": "function f = tt_loglikelihood(X,M)\n%TT_LOGLIKELIHOOD Compute log-likelihood of data X with model M.\n%\n% F = TT_LOGLIKELIHOOD(X,M) computes the log-likelihood of model M given\n% data X, where M is a ktensor and X is a tensor or sptensor.\n% Specifically, F = - (sum_i m_i - x_i * log_i) where i is a multiindex\n% across all tensor dimensions.\n%\n% See also cp_apr, tensor, sptensor, ktensor.\n%\n%MATLAB Tensor Toolbox.\n%Copyright 2012, Sandia Corporation.\n\n% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.\n% http://www.sandia.gov/~tgkolda/TensorToolbox.\n% Copyright (2012) Sandia Corporation. Under the terms of Contract\n% DE-AC04-94AL85000, there is a non-exclusive license for use of this\n% work by or on behalf of the U.S. Government. Export of this data may\n% require a license from the United States Government.\n% The full license terms can be found in the file LICENSE.txt\n\nN = ndims(X);\n\nif ~isa(M, 'ktensor')\n error('M must be a ktensor');\nend\n\nM = normalize(M,1,1);\n\nif isa(X, 'sptensor')\n xsubs = X.subs;\n A = M.U{1}(xsubs(:,1),:);\n for n = 2:N\n A = A .* M.U{n}(xsubs(:,n),:); \n end\n f = sum(X.vals .* log(sum(A,2))) - sum(sum(M.U{1}));\nelse\n f = sum(sum(double(tenmat(X,1)) .* log(double(tenmat(M,1))))) - sum(sum(M.U{1}));\nend\n\n\n", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/libs/tensor_toolbox_2.5/tt_loglikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7480443738019719}} {"text": "function [ n_data, x, fx ] = elliptic_ka_values ( n_data )\n\n%*****************************************************************************80\n%\n%% ELLIPTIC_KA_VALUES returns values of the complete elliptic integral K(ALPHA).\n%\n% Discussion:\n%\n% This is one form of what is sometimes called the complete elliptic integral\n% of the first kind.\n%\n% The function is defined by the formula:\n%\n% K(ALPHA) = integral ( 0 <= T <= PI/2 ) \n% dT / sqrt ( 1 - sin ( ALPHA )^2 * sin ( T )^2 )\n%\n% In Mathematica, the function can be evaluated by:\n%\n% EllipticK[(Sin[alpha*Pi/180])^2]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function, measured \n% in degrees.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 18;\n\n fx_vec = [ ...\n 0.1570796326794897E+01, ...\n 0.1573792130924768E+01, ...\n 0.1582842804338351E+01, ...\n 0.1598142002112540E+01, ...\n 0.1620025899124204E+01, ...\n 0.1648995218478530E+01, ...\n 0.1685750354812596E+01, ...\n 0.1731245175657058E+01, ...\n 0.1786769134885021E+01, ...\n 0.1854074677301372E+01, ...\n 0.1935581096004722E+01, ...\n 0.2034715312185791E+01, ...\n 0.2156515647499643E+01, ...\n 0.2308786798167196E+01, ...\n 0.2504550079001634E+01, ...\n 0.2768063145368768E+01, ...\n 0.3153385251887839E+01, ...\n 0.3831741999784146E+01 ];\n\n x_vec = [ ...\n 0.0E+00, ...\n 5.0E+00, ... \n 10.0E+00, ...\n 15.0E+00, ...\n 20.0E+00, ...\n 25.0E+00, ...\n 30.0E+00, ...\n 35.0E+00, ...\n 40.0E+00, ...\n 45.0E+00, ...\n 50.0E+00, ...\n 55.0E+00, ...\n 60.0E+00, ...\n 65.0E+00, ...\n 70.0E+00, ...\n 75.0E+00, ...\n 80.0E+00, ...\n 85.0E+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 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/elliptic_ka_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7480443738019719}} {"text": "function y = entr( x )\n\n%ENTR Scalar entropy.\n% ENTR(X) returns an array of the same size as X with the unnormalized\n% entropy function applied to each element:\n% { -X.*LOG(X) if X > 0,\n% ENTR(X) = { 0 if X == 0,\n% { -Inf otherwise.\n% If X is a vector representing a discrete probability distribution, then\n% SUM(ENTR(X)) returns its entropy.\n%\n% Disciplined convex programming information:\n% ENTR(X) is concave and nonmonotonic in X. Thus when used in CVX\n% expressions, X must be real and affine. Its use will effectively \n% constrain X to be nonnegative: there is no need to add an\n% additional X >= 0 to your model in order to enforce this.\n\nerror(nargchk(1,1,nargin));\ncvx_expert_check( 'entr', x );\ny = -rel_entr( x, 1 );\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/entr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7479996827355838}} {"text": "function [x] = gels(a,b,param)\n%\n% GELS Solves an overdetermined or underdetermined linear problem.\n%\n% [X] = GELS(A,B) same as [X] = GELS(A,B,'default') \n%\n% [X] = GELS(A,B,PARAM) if A is m-by-n and m > n then GELS computes the solution of the\n% linear least squares problem\n% min || A * X - B ||_F ,\n% if A is m-by-n and m < n then GELS computes the solution of the minimum norm problem\n% min || X ||_F s.t. A*X = B\n% PARAM controls the algorithm used:\n%\t\n% 'dc'\n% performs SVD factorization of A using the divide and conquer\n% method then solve the undetermined or overdetermined problem.\n% calls LAPACK routine _GELSD\n%\n% 'svd'\n% performs SVD factorization of A using QR iterations then solve the\n% undetermined or overdetermined problem.\n% calls LAPACK routine _GELSS\n%\n% 'y'\n% performs QR factorization of A then solve the undetermined or\n% overdetermined problem.\n% calls LAPACK routine _GELSY\n%\n% 'default'\n% (default)\n% performs QR factorization of A without pivoting, then solve the\n% undetermined or overdetermined problem. The fact that there is no\n% pivoting in the QR factorization means that A(:,1:min(size(A))\n% needs to be full rank.\n% calls LAPACK routine _GELS\n%\n% When A is m-by-n with m > n then [X] = GELS(A,B) is the same as X=A\\B.\n%\n% When A is m-by-n with m < n then [X] = GELS(A,B,PARAM) is _not_ the same as\n% X=A\\B. [X] = GELS(A,B,PARAM) solves the problem\n% (*) min_X || X ||_F s.t. AX=B\n% while X=A\\B solves AX=B by first performing a QR factorization of A\n% [Q,R,E] = QR(A)\n% then X is obtained via\n% X = E(:,1:m)*(R(:,1:m)\\(Q'*b))] \n%\tThe \\ method is faster than GELS, X is such that AX=B but X is not (in the\n%\tgeneral case) the solution of (*).\n%\n% See also: \\, MLDIVIDE.\n%\n\tx=[];\n\t\n\n\tif (nargout~=1),\n\t\tdisp('Wrong number of output parameters');\n\t\treturn;\n\tend;\n\n\tif (nargin~=2 && nargin~=3),\n\t\tdisp('Wrong number of input parameters');\n\t\treturn;\n\tend;\n\t\n\t%Do all the boring checking\n\tif (~isnumeric(a)),\n\t\tdisp('The matrix is not composed of numeric values.');\n\t\treturn;\n\telseif (isinteger(a)),\n\t\ta=double(a);\n\tend;\n\n\tif ((nargin == 2)||(strcmp(param,'default'))),\n\t\ttrans = 'N';\n\t\t[x,info] = gels_2(trans,a,b);\n\telse\n\t\tif (strcmp(param,'dc')),\n\t\t\trcond = -1; % machine precision\n\t\t\t[x,rank,info] = gelsd(a,b,rcond);\n\t\telseif (strcmp(param,'svd')),\n\t\t\trcond = -1; % machine precision\n\t\t\t[x,rank,info] = gelss(a,b,rcond);\n\t\telseif (strcmp(param,'y')),\n\t\t\trcond = eps; % machine precision\n\t\t\t[x,rank,info] = gelsy(a,b,rcond);\n\t\telse\n\t\t\tdisp('Type of algorithm not correct. Please choose dc, svd, y, or default.');\n\t\t\treturn;\n\t\tend;\n\tend;\t\n\n\t%Do post-call boring checking\n\tif (info~=0),\n\t\tdisp('Resolution failed, no solution returned!');\n\t\tx=[];\n\t\treturn;\n\tend;\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/LapWrap/lib/m_files/gels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7479996590171049}} {"text": "function[I]=besselitilde(varargin)\n%BESSELITILDE I-type Bessel function after factoring off exponential growth.\n%\n% ITILDE=BESSELITILDE(NU,Z) returns the modified Bessel function of the\n% first kind of order NU at argument Z, after factoring off the \n% asymptotic behavior of EXP(Z).\n%\n% BESSELITILDE is useful for products of modified Bessel functions in\n% which the exponential behaviors cancel, but that cannot be evaluated\n% directly because of numerical overflow.\n%\n% BESSELITILDE(NU,Z,N) use a summation truncated at N terms. The default\n% behavior uses N=30 and is highly accurate.\n%\n% See 10.40.1 of https://dlmf.nist.gov/10.40.\n%\n% This is low-level code used by WINDTRANS using an algorithm described \n% in Lilly and Elipot (2021).\n%\n% See also BESSELKTILDE.\n%\n% 'besselitilde --t' runs a test.\n%\n% Usage: I=besselitilde(nu,z);\n% I=besselitilde(nu,z,nterms);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2019--2021 J.M. Lilly --- type 'help jlab_license' for details\n \nif strcmp(varargin{1}, '--t')\n besselitilde_test,return\nend\n\nnu=varargin{1};\nz=varargin{2};\nnterms=30;\nif nargin==3\n nterms=varargin{3};\nend\n \nsizez=size(z);\nz=z(:);\n%let's sum over the third dimensions\nzk=vrep(-z,nterms,2); %this makes the alternating sign\nzk(:,1)=1;\nzk=cumprod(zk,2);\n\nk=(0:nterms-1)';\nak=(4*nu.^2-(2*k-1).^2);\nak(1)=1;\nak=cumprod(ak,1);\nak=frac(ak,factorial(k).*8.^k);\nif any(~isfinite(ak))\n ak=ak(1:find(~isfinite(ak),1,'first')-1);\nend\nzk=zk(:,1:length(ak));\n\nI=frac(1,sqrt(2*z*pi)).*((1./zk)*ak);\nI=reshape(I,sizez);\n%nterms\n\n% %let's sum over the third dimensions\n% zk=vrep(-z,nterms,3); %this makes the alternating sign\n% zk(:,:,1)=1;\n% zk=cumprod(zk,3);\n% \n% k=(0:nterms-1)';\n% ak=(4*nu.^2-(2*k-1).^2);\n% ak(1)=1;\n% ak=cumprod(ak,1);\n% ak=frac(ak,factorial(k).*8.^k);\n% if any(~isfinite(ak))\n% ak=ak(1:find(~isfinite(ak),1,'first')-1);\n% end\n% zk=zk(:,:,1:length(ak));\n% \n% ak=vrep(permute(ak,[3 2 1]),size(z),[1 2]);\n% \n% I=frac(1,sqrt(2*z*pi)).*sum(frac(ak,zk),3);\n\n\nfunction[]=besselitilde_test\n\n\nfor s=[1 -1]\n z=sqrt(s*1i)*[23:0.01:100]';\n %z=[20:0.01:100]';\n [bi0,bi]=vzeros(length(z),2);\n for i=1:2\n bi0(:,i)=exp(-z).*besseli(i-1,z);\n bi(:,i)=besselitilde(i-1,z);\n end\n \n if s==1\n reporttest('BESSELITILDE for z with phase of pi/4',allall(abs((bi0-bi)./bi)<1e-14))\n else\n reporttest('BESSELITILDE for z with phase of -pi/4',allall(abs((bi0-bi)./bi)<1e-14))\n end\n \n\tbi=vzeros(length(z),2);\n for i=1:2\n bi(:,i)=besselitilde(i-1,z,2);\n end\n \n if s==1\n reporttest('BESSELITILDE 2-term for z with phase of pi/4, order 0 and 1',allall(abs((bi0(:,1:2)-bi)./bi)<1e-3))\n else\n reporttest('BESSELITILDE 2-term for z with phase of -pi/4, order 0 and 1',allall(abs((bi0(:,1:2)-bi)./bi)<1e-3))\n end\n \n bi0=sqrt(frac(1,2*pi*z)).*(1+frac(1,8*z));\n bi1=sqrt(frac(1,2*pi*z)).*(1-frac(3,8*z)); \n \n if s==1\n reporttest('BESSELITILDE 2-term vs. analytic for z with phase of pi/4',allall(abs(([bi0 bi1]-bi)./bi)<1e-15))\n else\n reporttest('BESSELITILDE 2-term vs. analytic for z with phase of -pi/4',allall(abs(([bi0 bi1]-bi)./bi)<1e-15))\n end\nend\n\n% figure,plot(abs(z),abs(bi-bi0)),ylog\n\n\n% nu=5;\n% z=[0:0.001:100]';\n% tic;bi(:,1)=besselitilde(nu,z);toc\n% tic;bi(:,2)=sqrt(2*z*pi).*exp(-z).*besseli(nu,z);toc\n% figure,plot(z,log10(abs((bi(:,1)-bi(:,2))./bi(:,2))))\n% %wow, really excellent\n% \n% \n% tic;bi0=sqrt(2*z*pi).*exp(-z).*besseli(nu,z);toc\n% for i=1:50\n% bi(:,i)=besselitilde(nu,z,i);\n% end\n% bi0=vrep(bi0,size(bi,2),2);\n% plot(z,log10(abs((bi-bi0)./bi0)))\n% \n% \n\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/besselitilde.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7479560125494988}} {"text": "function MS = createMesh3D(varargin)\n% MeshStructure = createMesh3D(Nx, Ny, Nz, Width, Height, Depth)\n% creates a uniform 3D mesh:\n% Nx is the number of cells in x (horizontal) direction\n% Ny is the number of cells in y (vertical) direction\n% Nz is the number of cells in z (perpendicular) direction\n% Lx is the domain length in x direction\n% Ly is the domain length in y direction\n% Lz is the domain length in z direction\n%\n% SYNOPSIS:\n% MeshStructure = createMesh3D(Nx, Ny, Nz, Lx, Ly, Lz)\n%\n% PARAMETERS:\n% Nx: number of cells in the x direction\n% Lx: domain length in x direction\n% Ny: number of cells in the y direction\n% Ly: domain length in y direction\n% Nz: number of cells in the z direction\n% Lz: domain length in z direction\n%\n% RETURNS:\n% MeshStructure.\n% dimensions=3 (3D problem)\n% numbering: shows the indexes of cellsn from left to right\n% and top to bottom and back to front\n% cellsize: x, y, and z elements of the cell size =[Lx/Nx,\n% Ly/Ny, Lz/Nz]\n% cellcenters.x: location of each cell in the x direction\n% cellcenters.y: location of each cell in the y direction\n% cellcenters.z: location of each cell in the z direction\n% facecenters.x: location of interface between cells in the\n% x direction\n% facecenters.y: location of interface between cells in the\n% y direction\n% facecenters.z: location of interface between cells in the\n% z direction\n% numberofcells: [Nx, Ny, Nz]\n%\n%\n% EXAMPLE:\n% Nx = 2;\n% Lx = 1.0;\n% Ny = 3;\n% Ly = 2.0;\n% Nz = 4;\n% Lz = 3.0;\n% m = createMesh3D(Nx, Ny, Nz, Lx, Ly, Lz);\n% [X, Y, Z] = ndgrid(m.cellcenters.x, m.cellcenters.y, m.cellcenters.z);\n% [Xf, Yf, Zf] = ndgrid(m.facecenters.x, m.facecenters.y, m.facecenters.z);\n% plot3(X(:), Y(:), Z(:), 'or')\n% hold on;\n% plot3(Xf(:), Yf(:), Zf(:), '+b')\n% legend('cell centers', 'cell corners');\n%\n% SEE ALSO:\n% createMesh1D, createMesh2D, createMeshCylindrical1D, ...\n% createMeshCylindrical2D, createCellVariable, createFaceVariable\n\n% Written by Ali A. Eftekhari\n% See the license file\n\nif nargin==6\n % uniform 1D mesh\n Nx=varargin{1};\n Ny=varargin{2};\n Nz=varargin{3};\n Width=varargin{4};\n Height=varargin{5};\n Depth=varargin{6};\n % cell size is dx\n dx = Width/Nx;\n dy = Height/Ny;\n dz = Depth/Nz;\n G=reshape(1:(Nx+2)*(Ny+2)*(Nz+2), Nx+2, Ny+2, Nz+2);\n CellSize.x= dx*ones(Nx+2,1);\n CellSize.y= dy*ones(Ny+2,1);\n CellSize.z= dz*ones(Nz+2,1);\n CellLocation.x= [1:Nx]'*dx-dx/2;\n CellLocation.y= [1:Ny]'*dy-dy/2;\n CellLocation.z= [1:Nz]'*dz-dz/2;\n FaceLocation.x= [0:Nx]'*dx;\n FaceLocation.y= [0:Ny]'*dy;\n FaceLocation.z= [0:Nz]'*dz;\nelseif nargin==3\n % nonuniform 1D mesh\n facelocationX=varargin{1};\n facelocationY=varargin{2};\n facelocationZ=varargin{3};\n facelocationX=facelocationX(:);\n facelocationY=facelocationY(:);\n facelocationZ=facelocationZ(:);\n Nx = length(facelocationX)-1;\n Ny = length(facelocationY)-1;\n Nz = length(facelocationZ)-1;\n G=reshape(1:(Nx+2)*(Ny+2)*(Nz+2), Nx+2, Ny+2, Nz+2);\n CellSize.x= [facelocationX(2)-facelocationX(1); ...\n facelocationX(2:end)-facelocationX(1:end-1); ...\n facelocationX(end)-facelocationX(end-1)];\n CellSize.y= [facelocationY(2)-facelocationY(1); ...\n facelocationY(2:end)-facelocationY(1:end-1); ...\n facelocationY(end)-facelocationY(end-1)];\n CellSize.z= [facelocationZ(2)-facelocationZ(1); ...\n facelocationZ(2:end)-facelocationZ(1:end-1); ...\n facelocationZ(end)-facelocationZ(end-1)];\n CellLocation.x= 0.5*(facelocationX(2:end)+facelocationX(1:end-1));\n CellLocation.y= 0.5*(facelocationY(2:end)+facelocationY(1:end-1));\n CellLocation.z= 0.5*(facelocationZ(2:end)+facelocationZ(1:end-1));\n FaceLocation.x= facelocationX;\n FaceLocation.y= facelocationY;\n FaceLocation.z= facelocationZ;\nend\nc=G([1,end], [1,end], [1, end]);\ne1=G([1, end], [1, end], 2:Nz+1);\ne2=G([1, end], 2:Ny+1, [1, end]);\ne3=G(2:Nx+1, [1, end], [1, end]);\nMS=MeshStructure(3, ...\n [Nx,Ny, Nz], ...\n CellSize, ...\n CellLocation, ...\n FaceLocation, ...\n c(:), ...\n [e1(:); e2(:); e3(:)]);\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/MeshGeneration/createMesh3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7478852711306865}} {"text": "function t = traceProduct(A, B)\n\n% TRACEPRODUCT Returns the trace of the product of two matrices.\n% FORMAT\n% DESC returns the trace of the product of two matrices, tr(A*B).\n% ARG A : the first matrix in the product.\n% ARG B : the second matrix in the product.\n% RETURN t : the trace of the product.\n%\n% SEEALSO : trace\n%\n% COPYRIGHT : Neil D. Lawrence, 2004\n\n% NDLUTIL\n\nt = sum(sum(A.*B'));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ndlutil/traceProduct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7478852707426238}} {"text": "function value = year_is_embolismic_hebrew ( y )\n\n%*****************************************************************************80\n%\n%% YEAR_IS_EMBOLISMIC_HEBREW returns TRUE if the Hebrew year was embolismic.\n%\n% Discussion:\n%\n% In a 19 year cycle, there are 7 embolismic years. During these years,\n% an extra month, \"Adar II\", (sometimes called \"Veadar\") is inserted after\n% the month of Adar. Nonembolismic years are called \"common\" years.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 September 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer Y, the year to be checked.\n%\n% Output, logical VALUE, TRUE if the year was embolismic.\n%\n if ( 12 <= i4_modp ( 7 * y + 13, 19 ) )\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/calpak/year_is_embolismic_hebrew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.747885266492189}} {"text": "function ellipse_t = fit_ellipse( x,y,axis_handle )\n%\n% fit_ellipse - finds the best fit to an ellipse for the given set of points.\n%\n% Format: ellipse_t = fit_ellipse( x,y,axis_handle )\n%\n% Input: x,y - a set of points in 2 column vectors. AT LEAST 5 points are needed !\n% axis_handle - optional. a handle to an axis, at which the estimated ellipse \n% will be drawn along with it's axes\n%\n% Output: ellipse_t - structure that defines the best fit to an ellipse\n% a - sub axis (radius) of the X axis of the non-tilt ellipse\n% b - sub axis (radius) of the Y axis of the non-tilt ellipse\n% phi - orientation in radians of the ellipse (tilt)\n% X0 - center at the X axis of the non-tilt ellipse\n% Y0 - center at the Y axis of the non-tilt ellipse\n% X0_in - center at the X axis of the tilted ellipse\n% Y0_in - center at the Y axis of the tilted ellipse\n% long_axis - size of the long axis of the ellipse\n% short_axis - size of the short axis of the ellipse\n% status - status of detection of an ellipse\n%\n% Note: if an ellipse was not detected (but a parabola or hyperbola), then\n% an empty structure is returned\n\n% =====================================================================================\n% Ellipse Fit using Least Squares criterion\n% =====================================================================================\n% We will try to fit the best ellipse to the given measurements. the mathematical\n% representation of use will be the CONIC Equation of the Ellipse which is:\n% \n% Ellipse = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f = 0\n% \n% The fit-estimation method of use is the Least Squares method (without any weights)\n% The estimator is extracted from the following equations:\n%\n% g(x,y;A) := a*x^2 + b*x*y + c*y^2 + d*x + e*y = f\n%\n% where:\n% A - is the vector of parameters to be estimated (a,b,c,d,e)\n% x,y - is a single measurement\n%\n% We will define the cost function to be:\n%\n% Cost(A) := (g_c(x_c,y_c;A)-f_c)'*(g_c(x_c,y_c;A)-f_c)\n% = (X*A+f_c)'*(X*A+f_c) \n% = A'*X'*X*A + 2*f_c'*X*A + N*f^2\n%\n% where:\n% g_c(x_c,y_c;A) - vector function of ALL the measurements\n% each element of g_c() is g(x,y;A)\n% X - a matrix of the form: [x_c.^2, x_c.*y_c, y_c.^2, x_c, y_c ]\n% f_c - is actually defined as ones(length(f),1)*f\n%\n% Derivation of the Cost function with respect to the vector of parameters \"A\" yields:\n%\n% A'*X'*X = -f_c'*X = -f*ones(1,length(f_c))*X = -f*sum(X)\n%\n% Which yields the estimator:\n%\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n% | A_least_squares = -f*sum(X)/(X'*X) ->(normalize by -f) = sum(X)/(X'*X) |\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n%\n% (We will normalize the variables by (-f) since \"f\" is unknown and can be accounted for later on)\n% \n% NOW, all that is left to do is to extract the parameters from the Conic Equation.\n% We will deal the vector A into the variables: (A,B,C,D,E) and assume F = -1;\n%\n% Recall the conic representation of an ellipse:\n% \n% A*x^2 + B*x*y + C*y^2 + D*x + E*y + F = 0\n% \n% We will check if the ellipse has a tilt (=orientation). The orientation is present\n% if the coefficient of the term \"x*y\" is not zero. If so, we first need to remove the\n% tilt of the ellipse.\n%\n% If the parameter \"B\" is not equal to zero, then we have an orientation (tilt) to the ellipse.\n% we will remove the tilt of the ellipse so as to remain with a conic representation of an \n% ellipse without a tilt, for which the math is more simple:\n%\n% Non tilt conic rep.: A`*x^2 + C`*y^2 + D`*x + E`*y + F` = 0\n%\n% We will remove the orientation using the following substitution:\n% \n% Replace x with cx+sy and y with -sx+cy such that the conic representation is:\n% \n% A(cx+sy)^2 + B(cx+sy)(-sx+cy) + C(-sx+cy)^2 + D(cx+sy) + E(-sx+cy) + F = 0\n%\n% where: c = cos(phi) , s = sin(phi)\n%\n% and simplify...\n%\n% x^2(A*c^2 - Bcs + Cs^2) + xy(2A*cs +(c^2-s^2)B -2Ccs) + ...\n% y^2(As^2 + Bcs + Cc^2) + x(Dc-Es) + y(Ds+Ec) + F = 0\n%\n% The orientation is easily found by the condition of (B_new=0) which results in:\n% \n% 2A*cs +(c^2-s^2)B -2Ccs = 0 ==> phi = 1/2 * atan( b/(c-a) )\n% \n% Now the constants c=cos(phi) and s=sin(phi) can be found, and from them\n% all the other constants A`,C`,D`,E` can be found.\n%\n% A` = A*c^2 - B*c*s + C*s^2 D` = D*c-E*s\n% B` = 2*A*c*s +(c^2-s^2)*B -2*C*c*s = 0 E` = D*s+E*c \n% C` = A*s^2 + B*c*s + C*c^2\n%\n% Next, we want the representation of the non-tilted ellipse to be as:\n%\n% Ellipse = ( (X-X0)/a )^2 + ( (Y-Y0)/b )^2 = 1\n%\n% where: (X0,Y0) is the center of the ellipse\n% a,b are the ellipse \"radiuses\" (or sub-axis)\n%\n% Using a square completion method we will define:\n% \n% F`` = -F` + (D`^2)/(4*A`) + (E`^2)/(4*C`)\n%\n% Such that: a`*(X-X0)^2 = A`(X^2 + X*D`/A` + (D`/(2*A`))^2 )\n% c`*(Y-Y0)^2 = C`(Y^2 + Y*E`/C` + (E`/(2*C`))^2 )\n%\n% which yields the transformations:\n% \n% X0 = -D`/(2*A`)\n% Y0 = -E`/(2*C`)\n% a = sqrt( abs( F``/A` ) )\n% b = sqrt( abs( F``/C` ) )\n%\n% And finally we can define the remaining parameters:\n%\n% long_axis = 2 * max( a,b )\n% short_axis = 2 * min( a,b )\n% Orientation = phi\n%\n%\n\n% initialize\norientation_tolerance = 1e-3;\n\n% empty warning stack\nwarning( '' );\n\n% prepare vectors, must be column vectors\nx = x(:);\ny = y(:);\n\n% remove bias of the ellipse - to make matrix inversion more accurate. (will be added later on).\nmean_x = mean(x);\nmean_y = mean(y);\nx = x-mean_x;\ny = y-mean_y;\n\n% the estimation for the conic equation of the ellipse\nX = [x.^2, x.*y, y.^2, x, y ];\na = sum(X)/(X'*X);\n\n% check for warnings\nif ~isempty( lastwarn )\n disp( 'stopped because of a warning regarding matrix inversion' );\n ellipse_t = [];\n return\nend\n\n% extract parameters from the conic equation\n[a,b,c,d,e] = deal( a(1),a(2),a(3),a(4),a(5) );\n\n% remove the orientation from the ellipse\nif ( min(abs(b/a),abs(b/c)) > orientation_tolerance )\n \n orientation_rad = 1/2 * atan( b/(c-a) );\n cos_phi = cos( orientation_rad );\n sin_phi = sin( orientation_rad );\n [a,b,c,d,e] = deal(...\n a*cos_phi^2 - b*cos_phi*sin_phi + c*sin_phi^2,...\n 0,...\n a*sin_phi^2 + b*cos_phi*sin_phi + c*cos_phi^2,...\n d*cos_phi - e*sin_phi,...\n d*sin_phi + e*cos_phi );\n [mean_x,mean_y] = deal( ...\n cos_phi*mean_x - sin_phi*mean_y,...\n sin_phi*mean_x + cos_phi*mean_y );\nelse\n orientation_rad = 0;\n cos_phi = cos( orientation_rad );\n sin_phi = sin( orientation_rad );\nend\n\n% check if conic equation represents an ellipse\ntest = a*c;\nswitch (1)\ncase (test>0), status = '';\ncase (test==0), status = 'Parabola found'; warning( 'fit_ellipse: Did not locate an ellipse' );\ncase (test<0), status = 'Hyperbola found'; warning( 'fit_ellipse: Did not locate an ellipse' );\nend\n\n% if we found an ellipse return it's data\nif (test>0)\n \n % make sure coefficients are positive as required\n if (a<0), [a,c,d,e] = deal( -a,-c,-d,-e ); end\n \n % final ellipse parameters\n X0 = mean_x - d/2/a;\n Y0 = mean_y - e/2/c;\n F = 1 + (d^2)/(4*a) + (e^2)/(4*c);\n [a,b] = deal( sqrt( F/a ),sqrt( F/c ) ); \n long_axis = 2*max(a,b);\n short_axis = 2*min(a,b);\n\n % rotate the axes backwards to find the center point of the original TILTED ellipse\n R = [ cos_phi sin_phi; -sin_phi cos_phi ];\n P_in = R * [X0;Y0];\n X0_in = P_in(1);\n Y0_in = P_in(2);\n \n % pack ellipse into a structure\n ellipse_t = struct( ...\n 'a',a,...\n 'b',b,...\n 'phi',orientation_rad,...\n 'X0',X0,...\n 'Y0',Y0,...\n 'X0_in',X0_in,...\n 'Y0_in',Y0_in,...\n 'long_axis',long_axis,...\n 'short_axis',short_axis,...\n 'status','' );\nelse\n % report an empty structure\n ellipse_t = struct( ...\n 'a',[],...\n 'b',[],...\n 'phi',[],...\n 'X0',[],...\n 'Y0',[],...\n 'X0_in',[],...\n 'Y0_in',[],...\n 'long_axis',[],...\n 'short_axis',[],...\n 'status',status );\nend\n\n% check if we need to plot an ellipse with it's axes.\nif (nargin>2) & ~isempty( axis_handle ) & (test>0)\n \n % rotation matrix to rotate the axes with respect to an angle phi\n R = [ cos_phi sin_phi; -sin_phi cos_phi ];\n \n % the axes\n ver_line = [ [X0 X0]; Y0+b*[-1 1] ];\n horz_line = [ X0+a*[-1 1]; [Y0 Y0] ];\n new_ver_line = R*ver_line;\n new_horz_line = R*horz_line;\n \n % the ellipse\n theta_r = linspace(0,2*pi);\n ellipse_x_r = X0 + a*cos( theta_r );\n ellipse_y_r = Y0 + b*sin( theta_r );\n rotated_ellipse = R * [ellipse_x_r;ellipse_y_r];\n \n % draw\n hold_state = get( axis_handle,'NextPlot' );\n set( axis_handle,'NextPlot','add' );\n plot( new_ver_line(1,:),new_ver_line(2,:),'r' );\n plot( new_horz_line(1,:),new_horz_line(2,:),'r' );\n plot( rotated_ellipse(1,:),rotated_ellipse(2,:),'r' );\n set( axis_handle,'NextPlot',hold_state );\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/3215-fitellipse/fit_ellipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012739960733, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7476845848640791}} {"text": "function [m_database V_PCA V_Fisher ProjectedImages_Fisher] = FisherfaceCore(T)\n% Use Principle Component Analysis (PCA) and Fisher Linear Discriminant (FLD) to determine the most \n% discriminating features between images of faces.\n%\n% Description: This function gets a 2D matrix, containing all training image vectors\n% and returns 4 outputs which are extracted from training database.\n% Suppose Ti is a training image, which has been reshaped into a 1D vector.\n% Also, P is the total number of MxN training images and C is the number of\n% classes. At first, centered Ti is mapped onto a (P-C) linear subspace by V_PCA\n% transfer matrix: Zi = V_PCA * (Ti - m_database).\n% Then, Zi is converted to Yi by projecting onto a (C-1) linear subspace, so that \n% images of the same class (or person) move closer together and images of difference \n% classes move further apart: Yi = V_Fisher' * Zi = V_Fisher' * V_PCA' * (Ti - m_database)\n%\n% Argument: T - (M*NxP) A 2D matrix, containing all 1D image vectors.\n% All of 1D column vectors have the same length of M*N \n% and 'T' will be a MNxP 2D matrix.\n% \n% Returns: m_database - (M*Nx1) Mean of the training database\n% V_PCA - (M*Nx(P-C)) Eigen vectors of the covariance matrix of the \n% training database\n% V_Fisher - ((P-C)x(C-1)) Largest (C-1) eigen vectors of matrix J = inv(Sw) * Sb\n% ProjectedImages_Fisher - ((C-1)xP) Training images, which are projected onto Fisher linear space\n%\n% See also: EIG\n\n% Original version by Amir Hossein Omidvarnia, October 2007\n% Email: aomidvar@ece.ut.ac.ir \n\n\nClass_number = ( size(T,2) )/2; % Number of classes (or persons)\nClass_population = 2; % Number of images in each class\nP = Class_population * Class_number; % Total number of training images\n\n%%%%%%%%%%%%%%%%%%%%%%%% calculating the mean image \nm_database = mean(T,2); \n\n%%%%%%%%%%%%%%%%%%%%%%%% Calculating the deviation of each image from mean image\nA = T - repmat(m_database,1,P);\n\n%%%%%%%%%%%%%%%%%%%%%%%% Snapshot method of Eigenface algorithm\nL = A'*A; % L is the surrogate of covariance matrix C=A*A'.\n[V D] = eig(L); % Diagonal elements of D are the eigenvalues for both L=A'*A and C=A*A'.\n\n%%%%%%%%%%%%%%%%%%%%%%%% Sorting and eliminating small eigenvalues\nL_eig_vec = [];\nfor i = 1 : P-Class_number \n L_eig_vec = [L_eig_vec V(:,i)];\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%% Calculating the eigenvectors of covariance matrix 'C'\nV_PCA = A * L_eig_vec; % A: centered image vectors\n\n%%%%%%%%%%%%%%%%%%%%%%%% Projecting centered image vectors onto eigenspace\n% Zi = V_PCA' * (Ti-m_database)\nProjectedImages_PCA = [];\nfor i = 1 : P\n temp = V_PCA'*A(:,i);\n ProjectedImages_PCA = [ProjectedImages_PCA temp]; \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%% Calculating the mean of each class in eigenspace\nm_PCA = mean(ProjectedImages_PCA,2); % Total mean in eigenspace\nm = zeros(P-Class_number,Class_number); \nSw = zeros(P-Class_number,P-Class_number); % Initialization os Within Scatter Matrix\nSb = zeros(P-Class_number,P-Class_number); % Initialization of Between Scatter Matrix\n\nfor i = 1 : Class_number\n m(:,i) = mean( ( ProjectedImages_PCA(:,((i-1)*Class_population+1):i*Class_population) ), 2 )'; \n \n S = zeros(P-Class_number,P-Class_number); \n for j = ( (i-1)*Class_population+1 ) : ( i*Class_population )\n S = S + (ProjectedImages_PCA(:,j)-m(:,i))*(ProjectedImages_PCA(:,j)-m(:,i))';\n end\n \n Sw = Sw + S; % Within Scatter Matrix\n Sb = Sb + (m(:,i)-m_PCA) * (m(:,i)-m_PCA)'; % Between Scatter Matrix\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%% Calculating Fisher discriminant basis's\n% We want to maximise the Between Scatter Matrix, while minimising the\n% Within Scatter Matrix. Thus, a cost function J is defined, so that this condition is satisfied.\n[J_eig_vec, J_eig_val] = eig(Sb,Sw); % Cost function J = inv(Sw) * Sb\nJ_eig_vec = fliplr(J_eig_vec);\n\n%%%%%%%%%%%%%%%%%%%%%%%% Eliminating zero eigens and sorting in descend order\nfor i = 1 : Class_number-1 \n V_Fisher(:,i) = J_eig_vec(:,i); % Largest (C-1) eigen vectors of matrix J\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%% Projecting images onto Fisher linear space\n% Yi = V_Fisher' * V_PCA' * (Ti - m_database) \nfor i = 1 : Class_number*Class_population\n ProjectedImages_Fisher(:,i) = V_Fisher' * ProjectedImages_PCA(:,i);\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/17066-fld-based-face-recognition-system/FLD_based Face Recognition System_v2/FisherfaceCore.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7476526170086568}} {"text": "function MISE=GaussKernelGaussMixMISE(n,H,w,mu,P)\n%%GAUSSKERNELGAUSSMIXMISE Given a Gaussian mixture probability density\n% function (PDF) that one is attempting to approximate using a\n% kernel density estimator with Gaussian kernels all having\n% square root covariance matrix H, determine the mean integrated\n% squared error (MISE) of the estimate. The MISE is the expected\n% value of int_{R}(\\hat{f}(x)-f(x))^2dx where \\hat{f}(x) is the\n% kernel estimator based on a set of random samples of the true\n% density f(x) (since it is based on random samples, the mean\n% part is the expected value being taken over all possible\n% samples). This function is useful for assessing different\n% kernel bandwidth estimators (estimators of H) when using\n% Gaussian mixture sample problems.\n%\n%INPUTS: n The number of samples that the kernel-density estimator will\n% use.\n% H The dXd bandwidth matrix used in the kernel density estimator\n% (as one would use in the function kernelApprox).\n% w A numCompX1 or 1XnumComp vector of the weights associated with\n% each of the numComp components of the Gaussian mixture.\n% mu The dXnumComp matrix of the mean of each component of the\n% Gaussian mixture.\n% P The dXdXnumComp set of covariance matrices of the components of\n% the Gaussian mixture.\n%\n%OUTPUTS: MISE The MISE of thekernel estimator with the given number of\n% samples and bandwidth matrix.\n%\n%This function implements the formula for the MISE in an arbitrary number\n%of dimensions in Section 4 of [1].\n%\n%REFERENCES:\n%[1] M. P. Wand and M. C. Jones, \"Comparison of smoothing parameterizations\n% in bivariate kernel density estimation,\" Journal of the American\n% Statistical Association, vol. 88, no. 422, pp. 520-528, Jun. 1993.\n%\n%December 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%The number of components in the \nk=size(mu,2);\nd=size(mu,1);\n\n%The definition of the bandwidth used in the paper is the square of what is\n%used here.\nH=H*H';\n\nOmega0=zeros(k,k);\nOmega1=zeros(k,k);\nOmega2=zeros(k,k);\n\nfor l=1:k\n for lp=l:k\n Sigma=P(:,:,l)+P(:,:,lp);\n \n Omega0(l,lp)=GaussianD.PDF(mu(:,l),mu(:,lp),Sigma);\n Omega1(l,lp)=GaussianD.PDF(mu(:,l),mu(:,lp),Sigma+H);\n Omega2(l,lp)=GaussianD.PDF(mu(:,l),mu(:,lp),Sigma+2*H);\n end\nend\n\nMISE=(1/n)*(4*pi)^(-d/2)*1/sqrt(det(H))+w(:)'*((1-1/n)*Omega2-2*Omega1+Omega0)*w(:);\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/Kernel_Estimation/GaussKernelGaussMixMISE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7476370570792501}} {"text": "function value = p14_exact ( dim_num )\n\n%*****************************************************************************80\n%\n%% P14_EXACT returns the exact integral for problem 14.\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 spatial dimension.\n%\n% Output, real VALUE, the exact value of the integral.\n%\n value = ( - 1.0 / 3.0 ) * ( 1.0 - ( -1.0 / 2.0 )^dim_num );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/p14_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7476370508028419}} {"text": "function [Q,err] = quadgr(fun,a,b,tol,trace,varargin)\n%QUADGR Gauss-Legendre quadrature with Richardson extrapolation.\n% [Q,ERR] = QUADGR(FUN,A,B,TOL) approximates the integral of a function\n% FUN from A to B with an absolute error tolerance TOL. FUN is a function\n% handle and must accept vector arguments. TOL is 1e-6 by default. Q is\n% the integral approximation and ERR is an estimate of the absolute error.\n%\n% QUADGR uses a 12-point Gauss-Legendre quadrature. The error estimate is\n% based on successive interval bisection. Richardson extrapolation\n% accelerates the convergence for some integrals, especially integrals\n% with endpoint singularities.\n%\n% QUADGR(FUN,A,B,TOL,TRACE) with non-zero TRACE displays the\n% extrapolation table.\n%\n% QUADGR can also be used as the quadrature in DBLQUAD and TRIPLEQUAD.\n%\n% Examples:\n% Q = quadgr(@(x) log(x),0,1)\n% [Q,err] = quadgr(@(x) exp(x),0,9999i*pi)\n% [Q,err] = quadgr(@(x) sqrt(4-x.^2),0,2,1e-12)\n% [Q,err] = quadgr(@(x) x.^-0.75,0,1)\n% [Q,err] = quadgr(@(x) 1./sqrt(1-x.^2),-1,1)\n% [Q,err] = quadgr(@(x) exp(-x.^2),-inf,inf,1e-9) % sqrt(pi)\n% [Q,err] = quadgr(@(x) cos(x).*exp(-x),0,inf,1e-9)\n%\n% See also QUAD, QUADGK, DBLQUAD, TRIPLEQUAD\n\n% Author: Jonas Lundgren 2009\n\n% 2009-03-17 First published\n% 2010-04-14 Adapted to DBLQUAD and TRIPLEQUAD (varargin added)\n\nif nargin < 3, help quadgr, return, end\nif nargin < 4 || isempty(tol), tol = 1.e-6; end;\nif nargin < 5 || isempty(trace), trace = 0; end;\n\n% Order limits (required if infinite limits)\nif a == b\n Q = b - a;\n err = b - a;\n return\nelseif a > b\n reverse = true;\n atmp = a;\n a = b;\n b = atmp;\nelse\n reverse = false;\nend\n\n% Infinite limits\nif isinf(a) || isinf(b)\n % Check real limits\n if ~isreal(a) || ~isreal(b) || isnan(a) || isnan(b)\n error('quadgr:inflim','Infinite intervals must be real.')\n end\n % Change of variable\n if isfinite(a) && isinf(b)\n % a to inf\n fun1 = @(t,varargin) fun(a + t./(1-t), varargin{:})./(1-t).^2;\n [Q,err] = quadgr(fun1,0,1,tol,trace,varargin{:});\n elseif isinf(a) && isfinite(b)\n % -inf to b\n fun2 = @(t,varargin) fun(b + t./(1+t), varargin{:})./(1+t).^2;\n [Q,err] = quadgr(fun2,-1,0,tol,trace,varargin{:});\n else % -inf to inf\n fun1 = @(t,varargin) fun(t./(1-t), varargin{:})./(1-t).^2;\n fun2 = @(t,varargin) fun(t./(1+t), varargin{:})./(1+t).^2;\n [Q1,err1] = quadgr(fun1,0,1,tol/2,trace,varargin{:});\n [Q2,err2] = quadgr(fun2,-1,0,tol/2,trace,varargin{:});\n Q = Q1 + Q2;\n err = err1 + err2;\n end\n % Reverse direction\n if reverse\n Q = -Q;\n end\n return \nend\n\n% Gauss-Legendre quadrature (12-point)\nxq = [0.12523340851146894; 0.36783149899818018; 0.58731795428661748; ...\n 0.76990267419430469; 0.9041172563704748; 0.98156063424671924];\nwq = [0.24914704581340288, 0.23349253653835478, 0.20316742672306584, ...\n 0.16007832854334636, 0.10693932599531818, 0.047175336386511842];\nxq = [xq; -xq];\nwq = [wq, wq];\nnq = length(xq);\n\n% Initiate vectors\nmaxit = 17; % Max number of iterations\nQ0 = zeros(maxit,1); \t% Quadrature\nQ1 = zeros(maxit,1); \t% First Richardson extrapolation\nQ2 = zeros(maxit,1); \t% Second Richardson extrapolation\n\n% One interval\nhh = (b - a)/2; % Half interval length\nx = (a + b)/2 + hh*xq; % Nodes\n% Quadrature\nQ0(1) = hh*wq*fun(x,varargin{:});\n\n% Successive bisection of intervals\nfor k = 2:maxit\n \n % Interval bisection\n hh = hh/2;\n x = [x + a; x + b]/2;\n % Quadrature\n Q0(k) = hh*wq*sum(reshape(fun(x,varargin{:}),nq,[]),2);\n \n % Richardson extrapolation\n if k >= 5\n Q1(k) = richardson(Q0,k);\n Q2(k) = richardson(Q1,k);\n elseif k >= 3\n Q1(k) = richardson(Q0,k);\n end\n \n % Estimate absolute error\n if k >= 6\n Qv = [Q0(k), Q1(k), Q2(k)];\n Qw = [Q0(k-1), Q1(k-1), Q2(k-1)];\n elseif k >= 4\n Qv = [Q0(k), Q1(k)];\n Qw = [Q0(k-1), Q1(k-1)];\n else\n Qv = Q0(k);\n Qw = Q0(k-1);\n end\n [err,j] = min(abs(Qv - Qw));\n Q = Qv(j);\n \n % Convergence\n if err < tol || ~isfinite(Q)\n break;\n end \n \nend\n\n% Convergence check\nif ~isfinite(Q)\n warning('quadgr:infnan','Integral approximation is Infinite or NaN.')\nelseif err > tol\n warning('quadgr:maxiter','Max number of iterations reached without convergence.')\nend\n\n% The error estimate should not be zero\nerr = err + 2*eps(Q);\n% Reverse direction\nif reverse\n\tQ = -Q;\nend\n\n% Display convergence\nif trace\n disp(' ')\n disp([Q0(1:k) Q1(1:k) Q2(1:k)])\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction R = richardson(Q,k)\n% Richardson extrapolation with parameter estimation\nif Q(k) ~= Q(k-1)\n c = real((Q(k-1)-Q(k-2))/(Q(k)-Q(k-1))) - 1;\nelse\n c = 1;\nend\n% The lower bound 0.07 admits the singularity x.^-0.9\nc = max(c,0.07);\nR = Q(k) + (Q(k) - Q(k-1))/c;\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/23325-quadgr/quadgr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7476103095711469}} {"text": "function [ lambda, v, it_num ] = power_method2 ( n, a, x_init, it_max, tol )\n\n%*****************************************************************************80\n%\n%% POWER_METHOD2 applies the power method for possibly complex eigenvalues.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 July 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Eric VanDeVelde,\n% Concurrent Scientific Programming,\n% Springer, 1994,\n% ISBN: 0-387-94195-9,\n% LC: QA76.58.V35.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real A(N,N), the matrix.\n%\n% Input, real X(N), the initial estimate for the eigenvector.\n%\n% Input, integer IT_MAX, the maximum number of iterations to take.\n% 1 <= IT_MAX.\n%\n% Input, real TOL, an error tolerance.\n%\n% Output, complex LAMBDA, the estimate for the eigenvalue.\n%\n% Output, complex V(N), the estimate for the eigenvector.\n%\n% Output, integer IT_NUM, the number of iterations taken.\n%\n it_num = 0;\n%\n% Compute data necessary to start the iteration.\n%\n x(1:n,1) = x_init(1:n);\n pi_xx = x(1:n)' * x(1:n);\n x(1:n) = x(1:n) / pi_xx;\n y(1:n,1) = a(1:n,1:n) * x(1:n);\n pi_xy = x(1:n)' * y(1:n);\n pi_yy = y(1:n)' * y(1:n);\n\n for it = 1 : it_max\n\n if ( pi_yy - pi_xy * pi_xy < tol * tol * pi_yy )\n lambda = pi_xy;\n v(1:n) = y(1:n) / sqrt ( pi_yy );\n return\n end\n\n z(1:n,1) = a(1:n,1:n) * y(1:n);\n\n pi_xz = x(1:n)' * z(1:n);\n pi_yz = y(1:n)' * z(1:n);\n pi_zz = z(1:n)' * z(1:n);\n\n alpha = - ( pi_yz - pi_xy * pi_xz ) / ( pi_yy - pi_xy * pi_xy );\n beta = ( pi_xy * pi_yz - pi_yy * pi_xz ) / ( pi_yy - pi_xy * pi_xy );\n gamma = pi_zz + alpha * alpha * pi_yy + beta * beta ...\n + 2.0 * ( alpha * pi_yz + beta * pi_xz + alpha * beta * pi_xy );\n\n if ( gamma < tol * tol * pi_zz & alpha * alpha < 4.0 * beta )\n\n lambda_real = - alpha / 2.0;\n lambda_imag = sqrt ( 4.0D+00 * beta - alpha * alpha ) / 2.0;\n lambda = lambda_real + lambda_imag * sqrt ( - 1.0 );\n\n v(1:n) = ( lambda * y(1:n) - z(1:n) ) ...\n / sqrt ( beta * pi_yy + alpha * pi_yz + pi_zz );\n\n return\n end\n\n x(1:n) = y(1:n) / sqrt ( pi_yy );\n y(1:n) = z(1:n) / sqrt ( pi_yy );\n\n pi_xy = pi_yz / pi_yy;\n pi_yy = pi_zz / pi_yy;\n\n it_num = it;\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POWER_METHOD2 - Fatal error!\\n' );\n fprintf ( 1, ' Convergence was not reached.\\n' );\n\n error ( 'POWER_METHOD2 - Fatal error!' );\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/power_method/power_method2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7476103011117319}} {"text": "% 埃特金方法加速迭代方法求解方程\nclear;\nformat long;\ntol = 1e-10;\nN = 100;\nx0 = 0.5;\nphi = @(x) exp(-x);\n%phi = @(x) (x+1)^(1/3);\n\nfor k = 1 : N\n x1 = phi(x0);\n x2 = phi(x1);\n x2 = x2 - (x2 - x1)^2 / (x2 - 2 * x1 + x0);\n if abs(x2 - x0) < tol\n fprintf('方程的正根: %10.8f\\n', x1);\n break;\n end\n x0 = x2;\nend\nif k == N\n fprintf('迭代方法失败\\n');\nend\nfprintf('迭代次数: %d\\n', k);", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第五章 方程求根的迭代法/example_4_4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.747610299135042}} {"text": "function h = huber_pot(t, d)\n%| function h = huber_pot(t, d)\n%| huber potential function\n\nif nargin < 1, ir_usage, end\nif nargin < 2, huber_pot_test, return, end\n\nh = t.^2 / 2;\nii = abs(t) > d;\nh(ii) = d * abs(t(ii)) - d.^2/2;\n\nfunction huber_pot_test\nt = linspace(-9,9,101);\ndelta = 4;\nplot(t, huber_pot(t, delta), '-', delta, huber_pot(delta, delta), 'o')\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/penalty/huber_pot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7475818787997909}} {"text": "function mean = extreme_values_mean ( a, b )\n\n%*****************************************************************************80\n%\n%% EXTREME_VALUES_MEAN returns the mean of the Extreme Values PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the parameters of the PDF.\n% 0.0 < B.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n mean = a + b * euler_constant ( );\n\n return\nend\n", "meta": {"author": "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/extreme_values_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7475688127048848}} {"text": "function tinv = t_inv (x, v, mu, sigma)\n% T_INV Inverse of Student's T cumulative distribution function (cdf).\n% X=TINV(P,V,MU,SIGMA) returns the inverse of Student's T cdf with V degrees\n% of freedom, at the values in P, with mean MU and standard deviation\n% SIGMA.\n%\n% The size of X is the common size of P and V. A scalar input\n% functions as a constant matrix of the same size as the other input.\n\n% Copyright (c) 1995-1997, 2005-2007 Kurt Hornik\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.\nif nargin < 4\n sigma = 1;\nend\nif nargin < 3\n mu = 0;\nend\nif (~isscalar(mu) || ~isscalar(sigma))\n if ~((size(x,1) == size(mu,1)) && (size(mu,1) == size(sigma,1)))\n error ('norm_inv: x, mu and sigma must be of common size or scalars');\n end\nend\n\n\nx = (x-mu)./sigma;\n\nif (nargin < 2)\n error('must give atleast 2 input arguments')\nend\n\nif (~isscalar(v))\n \n if (size(x,1) ~= size(v,1))\n error ('tinv: x and v must be of common size or scalar');\n end\nend\n\ntinv = zeros(size(x));\n\nk = find( (x<0) || (x > 1) || isnan(x) || (v<0));\nif (any(k))\n tinv(k) = NaN;\nend\n\nk = find ((x == 0) & (v > 0));\nif (any (k))\n tinv(k) = -Inf;\nend\n\nk = find ((x == 1) & (v > 0));\nif (any (k))\n tinv(k) = Inf;\nend\n\nk = find ((x > 0) & (x < 1) & (v > 0) & (v < 10000));\nif (any (k))\n if (isscalar (v))\n tinv(k) = (sign (x(k) - 1/2) ...\n .* sqrt (v .* (1 ./ beta_inv (2*min(x(k),1-x(k)), ...\n v/2,1/2)-1)));\n else\n tinv(k) = (sign(x(k)-1/2) ...\n .* sqrt (v(k).*(1./beta_inv(2*min(x(k), 1-x(k)), ...\n v(k)/2,1/2)-1)));\n end\nend\n\n% For large v, use the quantiles of the standard normal\nk = find ((x > 0) & (x < 1) & (v >= 10000));\nif (any (k))\n tinv(k) = sqrt (2)*erfinv(2*x(k)-1);\nend\n\nend\n\n% inv = sqrt (2) * erfinv (2 * x - 1);", "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/t_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7475688006486535}} {"text": "function [px, py, gx, gy] = position_3_link(z,P) \n%[px,py,gx,gy] = POSITION_3_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\nl1 = P.l(1); % Link 1 length\nl2 = P.l(2); % Link 2 length\nl3 = P.l(3); % Link 3 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\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\n\nth1 = z(1,:); \nth2 = z(2,:); \nth3 = z(3,:); \n\nnTime = length(th1); \npx = zeros(3,nTime);\npy = zeros(3,nTime);\ngx = zeros(3,nTime);\ngy = zeros(3,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\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_3_link.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.7473905915692314}} {"text": "function exact = p44_exact ( )\n\n%*****************************************************************************80\n%\n%% P44_EXACT returns the exact integral for problem 44.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real EXACT, the value of the integral.\n%\n alpha = p44_param_get ( );\n\n exact = ( 20.0 * sin ( 2.0^alpha ) ...\n - 2.0^alpha * cos ( 2.0^alpha ) ...\n + 2.0^alpha * exp ( -20.0 ) ) / ( 400.0 + 4.0^alpha );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_int/p44_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7473800616848161}} {"text": "function [g,A] = minusOne_v2(f)\n%minusOne Multiplies an input array by (-1)^x+y.\n% [G,A] = minusOne(F) multiplies F by (-1)^x+y to produce G. F can be\n% a 1-D or 2-D array. On the output, G = (-1)^(x+y).*F, and A is the\n% array of values (-1)^(x+y). Output G is floating point with values\n% in the same numerical range as F.\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\n% Convert input to floating point for multiplication later.\nf = im2double(f);\n\n% Image size.\n[M,N] = size(f);\n\nx = (0:M - 1)';\ny = 0:N - 1;\n\nA = (-1).^(x + y);\n\n% Multiply input by matrix.\ng = A.*f;\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/minusOne.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8438950966654774, "lm_q1q2_score": 0.7473800607551944}} {"text": "function [J grad] = nnCostFunction(nn_params, ...\n input_layer_size, ...\n hidden_layer_size, ...\n num_labels, ...\n X, y, lambda)\n%NNCOSTFUNCTION Implements the neural network cost function for a two layer\n%neural network which performs classification\n% [J grad] = NNCOSTFUNCTON(nn_params, hidden_layer_size, numn,/_labels, ...\n% X, y, lambda) computes the cost and gradient of the neural network. The\n% parameters for the neural network are \"unrolled\" into the vector\n% nn_params and need to be converted back into the weight matrices. \n% \n% The returned parameter grad should be a \"unrolled\" vector of the\n% partial derivatives of the neural network.\n%\n\n% Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices\n% for our 2 layer neural network\nTheta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), ...\n hidden_layer_size, (input_layer_size + 1));\n\nTheta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), ...\n num_labels, (hidden_layer_size + 1));\n\n% Setup some useful variables\nm = size(X, 1);\n \n% You need to return the following variables correctly \nJ = 0;\nTheta1_grad = zeros(size(Theta1));\nTheta2_grad = zeros(size(Theta2));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should complete the code by working through the\n% following parts.\n%\n% Part 1: Feedforward the neural network and return the cost in the\n% variable J. After implementing Part 1, you can verify that your\n% cost function computation is correct by verifying the cost\n% computed in ex4.m\n%\n% Part 2: Implement the backpropagation algorithm to compute the gradients\n% Theta1_grad and Theta2_grad. You should return the partial derivatives of\n% the cost function with respect to Theta1 and Theta2 in Theta1_grad and\n% Theta2_grad, respectively. After implementing Part 2, you can check\n% that your implementation is correct by running checkNNGradients\n%\n% Note: The vector y passed into the function is a vector of labels\n% containing values from 1..K. You need to map this vector into a \n% binary vector of 1's and 0's to be used with the neural network\n% cost function.\n%\n% Hint: We recommend implementing backpropagation using a for-loop\n% over the training examples if you are implementing it for the \n% first time.\n%\n% Part 3: Implement regularization with the cost function and gradients.\n%\n% Hint: You can implement this around the code for\n% backpropagation. That is, you can compute the gradients for\n% the regularization separately and then add them to Theta1_grad\n% and Theta2_grad from Part 2.\n%\n% FORWARD PROPOGATION\na1 = [ones(m,1) X];\nz2 = (a1*Theta1');\na2 = [ones(size(z2,1),1) sigmoid(z2)];\nh_theta = sigmoid(a2*Theta2');\na3 = h_theta;\ny_matrix = eye(num_labels)(y,:);\nJ = (-sum(sum(y_matrix.*log(h_theta))) - sum(sum((1-y_matrix).*(log(1-h_theta)))))/m;\n\n% REGULARIZATION\nregularization_term = (lambda/(2*m))*((sum(sum(Theta1(:,2:end).^2))) + sum(sum(Theta2(:,2:end).^2)));\nJ = J + regularization_term;\n\n% BACK PROPOGATION\nd3 = a3 - y_matrix; % has same dimensions as a3\nd2 = (d3*Theta2).*[ones(size(z2,1),1) sigmoidGradient(z2)]; % has same dimensions as a2\n\nD1 = d2(:,2:end)' * a1; % has same dimensions as Theta1\nD2 = d3' * a2; % has same dimensions as Theta2\n\nTheta1_grad = Theta1_grad + (1/m) * D1;\nTheta2_grad = Theta2_grad + (1/m) * D2;\n\n\n% REGULARIZATION OF THE GRADIENT\n\nTheta1_grad(:,2:end) = Theta1_grad(:,2:end) + (lambda/m)*(Theta1(:,2:end));\nTheta2_grad(:,2:end) = Theta2_grad(:,2:end) + (lambda/m)*(Theta2(:,2:end));\n% -------------------------------------------------------------\n\n% =========================================================================\n\n% Unroll gradients\ngrad = [Theta1_grad(:) ; Theta2_grad(:)];\n\n\nend\n", "meta": {"author": "anirudhjayaraman", "repo": "Machine-Learning", "sha": "084e9c67ac3853f78461f9d0e46c7b41364da481", "save_path": "github-repos/MATLAB/anirudhjayaraman-Machine-Learning", "path": "github-repos/MATLAB/anirudhjayaraman-Machine-Learning/Machine-Learning-084e9c67ac3853f78461f9d0e46c7b41364da481/Andrew Ng Stanford Coursera/Week 05/ex4/nnCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7473196865820119}} {"text": "function X = positive_definite_karcher_mean(A)\n% Computes a Karcher mean of a collection of positive definite matrices.\n%\n% function X = positive_definite_karcher_mean(A)\n%\n% Input: A 3D matrix A of size nxnxm such that each slice A(:,:,k) is a\n% positive definite matrix of size nxn.\n% \n% Output: A positive definite matrix X of size nxn which is a Karcher mean\n% of the m matrices in A, that is, X minimizes the sum of squared\n% Riemannian distances to the matrices in A:\n% f(X) = sum_k=1^m .5*dist^2(X, A(:, :, k))\n% The distance is defined by the natural metric on the set of\n% positive definite matrices: dist(X,Y) = norm(logm(X\\Y), 'fro').\n% \n% This simple example is not the best way to compute Karcher means. Its\n% purpose it to serve as base code to explore other algorithms. In\n% particular, in the presence of large noise, this algorithm seems to not\n% be able to reach points with a very small gradient norm. This may be\n% caused by insufficient accuracy in the gradient computation.\n\n% This file is part of Manopt and is copyrighted. See the license file.\n% \n% Main author: Nicolas Boumal, Sept. 3, 2013\n% Contributors:\n% \n% Change log:\n% \n \n % Generate some random data to test the function if none is given.\n if ~exist('A', 'var') || isempty(A)\n n = 5;\n m = 10;\n A = zeros(n, n, m);\n ref = diag(max(.1, 1+.1*randn(n, 1)));\n for i = 1 : m\n noise = 0.01*randn(n);\n noise = (noise + noise')/2;\n [V D] = eig(ref + noise);\n A(:, :, i) = V*diag(max(.01, diag(D)))*V';\n end\n end\n \n % Retrieve the size of the problem:\n % There are m matrices of size nxn to average.\n n = size(A, 1);\n m = size(A, 3);\n assert(n == size(A, 2), ...\n ['The slices of A must be square, i.e., the ' ...\n\t 'first and second dimensions of A must be equal.']);\n \n % Our search space is the set of positive definite matrices of size n.\n % Notice that this is the only place we specify on which manifold we\n % wish to compute Karcher means. Replacing this factory for another\n % geometry will yield code to compute Karcher means on that other\n % manifold, provided that manifold is equipped with a dist function and\n % a logarithmic map log.\n M = sympositivedefinitefactory(n);\n \n % Define a problem structure, specifying the manifold M, the cost\n % function and its gradient.\n problem.M = M;\n problem.cost = @cost;\n problem.grad = @grad;\n \n % The functions below make many redundant computations. This\n % performance hit can be alleviated by using the caching system. We go\n % for a simple implementation here, as a tutorial example.\n \n % Cost function\n function f = cost(X)\n f = 0;\n for k = 1 : m\n f = f + M.dist(X, A(:, :, k))^2;\n end\n f = f/(2*m);\n end\n\n % Riemannian gradient of the cost function\n function g = grad(X)\n g = M.zerovec(X);\n for k = 1 : m\n % Update g in a linear combination of the form\n % g = g - [something]/m.\n g = M.lincomb(X, 1, g, -1/m, M.log(X, A(:, :, k)));\n end\n end\n \n % Execute some checks on the derivatives for early debugging.\n % These things can be commented out of course.\n % The slopes should agree on part of the plot at least. In this case,\n % it is sometimes necessary to inspect the plot visually to make the\n % call, but it is indeed correct.\n % checkgradient(problem);\n % pause;\n \n % Execute this if you want to force using a proper parallel vector\n % transport. This is not necessary. If you omit this, the default\n % vector transport is the identity map, which is (of course) cheaper\n % and seems to perform well in practice.\n % M.transp = M.paralleltransp;\n \n % Issue a call to a solver. Default options are selected.\n % Our initial guess is the first data point.\n X = trustregions(problem, A(:, :, 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/manopt/examples/positive_definite_karcher_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7472984676373308}} {"text": "function [gd,fnorm]=sgrpdlay(x,fnorm);\n%SGRPDLAY Group delay estimation of a signal.\n%\t[GD,FNORM]=SGRPDLAY(X,FNORM) estimates the group delay of\n%\tsignal X at the normalized frequency(ies) FNORM.\n%\n%\tX : signal in the time-domain.\n%\tFNORM : normalized frequency. By default, FNORM is a \n% linearly spaced vector between -0.5 and 0.5 with\n% length(X) elements.\n%\tGD : computed group delay. When GD equals zero, it means that\n%\t \tthe estimation of the group delay for this frequency was \n%\t\toutside the interval [1 xrow], and therefore meaningless.\n%\n%\tExample : \n%\t N=128; x=amgauss(N,64,30).*fmlin(N,0.1,0.4);\n%\t fnorm=0.1:0.04:0.38; gd=sgrpdlay(x,fnorm); \n%\t t=2:N-1; instf=instfreq(x,t);\n%\t plot(t,instf,gd,fnorm); axis([1 N 0 0.5]); \n\n%\tF. Auger, March 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 one parameter required');\nend;\n\n[xrow,xcol] = size(x); \nif (xcol~=1),\n error('x must have only one column');\nend;\nEx=mean(abs(x).^2); \nThreshold=1.0e-6;\n\nif (nargin==1), \n Num=fft(x .* (1:xrow)');\n Den=fft(x);\n ratio=(real(Num./Den) .* (real(Num./Den)>=1) .* (real(Num./Den)<=xrow+3));\n gd=fftshift(ratio);\n if (nargout==2),\n if (rem(xrow,2)==0),\n L=xrow/2;\n fnorm=(-L:L-1)/xrow;\n else\n L=(xrow-1)/2;\n fnorm=(-L:L)/xrow;\n end;\n end;\nelseif (nargin==2),\n [fnormrow,fnormcol] = size(fnorm);\n if (fnormrow~=1),\n error('FNORM must have only one row');\n end;\n expo=exp(-j*2.0*pi*fnorm'*(0:xrow-1));\n Num=expo*(x .* (1:xrow)');\n Den=expo*x; \n gd=(real(Num./Den) .* (real(Num./Den)>=1) .* (real(Num./Den)<=xrow+3));\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/sgrpdlay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7472494219500387}} {"text": "function pendulum()\n% Matlab code for simulating a simple pendulum\n\nP.g = 9.81; %(m/s^2) gravity acceleration\nP.l = 1.0; %(m) length of pendulum \nP.c = 1.0; %(1/s) viscous damping constant\nP.m = 1.0; %(kg) pendulum mass\n\nth0 = 0.5; %(rad) initial angle of pendulum, from -j axis\nw0 = 0.0; %(rad/s) initial angular rate of pendulum\nz0 = [th0;w0]; %Initial state vector\n\ntSpan = [0,4]; %(s) [start, end] times for simulation\ndtMax = 0.01; %(s) maximum allowable time step\n\nnStep = ceil(diff(tSpan)/dtMax); %Number of simulation steps\nt = linspace(tSpan(1),tSpan(2),nStep); %(s) time vector \nz = zeros(2,nStep); % Initialize the state matrix\nz(:,1) = z0;\n\n%Run the simulation, using Euler integration\nfor i=2:nStep\n dt = t(i)-t(i-1);\n zNow = z(:,i-1);\n z(:,i) = zNow + dt*dynamics(zNow,P);\nend\n\n%Generate a plot of the result:\nfigure(1); clf;\nsubplot(2,1,1); plot(t,z(1,:));\nxlabel('Time (s)'); ylabel('Angle (rad)'); \ntitle('Simple Damped Pendulum');\nsubplot(2,1,2); plot(t,z(2,:));\nxlabel('Time (s)'); ylabel('Rate (rad/s)'); \n\nend\n\nfunction dz = dynamics(z,P)\n% Compute the dynamics of a simple damped pendulum:\n\nth = z(1,:); w = z(2,:); %Unpack the state vector\n\n%Dynamics:\ndth = w; \ndw = -(P.g/P.l)*sin(th) - (P.c/(P.m*P.l*P.l))*w;\n\ndz = [dth; dw]; %Pack up state derivative\nend", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/SimpleTutorials/pendulum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7471982015969723}} {"text": "% By Sherif A. Tawfik, Faculty of Engineering, Cairo University\n% [x,val,status]=IP1(f,A,b,Aeq,beq,lb,ub,M,e)\n% this function solves the following mixed-integer linear programming problem\n% min f*x\n% subject to\n% A*x <=b\n% Aeq * x = beq \n% lb <= x <= ub\n% M is a vector of indeces for the variables that are constrained to be integers\n% e is the integarilty tolerance\n% the return variables are :\n% x : the solution\n% val: value of the objective function at the optimal solution\n% status =1 if successful\n% =0 if maximum number of iterations reached in he linprog function\n% =-1 if there is no solution\n% Example:\n% maximize 17 x1 + 12 x2 \n% subject to\n% \t 10 x1 + 7 x2 <=40\n% x1 + x2 <= 5\n% x1, x2 >=0 and are integers\n% f=[-17, -12]; %take the negative for maximization problems\n% A=[ 10 7; 1 1];\n% B=[40; 5];\n% lb=[0 0];\n% ub=[inf inf];\n% M=[1,2];\n% e=2^-24;\n% [x v s]= IP(f,A,B,[],[],lb,ub,M,e)\n\nfunction [x,val,status]=IP1(f,A,b,Aeq,beq,lb,ub,M,e)\noptions = optimset('display','off');\nbound=inf; % the initial bound is set to +ve infinity\n[x0,val0]=linprog(f,A,b,Aeq,beq,lb,ub,[],options); \n[x,val,status,b]=rec(f,A,b,Aeq,beq,lb,ub,x0,val0,M,e,bound); % a recursive function that processes the BB tree \n\nfunction [xx,val,status,bb]=rec(f,A,b,Aeq,beq,lb,ub,x,v,M,e,bound) \noptions = optimset('display','off');\n% x is an initial solution and v is the corressponding objective function value\n\n% solve the corresponding LP model with the integarily constraints removed\n[x0,val0,status0]=linprog(f,A,b,Aeq,beq,lb,ub,[],options); \n\n% if the solution is not feasible or the value of the objective function is\n% higher than the current bound return with the input intial solution\nif status0<=0 | val0 > bound \n xx=x; val=v; status=status0; bb=bound;\n return;\nend\n\n% if the integer-constraint variables turned to be integers within the\n% input tolerance return\nind=find( abs(x0(M)-round(x0(M)))>e ); \nif isempty(ind)\n status=1; \n if val0 < bound % this solution is better than the current solution hence replace\n x0(M)=round(x0(M));\n xx=x0; \n val=val0;\n bb=val0;\n else\n xx=x; % return the input solution\n val=v;\n bb=bound;\n end\n return\nend\n\n% if we come here this means that the solution of the LP relaxation is\n% feasible and gives a less value than the current bound but some of the\n% integer-constraint variables are not integers. \n% Therefore we pick the first one that is not integer and form two LP problems\n% and solve them recursively by calling the same function (branching)\n\n% first LP problem with the added constraint that Xi <= floor(Xi) , i=ind(1)\nbr_var=M(ind(1));\nbr_value=x(br_var);\nif isempty(A)\n [r c]=size(Aeq);\nelse\n [r c]=size(A);\nend\nA1=[A ; zeros(1,c)];\nA1(end,br_var)=1;\nb1=[b;floor(br_value)];\n\n% second LP problem with the added constraint that Xi >= ceil(Xi) , i=ind(1)\nA2=[A ;zeros(1,c)];\nA2(end,br_var)=-1;\nb2=[b; -ceil(br_value)];\n\n\n% solve the first LP problem\n[x1,val1,status1,bound1]=rec(f,A1,b1,Aeq,beq,lb,ub,x0,val0,M,e,bound);\nstatus=status1;\nif status1 >0 & bound10 & bound2.\n%\n% http://www.petercorke.com\n\nfunction delta = delta2tr(d)\n d = d(:);\n delta = eye(4,4) + [skew(d(4:6)) d(1:3); 0 0 0 0];\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/delta2tr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7471981973766708}} {"text": "function nuclides\n% Solution for a chain of radionuclides\n% using MATLAB expm \n% $Ekkehard Holzbecher $Date: 2006/28/12 $\n%--------------------------------------------------------------------------\n\nT = 10; % maximum time\nlambda = [1; 0.1; 0.5];% decay rates \nc0 = [1; 0; 0]; % initial concentrations\nq = [0.1; 0; 0]; % source rates\nN = 60; % discretization of time\n\nt = linspace (0,T,N);\nB = -diag(lambda);\nfor i = 2:size(lambda,1)\n B(i,i-1) = lambda(i-1); \nend\nc = c0;\n\nfor i = 2:N\n E = expm(B*t(i));\n c = [c E*c0-(eye(size(B,1))-E)*inv(B)*q];\nend \nplot (t,c');\nlegend ('mother','daughter 1','daughter 2');\ntext (T/2,0.8,'Steady state:'); text (T/2,0.7,num2str(-(inv(B)*q)')); \nxlabel ('time');", "meta": {"author": "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/nuclides.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474233166329, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7471667140195097}} {"text": "classdef house\n\nmethods(Static)\n\nfunction [v, beta] = gen(x)\n % Generates the householder reflection vector for a given vector x\n % P = I - beta * v * v' is the householder projection matrix\n % P is an orthogonal projector\n % P *x changes x in such a way that only 1st entry is non-zero\n % GVL4: algorithm 5.1.1\n m = length(x);\n if m == 1\n v = 0; beta = 0; return;\n end\n sigma = x(2:m)' * x(2:m);\n v = [1; x(2:m)];\n if sigma == 0 && x(1) >= 0\n beta = 0;\n elseif sigma == 0 && x(1) < 0\n beta = -2;\n else\n mu = sqrt(x(1)^2 + sigma);\n if x(1) < 0\n v(1) = x(1) - mu;\n else\n v(1) = -sigma /(x(1) + mu);\n end % if\n beta = 2 * v(1)^2 / (sigma + v(1)^2);\n v = v / v(1);\n end % if\nend % func\n\nfunction B = premul(A, v, beta)\n % Efficiently computes B = PA = (I - beta v v') A\n B = A - (beta * v) *(v' * A);\nend % func\n\nfunction B = postmul(A, v, beta)\n % Efficiently computes B = AP = A (I - beta v v')\n B = A - (A*v) * (beta * v)';\nend % func\n\nfunction beta = beta_from_v(v)\n beta = 2/(v'*v);\nend% function\n\nfunction v = from_essential_v(essential)\n v = [zeros(j-1,1); 1; essential];\nend% function\n\nfunction [W, Y] = wy(QF)\n % Let Q be stored in the factored form Q = Q_1 * ... * Q_r\n % where Q_i = I - beta * v * v'\n % This algorithm computes W and Y such that\n % Q = I_r - W * Y';\n % GVL4: algorithm 5.1.2\n [m,r] = size(QF);\n for j=1:r\n % extract j-th v from the factors array\n % The essential part of v\n essential = QF(j+1:m,j);\n % Insert additional zeros and one to complete v\n v = [zeros(j-1,1); 1; essential];\n % Compute beta from v [it is not stored in factors array]\n beta = 2/(v'*v);\n if j==1\n % Initialize W and Y\n Y = v;\n W = beta*v;\n else\n % Update W and Y\n z = beta*(v - W*(Y(j:m,:)'*v(j:m)));\n Y = [Y v];\n W = [W z]; \n end\n end\nend% function\n\nfunction B = wy_premul(A, W, Y)\n % Efficiently computes B = (I - WY') A\n B = A - W*(Y'*A);\nend % func\n\nfunction B = wy_postmul(A, W, Y)\n % Efficiently computes B = A (I - WY')\n B = A - (A*W)*Y';\nend % func\n\n\nfunction [QF, R] = qr(A)\n % Performs A = QR factorization\n % using Householder reflections\n % GVL4: Algorithm 5.2.1\n import spx.la.house;\n [m,n] = size(A);\n for j=1:min(n,m-1)\n % Compute the jth Householder matrix Q{j}...\n [v,beta] = house.gen(A(j:m,j));\n % Update... A = Q_j A\n A(j:m,j:n) = house.premul(A(j:m,j:n), v, beta);\n % Save the essential part of householder vector...\n A(j+1:m,j) = v(2:m-j+1);\n end\n % extract the R component\n R = triu(A(1:n,1:n));\n % extract the Q component in factored form\n QF = tril(A,-1);\nend% function\n\nfunction [QF, R, P] = qr_pivot(A)\n % Householder QR with column pivoting\n % Achieves factorization AP = QR\n % GVL4 : algorithm 5.4.1 \n import spx.la.house;\n [m,n] = size(A);\n % Space for keeping squared norms of columns\n c = zeros(1,n);\n % Compute squared norms of each column\n for j=1:n\n c(j) = A(:,j)'*A(:,j);\n end\n % space for the permutation matrix\n P = 1:n;\n % index of column being processed\n r = 0;\n % Find the index of maximum norm column\n [tau,k] = max(c);\n % The tau > 0 check ensures that we process only till \n % rank of A\n while tau>1e-10 && r0\n % premultiply Q with the householder projector\n Q = Q - (beta*v)*(v'*Q);\n end\n end\nend% function\n\n\nfunction Q = q_back_accum_full(QF)\n % Explicit formation of an orthogonal matrix from its factored form\n % representation. Uses backward accumulation.\n % QF is m x n and \n % Produces an m x m Q that is the product of of Q_{1}...Q_{n}.\n % GVL4: Section 5.2.2\n [m,n] = size(QF);\n % We start with a matrix of size (m-n) x (m -n)\n % If m <= n, then we start with a matrix of size 1 x 1\n Q = eye(max(m-n,1),max(m-n,1));\n % We iterative over columns backwards\n for j=min(n,m-1):-1:1\n % Q_fact(j+1:m,j) is the essential part of the \n % j-th Householder matrix Q_{j}.\n % Get the essential part of householder vector in this column\n essential = QF(j+1:m,j);\n % Extend the vector with 1\n v = [1;essential];\n % Compute beta from the householder vector\n beta = 2/(v'*v);\n % Expand Q with zeros\n k = m-j;\n Q = [1 zeros(1,k);\n zeros(k,1) Q];\n % check for zero changes.\n if norm(essential)>0\n % premultiply with Householder projector\n Q = Q - (beta*v)*(v'*Q);\n end\n end\nend % function\n\nfunction [UF, B, VF] = bidiag(A)\n % Performs bidiagonalization of A = U B V'. \n % U and V are stored in factored forms.\n % GVL4: algorithm 5.4.2\n import spx.la.house;\n [m,n] = size(A);\n % Iterate over columns of A from first to last column.\n % If A is tall, then we can process all columns.\n % If A is square, then we will process m -1 columns\n % If A is wide, we can process all columns.\n for j=1:min(n,m-1)\n % zero out the j-th column\n % Compute the jth Householder vector for U_j\n [u,beta] = house.gen(A(j:m,j));\n % Update... A = U_j A\n A(j:m,j:n) = A(j:m,j:n) - (beta*u)*(u'*A(j:m,j:n));\n % Save the essential part of householder vector...\n A(j+1:m,j) = u(2:m-j+1);\n if j+2<=n\n % zero out the j-th row now\n % Compute the j-th Householder vector for V_j\n [v,beta] = house.gen(A(j,j+1:n)');\n % Update... A = A V_j\n A(j:m,j+1:n) = A(j:m,j+1:n) - (A(j:m,j+1:n)*v)*(beta*v)';\n % Save the essential Householder vector in j-th row\n A(j,j+2:n) = v(2:n-j)'; \n end \n end\n % Extract the diagonal and first super-diagonal\n B = tril(triu(A),1);\n % Extract the subdiagonal lower triangular part\n UF = tril(A,-1);\n % Space for V factors\n VF = zeros(n,n);\n % Extract the factors row by row\n for j=1:n-2\n % j-th row householder vector\n VF(j+2:n,j+1) = A(j,j+2:n)';\n end\nend % function\n\nend % methods \n\nend % classdef\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/library/+spx/+la/house.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317102, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.747113725109727}} {"text": "function c=ref_dgt_3(f,g,a,M)\n%REF_DGT_3 DGT algorithm 3\n\nL=size(g,1);\nN=L/a;\nb=L/M;\n\n[c,h_a,h_m]=gcd(-a,M);\np=a/c;\nq=M/c;\nd=N/q;\n\nw=zeros(M,N);\n\nif 0\n\n % This version uses the definition.\n\n F=zeros(c,d,p,q);\n G=zeros(c,d,p,q);\n \n for r=0:c-1 \n for s=0:d-1\n for k=0:p-1\n\tfor l=0:q-1\n\t for st=0:d-1\n\t F(r+1,s+1,k+1,l+1)=F(r+1,s+1,k+1,l+1)+f(mod(r+k*M+st*p*M-l*h_a*a,L)+1)*exp(-2*pi*i*s*st/d);\n\t G(r+1,s+1,k+1,l+1)=G(r+1,s+1,k+1,l+1)+g(mod(r+k*M-l*a+st*p*M,L)+1)*exp(-2*pi*i*s*st/d);\n\t end;\n\tend;\n end;\n end;\n end;\n\n for r=0:c-1 \n for l=0:q-1\n for u=0:q-1\n\tfor s=0:d-1\n\t for v=0:d-1\n\t for k=0:p-1\n\t w(r+l*c+1,mod(u+s*q-l*h_a,N)+1)=w(r+l*c+1,mod(u+s*q-l*h_a,N)+1)+...\n\t\t 1/d*F(r+1,v+1,k+1,l+1)*conj(G(r+1,v+1,k+1,u+1))*exp(2*pi*i*v*s/d);\n\t end;\n\t end;\n\tend;\n end;\n end;\n end;\n \n\nelse\n\n % This version uses matrix-vector products and ffts\n\n F=zeros(c,d,p,q);\n G=zeros(c,d,p,q);\n C=zeros(c,d,q,q);\n \n % Set up the matrices\n for r=0:c-1 \n for s=0:d-1\n for k=0:p-1\n\tfor l=0:q-1\n\t F(r+1,s+1,k+1,l+1)=f(mod(r+k*M+s*p*M-l*h_a*a,L)+1);\n\t G(r+1,s+1,k+1,l+1)=sqrt(M*d)*g(mod(r+k*M-l*a+s*p*M,L)+1);\n\tend;\n end;\n end;\n end;\n\n % fft them\n F=dft(F,[],2);\n G=dft(G,[],2);\n \n % Multiply them\n for r=0:c-1 \n for s=0:d-1\n GM=reshape(G(r+1,s+1,:,:),p,q);\n FM=reshape(F(r+1,s+1,:,:),p,q);\n C(r+1,s+1,:,:)=GM'*FM;\n end;\n end;\n\n % Inverse fft\n C=idft(C,[],2);\n\n % Place the result\n for r=0:c-1 \n for l=0:q-1\n for u=0:q-1\n\tfor s=0:d-1\n\t w(r+l*c+1,mod(u+s*q-l*h_a,N)+1)=C(r+1,s+1,u+1,l+1);\n\tend;\n end;\n end;\n end; \n \nend;\n\nc=dft(w);\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_dgt_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7471137234700435}} {"text": "function [pos, tri] = mesh_icosahedron\n\n% MESH_ICOSAHEDRON returns the vertices and triangle of a 12-vertex icosahedral\n% mesh.\n%\n% Use as\n% [pos, tri] = mesh_icosahedron\n%\n% See also MESH_TETRAHEDRON, MESH_OCTAHEDRON, MESH_SPHERE\n\n% Copyright (C) 2002, Robert Oostenveld\n% Copyright (C) 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%\n\n\ntri = [\n 1 2 3\n 1 3 4\n 1 4 5\n 1 5 6\n 1 6 2\n 2 8 3\n 3 9 4\n 4 10 5\n 5 11 6\n 6 7 2\n 7 8 2\n 8 9 3\n 9 10 4\n 10 11 5\n 11 7 6\n 12 8 7\n 12 9 8\n 12 10 9\n 12 11 10\n 12 7 11\n ];\n\npos = zeros(12, 3);\n\nrho = 0.4*sqrt(5);\nphi = 2*pi*(0:4)/5;\n\npos( 1, :) = [0 0 1]; % top point\n\npos(2:6, 1) = rho*cos(phi)';\npos(2:6, 2) = rho*sin(phi)';\npos(2:6, 3) = rho/2;\n\npos(7:11, 1) = rho*cos(phi - pi/5)';\npos(7:11, 2) = rho*sin(phi - pi/5)';\npos(7:11, 3) = -rho/2;\n\npos(12, :) = [0 0 -1]; % bottom point\n\n% scale all vertices to the unit sphere\npos = 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_icosahedron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.747070176095745}} {"text": "function [DVal,totalError,exitCode]=KLDistApproxGaussMix(w1,mu1,P1,w2,mu2,P2,algorithm,param8,w)\n%%KLDISTAPPROXGAUSSMIX Approximate the Kullback-Leibler (KL) divergence\n% (also known as the KL distance or relative entropy) between two\n% multivariate Gaussian mixture distributions. Whereas an explicit\n% solution is available for the KL distance between two Gaussian\n% PDFs, no explicit solution exists between a Gaussian PDF and a\n% Gaussian mixture. Thus, various approximations are necessary.\n% As defined in Chapter 8.5 of [4], the relative entropy between\n% two continuous PDFs, f and g, is\n% D(f||g)=integral_{x} f(x) log(f(x)/g(x)) dx\n% The integral is over an appropriate domain of x, in this case\n% the d-dimensional real space for an n-dimensional state. Note\n% that changing the order of f and g changes the result (the\n% operation is not commutative).\n%\n%INPUTS: w1 The 1Xn1 or n1X1 set of weights of the first Gaussian mixture's\n% components such that all w>=0 and sum(w)=1.\n% mu1 The dXn1 set of mean values of the first Gaussian mixture's\n% components.\n% P1 The dXxdXn1 set of covariance matrices of the first Gaussian\n% mixture's components.\n% w2,mu2,P2 The equivalent of w1, mu1 and P1 for the second mixtures\n% components. There length-n2, dXn2, and dXdXn2 in size.\n% algorithm An optional parameter specifying the algorithm used to obtain\n% the approximation of the KL divergence. Possible values are\n% for:\n% 0 Use adaptive numeric integration to directly evaluate the\n% Kullback-Leiberler divergence integral over a rectangular \n% region that is standard deviations from the means of the\n% distributions. The default number of standard deviations in\n% each direction is 4.5 and can be adjusted by passing a member\n% of param8 named 'numStdDev'. In 1D, the function\n% integral1DAdaptiveCC is used for the integration and the\n% inputs to that function 'RelTol', 'AbsTol', 'NPowMin', and\n% 'NPowMax' can be passed as members of param8 if one wishes to\n% not use the defaults. If higher dimensions, the function\n% integrateUnifCub57Adaptive is used for the numeric\n% integration and the inputs to that function 'maxSearchReg',\n% 'AbsTol', and 'RelTol' can be passed if one wishes to not use\n% the defaults. This approximation can produce negative\n% values, though it is often good.\n% 1 Monte Carlo sampling from Equation 4 of Section 2 of [3].\n% This uses param8 as the number of samples (if given). The\n% default if param8 is not given is 3e3. As the number of\n% samples increases, this method should become increasingly\n% accurate. This approximation can produce negative values.\n% 2 (The default if omitted or an empty matrix is passed) The\n% cubature integration approximation from Equation 8 in Section\n% 3 of [3]. This uses param8 as the cubature points and w as\n% the weights, if provided. If not provided, then\n% fifthOrderCubPoints is used to obtain fifth-order xDim-\n% dimensional cubature points. This approximation can produce\n% negative values.\n% 3 Use the variational upper bound from Section 8 of [3]. This\n% approximation should always be positive. 10 iterations are\n% performed. This bound is typically not zero when the two\n% input PDFs are equal.\n% 4 The variational approximation from Section 7 of [3] (also\n% given in [1]). This approximation can produce negative\n% values.\n% 5 The product of Gaussians approximation in [1] and Section 5\n% of [3]. This approximation can produce negative values.\n% 6 Take the average of algorithms 5 and 4, which tend to be\n% upper and lower bounds.\n% 7 Goldberger's approximation from Equation 2 of [2]. This is\n% also given in Section 6 of [3] as the matched bound\n% approximation. This approximation can produce negative\n% values and is often quite bad with certain classes of\n% distributions.\n% param8 An optional parameter. If algorithm=0, then this is a structure\n% that can take members as described above for algorithm 0. If\n% algorithm=1, then this is the number of samples to use. If\n% algorithm=2, then this is a set of cubature points as a\n% dXnumPoints matrix. For other values of algorithm, this input\n% is not used.\n% w This input is only used if algorithm=2, in which case it is the\n% set of cubature weights (sum(w)=1). that are associated with\n% the cubature points in param8. If param8 is omitted or an empty\n% matrix is passed, then w will be the weights associated with\n% the points from the fifthOrderCubPoints function.\n%\n%%OUTPUTS: val The approximate value of the Kullback-Leibler divergence\n% between the first and the second Gaussian mixture\n% distributions.\n%\n%Some approximations can produce negative values (the true KL divergence\n%can never be negative).\n%\n%EXAMPLE 1:\n%Though many of the algorithms are often cited in the literature, many of\n%the approximations can be quite bad. Here, we consider a 1D example and\n%then the mixture missing a few components and also the moment-matched\n%Gaussian approximation.\n% w1=[0.03,0.18,0.12,0.19,0.02,0.16,0.06,0.1,0.08,0.06];\n% n1=length(w1);\n% mu1=[1.45,2.20,0.67,0.48,1.49,0.91,1.01,1.42,2.77,0.89];\n% P1=[0.0487,0.0305,0.1171,0.0174,0.0295,0.0102, 0.0323, 0.0380, 0.0115, 0.0679];\n% P1=reshape(P1,[1,1,n1]);\n% \n% %The second PDF is the first with the five least-weight components deleted.\n% w2=[0.18,0.12,0.19,0.16,0.1,0.08];\n% w2=w2/sum(w2);\n% n2=length(w2);\n% mu2=[2.20,0.67,0.48,0.91,1.42,2.77];\n% P2=[0.0305,0.1171,0.0174,0.0102,0.0380,0.0115];\n% P2=reshape(P2,[1,1,n2]);\n% \n% %The third PDF is the second PDF with two more components deleted.\n% w3=[0.18,0.12,0.19,0.16];\n% w3=w3/sum(w3);\n% n3=length(w3);\n% mu3=[2.20,0.67,0.48,0.917];\n% P3=[0.0305,0.1171,0.0174,0.0102];\n% P3=reshape(P3,[1,1,n3]);\n% \n% %The fourth PDF is just the Gaussian matching the first two moments of the\n% %original PDF.\n% w4=1;\n% [mu4,P4]=calcMixtureMoments(mu1,w1,P1);\n% \n% DVal=zeros(8,3);\n% for curAlg=0:7\n% DVal(curAlg+1,1)=KLDistApproxGaussMix(w1,mu1,P1,w2,mu2,P2,curAlg);\n% DVal(curAlg+1,2)=KLDistApproxGaussMix(w1,mu1,P1,w3,mu3,P3,curAlg);\n% DVal(curAlg+1,3)=KLDistApproxGaussMix(w1,mu1,P1,w4,mu4,P4,curAlg);\n% end\n% RelErr=abs(bsxfun(@rdivide,bsxfun(@minus,DVal,DVal(1,:)),DVal(1,:)))\n% %The rows of RelErr are the algorithms and the PDF chosen for comparison\n% %against the original PDF is given by the column. The value obtained\n% %through the numeric integration (algorithm 0) is nearly exact, so it is\n% %taken as a basis of comparison for the relative error of the\n% %approximations. It can be seen that some approximations are much worse\n% %than others.\n% %We can visualize the above PDFs.\n% numPoints=500;\n% xVals=linspace(0,3,numPoints);\n% PDFVals1=GaussianMixtureD.PDF(xVals,w1,mu1,P1);\n% PDFVals2=GaussianMixtureD.PDF(xVals,w2,mu2,P2);\n% PDFVals3=GaussianMixtureD.PDF(xVals,w3,mu3,P3);\n% PDFVals4=GaussianMixtureD.PDF(xVals,w4,mu4,P4);\n% figure(1)\n% clf\n% hold on\n% plot(xVals,PDFVals1,'-k','linewidth',4)\n% plot(xVals,PDFVals2,'-r','linewidth',2)\n% plot(xVals,PDFVals3,'--g','linewidth',2)\n% plot(xVals,PDFVals4,'-.b','linewidth',2)\n% legend('10 Elements', '5 Elements', '3 Elements','Matched Gaussian')\n%\n%EXAMPLE 2:\n%Here is an example with bivariare Gaussian mixtures. \n% w1=[0.25;0.5;0.25];\n% mu1=zeros(2,2);\n% mu1(:,1)=[1;-1];\n% mu1(:,2)=[-1;1];\n% mu1(:,3)=[0;0];\n% P1=zeros(2,2,2);\n% P1(:,:,1)=[4/9, 14/45;\n% 14/45,4/9];\n% P1(:,:,2)=[4/9, 0;\n% 0, 4/9];\n% P1(:,:,3)=[2/9, -1/9;\n% -1/9, 3/9];\n% \n% %The second distribution just throws out the first component.\n% w2=w1(2:3);\n% w2=w2/sum(w2);\n% mu2=mu1(:,2:3);\n% P2=P1(:,:,2:3);\n% \n% %The third distribution replaces the original distribution with a single\n% %moment-matched Gaussian.\n% w3=1;\n% [mu3,P3]=calcMixtureMoments(mu1,w1,P1);\n% \n% DVal=zeros(8,2);\n% for curAlg=0:7\n% DVal(curAlg+1,1)=KLDistApproxGaussMix(w1,mu1,P1,w2,mu2,P2,curAlg);\n% DVal(curAlg+1,2)=KLDistApproxGaussMix(w1,mu1,P1,w3,mu3,P3,curAlg);\n% end\n% RelErr=abs(bsxfun(@rdivide,bsxfun(@minus,DVal,DVal(1,:)),DVal(1,:)))\n% %The rows of RelErr are the algorithms and the PDF chosen for comparison\n% %against the original PDF is given by the column. The value obtained\n% %through the numeric integration (algorithm 0) has a few digits of\n% %accuracy, so it is taken as a basis of comparison for the relative\n% %error of the approximations. It can be seen that some approximations are\n% %much worse than others.\n% %We can visualize the above PDFs.\n% figure(1)\n% clf\n% subplot(3,1,1);\n% numPoints=250;\n% vals=linspace(-3,3,numPoints);\n% [X,Y]=meshgrid(vals,vals);\n% points=[X(:)';Y(:)'];\n% PDFVals=GaussianMixtureD.PDF(points,w1,mu1,P1);\n% PDFVals=reshape(PDFVals,numPoints,numPoints);\n% surf(X,Y,PDFVals,'EdgeColor','none')\n% title('Full PDF')\n% %Plot the reduced PDF\n% subplot(3,1,2);\n% numPoints=250;\n% vals=linspace(-3,3,numPoints);\n% [X,Y]=meshgrid(vals,vals);\n% points=[X(:)';Y(:)'];\n% PDFVals=GaussianMixtureD.PDF(points,w2,mu2,P2);\n% PDFVals=reshape(PDFVals,numPoints,numPoints);\n% surf(X,Y,PDFVals,'EdgeColor','none')\n% title('Missing 1 Component')\n% %Plot the Gaussian approximation.\n% subplot(3,1,3);\n% numPoints=250;\n% vals=linspace(-3,3,numPoints);\n% [X,Y]=meshgrid(vals,vals);\n% points=[X(:)';Y(:)'];\n% PDFVals=GaussianMixtureD.PDF(points,w3,mu3,P3);\n% PDFVals=reshape(PDFVals,numPoints,numPoints);\n% surf(X,Y,PDFVals,'EdgeColor','none')\n% title('Gaussian Approximation')\n%\n%REFERENCES:\n%[1] J. L. Durrieu, J. P. Thiran, and F. Kelly, \"Lower and upper bounds for\n% approximation of Kullback-Leibler divergence between Gaussian mixture\n% models,\" in Proceedings of the IEEE International Conference on\n% Acoustics, Speech and Signal Processing, Kyoto, Japan, 25-30 Mar.\n% 2012, pp. 4833-4836.\n%[2] J. Goldberger, S. Gordon, and H. Greenspan, \"An efficient image\n% similarity measure based on approximations of KL-divergence between\n% two Gaussian mixtures,\" in Proceedings of the Ninth IEEE International\n% Conference on Computer Vision, Nice, France, 2003.\n%[3] J. R. Hershey and P. A. Olden, \"Approximating the Kullback Leibler\n% divergence between Gaussian mixture models,\" in Proceedings of the\n% IEEE International Conference on Acoustics, Speech and Signal\n% Processing, Honolulu, HI, 15-20 Apr. 2007.\n%[4] T. M. Cover and J. A. Thomas, Elements of Information Theory, 2nd ed.\n% Hoboken, NJ: Wiley-Interscience, 2006.\n%\n%July 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<7||isempty(algorithm))\n algorithm=2;\nend\n\nd=size(mu1,1);\nn1=length(w1);\nn2=length(w2);\n\ntotalError=[];\nexitCode=0;\nswitch(algorithm)\n case 0%Numeric integration over a bounded region.\n if(nargin>7&&~isempty(param8))\n if(isfield(param8,'numStdDev'))\n numStdDev=param8.numStdDev;\n end\n else\n numStdDev=4.5;\n end\n\n [mu1Merged,P1Merged]=calcMixtureMoments(mu1,w1,P1);\n [mu2Merged,P2Merged]=calcMixtureMoments(mu2,w2,P2);\n\n stdDevStep1=numStdDev*sqrt(diag(P1Merged));\n stdDevStep2=numStdDev*sqrt(diag(P2Merged));\n \n P1Inv=zeros(d,d,n1);\n P1InvDet=zeros(n1,1);\n P2Inv=zeros(d,d,n2);\n P2InvDet=zeros(n2,1);\n for k=1:n1\n P1Inv(:,:,k)=inv(P1(:,:,k));\n P1InvDet(k)=det(P1Inv(:,:,k));\n end\n for k=1:n2\n P2Inv(:,:,k)=inv(P2(:,:,k));\n P2InvDet(k)=det(P2Inv(:,:,k));\n end\n \n upperBounds=max(mu1Merged+stdDevStep1,mu2Merged+stdDevStep2);\n lowerBounds=min(mu1Merged-stdDevStep1,mu2Merged-stdDevStep2);\n\n f=@(x)KLArgGaussMix(x,w1,mu1,P1Inv,P1InvDet,w2,mu2,P2Inv,P2InvDet);\n\n if(d==1)\n %A different integration routine is used for 1D veruss\n %arbitrary dimensional integrals.\n bounds=[lowerBounds;upperBounds];\n\n RelTol=[];\n AbsTol=[];\n NPowMin=[];\n NPowMax=[];\n if(nargin>7&&~isempty(param8))\n if(isfield(param8,'RelTol'))\n RelTol=param8.RelTol;\n end\n \n if(isfield(param8,'AbsTol'))\n AbsTol=param8.AbsTol;\n end\n \n if(isfield(param8,'NPowMin'))\n NPowMin=param8.NPowMin;\n end\n \n if(isfield(param8,'NPowMax'))\n NPowMax=param8.NPowMax;\n end\n end\n\n [DVal,totalError,exitCode]=integral1DAdaptiveCC(f,bounds,RelTol,AbsTol,NPowMin,NPowMax);\n else\n maxSearchReg=[];\n AbsTol=[];\n RelTol=[];\n if(nargin>7&&~isempty(param8))\n if(isfield(param8,'RelTol'))\n RelTol=param8.RelTol;\n end\n \n if(isfield(param8,'AbsTol'))\n AbsTol=param8.AbsTol;\n end\n \n if(isfield(param8,'maxSearchReg'))\n maxSearchReg=param8.maxSearchReg;\n end\n end\n\n [DVal,totalError,exitCode]=integrateUnifCub57Adaptive(f,lowerBounds,upperBounds,maxSearchReg,AbsTol,RelTol);\n end\n case 1%Monte Carlo sampling from Equation 4 of Section 2 of [3].\n if((nargin<8||isempty(param8)))\n numSamp=2e3;\n else\n numSamp=param8;\n end\n \n S1=zeros(d,d,n1);\n S2=zeros(d,d,n2);\n for k=1:n1\n S1(:,:,k)=chol(P1(:,:,k),'lower');\n end\n for k=1:n2\n S2(:,:,k)=chol(P2(:,:,k),'lower');\n end\n \n x1Samp=GaussianMixtureD.randS(numSamp,w1,mu1,S1);\n PDFVals1=GaussianMixtureD.PDFS(x1Samp,w1,mu1,S1);\n \n logVals=log(PDFVals1)-log(GaussianMixtureD.PDFS(x1Samp,w2,mu2,S2));\n %Get rid of points where PDFVals1==0 due to finite precision\n %errors. This probably won't occur. However, eliminating them also\n %gets rid of any unlikely points where both PDFs evaluate to 0 and\n %thus avoids returning NaN values.\n sel=(PDFVals1==0);\n logVals(sel)=0;\n\n DVal=sum(logVals)/numSamp;\n case 2%The cubature integration approximation from Equation 8 in\n %Section 3 of [3].\n if(nargin<8||isempty(param8))\n [xi,w]=fifthOrderCubPoints(d);\n else\n xi=param8;\n end\n\n S1=zeros(d,d,n1);\n S2=zeros(d,d,n2);\n for k=1:n1\n S1(:,:,k)=chol(P1(:,:,k),'lower');\n end\n for k=1:n2\n S2(:,:,k)=chol(P2(:,:,k),'lower');\n end\n \n w=w(:).';\n DVal=0;\n for a=1:n1\n %The component over which the expected value is taken.\n xiCur=transformCubPoints(xi,mu1(:,a),S1(:,:,a));\n\n logVals=log(GaussianMixtureD.PDFS(xiCur,w1,mu1,S1))-log(GaussianMixtureD.PDFS(xiCur,w2,mu2,S2));\n %Get rid of NaN values.\n %logVals(isnan(logVals))=0;\n \n DVal=DVal+w1(a)*sum(logVals.*w);\n end \n case 3%The variational upper bound from Section 8 of [3].\n psi=zeros(n1,n2);\n phi=zeros(n2,n1);\n \n %We start with psi and phi being the same and equal to what would\n %produce the convexity bound:\n for a=1:n1\n for b=1:n2\n psi(a,b)=w1(a)*w2(b);\n phi(b,a)=psi(a,b);\n end\n end\n \n %Get all pairwise KL-divergences.\n DKLg=zeros(n1,n2);\n for a=1:n1\n for b=1:n2\n DKLg(a,b)=KLDistGauss(mu1(:,a),P1(:,:,a),mu2(:,b),P2(:,:,b));\n end\n end\n expnDKLg=exp(-DKLg);\n\n numIter=10;\n for curIter=1:numIter\n %Equation 24 for phi.\n for a=1:n1\n denom=sum(psi(a,:).*expnDKLg(a,:));\n for b=1:n2\n phi(b,a)=w1(a)*psi(a,b)*expnDKLg(a,b)/denom;\n end\n end\n \n %Equation 23 for psi\n for b=1:n2\n denom=sum(phi(b,:));\n for a=1:n1 \n psi(a,b)=w2(b)*phi(b,a)/denom;\n end\n end\n end\n \n %The first term in Equation 22\n term1=0;\n term2=0;\n for a=1:n1\n for b=1:n2\n val=phi(b,a)*log(phi(b,a)/psi(a,b));\n if(isnan(val))\n val=0;\n end\n term1=term1+val;\n\n term2=term2+phi(b,a)*DKLg(a,b);\n end\n end\n\n DVal=term1+term2;\n case 4%The variational approximation from Section 2.3 of [1] and\n %Section 7 of [3].\n\n %Compute the necessary KL divergences.\n DKLf=zeros(n1,n1);\n DKLg=zeros(n1,n2);\n for a=1:n1\n DKLf(a,a)=KLDistGauss(mu1(:,a),P1(:,:,a),mu1(:,a),P1(:,:,a));\n for ap=(a+1):n1\n DKLf(a,ap)=KLDistGauss(mu1(:,a),P1(:,:,a),mu1(:,ap),P1(:,:,ap));\n DKLf(ap,a)=KLDistGauss(mu1(:,ap),P1(:,:,ap),mu1(:,a),P1(:,:,a));\n end\n\n for b=1:n2\n DKLg(a,b)=KLDistGauss(mu1(:,a),P1(:,:,a),mu2(:,b),P2(:,:,b));\n end\n end\n\n %Evaluate the sum in Equation 18 of [1], which is the same as\n %Equation 20 of [3].\n DVal=0;\n w1=w1(:).';\n w2=w2(:).';\n for a=1:n1\n DVal=DVal+w1(a)*(log(sum(w1.*exp(-DKLf(a,:))))-log(sum(w2.*exp(-DKLg(a,:)))));\n end\n case 5%The product of Gaussians approximation in [1] and Section 5 of\n %[3].\n \n P1Inv=zeros(d,d,n1);\n P2Inv=zeros(d,d,n2);\n for k=1:n1\n P1Inv(:,:,k)=inv(P1(:,:,k));\n end\n for k=1:n2\n P2Inv(:,:,k)=inv(P2(:,:,k));\n end\n\n %We have to first compute the z and t terms. The logarithms of the z\n %and t terms are given in Equation 22 in [1]. However, that\n %expression is incorrect; the corrected expression is used here\n\n zaap=zeros(n1,n1);\n tab=zeros(n1,n2);\n for a=1:n1\n for ap=a:n1\n diff=mu1(:,a)-mu1(:,ap);\n Sigmad=inv(P1Inv(:,:,a)+P1Inv(:,:,ap));\n const=sqrt(det(2*pi*Sigmad))/(sqrt(det(2*pi*P1(:,:,a))*det(2*pi*P1(:,:,ap))));\n \n B=P1Inv(:,:,a)*Sigmad*P1Inv(:,:,ap);\n zaap(a,ap)=const*exp(-(1/2)*diff'*B*diff);\n zaap(ap,a)=zaap(a,ap);\n end\n\n for b=1:n2\n diff=mu1(:,a)-mu2(:,b);\n Sigmad=inv(P1Inv(:,:,a)+P2Inv(:,:,b));\n const=sqrt(det(2*pi*Sigmad))/(sqrt(det(2*pi*P1(:,:,a))*det(2*pi*P2(:,:,b))));\n \n B=P1Inv(:,:,a)*Sigmad*P2Inv(:,:,b);\n tab(a,b)=const*exp(-(1/2)*diff'*B*diff);\n end\n end\n \n %Evaluate the sum in Equation 12 of [1], which is the same as\n %Equation 12 of [3].\n DVal=0;\n w1=w1(:).';\n w2=w2(:).';\n for a=1:n1\n DVal=DVal+w1(a)*(log(sum(w1.*zaap(a,:)))-log(sum(w2.*tab(a,:))));\n end\n case 6\n DProd=KLDistApproxGaussMix(w1,mu1,P1,w2,mu2,P2,5);\n DVar=KLDistApproxGaussMix(w1,mu1,P1,w2,mu2,P2,4);\n DVal=(DProd+DVar)/2;\n case 7%Goldberger's approximation from Equation 2 of [2].\n DKLg=zeros(n1,n2);\n for a=1:n1\n for b=1:n2\n DKLg(a,b)=KLDistGauss(mu1(:,a),P1(:,:,a),mu2(:,b),P2(:,:,b));\n end\n end\n \n w2=w2(:).';\n\n %Perform the minimization in Equation 1 of [2], which is also given\n %in Equation 14 of [3] and simultaneously evaluate Equation 2 of\n %[2], which is the same as Equation 15 in [3].\n DVal=0;\n logw2=log(w2);\n for a=1:n1\n minVal=min(DKLg(a,:)-logw2);\n DVal=DVal+w1(a)*(log(w1(a))+minVal);\n end\n otherwise\n error('Unknown algorithm specified.')\nend\nend\n\nfunction val=KLArgGaussMix(x,w1,mu1,P1Inv,P1InvDet,w2,mu2,P2Inv,P2InvDet)\n%%KLSAMPGAUSSMIX The KL divergence is an integral. This evaluates the\n% argument of the integral for the KL divergences between\n% two Gaussian mixtures.\n%\n%July 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nPDF1=GaussianMixtureD.PDFI(x,w1,mu1,P1Inv,P1InvDet);\nPDF2=GaussianMixtureD.PDFI(x,w2,mu2,P2Inv,P2InvDet);\n\nval=PDF1.*(log(PDF1)-log(PDF2));\nval(isnan(val))=0;\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/KLDistApproxGaussMix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7470701740633064}} {"text": "function r = gedrnd(v,varargin)\n% Generate random variables from a Generalized Error Distribution (GED) with V degrees of freedom\n%\n% USAGE:\n% R=gedrnd(V)\n% R=gedrnd(V,S1)\n% R=gedrnd(V,S1,S2,S3,...,SN)\n% R=gedrnd(V,[S1 S2 S3 ... SN])\n%\n% INPUTS:\n% V - Degree of freedom parameter. Either scalar or matrix.\n% Sx - [OPTIONAL] Size of output.\n% R will be:\n% 1 by 1 if V is scalar and no S are entered\n% size(V) if V is non-scalar and no S are entered\n% S1 by S1 if V is scalar and only S1 is entered\n% [S1 S2 ... SN] otherwise\n% If V is non-scalar and S are provided, size(V) must equal [S1 S2 ... SN]\n%\n% OUTPUTS:\n% R - GED distributed random variables\n%\n% COMMENTS:\n% V>=1\n% A scalar GED r.v. with variance normalized to 1 has probability\n% density given by:\n% f(x,v) = [v/(lda*2^(1+1/v)*gamma(1/v))]*exp(-0.5*|x/lda|^v)\n% lda = [2^(-2/v)*gamma(1/v)/gamma(3/v)]^0.5\n% If X~GED(v) then abs(X)^v = Y~Gamma(1/v) (cf. Tadikamalla 1980).\n% GAMRND does the computational work.\n%\n% REFERENCES:\n% [1] Tadikamalla (1980), J.Am.Stat.Assoc. (75)\n% [2] Nelson (1991), Econometrica\n%\n% See also GEDPDF, GEDCDF, GEDINV, GEDLL, GAMRND\n\n% Copyright: Ivana Komunjer \n% komunjer@hss.caltech.edu\n% Modifications Copyright:\n% Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 9/1/2005\n\nif nargin < 1,\n error('Requires at least one input argument.');\nend\n\nv(v<1)=NaN;\n\n[err, errtext, sizeOut] = iscompatible(1,v,varargin{:});\n\nif err\n error(errtext)\nend\n\n% Return NaN if the argument V is outside its limit.\nr = gamrnd(1./v,1,sizeOut);\nr = r.^(1./v);\nrndsgn = 2*((rand(sizeOut)>0.5)-0.5); % generates a random sign -1 or +1\nr = r.*rndsgn;\n\nscalex = (gamma(3./v)./gamma(1./v)).^0.5; % standardizes the obtained values\nr = r./scalex;", "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/distributions/gedrnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7470557584904637}} {"text": "function [M, Mx, My, Mz] = convectionTerm3D(u)\n% This function uses the central difference scheme to discretize a 2D\n% convection term in the form \\grad (u \\phi) where u is a face vactor\n% It also returns the x and y parts of the matrix of coefficient.\n%\n% SYNOPSIS:\n% [M, Mx, My, Mz] = convectionTerm3D(u)\n%\n% PARAMETERS:\n% u - FaceVariable \n%\n% RETURNS:\n%\n%\n% EXAMPLE:\n%\n% SEE ALSO:\n%\n\n% extract data from the mesh structure\nNx = u.domain.dims(1);\nNy = u.domain.dims(2);\nNz = u.domain.dims(3);\nG=reshape((1:(Nx+2)*(Ny+2)*(Nz+2)), Nx+2, Ny+2, Nz+2);\nDXe = repmat(u.domain.cellsize.x(3:end), 1, Ny, Nz);\nDXw = repmat(u.domain.cellsize.x(1:end-2), 1, Ny, Nz);\nDXp = repmat(u.domain.cellsize.x(2:end-1), 1, Ny, Nz);\nDYn = repmat(u.domain.cellsize.y(3:end)', Nx, 1, Nz);\nDYs = repmat(u.domain.cellsize.y(1:end-2)', Nx, 1, Nz);\nDYp = repmat(u.domain.cellsize.y(2:end-1)', Nx, 1, Nz);\nDZ = zeros(1,1,Nz+2);\nDZ(1,1,:) = u.domain.cellsize.z;\nDZf=repmat(DZ(1,1,3:end), Nx, Ny, 1);\nDZb=repmat(DZ(1,1,1:end-2), Nx, Ny, 1);\nDZp=repmat(DZ(1,1,2:end-1), Nx, Ny, 1);\n\n% define the vectors to stores the sparse matrix data\niix = zeros(3*(Nx+2)*(Ny+2)*(Nz+2),1);\njjx = zeros(3*(Nx+2)*(Ny+2)*(Nz+2),1);\nsx = zeros(3*(Nx+2)*(Ny+2)*(Nz+2),1);\niiy = zeros(3*(Nx+2)*(Ny+2)*(Nz+2),1);\njjy = zeros(3*(Nx+2)*(Ny+2)*(Nz+2),1);\nsy = zeros(3*(Nx+2)*(Ny+2)*(Nz+2),1);\niiz = zeros(3*(Nx+2)*(Ny+2)*(Nz+2),1);\njjz = zeros(3*(Nx+2)*(Ny+2)*(Nz+2),1);\nsz = zeros(3*(Nx+2)*(Ny+2)*(Nz+2),1);\nmnx = Nx*Ny*Nz;\tmny = Nx*Ny*Nz; mnz = Nx*Ny*Nz;\n\n% reassign the east, west, north, and south velocity vectors for the\n% code readability\nue = u.xvalue(2:Nx+1,:,:)./(DXp+DXe);\nuw = u.xvalue(1:Nx,:,:)./(DXp+DXw);\nvn = u.yvalue(:,2:Ny+1,:)./(DYp+DYn);\nvs = u.yvalue(:,1:Ny,:)./(DYp+DYs);\nwf = u.zvalue(:,:,2:Nz+1)./(DZp+DZf);\nwb = u.zvalue(:,:,1:Nz)./(DZp+DZb);\n\n% calculate the coefficients for the internal cells\nAE = reshape(ue,mnx,1);\nAW = reshape(-uw,mnx,1);\nAN = reshape(vn,mny,1);\nAS = reshape(-vs,mny,1);\nAF = reshape(wf,mnz,1);\nAB = reshape(-wb,mnz,1);\nAPx = reshape((ue.*DXe-uw.*DXw)./DXp,mnx,1);\nAPy = reshape((vn.*DYn-vs.*DYs)./DYp,mny,1);\nAPz = reshape((wf.*DZf-wb.*DZb)./DZp,mnz,1);\n\n% build the sparse matrix based on the numbering system\nrowx_index = reshape(G(2:Nx+1,2:Ny+1,2:Nz+1),mnx,1); % main diagonal x\niix(1:3*mnx) = repmat(rowx_index,3,1);\nrowy_index = reshape(G(2:Nx+1,2:Ny+1,2:Nz+1),mny,1); % main diagonal y\niiy(1:3*mny) = repmat(rowy_index,3,1);\nrowz_index = reshape(G(2:Nx+1,2:Ny+1,2:Nz+1),mnz,1); % main diagonal z\niiz(1:3*mnz) = repmat(rowz_index,3,1);\njjx(1:3*mnx) = [reshape(G(1:Nx,2:Ny+1,2:Nz+1),mnx,1); reshape(G(2:Nx+1,2:Ny+1,2:Nz+1),mnx,1); reshape(G(3:Nx+2,2:Ny+1,2:Nz+1),mnx,1)];\njjy(1:3*mny) = [reshape(G(2:Nx+1,1:Ny,2:Nz+1),mny,1); reshape(G(2:Nx+1,2:Ny+1,2:Nz+1),mny,1); reshape(G(2:Nx+1,3:Ny+2,2:Nz+1),mny,1)];\njjz(1:3*mnz) = [reshape(G(2:Nx+1,2:Ny+1,1:Nz),mnz,1); reshape(G(2:Nx+1,2:Ny+1,2:Nz+1),mnz,1); reshape(G(2:Nx+1,2:Ny+1,3:Nz+2),mnz,1)];\nsx(1:3*mnx) = [AW; APx; AE];\nsy(1:3*mny) = [AS; APy; AN];\nsz(1:3*mnz) = [AB; APz; AF];\n\n% build the sparse matrix\nkx = 3*mnx;\nky = 3*mny;\nkz = 3*mnz;\nMx = sparse(iix(1:kx), jjx(1:kx), sx(1:kx), (Nx+2)*(Ny+2)*(Nz+2), (Nx+2)*(Ny+2)*(Nz+2));\nMy = sparse(iiy(1:ky), jjy(1:ky), sy(1:ky), (Nx+2)*(Ny+2)*(Nz+2), (Nx+2)*(Ny+2)*(Nz+2));\nMz = sparse(iiz(1:kz), jjz(1:kz), sz(1:kz), (Nx+2)*(Ny+2)*(Nz+2), (Nx+2)*(Ny+2)*(Nz+2));\nM = Mx + My + Mz;\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Discretization/convectionTerm3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7470557567867762}} {"text": "% An example of nonnegative CP decomposition from partial observations\n%% Generate synthetic 4-order tensor\nrand('seed',0); randn('seed',0);\nN1 = 30; N2 = 30; N3 = 30; N4 = 30; % tensor dimension\nR = 10; % tensor rank\n\n% randomly generate factor matrices\nA1 = max(0,randn(N1,R));\nA2 = max(0,randn(N2,R));\nA3 = max(0,randn(N3,R));\nA4 = max(0,randn(N4,R));\n% generate tensor M using the above factor matrices\nM = ktensor({A1,A2,A3,A4});\nM = full((arrange(M)));\n\nsr = 0.4; % percentage of samples\n% randomly choose samples\nknown = randsample(N1*N2*N3*N4,round(sr*N1*N2*N3*N4));\ndata = M.data(known);\n\nsn = 60; % signal to noise\n% -- add noise --\nNoise = max(0,randn(size(data)));\ndata = data + 10^(-sn/20)*norm(data)/norm(Noise)*Noise;\nndim = [N1,N2,N3,N4];\n\n%% Solve problem\n% exact rank works but a rough rank overestimate is also fine\nesr = round(1.25*R); % overestimate of rank\nopts.tol = 1e-4; opts.maxit = 1000;\nt0 = tic;\n[A,Out] = ncpc(data,known,ndim,esr,opts);\ntime = toc(t0);\n\n%% Reporting\nrelerr = norm(full(A)-M)/norm(M);\nfprintf('time = %4.2e, ',time);\nfprintf('solution relative error = %4.2e\\n\\n',relerr);\n\nfigure;\nsemilogy(1:Out.iter, Out.hist_obj,'k-','linewidth',2);\nxlabel('iteration','fontsize',12);\nylabel('objective value','fontsize',12)\n\nfigure;\nsemilogy(1:Out.iter, Out.hist_rel(2,:),'k-','linewidth',2);\nxlabel('iteration','fontsize',12);\nylabel('relative residual','fontsize',12)\n\n%% ", "meta": {"author": "andrewssobral", "repo": "mctc4bmi", "sha": "fbcbcd25654b818646387c3d6a64304fb60e12dd", "save_path": "github-repos/MATLAB/andrewssobral-mctc4bmi", "path": "github-repos/MATLAB/andrewssobral-mctc4bmi/mctc4bmi-fbcbcd25654b818646387c3d6a64304fb60e12dd/algs_tc/NCPC/example_ncpc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347121, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7470557524971521}} {"text": "function [E, V] = VBA_dirichlet_moments (a)\n% // VBA toolbox //////////////////////////////////////////////////////////\n%\n% [E, V] = VBA_dirichlet_moments (a)\n% Derives the first- and second-order moments of a Dirichlet density\n%\n% IN:\n% - a: parameters of the Dirichlet distribution (pseudo-counts)\n% OUT:\n% - E: first-order moment (expectation)\n% - V: second-order moment (variance)\n%\n% /////////////////////////////////////////////////////////////////////////\n\n% Let X = (X_1, ..., X_k) ~ Dir(a)\n\n% shorthand\na0 = sum(a);\n\n% First-order moment E[X]\nE = a./a0;\n\n% second order moment Var[X]\nV = (a .* (a0-a)) ./ (a0.^2 * (a0+1)); ", "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/utils/VBA_dirichlet_moments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574299, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7470469786890647}} {"text": "function [ C ] = gsp_ngwft(G,f,g, param)\n%GSP_NGWFT Normalized graph windowed Fourier transform\n% Usage: G = gsp_ngwft(G,f,g, param);\n% G = gsp_ngwft(G,f,g);\n%\n% Input parameters:\n% G : Graph\n% f : Graph signal\n% g : window\n% param : Structure of optional parameter\n% Output parameters:\n% C : Coefficient\n%\n% This function compute the normalized graph windowed Fourier transform\n% of a signal *f* with the window *g*. The function returns a matrix of\n% size N^2*N. \n%\n% *param* a Matlab structure containing the following fields:\n% \n% * *param.verbose* : 0 no log, 1 print main steps, 2 print all steps.\n% By default, it is 1.\n% * *param.lowmemory* : use less memory. By default, it is 1.\n%\n\n% Author : Nathanael Perraudin\n% Testing: test_ngwft\n\n% Optional input arguments\nif nargin<4, param=struct; end\nif ~isfield(param, 'verbose'), param.verbose=1 ; end\nif ~isfield(param, 'lowmemory'), param.lowmemory=1 ; end\n\nif ~isfield(G,'U')\n error(['GSP_NGWFT: You need first to compute the Fourier basis\\n',...\n 'You can do it with the function gsp_compute_fourier_basis']);\nend\n\nif ~param.lowmemory\n % Compute the Frame into a big matrix\n Frame=gsp_ngwft_frame_matrix(G,g,param);\n\n C=Frame'*f;\n\n C=reshape(C,G.N,G.N);\nelse\n % Compute the translate of g\n ghat=G.U'*g;\n Ftrans=sqrt(G.N)*G.U*(repmat(ghat,1,G.N).*G.U');\n C=zeros(G.N);\n for ii=1:G.N\n atoms = (repmat(1./G.U(:,1),1,G.N) .* ...\n G.U.*repmat(Ftrans(:,ii),1,G.N))';\n % normalization\n atoms = atoms./ repmat(sqrt(sum(abs(atoms).^2,2)),1,G.N);\n C(:,ii)=atoms*f;\n end\n \nend\n\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/operators/gsp_ngwft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7469987219308493}} {"text": "% CAMCALD Camera calibration from data points\n%\n% C = CAMCALD(D) is the camera matrix (3x4) determined by least squares \n% from corresponding world and image-plane points. D is a table \n% of points with rows of the form [X Y Z U V] where (X,Y,Z) is the \n% coordinate of a world point and [U,V] is the corresponding image \n% plane coordinate. \n%\n% [C,E] = CAMCALD(D) as above but E is the maximum residual error after \n% back substitution [pixels]. \n% \n% Notes:\n% - This method assumes no lense distortion affecting the image plane\n% coordinates.\n%\n% See also CentralCamera.\n\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB 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% MVTB 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 MVTB. If not, see .\n\n\n\nfunction [C, resid] = camcald(XYZ, uv)\n\n if numcols(XYZ) ~= numcols(uv)\n error('must have same number of world and image-plane points');\n end\n\n n = numcols(XYZ);\n if n < 6,\n error('At least 6 points required for calibration');\n end\n%\n% build the matrix as per Ballard and Brown p.482\n%\n% the row pair are one row at this point\n%\n A = [ XYZ' ones(n,1) zeros(n,4) -repmat(uv(1,:)', 1,3).*XYZ' ...\n zeros(n,4) XYZ' ones(n,1) -repmat(uv(2,:)', 1,3).*XYZ' ];\n%\n% reshape the matrix, so that the rows interleave\n%\n A = reshape(A',11, n*2)';\n if rank(A) < 11,\n error('Rank deficient, perhaps points are coplanar or collinear');\n end\n\n B = reshape( uv, 1, n*2)';\n\n C = A\\B; % least squares solution\n resid = max(max(abs(A * C - B)));\n if resid > 1,\n warning('Residual greater than 1 pixel');\n end\n fprintf('maxm residual %f pixels.\\n', resid);\n C = reshape([C;1]',4,3)';\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/camcald.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7469986071798613}} {"text": "function [kden,N,K] = density_dir(CIJ)\n%DENSITY Density\n%\n% kden = density_dir(CIJ);\n% [kden,N,K] = density_dir(CIJ);\n%\n% Density is the fraction of present connections to possible connections.\n%\n% Input: CIJ, directed (weighted/binary) connection matrix\n%\n% Output: kden, density\n% N, number of vertices\n% K, number of edges\n%\n% Notes: Assumes CIJ is directed and has no self-connections.\n% Weight information is discarded.\n%\n%\n% Olaf Sporns, Indiana University, 2002/2007/2008\n\nN = size(CIJ,1);\nK = nnz(CIJ);\nkden = K/(N^2-N);\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/density_dir.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7469986070710147}} {"text": "function c = tapas_unitsq_sgm_config\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Contains the configuration for the unit square sigmoid observation model for binary responses\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% The unit square sigmoid (ussgm) is the function\n%\n% f(x) = x^zeta/(x^zeta + (1-x)^zeta) = ustapas_sgm(x; zeta),\n%\n% where x is in the unit interval, and zeta > 0 is a parameter that determines the shape of the\n% sigmoid. Since both its argument and value are always in the unit interval, its graph is\n% restricted to the unit square, hence the name unit square sigmoid.\n%\n% In the application here, the ussgm is the probability of observing a decision y=1 (rather than\n% the only alternative y=0) given the current probability mu1hat (or value) of input u=1:\n% \n% p(y=1|mu1hat) = ustapas_sgm(mu1hat; zeta)\n%\n% The parameter zeta regulates the steepness of the sigmoid such that it forms the diagonal of\n% the unit square for zeta=1 and approaches a step function at 0.5 as zeta approaches infinity.\n% Values of 0 < zeta < 1 lead to sigmoids with reverse concavity than usual, but they still\n% represent valid observation models.\n%\n% Zeta can be interpreted as inverse decision noise. To have a shrinkage prior on this, choose a\n% high value. It is estimated log-space since it has a natural lower bound at zero.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% 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 = 'tapas_unitsq_sgm';\n\n% Sufficient statistics of Gaussian parameter priors\n\n% Zeta\nc.logzemu = log(48);\nc.logzesa = 1;\n\n% Gather prior settings in vectors\nc.priormus = [\n c.logzemu,...\n ];\n\nc.priorsas = [\n c.logzesa,...\n ];\n\n% Model filehandle\nc.obs_fun = @tapas_unitsq_sgm;\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_unitsq_sgm_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_unitsq_sgm_config.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7469986030098043}} {"text": "function [v,r] = dquat2line(dq)\n\n% DQUAT2LINE Transforms a line position dual quaternion into \n% its vector representation (orientation + position).\n%\n% [V,R] = DQUAT2LINE(DQ) transforms the double quaternion\n% representation of a line position (in the euclidean space) into a\n% vector V which represents the line orientation (unitary vector) \n% and a vector R which is the coordinates of the nearest point from\n% the origin belonging to the line (it could be another r, it is\n% NOT unique).\n% DQ is either a vector of size 8 or an array of size 8*N (each\n% column represents a line position dual quaternion) where N is the\n% number of lines. V and R have the same size. They are either a\n% vector of size 3 or an array of size 3*N depending on the input\n% format.\n%\n% See also DQUAT2POS, DQUAT2VEL, DQUAT2LINEVEL, LINE2DQUAT \n\nif nargout < 2 || nargout > 2\n error('DualQuaternion:dquat2line:wrongNumberOfOutputs',...\n 'You specified %d outputs. It should be 2 (see documentation).',nargout);\nend\n\nsdq = size(dq);\nif sdq == [1 8], dq = dq'; sdq = size(dq); end\n\n% wrong format\nif sdq(1) ~= 8 \n error('DualQuaternion:dquat2line:wrongsize',...\n '%d rows in the DQ array. It should be 8.',sdq(1));\nend\n\n% check line position dual quaternion\ntol = 1e-6;\n[maxval,imax] = max(max(abs(dq([1 5],:))));\nif maxval > tol\n warning('DualQuaternion:dquat2line:wrongFormat',...\n 'At least one dual quaternion is not a line position dual quaternion (tol = %.1e).\\n Indices of max values: %d \\n Max value = %.2e',...\n tol,imax,maxval);\nend\n\n% extraction of the line position parameters, v and r\nv = dq(2:4,:);\nw = dq(6:8,:);\n\n% check if the norm of v is unitary (it should be)\nnormv2 = sum(v.^2);\n[maxval2,imax2] = max(normv2);\n[minval2,imin2] = min(normv2);\ni2 = union(imax2,imin2);\nif maxval2 > 1+tol || minval2 < 1-tol\n warning('DualQuaternion:dquat2line:wrongFormatNotUnitary',...\n 'At least one dual quaternion has not a unitary orientation ( is it a line position dual quaternion?) (tol = %.1e).\\n Indices of max values: %d \\n Min and Max value = [%.2e %.2e]',...\n tol,i2,minval2,maxval2);\nend\n% r is the position vector of the point belonging to the line such that\n% this point is the nearest point from the origin (it is orthogonal to the\n% line orientation)\nnormv2 = repmat(normv2,3,1);\nr = cross(v,w)./normv2;\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/39288-dual-quaternion-toolbox/Dual quaternion toolbox v2/dquat2line.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7469844450151236}} {"text": "clear all\nclf\n\nprojV=@(x,A)A*inv(A'*A)*A'*x;\nV1=[1 0 0]';\nV2=[1 1 0]';\n\n% Alternating projections.\nx=[0.5 1 1]';\nsubplot(121)\nplot3([0 V1(1)],[0 V1(2)],[0 V1(3)],'-b','LineWidth',2);hold on\nplot3([0 V2(1)],[0 V2(2)],[0 V2(3)],'-b','LineWidth',2);\nplot3(x(1),x(2),x(3),'.k','MarkerSize',20);\nfor i=1:5\n xV1=projV(x,V1);\n h=arrow(x,xV1,'Length',5);\n set(h,'LineStyle',':','EdgeColor','r','FaceColor','r');\n text(xV1(1),xV1(2),xV1(3),['P_{V_1}(x)'])\n x=projV(xV1,V2);\n h=arrow(xV1,x,'Length',5);\n text(x(1),x(2),x(3),['P_{V_2}(P_{V_1}(x))'])\n plot3(x(1),x(2),x(3),'.k','MarkerSize',20);\nend\naxis([0 1 0 1 0 1]);box on;axis equal;axis tight\ntitle('Alternating projections');\n\n% Average Alternating Reflections/DR.\nx=[0.5 1 1]';\nsubplot(122)\nplot3([-1 V1(1)],[0 V1(2)],[0 V1(3)],'-b','LineWidth',2);hold on\nplot3([-1 V2(1)],[-1 V2(2)],[0 V2(3)],'-b','LineWidth',2);\nplot3(x(1),x(2),x(3),'.k','MarkerSize',20);\nfor i=1:5\n xV1=2*projV(x,V1)-x;\n h=arrow(x,xV1,'Length',5);\n set(h,'LineStyle',':','EdgeColor','r','FaceColor','r');\n text(xV1(1),xV1(2),xV1(3),['R_{V_1}(x)'])\n xV2=2*projV(xV1,V2)-xV1;\n h=arrow(xV1,xV2,'Length',5);\n set(h,'LineStyle',':','EdgeColor','r','FaceColor','r');\n text(xV2(1),xV2(2),xV2(3),['R_{V_2}(R_{V_1}(x))'])\n x=(xV2+x)/2;\n arrow(xV2,x,'Length',5);\n text(x(1),x(2),x(3),['(R_{V_2}(R_{V_1}(x))+x)/2'])\n plot3(x(1),x(2),x(3),'.k','MarkerSize',20);\nend\naxis([-1 1 -1 1 -1 1]);box on;axis equal;axis tight\ntitle('Average Alternating Reflections/DR');\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_DRAP3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.746984420967704}} {"text": "% Signal Processing Q17734\n% https://dsp.stackexchange.com/questions/17734\n% Estimate the Discrete Fourier Series of a Signal with Missing Samples\n% References:\n% 1. aa\n% Remarks:\n% 1. sa\n% TODO:\n% \t1. ds\n% Release Notes\n% - 1.0.001 17/01/2021 Royi Avital RoyiAvital@yahoo.com\n% * First release.\n% - 1.0.000 20/07/2017\n% * First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 79;\nrun('InitScript.m');\n\nfigureIdx = 0;\nfigureCounterSpec = '%04d';\n\ngenerateFigures = OFF;\n\n\n%% Simulation Parameters\n\nnumSamples = 150;\nnumGivenSamples = 120; %.\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 dim = 0;\nend\n\n% get size of the input function\nsz = size(f);\n\n% check if input is 1D or user defined input dimension is given\nif dim || (nargout == 1 && (max(sz) == prod(sz)))\n \n % check if a single dn value is given, if not, extract the required\n % value\n if numel(dn) ~= 1\n dn = dn(dim);\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 wavenumbers\n kx = getWavenumbers(Nx, dn, dim);\n\n % calculate derivative and assign output \n varargout{1} = ifft( bsxfun(@times, (1i*kx).^deriv_order, fft(f, [], dim)) , [], dim, 'symmetric');\n \nelse\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 \n % check for the correct number of outputs\n if nargout ~= length(sz)\n error(['Incorrect number of output arguments for ' num2str(length(sz)) '-dimensional input matrix']);\n end\n\n % calculate the gradient for each non-singleton dimension\n for dim = 1:ndims(f)\n if sz(dim) > 1\n\n % get the wavenumbers\n kx = getWavenumbers(sz(dim), dn(dim), dim);\n\n % calculate derivative and assign output \n varargout{dim} = ifft( bsxfun(@times, (1i*kx).^deriv_order, fft(f, [], dim)) , [], dim, 'symmetric');\n\n else\n % assign the derivate for singleton dimensions to be 0\n varargout{dim} = 0;\n end\n end\nend\n\nfunction kx = getWavenumbers(Nx, dx, dim)\n% subfuction to compute the wavenumber vector\n\n% calculate the wavenumbers\nif rem(Nx, 2) == 0\n % grid dimension has an even number of points\n nx = ((-Nx/2:Nx/2-1)/Nx).';\nelse\n % grid dimension has an odd number of points\n nx = ((-(Nx-1)/2:(Nx-1)/2)/Nx).';\nend\nkx = ifftshift((2*pi/dx).*nx); \n\n% permute to be in the correction direction for use with bsxfun\nif dim == 1\n kx = reshape(kx, Nx, 1);\nelse\n kx = reshape(kx, [ones(1, dim - 1), Nx]);\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/gradientSpect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7468715841208982}} {"text": "function y = huber_pos( x, M, t )\n\n%HUBER_POS Monotonic huber penalty function.\n% For a vector X, HUBER_POS(X) computes the monotonic Huber-style function\n% \n% 0 if 0>=X\n% HUBER_POS(X) = X^2 if 0<=X<=1\n% 2*X-1 if X>=1\n%\n% HUBER_POS(X,M) is the monotonic Huber-style penalty function of\n% halfwidth M, M.^2.*HUBER_POS(X./M). M must be real and positive.\n%\n% HUBER_POS(X,M,T) computes the monotonic Huber-style penalty function \n% with halfwidth M and concomitant scale T:\n%\n% HUBER_POS(X,M,T) = T.*HUBER_POS(X./T,M) if T > 0\n% +Inf if T <= 0\n%\n% See the help file for HUBER for information about this usage.\n%\n% For matrices and N-D arrays, the penalty function is applied to each\n% element of X independently. M and T must be compatible with X in the same\n% sense as .*: one must be a scalar, or they must have identical size.\n%\n% Disciplined convex programming information:\n% HUBER_POS is jointly convex in X and T. It is nondecreasing in X and\n% nonincreasing in T. Therefore, when used in CVX specifications, X\n% must be convex and T must be concave (or affine). Both must be real.\n\n%\n% Check arguments\n%\n\nnarginchk(1,3);\nif ~isreal( x ),\n error( 'First argument must be real.' );\nend\nif nargin < 2,\n M = 1;\nelseif ~isreal( M ) || any( M( : ) <= 0 ),\n error( 'Second argument must be real and positive.' );\nend\nif nargin < 3,\n t = 1;\nelseif ~isreal( t ),\n error( 'Third argument must be real.' );\nend\nsz = cvx_size_check( x, M, t );\nif isempty( sz ),\n error( 'Sizes are incompatible.' );\nend\n\n%\n% Compute result\n%\n\ny = max( x, 0 );\nz = min( y, M );\ny = t .* z .* ( 2 * y - z );\nq = t <= 0;\nif nnz( q ),\n if length( t ) == 1,\n y = Inf * ones( sy );\n else\n y( q ) = Inf;\n end\nend\n\n% Copyright 2005-2016 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/functions/huber_pos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7468715760693805}} {"text": "function a = pascal3_inverse ( n, alpha )\n\n%*****************************************************************************80\n%\n%% PASCAL3_INVERSE returns the inverse of the PASCAL3 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Input, real ALPHA, the parameter.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n\n if ( i == 1 )\n\n if ( j == 1 )\n a(i,j) = 1.0;\n else\n a(i,j) = 0.0;\n end\n\n elseif ( j == 1 )\n\n a(i,j) = - alpha * a(i-1,j);\n\n else\n\n a(i,j) = a(i-1,j-1) - alpha * a(i-1,j);\n\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/pascal3_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045817875225, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7468715695474756}} {"text": "function op = prox_l1_deadzone( q, epsilon )\n\n%PROX_L1_DEADZONE L1 norm with deadzone [-eps,eps]\n% OP = PROX_L1_DEADZONE( q, eps ) implements the nonsmooth function\n% OP(X) = q*sum_i max(0,x-eps)+max(0,-x-eps) = q*sum_i\n% max(0,|x|-eps)\n% Q is optional; if omitted, Q=1 is assumed. But if Q is supplied,\n% then it must be a positive real scalar (or must be same size as X).\n%\n\n% New March 2 2016\n\nif nargin == 0,\n\tq = 1;\nelseif ~isnumeric( q ) || ~isreal( q ) || any( q(:) < 0 ) || all(q(:)==0) %|| numel( q ) ~= 1\n if q==0\n op = prox_0;\n warning('TFOCS:zeroQ','q=0 so returning the proximal operator for the zero function');\n return;\n else\n error( 'Argument must be positive.' );\n end\nend\n\n% This is Matlab and Octave compatible code\nop = tfocs_prox( @(x)f(q, epsilon,x), @(x,t)prox_f(q, epsilon,x,t) , 'vector' );\nend\n\n% These are now subroutines, that are NOT in the same scope\nfunction v = f(qq,epsilon, x)\n v = sum( qq(:).*max(0,abs(x(:))-epsilon), 1 );\nend\n\nfunction x = prox_f(qq,epsilon, x,t) \n% p = x if |x| tq\n% i.e., if |x|>eps, p = sign(x).*max( |x|-tq, eps )\n tq = t .* qq; \n x = sign(x).*( abs(x).*( abs(x)= epsilon) );\nend\n\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.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/prox_l1_deadzone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.7468683197422576}} {"text": "function [ n_data, c, x, fx ] = student_cdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% STUDENT_CDF_VALUES returns some values of the Student CDF.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Needs[\"Statistics`ContinuousDistributions`\"]\n% dist = StudentTDistribution [ df ]\n% CDF [ dist, x ]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 November 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% 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 C, is usually called the number of \n% degrees of freedom of the distribution. C is typically an \n% integer, but that is not essential. It is required that\n% C be strictly positive.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 13;\n\n c_vec = [ ...\n 1.0, 2.0, 3.0, 4.0, ...\n 5.0, 2.0, 5.0, 2.0, ...\n 5.0, 2.0, 3.0, 4.0, ...\n 5.0 ];\n\n fx_vec = [ ...\n 0.6000231200328521, ...\n 0.6001080279134390, ...\n 0.6001150934648930, ...\n 0.6000995134721354, ...\n 0.5999341989834830, ...\n 0.7498859393137811, ...\n 0.7500879487671045, ...\n 0.9500004222186464, ...\n 0.9499969138365968, ...\n 0.9900012348724744, ...\n 0.9900017619355059, ...\n 0.9900004567580596, ...\n 0.9900007637471291 ];\n\n x_vec = [ ...\n 0.325, ...\n 0.289, ...\n 0.277, ...\n 0.271, ...\n 0.267, ...\n 0.816, ...\n 0.727, ...\n 2.920, ...\n 2.015, ...\n 6.965, ...\n 4.541, ...\n 3.747, ...\n 3.365 ];\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 c = 0.0;\n x = 0.0;\n fx = 0.0;\n else\n c = c_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/student_cdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7468683146693841}} {"text": "function [ xtab, ytab, weight ] = hexagon_unit_set ( rule, order )\n\n%*****************************************************************************80\n%\n%% HEXAGON_UNIT_SET sets a quadrature rule inside the unit hexagon in 2D.\n%\n% Integration region:\n%\n% The definition is given in terms of THETA, the angle in degrees of the\n% vector (X,Y). The following six conditions apply, respectively,\n% between the bracketing values of THETA of 0, 60, 120, 180, 240,\n% 300, and 360.\n%\n% 0 <= Y <= - SQRT(3) * X + SQRT(3)\n% 0 <= Y <= SQRT(3)/2\n% 0 <= Y <= SQRT(3) * X + SQRT(3)\n% - SQRT(3) * X - SQRT(3) <= Y <= 0\n% - SQRT(3)/2 <= Y <= 0\n% SQRT(3) * X - SQRT(3) <= Y <= 0\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 18 March 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Abramowitz and Stegun,\n% Handbook of Mathematical Functions,\n% National Bureau of Standards, 1964.\n%\n% Arthur H Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971.\n%\n% Parameters:\n%\n% Input, integer RULE, the rule desired.\n% 1, 1 point, degree 1;\n% 2, 4 points, degree 3;\n% 3, 7 points, degree 3;\n% 4, 7 points, degree 5;\n%\n% Input, integer ORDER, the order of the desired rule.\n%\n% Output, real XTAB(ORDER), YTAB(ORDER), the abscissase.\n%\n% Output, real WEIGHT(ORDER), the weights.\n%\n if ( rule == 1 )\n\n xtab(1) = 0.0;\n ytab(1) = 0.0;\n weight(1) = 1.0;\n%\n% Stroud rule H2:3-1.\n%\n elseif ( rule == 2 )\n\n a = sqrt ( 5.0 / 12.0 );\n b = 1.0 / 4.0;\n z = 0.0;\n\n xtab(1:4) = [ a, -a, z, z ];\n ytab(1:4) = [ z, z, a, -a ];\n weight(1:4) = [ b, b, b, b ];\n%\n% Stroud rule H2:3-2.\n%\n elseif ( rule == 3 )\n\n a = sqrt ( 3.0 ) / 2.0;\n b = 0.5;\n c = 1.0;\n d = 5.0 / 72.0;\n e = 42.0 / 72.0;\n z = 0.0;\n\n xtab(1:7) = [ z, c, -c, b, -b, b, -b ];\n ytab(1:7) = [ z, z, z, a, a, -a, -a ];\n weight(1:7) = [ e, d, d, d, d, d, d ];\n%\n% Stroud rule H2:5-1.\n%\n elseif ( rule == 4 )\n\n a = sqrt ( 14.0 ) / 5.0;\n b = sqrt ( 14.0 ) / 10.0;\n c = sqrt ( 42.0 ) / 10.0;\n d = 125.0 / 1008.0;\n e = 258.0 / 1008.0;\n z = 0.0;\n\n xtab(1:7) = [ z, a, -a, b, -b, b, -b ];\n ytab(1:7) = [ z, z, z, c, c, -c, -c ];\n weight(1:7) = [ e, d, d, d, d, d, d ];\n\n else\n\n xtab = [];\n ytab = [];\n weight = [];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HEXAGON_UNIT_SET - Fatal error!\\n' );\n fprintf ( 1, ' Nonexistent rule number %d requested.\\n', rule );\n error ( 'HEXAGON_UNIT_SET - Fatal 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/stroud/hexagon_unit_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7468423247292473}} {"text": "function tw = trigauss_conversion ( xw, omega )\n\n%*****************************************************************************80\n%\n%% TRIGAUSS_CONVERSION converts Gauss to trigonometric Gauss quadrature.\n%\n% Modified:\n%\n% 19 May 2013\n%\n% Author:\n%\n% Gaspare Da Fies, Alvise Sommariva, Marco Vianello\n%\n% Parameters:\n%\n% Input, real XW(N,2), the points and weights of a Gauss quadrature rule\n% on [-1,+1].\n%\n% Input, real OMEGA, the arc angle, 0 < OMEGA <= PI.\n%\n% Output, real TW(N,2), the angles and weights for the trigonometic\n% quadrature rule over [-OMEGA,+OMEGA].\n%\n tw(:,1) = 2.0 * asin ( sin ( omega / 2.0 ) * xw(:,1) );\n tw(:,2) = xw(:,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/circle_segment/trigauss_conversion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7468423211838862}} {"text": "function fem2d_poisson_sparse ( prefix )\n\n%*****************************************************************************80\n%\n%% MAIN is the main routine for FEM2D_POISSON_SPARSE.\n%\n% Discussion:\n%\n% This program uses MATLAB's sparse matrix storage, factorization \n% and solution facilities to compute an approximate solution to\n% the Poisson equation via the finite element method.\n%\n% Three functions are changed from those in the FEM2D_POISSON code:\n% * the main program FEM2D_POISSON is replaced by FEM2D_POISSON_SPARSE.\n% * the routine ASSEMBLE_POISSON is replaced by ASSEMBLE_POISSON_SPARSE.\n% * the routine DIRICHLET_APPLY is replaced by DIRICHLET_APPLY_SPARSE.\n%\n% This program solves the Poisson equation\n%\n% -DEL H(X,Y) DEL U(X,Y) + K(X,Y) * U = F(X,Y)\n%\n% in a triangulated region in the plane.\n%\n% Along the boundary of the region, Dirichlet conditions\n% are imposed:\n%\n% U(X,Y) = G(X,Y)\n%\n% The code uses continuous piecewise linear basis functions on\n% triangles.\n%\n% Problem specification:\n%\n% The user defines the geometry by supplying two data files\n% which list the node coordinates, and list the nodes that make up\n% each element.\n%\n% The user specifies the right hand side of the Dirichlet boundary\n% conditions by supplying a function\n%\n% function node_bc = dirichlet_condition ( node_num, node_xy )\n%\n% The user specifies the coefficient function H(X,Y):\n%\n% function node_h = h_coef ( node_num, node_xy )\n%\n% The user specifies the coefficient function K(X,Y):\n%\n% function node_k = k_coef ( node_num, node_xy )\n%\n% The user specifies the right hand side of the Poisson equation\n% by supplying a routine of the form\n%\n% function node_rhs = rhs ( node_num, node_xy )\n%\n% Usage:\n%\n% fem2d_poisson_sparse ( 'prefix' )\n%\n% where:\n%\n% 'prefix' is the common prefix for the node and element files:\n%\n% * prefix_nodes.txt, the node coordinates.\n% * prefix_elements.txt, the nodes that make up each element.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 July 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Local parameters:\n%\n% Local, real sparse A(:,), the finite element coefficient matrix.\n%\n% Local, integer ELEMENT_NODE[3*ELEMENT_NUM];\n% ELEMENT_NODE(I,J) is the global index of local node I in element J.\n%\n% Local, integer ELEMENT_NUM, the number of elements.\n%\n% Local, integer ELEMENT_ORDER, the element order.\n%\n% Local, real F(NODE_NUM,1), the right hand side.\n%\n% Local, logical NODE_BOUNDARY(NODE_NUM), is TRUE if the node is\n% found to lie on the boundary of the region.\n%\n% Local, integer NODE_CONDITION(NODE_NUM),\n% indicates the condition used to determine the variable at a node.\n% 0, there is no condition (and no variable) at this node.\n% 1, a finite element equation is used;\n% 2, a Dirichlet condition is used.\n% 3, a Neumann condition is used.\n%\n% Local, integer NODE_NUM, the number of nodes.\n%\n% Local, real NODE_R(NODE_NUM), the residual error.\n%\n% Local, real NODE_U(NODE_NUM), the finite element coefficients.\n%\n% Local, real NODE_XY(2,NODE_NUM), the coordinates of nodes.\n%\n% Local, integer QUAD_NUM, the number of quadrature points used for\n% assembly. This is currently set to 3, the lowest reasonable value.\n% Legal values are 1, 3, 4, 6, 7, 9, 13, and for some problems, a value\n% of QUAD_NUM greater than 3 may be appropriate.\n%\n debugging = 0;\n quad_num = 3;\n\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_POISSON_SPARSE:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A version of FEM2D_POISSON using MATLAB''s \\n' );\n fprintf ( 1, ' sparse matrix storage, factor and solve facilities.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Finite element solution of the \\n' );\n fprintf ( 1, ' steady Poisson equation on a triangulated region\\n' );\n fprintf ( 1, ' in 2 dimensions.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' - DEL H(x,y) DEL U(x,y) + K(x,y) * U(x,y) = F(x,y) in the region\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' U(x,y) = G(x,y) on the boundary.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The finite element method is used,\\n' );\n fprintf ( 1, ' with triangular elements,\\n' );\n fprintf ( 1, ' which must be a 3 node linear triangle.\\n' );\n%\n% Must have prefix.\n%\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_POISSON_SPARSE - Fatal error!\\n' );\n fprintf ( 1, ' Missing \"prefix\", the common filename prefix input.\\n' );\n error ( 'FEM2D_POISSON_SPARSE - Fatal error!\\n' )\n end\n%\n% Create the file names.\n%\n node_filename = strcat ( prefix, '_nodes.txt' );\n element_filename = strcat ( prefix, '_elements.txt' );\n solution_filename = strcat ( prefix, '_values.txt' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Node file is \"%s\".\\n', node_filename );\n fprintf ( 1, ' Element file is \"%s\".\\n', element_filename );\n%\n% Read the node coordinate file.\n%\n node_xy = load ( node_filename );\n node_xy = node_xy';\n [ dim_num, node_num ] = size ( node_xy );\n\n fprintf ( 1, ' Number of nodes = %d\\n', node_num );\n\n r8mat_transpose_print_some ( dim_num, node_num, node_xy, 1, 1, 2, 10, ...\n ' First 10 nodes' );\n%\n% Read the element description file.\n%\n element_node = load ( element_filename );\n element_node = element_node';\n [ element_order, element_num ] = size ( element_node );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Element order = %d\\n', element_order );\n fprintf ( 1, ' Number of elements = %d\\n', element_num );\n\n if ( element_order ~= 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_POISSON_SPARSE - Fatal error!\\n' );\n fprintf ( 1, ' The input triangulation has order %d.\\n', element_order );\n fprintf ( 1, ' However, a triangulation of order 3 is required.' );\n error ( 'FEM2D_POISSON_SPARSE - Fatal error!' );\n end\n\n i4mat_transpose_print_some ( 3, element_num, ...\n element_node, 1, 1, 3, 10, ' First 10 elements' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Quadrature order = %d\\n', quad_num );\n%\n% Determine which nodes are boundary nodes and which have a\n% finite element unknown. Then set the boundary values.\n%\n node_boundary = triangulation_order3_boundary_node ( node_num, ...\n element_num, element_node );\n%\n% Determine the node conditions.\n% For now, we'll just assume all boundary nodes are Dirichlet.\n%\n node_condition(1:node_num) = 1;\n\n for node = 1 : node_num\n if ( node_boundary(node) )\n node_condition(node) = 2;\n end\n end\n%\n% Determine the element neighbor array, just so we can estimate\n% the nonzeros.\n%\n element_neighbor = triangulation_neighbor_triangles ( ...\n element_order, element_num, element_node );\n%\n% Determine the maximum number of nonzeros.\n%\n [ nz_num, adj_col ] = triangulation_order3_adj_count ( node_num, ...\n element_num, element_node, element_neighbor );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' TRIANGULATION_ORDER3_ADJ_COUNT returns NZ_NUM = %d\\n', ...\n nz_num );\n%\n% Assemble the finite element coefficient matrix A and the right-hand side F.\n%\n [ a, f ] = assemble_poisson_sparse ( node_num, node_xy, ...\n element_num, element_node, quad_num, nz_num );\n\n if ( debugging )\n\n a_copy = full ( a );\n r8mat_print_some ( node_num, node_num, a_copy, 1, 1, 10, 10, ...\n ' Part of Poisson stiffness matrix A:' );\n\n r8vec_print_some ( node_num, f, 1, 10, ...\n ' Part of finite element right hand side vector F:' );\n\n end\n%\n% Adjust the linear system to account for Dirichlet boundary conditions.\n%\n [ a, f ] = dirichlet_apply_sparse ( node_num, node_xy, node_condition, ...\n a, f );\n\n if ( debugging )\n\n a_copy = full ( a );\n r8mat_print_some ( node_num, node_num, a_copy, 1, 1, 10, 10, ...\n ' Part of Matrix A after Dirichlet boundary adjustments:' );\n\n r8mat_print_some ( node_num, 1, f, 1, 1, 10, 1, ...\n ' Part of right hand side after Dirichlet boundary adjustments:' );\n\n end\n%\n% Solve the linear system using MATLAB's sparse solver.\n%\n node_u = a \\ f;\n\n r8vec_print_some ( node_num, node_u, 1, 10, ...\n ' Part of the solution vector:' );\n\n node_r = residual_poisson ( node_num, node_xy, node_condition, ...\n element_num, element_node, quad_num, a, f, node_u );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Maximum absolute residual = %f\\n', ...\n max ( abs ( node_r(1:node_num) ) ) );\n%\n% Write an ASCII file that can be read into MATLAB.\n%\n save ( solution_filename, '-ascii', 'node_u' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_POISSON_SPARSE:\\n' );\n fprintf ( 1, ' Wrote solution to the file \"%s\"\\n', solution_filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM2D_POISSON_SPARSE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction [ a, f ] = assemble_poisson_sparse ( node_num, node_xy, ...\n element_num, element_node, quad_num, nz_num )\n\n%*****************************************************************************80\n%\n%% ASSEMBLE_POISSON_SPARSE assembles the system for the Poisson equation.\n%\n% Discussion:\n%\n% The matrix is stored in MATLAB sparse matrix format.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 July 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, real NODE_XY(2,NODE_NUM), the coordinates of nodes.\n%\n% Input, integer ELEMENT_NUM, the number of elements.\n%\n% Input, integer ELEMENT_NODE(3,ELEMENT_NUM);\n% element_NODE(I,J) is the global index of local node I in element J.\n%\n% Input, integer QUAD_NUM, the number of quadrature points used in assembly.\n%\n% Input, integer NZ_NUM, the (maximum) number of nonzeros in the matrix.\n% If set to 0 on input, we hope MATLAB's sparse utility will be able\n% to take over the task of reallocating space as necessary.\n%\n% Output, real sparse A(:,:), the coefficient matrix.\n%\n% Output, real F(NODE_NUM,1), the right hand side.\n%\n% Local parameters:\n%\n% Local, real BI, DBIDX, DBIDY, the value of some basis function\n% and its first derivatives at a quadrature point.\n%\n% Local, real BJ, DBJDX, DBJDY, the value of another basis\n% function and its first derivatives at a quadrature point.\n%\n\n%\n% Initialize the arrays to zero.\n%\n f(1:node_num,1) = 0.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ASSEMBLE_POISSON_SPARSE:\\n' );\n fprintf ( 1, ' Setting up sparse Poisson matrix with NZ_NUM = %d\\n', nz_num );\n\n a = sparse ( [], [], [], node_num, node_num, nz_num );\n%\n% Get the quadrature weights and nodes.\n%\n [ quad_w, quad_xy ] = quad_rule ( quad_num );\n%\n% Add up all quantities associated with the element-th element.\n%\n for element = 1 : element_num\n%\n% Make a copy of the element.\n%\n t3(1:2,1:3) = node_xy(1:2,element_node(1:3,element));\n%\n% Map the quadrature points QUAD_XY to points PHYS_XY in the physical element.\n%\n phys_xy(1:2,1:quad_num) = reference_to_physical_t3 ( t3, quad_num, quad_xy );\n\n area = abs ( triangle_area_2d ( t3 ) );\n\n w(1:quad_num,1) = quad_w(1:quad_num,1) * area;\n\n phys_rhs = rhs ( quad_num, phys_xy );\n phys_h = h_coef ( quad_num, phys_xy );\n phys_k = k_coef ( quad_num, phys_xy );\n%\n% Consider the QUAD-th quadrature point..\n%\n for quad = 1 : quad_num\n%\n% Consider the TEST-th test function.\n%\n% We generate an integral for every node associated with an unknown.\n% But if a node is associated with a boundary condition, we do nothing.\n%\n for test = 1 : 3\n\n i = element_node(test,element);\n\n [ bi, dbidx, dbidy ] = basis_11_t3 ( t3, test, phys_xy(1:2,quad) );\n\n f(i,1) = f(i,1) + w(quad,1) * phys_rhs(quad,1) * bi;\n%\n% Consider the BASIS-th basis function, which is used to form the\n% value of the solution function.\n%\n for basis = 1 : 3\n\n j = element_node(basis,element);\n\n [ bj, dbjdx, dbjdy ] = basis_11_t3 ( t3, basis, phys_xy(1:2,quad) );\n\n a(i,j) = a(i,j) + w(quad,1) * ( ...\n phys_h(quad) * ( dbidx * dbjdx + dbidy * dbjdy ) ...\n + phys_k(quad) * bj * bi );\n\n end\n\n end\n\n end\n\n end\n\n return\nend\nfunction [ qi, dqidx, dqidy ] = basis_11_t3 ( t, i, p )\n\n%*****************************************************************************80\n%\n%% BASIS_11_T3: one basis at one point for the T3 element.\n%\n% Discussion:\n%\n% The routine is given the coordinates of the nodes of a triangle.\n%\n% 3\n% / \\\n% / \\\n% / \\\n% 1-------2\n%\n% It evaluates the linear basis function Q(I)(X,Y) associated with\n% node I, which has the property that it is a linear function\n% which is 1 at node I and zero at the other two nodes.\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% Input, real T(2,3), the coordinates of the nodes.\n%\n% Input, integer I, the index of the desired basis function.\n% I should be between 1 and 3.\n%\n% Input, real P(2), the coordinates of a point at which the basis\n% function is to be evaluated.\n%\n% Output, real QI, DQIDX, DQIDY, the values of the basis function\n% and its X and Y derivatives.\n%\n area = abs ( 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 if ( area == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BASIS_11_T3 - Fatal error!\\n' );\n fprintf ( 1, ' Element has zero area.\\n' );\n error ( 'BASIS_11_T3 - Fatal error!' );\n end\n\n if ( i < 1 | 3 < i )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BASIS_11_T3 - Fatal error!\\n' );\n fprintf ( 1, ' Basis index I is not between 1 and 3.\\n' );\n fprintf ( 1, ' I = %d\\n', i );\n error ( 'BASIS_11_T3 - Fatal error!' );\n end\n\n if ( i == 1 )\n ip1 = 2;\n ip2 = 3;\n elseif ( i == 2 )\n ip1 = 3;\n ip2 = 1;\n else\n ip1 = 1;\n ip2 = 2;\n end\n\n qi = ( ( t(1,ip2) - t(1,ip1) ) * ( p(2) - t(2,ip1) ) ...\n - ( t(2,ip2) - t(2,ip1) ) * ( p(1) - t(1,ip1) ) ) / area;\n\n dqidx = - ( t(2,ip2) - t(2,ip1) ) / area;\n dqidy = ( t(1,ip2) - t(1,ip1) ) / area;\n\n return\nend\nfunction [ a, f ] = dirichlet_apply_sparse ( node_num, node_xy, ...\n node_condition, a, f )\n\n%*****************************************************************************80\n%\n%% DIRICHLET_APPLY_SPARSE accounts for Dirichlet boundary conditions.\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% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, real NODE_XY(2,NODE_NUM), the coordinates of nodes.\n%\n% Input, integer NODE_CONDITION(NODE_NUM), reports the condition\n% used to set the unknown associated with the node.\n% 0, unknown.\n% 1, finite element equation.\n% 2, Dirichlet condition;\n% 3, Neumann condition.\n%\n% Input, real sparse A(:,:), the coefficient matrix.\n%\n% Input, real F(NODE_NUM,1), the right hand side.\n%\n% Output, real sparse A(:,:), the coefficient matrix,\n% adjusted for Dirichlet boundary conditions.\n%\n% Output, real F(NODE_NUM), the right hand side, adjusted for\n% Dirichlet boundary conditions.\n%\n node_bc = dirichlet_condition ( node_num, node_xy );\n\n DIRICHLET = 2;\n\n for node = 1 : node_num\n\n if ( node_condition(node) == DIRICHLET )\n\n a(node,:) = 0.0;\n a(node,node) = 1.0;\n\n f(node,1) = node_bc(node);\n\n end\n\n end\n\n return\nend\nfunction isgn = i4col_compare ( m, n, a, i, j )\n\n%*****************************************************************************80\n%\n%% I4COL_COMPARE compares columns I and J of a integer array.\n%\n% Example:\n%\n% Input:\n%\n% M = 3, N = 4, I = 2, J = 4\n%\n% A = (\n% 1 2 3 4\n% 5 6 7 8\n% 9 10 11 12 )\n%\n% Output:\n%\n% ISGN = -1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 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 array of N columns of vectors of length M.\n%\n% Input, integer I, J, the columns to be compared.\n% I and J must be between 1 and N.\n%\n% Output, integer ISGN, the results of the comparison:\n% -1, column I < column J,\n% 0, column I = column J,\n% +1, column J < column I.\n%\n\n%\n% Check.\n%\n if ( i < 1)\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4COL_COMPARE - Fatal error!\\n' );\n fprintf ( 1, ' Column index I = %d < 1.\\n', i );\n error ( 'I4COL_COMPARE - Fatal error!' );\n end\n\n if ( n < i )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4COL_COMPARE - Fatal error!\\n' );\n fprintf ( 1, ' N = %d < column index I = %d.\\n', n, i );\n error ( 'I4COL_COMPARE - Fatal error!' );\n end\n\n if ( j < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4COL_COMPARE - Fatal error!\\n' );\n fprintf ( 1, ' Column index J = %d < 1.\\n', j );\n error ( 'I4COL_COMPARE - Fatal error!' );\n end\n\n if ( n < j )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4COL_COMPARE - Fatal error!\\n' );\n fprintf ( 1, ' N = %d < column index J = %d.\\n', n, j );\n error ( 'I4COL_COMPARE - Fatal error!' );\n end\n\n isgn = 0;\n\n if ( i == j )\n return\n end\n\n k = 1;\n\n while ( k <= m )\n\n if ( a(k,i) < a(k,j) )\n isgn = -1;\n return\n elseif ( a(k,j) < a(k,i) )\n isgn = +1;\n return\n end\n\n k = k + 1;\n\n end\n\n return\nend\nfunction a = i4col_sort_a ( m, n, a )\n\n%*****************************************************************************80\n%\n%% I4COL_SORT_A ascending sorts an I4COL.\n%\n% Discussion:\n%\n% In lexicographic order, the statement \"X < Y\", applied to two real\n% vectors X and Y of length M, means that there is some index I, with\n% 1 <= I <= M, with the property that\n%\n% X(J) = Y(J) for J < I,\n% and\n% X(I) < Y(I).\n%\n% In other words, the first time they differ, X is smaller.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows of A, and the length of\n% a vector of data.\n%\n% Input, integer N, the number of columns of A.\n%\n% Input, integer A(M,N), the array of N columns of M-vectors.\n%\n% Output, integer A(M,N), the columns of A have been sorted in ascending\n% lexicographic order.\n%\n if ( m <= 0 )\n return\n end\n\n if ( n <= 1 )\n return\n end\n%\n% Initialize.\n%\n i = 0;\n indx = 0;\n isgn = 0;\n j = 0;\n%\n% Call the external heap sorter.\n%\n while ( 1 )\n\n [ indx, i, j ] = sort_heap_external ( n, indx, isgn );\n%\n% Interchange the I and J objects.\n%\n if ( 0 < indx )\n\n a = i4col_swap ( m, n, a, i, j );\n%\n% Compare the I and J objects.\n%\n elseif ( indx < 0 )\n\n isgn = i4col_compare ( m, n, a, i, j );\n\n elseif ( indx == 0 )\n\n break\n\n end\n\n end\n\n return\nend\nfunction a = i4col_swap ( m, n, a, i, j )\n\n%*****************************************************************************80\n%\n%% I4COL_SWAP swaps columns I and J of a integer array of column data.\n%\n% Example:\n%\n% Input:\n%\n% M = 3, N = 4, I = 2, J = 4\n%\n% A = (\n% 1 2 3 4\n% 5 6 7 8\n% 9 10 11 12 )\n%\n% Output:\n%\n% A = (\n% 1 4 3 2\n% 5 8 7 6\n% 9 12 11 10 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns in the array.\n%\n% Input, integer A(M,N), an array of N columns of length M.\n%\n% Input, integer I, J, the columns to be swapped.\n%\n% Output, integer A(M,N), the array, with columns I and J swapped.\n%\n if ( i < 1 | n < i | j < 1 | n < j )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4COL_SWAP - Fatal error!\\n' );\n fprintf ( 1, ' I or J is out of bounds.\\n' );\n fprintf ( 1, ' I = %d\\n', i );\n fprintf ( 1, ' J = %d\\n', j );\n fprintf ( 1, ' N = %d\\n', n );\n error ( 'I4COL_SWAP - Fatal error!' );\n end\n\n if ( i == j )\n return\n end\n\n col(1:m) = a(1:m,i)';\n a(1:m,i) = a(1:m,j);\n a(1:m,j) = col(1:m)';\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 [ quad_w, quad_xy ] = quad_rule ( quad_num )\n\n%*****************************************************************************80\n%\n%% QUAD_RULE sets the quadrature rule for assembly.\n%\n% Discussion:\n%\n% The quadrature rule is given for a reference element, points (X,Y) such\n% that\n%\n% 0 <= X,\n% 0 <= Y, and\n% X + Y <= 1.\n%\n% ^\n% 1 | *\n% | |\\\n% Y | | \\\n% | | \\\n% 0 | *---*\n% +------->\n% 0 X 1\n%\n% The rules have the following precision:\n%\n% QUAD_NUM Precision\n%\n% 1 1\n% 3 2\n% 4 3\n% 6 4\n% 7 5\n% 9 6\n% 13 7\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% Input, integer QUAD_NUM, the number of quadrature nodes.\n% Legal values are 1, 3, 4, 6, 7, 9, 13.\n%\n% Output, real QUAD_W(QUAD_NUM,1), the quadrature weights.\n%\n% Output, real QUAD_XY(2,QUAD_NUM), the quadrature nodes.\n%\n if ( quad_num == 1 )\n\n quad_xy(1:2,1:quad_num) = [ 1.0 / 3.0, 1.0 / 3.0 ]';\n\n quad_w(1:quad_num,1) = 1.0;\n\n elseif ( quad_num == 3 )\n\n quad_xy(1:2,1:quad_num) = [ ...\n 0.5, 0.0; ...\n 0.5, 0.5; ...\n 0.0, 0.5 ]';\n\n quad_w(1:quad_num,1) = 1.0 / 3.0;\n\n elseif ( quad_num == 4 )\n\n a = 6.0;\n b = 10.0;\n c = 18.0;\n d = 25.0;\n e = -27.0;\n f = 30.0;\n g = 48.0;\n\n quad_xy(1:2,1:quad_num) = [ ...\n b, b; ...\n c, a; ...\n a, c; ...\n a, a ]' / f;\n\n quad_w(1:quad_num,1) = [ e, d, d, d ]' / g;\n\n elseif ( quad_num == 6 )\n\n a = 0.816847572980459;\n b = 0.091576213509771;\n c = 0.108103018168070;\n d = 0.445948490915965;\n v = 0.109951743655322;\n w = 0.223381589678011;\n\n quad_xy(1:2,1:quad_num) = [\n a, b; ...\n b, a; ...\n b, b; ...\n c, d; ...\n d, c; ...\n d, d ]';\n\n quad_w(1:6,1) = [ v, v, v, w, w, w ]';\n\n elseif ( quad_num == 7 )\n\n a = 1.0 / 3.0;\n b = ( 9.0 + 2.0 * sqrt ( 15.0 ) ) / 21.0;\n c = ( 6.0 - sqrt ( 15.0 ) ) / 21.0;\n d = ( 9.0 - 2.0 * sqrt ( 15.0 ) ) / 21.0;\n e = ( 6.0 + sqrt ( 15.0 ) ) / 21.0;\n u = 0.225;\n v = ( 155.0 - sqrt ( 15.0 ) ) / 1200.0;\n w = ( 155.0 + sqrt ( 15.0 ) ) / 1200.0;\n\n quad_xy(1:2,1:quad_num) = [ ...\n a, a; ...\n b, c; ...\n c, b; ...\n c, c; ...\n d, e; ...\n e, d; ...\n e, e ]';\n\n quad_w(1:quad_num,1) = [ u, v, v, v, w, w, w ]';\n\n elseif ( quad_num == 9 )\n\n a = 0.124949503233232;\n b = 0.437525248383384;\n c = 0.797112651860071;\n d = 0.165409927389841;\n e = 0.037477420750088;\n\n u = 0.205950504760887;\n v = 0.063691414286223;\n\n quad_xy(1:2,1:quad_num) = [ ...\n a, b; ...\n b, a; ...\n b, b; ...\n c, d; ...\n c, e; ...\n d, c; ...\n d, e; ...\n e, c; ...\n e, d ]';\n\n quad_w(1:quad_num,1) = [ u, u, u, v, v, v, v, v, v ]';\n\n elseif ( quad_num == 13 )\n\n h = 1.0 / 3.0;\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\n w = -0.149570044467670;\n t = 0.175615257433204;\n u = 0.053347235608839;\n v = 0.077113760890257;\n\n quad_xy(1:2,1:quad_num) = [\n h, h; ...\n a, b; ...\n b, a; ...\n b, b; ...\n c, d; ...\n d, c; ...\n d, d; ...\n e, f; ...\n e, g; ...\n f, e; ...\n f, g; ...\n g, e; ...\n g, f ]';\n\n quad_w(1:quad_num,1) = [ w, t, t, t, u, u, u, v, v, v, v, v, v ]';\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QUAD_RULE - Fatal error!\\n' );\n fprintf ( 1, ' No rule is available of order QUAD_NUM = %d\\n', ...\n quad_num );\n error ( 'QUAD_RULE - Fatal error!\\n' );\n\n end\n\n return\nend\nfunction r8mat_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )\n\n%*****************************************************************************80\n%\n%% R8MAT_PRINT_SOME prints out a portion of an R8MAT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns of the matrix.\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, a title.\n%\n incx = 5;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n\n for j2lo = max ( jlo, 1 ): incx : min ( jhi, n )\n\n j2hi = j2lo + incx - 1;\n j2hi = min ( j2hi, n );\n j2hi = min ( j2hi, jhi );\n\n inc = j2hi + 1 - j2lo;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Col: ' );\n\n for j = j2lo : j2hi\n fprintf ( 1, '%7d ', j );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Row\\n' );\n\n i2lo = max ( ilo, 1 );\n i2hi = min ( ihi, m );\n\n for i = i2lo : i2hi\n\n fprintf ( 1, '%7d ', i );\n\n for j = j2lo : j2hi\n fprintf ( 1, '%12g ', a(i,j) );\n end\n\n fprintf ( 1, '\\n' );\n\n end\n\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, a title.\n%\n incx = 5;\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\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 r8vec_print_some ( n, a, i_lo, i_hi, title )\n\n%*****************************************************************************80\n%\n%% R8VEC_PRINT_SOME prints \"some\" of an R8VEC.\n%\n% Discussion:\n%\n% An R8VEC is a vector of R8 values.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 October 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the dimension of the vector.\n%\n% Input, real A(N), the vector to be printed.\n%\n% Input, integer MAX_PRINT, the maximum number of lines to print.\n%\n% Input, string TITLE, a title.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, '%s\\n', title );\n fprintf ( 1, '\\n' );\n\n for i = max ( 1, i_lo ) : min ( n, i_hi )\n fprintf ( 1, ' %8d %12f\\n', i, a(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 literally halfway along the sides of\n% the physical triangle.\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 February 2003\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 objects 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 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 node_r = residual_poisson ( node_num, node_xy, node_condition, ...\n element_num, element_node, quad_num, a, f, node_u )\n\n%*****************************************************************************80\n%\n%% RESIDUAL_POISSON evaluates the residual for the Poisson equation.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 July 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, real NODE_XY(2,NODE_NUM), the\n% coordinates of nodes.\n%\n% Input, integer NODE_CONDITION(NODE_NUM), reports the condition\n% used to set the unknown associated with the node.\n% 0, unknown.\n% 1, finite element equation.\n% 2, Dirichlet condition;\n% 3, Neumann condition.\n%\n% Input, integer ELEMENT_NUM, the number of elements.\n%\n% Input, integer ELEMENT_NODE(3,ELEMENT_NUM);\n% ELEMENT_NODE(I,J) is the global index of local node I in element J.\n%\n% Input, integer QUAD_NUM, the number of quadrature points used in assembly.\n%\n% Input, integer INDX(NODE_NUM), gives the index of the unknown quantity\n% associated with the given node.\n%\n% Workspace, real sparse A(:,:), the NODE_NUM by NODE_NUM\n% coefficient matrix, stored in MATLAB sparse format.\n%\n% Workspace, real F(NODE_NUM,1), the right hand side.\n%\n% Input, real NODE_U(NODE_NUM), the value of the solution\n% at each node.\n%\n% Output, real NODE_R(NODE_NUM), the finite element\n% residual at each node.\n%\n% Local parameters:\n%\n% Local, real BI, DBIDX, DBIDY, the value of some basis function\n% and its first derivatives at a quadrature point.\n%\n% Local, real BJ, DBJDX, DBJDY, the value of another basis\n% function and its first derivatives at a quadrature point.\n%\n\n%\n% Initialize the arrays to zero.\n%\n f(1:node_num,1) = 0.0;\n a(:,:) = 0.0;\n%\n% Get the quadrature weights and nodes.\n%\n [ quad_w, quad_xy ] = quad_rule ( quad_num );\n%\n% The actual values of A and F are determined by summing up\n% contributions from all the elements.\n%\n for element = 1 : element_num\n%\n% Make a copy of the element.\n%\n t3(1:2,1:3) = node_xy(1:2,element_node(1:3,element));\n%\n% Map the quadrature points QUAD_XY to points PHYS_XY in the physical element.\n%\n phys_xy(1:2,1:quad_num) = reference_to_physical_t3 ( t3, quad_num, quad_xy );\n area = abs ( triangle_area_2d ( t3 ) );\n w(1:quad_num) = area * quad_w(1:quad_num);\n\n phys_rhs = rhs ( quad_num, phys_xy );\n phys_h = h_coef ( quad_num, phys_xy );\n phys_k = k_coef ( quad_num, phys_xy );\n%\n% Consider a quadrature point QUAD, with coordinates (X,Y).\n%\n for quad = 1 : quad_num\n%\n% Consider one of the basis functions, which will play the\n% role of test function in the integral.\n%\n% We generate an integral for every node associated with an unknown.\n% But if a node is associated with a boundary condition, we do nothing.\n%\n for test = 1 : 3\n\n i = element_node(test,element);\n\n [ bi, dbidx, dbidy ] = basis_11_t3 ( t3, test, phys_xy(1:2,quad) );\n\n f(i,1) = f(i,1) + w(quad) * phys_rhs(quad) * bi;\n%\n% Consider another basis function, which is used to form the\n% value of the solution function.\n%\n for basis = 1 : 3\n\n j = element_node(basis,element);\n\n [ bj, dbjdx, dbjdy ] = basis_11_t3 ( t3, basis, phys_xy(1:2,quad) );\n\n a(i,j) = a(i,j) + w(quad) * ( ...\n phys_h(quad) * ( dbidx * dbjdx + dbidy * dbjdy ) ...\n + phys_k(quad) * bj * bi );\n\n end\n\n end\n\n end\n\n end\n%\n% Apply boundary conditions.\n%\n [ a, f ] = dirichlet_apply_sparse ( node_num, node_xy, node_condition, a, f );\n%\n% Compute A*U.\n%\n node_r = a * node_u;\n%\n% Set RES = A * U - F.\n%\n node_r(1:node_num) = node_r(1:node_num) - f(1:node_num,1);\n\n return\nend\nfunction [ indx, i, j ] = sort_heap_external ( n, indx, isgn )\n\n%*****************************************************************************80\n%\n%% SORT_HEAP_EXTERNAL externally sorts a list of items into ascending order.\n%\n% Discussion:\n%\n% The actual list of data is not passed to the routine. Hence this\n% routine may be used to sort integers, reals, numbers, names,\n% dates, shoe sizes, and so on. After each call, the routine asks\n% the user to compare or interchange two items, until a special\n% return value signals that the sorting is completed.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Albert Nijenhuis, Herbert Wilf.\n% Combinatorial Algorithms,\n% Academic Press, 1978, second edition,\n% ISBN 0-12-519260-6.\n%\n% Parameters:\n%\n% Input, integer N, the number of items to be sorted.\n%\n% Input, integer INDX, the main communication signal.\n% The user must set INDX to 0 before the first call.\n% Thereafter, the user should set the input value of INDX\n% to the output value from the previous call.\n%\n% Input, integer ISGN, results of comparison of elements I and J.\n% (Used only when the previous call returned INDX less than 0).\n% ISGN <= 0 means I is less than or equal to J;\n% 0 <= ISGN means I is greater than or equal to J.\n%\n% Output, integer INDX, the main communication signal.\n% If INDX is\n%\n% greater than 0, the user should:\n% * interchange items I and J;\n% * call again.\n%\n% less than 0, the user should:\n% * compare items I and J;\n% * set ISGN = -1 if I < J, ISGN = +1 if J < I;\n% * call again.\n%\n% equal to 0, the sorting is done.\n%\n% Output, integer I, J, the indices of two items.\n% On return with INDX positive, elements I and J should be interchanged.\n% On return with INDX negative, elements I and J should be compared, and\n% the result reported in ISGN on the next call.\n%\n persistent i_save;\n persistent j_save;\n persistent k;\n persistent k1;\n persistent n1;\n\n if ( isempty ( i_save ) )\n i_save = -1;\n end\n\n if ( isempty ( j_save ) )\n j_save = -1;\n end\n%\n% INDX = 0: This is the first call.\n%\n if ( indx == 0 )\n\n k = floor ( n / 2 );\n k1 = k;\n n1 = n;\n%\n% INDX < 0: The user is returning the results of a comparison.\n%\n elseif ( indx < 0 )\n\n if ( indx == -2 )\n\n if ( isgn < 0 )\n i_save = i_save + 1;\n end\n\n j_save = k1;\n k1 = i_save;\n indx = -1;\n i = i_save;\n j = j_save;\n return;\n end\n\n if ( 0 < isgn )\n indx = 2;\n i = i_save;\n j = j_save;\n return;\n end\n\n if ( k <= 1 )\n\n if ( n1 == 1 )\n i_save = 0;\n j_save = 0;\n indx = 0;\n else\n i_save = n1;\n n1 = n1 - 1;\n j_save = 1;\n indx = 1;\n end\n\n i = i_save;\n j = j_save;\n return;\n\n end\n\n k = k - 1;\n k1 = k;\n%\n% 0 < INDX, the user was asked to make an interchange.\n%\n elseif ( indx == 1 )\n\n k1 = k;\n\n end\n\n while ( 1 )\n\n i_save = 2 * k1;\n\n if ( i_save == n1 )\n j_save = k1;\n k1 = i_save;\n indx = -1;\n i = i_save;\n j = j_save;\n return;\n elseif ( i_save <= n1 )\n j_save = i_save + 1;\n indx = -2;\n i = i_save;\n j = j_save;\n return;\n end\n\n if ( k <= 1 )\n break;\n end\n\n k = k - 1;\n k1 = k;\n\n end\n\n if ( n1 == 1 )\n i_save = 0;\n j_save = 0;\n indx = 0;\n i = i_save;\n j = j_save;\n else\n i_save = n1;\n n1 = n1 - 1;\n j_save = 1;\n indx = 1;\n i = i_save;\n j = j_save;\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\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% 14 February 2003\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 triangle_neighbor = triangulation_neighbor_triangles ( ...\n triangle_order, triangle_num, triangle_node )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_NEIGHBOR_TRIANGLES determines triangle neighbors.\n%\n% Discussion:\n%\n% A triangulation of a set of nodes can be completely described by\n% the coordinates of the nodes, and the list of nodes that make up\n% each triangle. However, in some cases, it is necessary to know\n% triangle adjacency information, that is, which triangle, if any,\n% is adjacent to a given triangle on a particular side.\n%\n% This routine creates a data structure recording this information.\n%\n% The primary amount of work occurs in sorting a list of 3 * TRIANGLE_NUM\n% data items.\n%\n% This routine was modified to use columns instead of rows.\n%\n% Example:\n%\n% The input information from TRIANGLE_NODE:\n%\n% Triangle Nodes\n% -------- ---------------\n% 1 3 4 1\n% 2 3 1 2\n% 3 3 2 8\n% 4 2 1 5\n% 5 8 2 13\n% 6 8 13 9\n% 7 3 8 9\n% 8 13 2 5\n% 9 9 13 7\n% 10 7 13 5\n% 11 6 7 5\n% 12 9 7 6\n% 13 10 9 6\n% 14 6 5 12\n% 15 11 6 12\n% 16 10 6 11\n%\n% The output information in TRIANGLE_NEIGHBOR:\n%\n% Triangle Neighboring Triangles\n% -------- ---------------------\n%\n% 1 -1 -1 2\n% 2 1 4 3\n% 3 2 5 7\n% 4 2 -1 8\n% 5 3 8 6\n% 6 5 9 7\n% 7 3 6 -1\n% 8 5 4 10\n% 9 6 10 12\n% 10 9 8 11\n% 11 12 10 14\n% 12 9 11 13\n% 13 -1 12 16\n% 14 11 -1 15\n% 15 16 14 -1\n% 16 13 15 -1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 September 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer TRIANGLE_ORDER, the order of the triangles.\n%\n% Input, integer TRIANGLE_NUM, the number of triangles.\n%\n% Input, integer TRIANGLE_NODE(TRIANGLE_ORDER,TRIANGLE_NUM), the nodes that\n% make up each triangle.\n%\n% Output, integer TRIANGLE_NEIGHBOR(3,TRIANGLE_NUM), the three triangles\n% that are direct neighbors of a given triangle. TRIANGLE_NEIGHBOR(1,I) is\n% the index of the triangle which touches side 1, defined by nodes 2 and 3,\n% and so on. TRIANGLE_NEIGHBOR(1,I) is negative if there is no neighbor\n% on that side. In this case, that side of the triangle lies on the\n% boundary of the triangulation.\n%\n\n%\n% Step 1.\n% From the list of nodes for triangle T, of the form: (I,J,K)\n% construct the three neighbor relations:\n%\n% (I,J,3,T) or (J,I,3,T),\n% (J,K,1,T) or (K,J,1,T),\n% (K,I,2,T) or (I,K,2,T)\n%\n% where we choose (I,J,3,T) if I < J, or else (J,I,3,T)\n%\n col = zeros ( 4, triangle_order * triangle_num );\n\n for tri = 1 : triangle_num\n\n i = triangle_node(1,tri);\n j = triangle_node(2,tri);\n k = triangle_node(3,tri);\n\n if ( i < j )\n col(1:4,1+3*(tri-1)) = [ i, j, 3, tri ]';\n else\n col(1:4,1+3*(tri-1)) = [ j, i, 3, tri ]';\n end\n\n if ( j < k )\n col(1:4,2+3*(tri-1)) = [ j, k, 1, tri ]';\n else\n col(1:4,2+3*(tri-1)) = [ k, j, 1, tri ]';\n end\n\n if ( k < i )\n col(1:4,3+3*(tri-1)) = [ k, i, 2, tri ]';\n else\n col(1:4,3+3*(tri-1)) = [ i, k, 2, tri ]';\n end\n\n end\n%\n% Step 2. Perform an ascending dictionary sort on the neighbor relations.\n% We only intend to sort on rows 1 and 2; the routine we call here\n% sorts on rows 1 through 4 but that won't hurt us.\n%\n% What we need is to find cases where two triangles share an edge.\n% Say they share an edge defined by the nodes I and J. Then there are\n% two columns of COL that start out ( I, J, ?, ? ). By sorting COL,\n% we make sure that these two columns occur consecutively. That will\n% make it easy to notice that the triangles are neighbors.\n%\n col = i4col_sort_a ( 4, 3*triangle_num, col );\n%\n% Step 3. Neighboring triangles show up as consecutive columns with\n% identical first two entries. Whenever you spot this happening,\n% make the appropriate entries in TRIANGLE_NEIGHBOR.\n%\n triangle_neighbor(1:3,1:triangle_num) = -1;\n\n icol = 1;\n\n while ( 1 )\n\n if ( 3 * triangle_num <= icol )\n break\n end\n\n if ( col(1,icol) ~= col(1,icol+1) || col(2,icol) ~= col(2,icol+1) )\n icol = icol + 1;\n continue\n end\n\n side1 = col(3,icol);\n tri1 = col(4,icol);\n side2 = col(3,icol+1);\n tri2 = col(4,icol+1);\n\n triangle_neighbor(side1,tri1) = tri2;\n triangle_neighbor(side2,tri2) = tri1;\n\n icol = icol + 2;\n\n end\n\n return\nend\nfunction [ adj_num, adj_col ] = triangulation_order3_adj_count ( node_num, ...\n tri_num, triangle_node, triangle_neighbor )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_ORDER3_ADJ_COUNT counts 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% 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% 14 February 2003\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% Output, integer ADJ_NUM, the number of adjacencies.\n%\n% Output, 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 triangle_order = 3;\n adj_num = 0;\n%\n% Set every node to be adjacent to itself.\n%\n adj_col(1:node_num) = 1;\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_col(n1) = adj_col(n1) + 1;\n adj_col(n2) = adj_col(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_col(n2) = adj_col(n2) + 1;\n adj_col(n3) = adj_col(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_col(n1) = adj_col(n1) + 1;\n adj_col(n3) = adj_col(n3) + 1;\n end\n\n end\n%\n% We used ADJ_COL to count the number of entries in each column.\n% Convert it to pointers into the ADJ array.\n%\n adj_col(2:node_num+1) = adj_col(1:node_num);\n\n adj_col(1) = 1;\n for i = 2 : node_num+1\n adj_col(i) = adj_col(i-1) + adj_col(i);\n end\n\n adj_num = adj_col(node_num+1) - 1;\n\n return\nend\nfunction node_boundary = triangulation_order3_boundary_node ( node_num, ...\n triangle_num, triangle_node )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_ORDER3_BOUNDARY_NODE indicates which nodes are on the boundary.\n%\n% Discussion:\n%\n% This routine is given a triangulation, an abstract list of sets of\n% of nodes. It is assumed that the nodes in each triangle are listed\n% in a counterclockwise order, although the routine should work\n% if the nodes are consistently listed in a clockwise order as well.\n%\n% It is assumed that each edge of the triangulation is either\n% * an INTERIOR edge, which is listed twice, once with positive\n% orientation and once with negative orientation, or;\n% * a BOUNDARY edge, which will occur only once.\n%\n% This routine should work even if the region has holes - as long\n% as the boundary of the hole comprises more than 3 edges!\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% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, integer TRIANGLE_NUM, the number of triangles.\n%\n% Input, integer TRIANGLE_NODE(3,TRIANGLE_NUM),\n% the nodes that make up the triangles. These should be listed\n% in counterclockwise order.\n%\n% Output, logical NODE_BOUNDARY(NODE_NUM), is TRUE if the node\n% is on a boundary edge.\n%\n m = 2;\n n = 3 * triangle_num;\n%\n% Set up the edge array.\n%\n edge(1:2, 1: triangle_num) = triangle_node(1:2,1:triangle_num);\n edge(1:2, triangle_num+1:2*triangle_num) = triangle_node(2:3,1:triangle_num);\n edge(1, 2*triangle_num+1:3*triangle_num) = triangle_node(3, 1:triangle_num);\n edge(2, 2*triangle_num+1:3*triangle_num) = triangle_node(1, 1:triangle_num);\n%\n% In each column, force the smaller entry to appear first.\n%\n e1(1:n) = min ( edge(1:2,1:n) );\n e2(1:n) = max ( edge(1:2,1:n) );\n\n edge(1,1:n) = e1(1:n);\n edge(2,1:n) = e2(1:n);\n%\n% Ascending sort the column array.\n%\n edge = i4col_sort_a ( m, n, edge );\n%\n% Records which appear twice are internal edges and can be ignored.\n%\n node_boundary(1:node_num) = 0;\n\n i = 0;\n\n while ( i < 3 * triangle_num )\n\n i = i + 1;\n\n if ( i == 3 * triangle_num )\n node_boundary(edge(1:m,i)) = 1;\n elseif ( all ( edge(1:m,i) == edge(1:m,i+1) ) )\n i = i + 1;\n else\n node_boundary(edge(1:m,i)) = 1;\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/fem2d_poisson_sparse/fem2d_poisson_sparse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.916109606718245, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7468423131479527}} {"text": "%KSOBEL Sobel edge detector\n%\n% K = KSOBEL() is the Sobel x-derivative kernel:\n% 1/8 |1 0 -1|\n% |2 0 -2|\n% |1 0 -1|\n%\n% Notes::\n% - This kernel is an effective vertical-edge detector\n% - The y-derivative (horizontal-edge) kernel is K'\n%\n% See also ISOBEL.\n\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB 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% MVTB 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 MVTB. If not, see .\n\nfunction k = ksobel\n\n k = [ 1 0 -1\n 2 0 -2\n 1 0 -1] / 8;\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/ksobel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7467687130458764}} {"text": "function Corr = tapas_Cov2Corr(Cov)\n% Converts a covariance matrix into a correlation matrix\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Check if Cov is symmetric\nif any(any(Cov'~=Cov))\n error('tapas:hgf:Cov2Corr:MatNotSymm', 'Input matrix is not symmetric.');\nend\n\n% Check if Cov is positive semi-definite\nif any(isinf(Cov(:))) || any(isnan(Cov(:))) || any(eig(Cov)<0)\n error('tapas:hgf:Cov2Corr:MatNotPosDef', 'Input matrix is not positive semi-definite.');\nend\n\nsdev = sqrt(diag(Cov));\nNorm = sdev * sdev';\nCorr = Cov./Norm;\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_Cov2Corr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7467687118051364}} {"text": "function [Xrls,yrls,s]=RLSreg(y,X)\n%Syntax: [Xrls,yrls,s]=RLSreg(y,X)\n%_______________________________\n%\n% Calculates the Reweighted Least Squares (RLS) regression data points\n% and the scale parameter from the LMS regression.\n%\n% Xrls is the X values matrix to be taken into account for RLS.\n% yrls is the y values vector to be taken into account for RLS.\n% s is RLS scale parameter.\n% y is the vector of the dependent variable.\n% X is the data matrix of the independent variable.\n%\n% Reference:\n% Rousseeuw PJ, Leroy AM (1987): Robust regression and outlier detection. Wiley.\n%\n%\n% Alexandros Leontitsis\n% Institute of Mathematics and Statistics\n% University of Kent at Canterbury\n% Canterbury\n% Kent, CT2 7NF\n% U.K.\n%\n% University e-mail: al10@ukc.ac.uk (until December 2002)\n% Lifetime e-mail: leoaleq@yahoo.com\n% Homepage: http://www.geocities.com/CapeCanaveral/Lab/1421\n%\n% Sep 3, 2001.\n\nif nargin<1 | isempty(y)==1\n error('Not enough input arguments.');\nend\n\n% Estimate the LMS values\nif nargin<2 | isempty(X)==1\n LMSout=LMSreg(y);\n X=(1:length(y))';\nelse\n LMSout=LMSreg(y,X);\nend\n\n% p is the number of parameters to be estimated\np=size(X,2)+1;\n\n% Calculate the residuals\nr=y-LMSout;\n\n% Estimate the preliminary scale parameter\ns=LMSsca(r,0,p);\n\n% Take into account a data point, if its residual is relatively small\nw=find(abs(r/s)<=2.5);\nXrls=X(w,:);\nyrls=y(w);\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/801-lms-toolbox/RLSreg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7467687002312294}} {"text": "%computes the correlation (matrix) sequence given a stable ss description\nfunction [corrmat]=ss2corr_v000(A, Q, C, P0, dt, crind)\n\nnout=size(C,1);\nnout=nout*(nout+1)/2;\nnst=size(A,1);\ncorrmat=zeros(nout,length(crind));\n\n%compute the initial covariance\nif (isempty(P0))\n %check whether system is stable or not\n eigenval=eig(A);\n if (~isempty(find(eigenval>=1,1)))\n disp('A is not stable');\n eigenval\n return;\n else\n %Use lyapunov eq.\n P0=dlyap(A,Q);\n end\nend\n\n%convert the discrete time into cont\ncrcind=crind*dt;\n[Ac, Qc]=dc2dc_v000(A, Q, [], dt, 1,[]);\n\n%compute the covariances\nfor in=1:length(crind)\n sr_a=crcind(in);\n Ad=expm(Ac*abs(sr_a));\n %[Ad, Qd]=dc2dc_v000(Ac, Qc, [], abs(crcind(in)), 0,[]);\n if (sr_a>0)\n mx_a=C*(Ad*P0)*C';\n elseif (sr_a<0)\n mx_a=C*(P0*Ad')*C';\n else\n mx_a=C*P0*C';\n end\n corrmat(:,in)=mat2vec(mx_a);\nend\n\n\nfunction vec=mat2vec(mat)\nnrow=size(mat,1);\nnout=nrow*(nrow+1)/2;\nvec=zeros(nout,1);\nlb=1;\nub=nrow;\nfor in=1:size(mat,1)\n vec(lb:ub)=diag(mat,in-1);\n lb=ub+1;\n ub=ub+nrow-in;\nend\n\n \n \n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/Common/ss2corr_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7467686989904895}} {"text": "% generate the Companion matrix of the polynomials f \n% \n% Syntax: >> C = CompanionMatrix(f)\n% \n% Input: f --- (string or coefficient vector) polynomial\n% \n% Output: C --- (matrix) The companion matrix\n% \n% Example: >> CompanionMatrix('x^4 + 2*x^3 + 3*x^2 + 4*x+5')\n% \n% ans =\n% \n% -2 -3 -4 -5\n% 1 0 0 0\n% 0 1 0 0\n% 0 0 1 0\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/homotopy/CompanionMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.7467686986447835}} {"text": "% Compute the error of a pose-pose constraint\n% x1 3x1 vector (x,y,theta) of the first robot pose\n% x2 3x1 vector (x,y,theta) of the second robot pose\n% z 3x1 vector (x,y,theta) of the measurement\n%\n% You may use the functions v2t() and t2v() to compute\n% a Homogeneous matrix out of a (x, y, theta) vector\n% for computing the error.\n%\n% Output\n% e 3x1 error of the constraint\n% A 3x3 Jacobian wrt x1\n% B 3x3 Jacobian wrt x2\nfunction [e, A, B] = linearize_pose_pose_constraint(x1, x2, z)\n\n % TODO compute the error and the Jacobians of the error\n X1 = v2t(x1);\n X2 = v2t(x2);\n Z = v2t(z);\n e = t2v(Z\\(X1\\X2));\n \n Rij = Z(1:3,1:3);\n Ri = X1(1:3,1:3);\n\n thi = atan2(Ri(2,1),Ri(1,1));\n thij = atan2(Rij(2,1),Rij(1,1));\n \n xi = x1(1);\n yi = x1(2);\n xj = x2(1);\n yj = x2(2);\n\n% A = [-Rij'*Ri' 0 0; 0 -Rij'*Ri' 0; 0 0 -1];\n% B = [Rij'*Ri' 0 0; 0 Rij'*Ri' 0; 0 0 1];\n\n A = [-cos(thi)*cos(thij)+sin(thi)*sin(thij) -sin(thi)*cos(thij)-cos(thi)*sin(thij) 0; cos(thi)*sin(thij)+sin(thi)*cos(thij) sin(thi)*sin(thij)-cos(thi)*cos(thij) 0; 0 0 -1];\n\n A(1:2,3) = [cos(thij)*(-sin(thi)*(xj-xi)+cos(thi)*(yj-yi))+sin(thij)*(-cos(thi)*(xj-xi)-sin(thi)*(yj-yi)); -sin(thij)*(-sin(thi)*(xj-xi)+cos(thi)*(yj-yi))+cos(thij)*(-cos(thi)*(xj-xi)-sin(thi)*(yj-yi))];\n\n B = [cos(thi)*cos(thij)-sin(thi)*sin(thij) sin(thi)*cos(thij)+cos(thi)*sin(thij) 0; -cos(thi)*sin(thij)-sin(thi)*cos(thij) -sin(thi)*sin(thij)+cos(thi)*cos(thij) 0; 0 0 1];\n\nend;\n", "meta": {"author": "kiran-mohan", "repo": "SLAM-Algorithms-Octave", "sha": "e0254ad38cfca2170b2af68c96c183df77c76252", "save_path": "github-repos/MATLAB/kiran-mohan-SLAM-Algorithms-Octave", "path": "github-repos/MATLAB/kiran-mohan-SLAM-Algorithms-Octave/SLAM-Algorithms-Octave-e0254ad38cfca2170b2af68c96c183df77c76252/8_GraphSLAM/octave/linearize_pose_pose_constraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953966093674472, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.7466334773844456}} {"text": "%\n% Example #1 Best-Fit Circle\n%\n%{\n\n% pseudo-data setting\nt=-pi:.01:pi; \nx=sin(t);\ny=cos(t); \nxn=.05*randn(1,629);\nyn=.05*randn(1,629); \nx=x+xn;\ny=y+yn;\n\n% additional data for objective function\nmydata.x=x;\nmydata.y=y;\n\nds(1,'circlefit',mydata,10,3,-10,10,2000)\n\n\nplot(x,y,'o','markersize',2);\nhold on\nplotcircle(globalminimizer(1),globalminimizer(2),globalminimizer(3),'r')\ndaspect([1 1 1])\nshg\n\n\n\n%}\nfunction out=circlefit(X,mydata)\n\nxdata=mydata.x;\nydata=mydata.y;\n\n[N,~]=size(X);\nout=ones(N,1); % pre-memory\nfor i=1:N\n x=X(i,:);\n a=x(1);\n b=x(2);\n r=x(3);\n \n out(i)=sum(abs((xdata-a).^2+(ydata-b).^2-repmat(r.^2,[size(xdata,1),1])));\nend\n\n% out---> Nx1 sized, where N:size of superorganism (i.e., population size; pattern-matrix size)\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/43390-differential-search-algorithm-a-modernized-particle-swarm-optimization-algorithm/circlefit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374444, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7466079082353655}} {"text": "function [Rob,Sen,Lmk,Obs,Frm,Fac] = solveGraphQR(Rob,Sen,Lmk,Obs,Frm,Fac,options)\n\n% SOLVEGRAPHQR Solves the SLAM graph using QR decomposition.\n% [Rob,Sen,Lmk,Obs,Frm,Fac] = SOLVEGRAPHQR(Rob,Sen,Lmk,Obs,Frm,Fac)\n% solves the graph-SLAM problem using QR decomposition of the\n% Hessian matrix. \n%\n% IMPORTANT NOTE: This method is illustrative and constitutes the\n% motivation for this toolbox. One can achieve better performances, both\n% in computing time and possibly in robustness and accuracy, by using\n% Matlab's built-in nonlinear optimization tools, such as LSQNONLIN.\n% \n% See courseSLAM.pdf in the documentation for details about the QR\n% decomposition for solving the graph-SLAM problem.\n%\n% See also SOLVEGRAPHCHOLESKY, ERRORSTATEJACOBIANS, UPDATESTATES,\n% COMPUTEERROR, COMPUTERESIDUAL, COLAMD, '\\', MLDIVIDE, LSQNONLIN.\n\n% Copyright 2015- Joan Sola @ IRI-UPC-CSIC.\n\nglobal Map\n\n% Control of iterations and exit conditions\nn_iter = options.niterations; % exit criterion of number of iterations\ntarget_dres = options.target_dres; % exit criterion for error variation\ntarget_res = options.target_res; % exit criterion for current residual\nres_old = 1e10; % last iteration's error\n\n% Map states range\nMap.mr = find(Map.used);\n% Map factors range\nerrs = [Fac.err];\nMap.fr = 1:sum([errs.size]);\n\nfor it = 1:n_iter\n \n % Compute Jacobians for projection onto the manifold\n [Frm,Lmk] = errorStateJacobians(Frm,Lmk);\n \n % Build Hessian A and rhs vector b, in global Map\n Fac = buildProblem(Rob,Sen,Lmk,Obs,Frm,Fac);\n \n if it == 1 % do this only once:\n \n % Column permutation\n p = colamd(Map.A(Map.fr,Map.mr))';\n \n % Permutated map range\n pr = Map.mr(p);\n Map.pr = pr;\n \n end\n \n % Decomposition\n [Map.d, Map.R] = qr(Map.A(Map.fr,pr), Map.b(Map.fr), 0);\n \n % Solve for dx and reorder:\n % - dx is Map.x(mr)\n % - reordered dx is Map.x(pr)\n Map.x(pr) = -Map.R\\Map.d; % solve for dx;\n \n % NOTE: Matlab is able to do all the reordering and QR factorization\n % for you. If you just use the operator '\\', as in 'dx = -A\\b', Matlab\n % will reorder A, then factor it to get R and d, then solve the\n % factored problem, then reorder back the result into dx. Use the\n % following line to accomplish this, and comment out the code from line\n % 'if it == 1' until here:\n %\n % Map.x(Map.mr) = -Map.A(Map.fr,Map.mr)\\Map.b(Map.fr);\n \n % Update nominal states\n [Rob,Lmk,Frm] = updateStates(Rob,Lmk,Frm);\n \n % Check resulting errors\n [res, err_max] = computeResidual(Rob,Sen,Lmk,Obs,Frm,Fac);\n dres = res - res_old;\n res_old = res;\n \n % Test and exit\n if ( ( -dres <= target_dres ) || (err_max <= target_res) ) %&& ( abs(derr) < target_derr) )\n break;\n end\n \nend\n\n% Compute full covariance matrix.\nMap.P(pr,pr) = inv(full(Map.R))*inv(full(Map.R))';\n\nend\n\nfunction Fac = buildProblem(Rob,Sen,Lmk,Obs,Frm,Fac)\n\n% BUILDPROBLEM Build least squares problem's matrix A and vector b \n% Fac = BUILDPROBLEM(Rob,Sen,Lmk,Obs,Frm,Fac) Builds the least squares\n% problem's matrix A and vector b for a solution using sparse QR\n% factorization of A.\n\nglobal Map\n\n\n% Reset Hessian and rhs vector\nMap.A(Map.fr,Map.mr) = 0;\nMap.b(Map.fr) = 0;\n\n% Iterate all factors\nfacCount = 1;\nfor fac = find([Fac.used])\n \n % Extract some pointers\n rob = Fac(fac).rob;\n sen = Fac(fac).sen;\n lmk = Fac(fac).lmk;\n frames = Fac(fac).frames;\n \n % Compute factor error, info mat, and Jacobians\n [Fac(fac), e, ~, Wsqrt, J1, J2, r1, r2] = computeError(...\n Rob(rob), ...\n Sen(sen), ...\n Lmk(lmk), ...\n Obs(sen,lmk), ...\n Frm(frames), ...\n Fac(fac));\n \n % row band matrix size\n m = numel(e);\n mr = (facCount : facCount + m - 1);\n \n % Update A and b\n Map.A(mr,r1) = Wsqrt * J1;\n Map.A(mr,r2) = Wsqrt * J2;\n \n Map.b(mr,1) = Wsqrt * e;\n\n % Advance to next row band\n facCount = facCount + m;\n\nend\n\nend\n\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/InterfaceLevel/solveGraphQR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7466079075209568}} {"text": "function phi=sinCosConformLat2EllipsLat(sinChi,cosChi,f)\n%%SINCOSCONFORMLAT2ELLIPSLAT Given the sine and cosine of a conformal\n% latitude, determine an ellipsoidal (geodetic) latitude. A\n% conformal latitude is a latitude in terms of a sphere that is\n% conformal with regard to the ellipsoid. That is, the\n% transformation from the ellipsoid to the sphere preserves\n% angles. This is such that the angle of intersection between\n% any two lines on the ellipsoid is the same as the corresponding\n% angle on the sphere.\n%\n%INPUTS: sinChi The real sine of the conformal latitude. This can be a\n% scalar or a matrix of values to convert.\n% cosChi The real cosine of the conformal latitude. This can be a\n% scalar or a matrix of values to convert. This has to be the\n% same size as sinChi.\n% f The flattening factor of the reference ellipsoid. If this\n% argument is omitted, the value in Constants.WGS84Flattening\n% is used. This function is only accurate for values from 0\n% to about 0.999. Typically, this will be close to zero, as\n% in Constants.WGS84Flattening.\n%\n%OUTPUTS: phi The ellipsoidal latitudes in radians. This is the same size\n% as sinChi and cosChi.\n%\n%Conformal latitudes are discussed in Chapter 3 of [1]. This function\n%implements the fixed-point iteration that is described in Section 2.9 of\n%[2]. Smaller values of f lead to faster convergence. The maximum number of\n%iterations in the function, which is typically never obtained, is set to\n%be able to convert unusually large values of f up to about 0.999. A\n%different fixed point iteration when given the conformal latitude itself\n%is given in [3].\n%\n%REFERENCES:\n%[1] J. P. Snyder, \"Map projections- a working manual,\" U.S. Geological\n% Survey, Tech. Rep. 1395, 1987.\n%[2] Office of Geomatics, \"National geospatial-intelligence agency\n% standardization document: Implementation practice: The universal\n% grids and the transverse mercator and polar stereographic\n% map projections,\" 25 Mar. 2014. [Online]. Available:\n% http://earth-info.nga.mil/GandG/publications/NGA_SIG_0012_2_0_0_UTMUPS/NGA.SIG.0012_2.0.0_UTMUPS.pdf\n%[3] Weisstein, Eric W. \"Conformal Latitude.\" From MathWorld--A Wolfram Web\n% Resource. http://mathworld.wolfram.com/ConformalLatitude.html\n%\n%July 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(f))\n f=Constants.WGS84Flattening;\nend\n\n%The first numerical eccentricity of the ellipsoid.\ne=sqrt(2*f-f^2);\n\nN=numel(sinChi);\nphi=zeros(size(sinChi));\n\nfor curPoint=1:N\n s=sinChi(curPoint);\n %It should converge in 7 or fewer iterations for\n %f=Constants.WGS84Flattening. The upper bound of 5e7 should be enough for\n %f=0.999.\n for curIter=1:3e7\n P=exp(e*atanh(e*s));\n term1=(1+sinChi(curPoint))*P*P;\n term2=(1-sinChi(curPoint));\n\n sNew=(term1-term2)/(term1+term2);\n\n if(abs(s-sNew)<=eps(s))\n break\n end\n s=sNew;\n end\n P=exp(e*atanh(e*s));\n c=(1/2)*((1+s)/P+(1-s)*P)*cosChi(curPoint);\n phi(curPoint)=atan2(s,c);\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/Latitude_Conversion/sinCosConformLat2EllipsLat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195635, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7466025799710906}} {"text": "function det = r8pbl_det ( n, mu, a_lu )\n\n%*****************************************************************************80\n%\n%% R8PBL_DET computes the determinant of a matrix factored by R8PBL_FA.\n%\n% Discussion:\n%\n% The R8PBL storage format is for a symmetric positive definite band matrix.\n%\n% To save storage, only the diagonal and lower triangle of A is stored,\n% in a compact diagonal format that preserves columns.\n%\n% The diagonal is stored in row 1 of the array.\n% The first subdiagonal in row 2, columns 1 through MU.\n% The second subdiagonal in row 3, columns 1 through MU-1.\n% The MU-th subdiagonal in row MU+1, columns 1 through 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 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, Philadelphia, 1979.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, integer MU, the upper (and lower) bandwidth.\n% MU must be nonnegative, and no greater than N-1.\n%\n% Input, real A_LU(MU+1,N), the LU factors from R8PBL_FA.\n%\n% Output, real DET, the determinant of the matrix.\n%\n det = prod ( a_lu(1,1:n).^2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r8pbl_det.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7466025688199208}} {"text": "function [ x, seed ] = hyperball01_sample ( m, n, seed )\n\n%*****************************************************************************80\n%\n%% HYPERBALL01_SAMPLE uniformly samples the unit hyperball in M dimensions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 05 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Russell Cheng,\n% Random Variate Generation,\n% in Handbook of Simulation,\n% edited by Jerry Banks,\n% Wiley, 1998, pages 168.\n%\n% Reuven Rubinstein,\n% Monte Carlo Optimization, Simulation, and Sensitivity \n% of Queueing Networks,\n% Krieger, 1992,\n% ISBN: 0894647644,\n% LC: QA298.R79.\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input/output, integer SEED, a seed for the random \n% number generator.\n%\n% Output, real X(M,N), the points.\n%\n x = randn ( m, n );\n norm = ones ( 1, m ) * ( x.^2 );\n norm = sqrt ( norm );\n for i = 1 : m\n x(i,1:n) = x(i,1:n) ./ norm(1:n);\n end\n\n for j = 1 : n\n r = rand ( 1, 1 );\n x(1:m,j) = r ^ ( 1.0 / m ) * x(1:m,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/hyperball_integrals/hyperball01_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7466025672741085}} {"text": "function b = NormalizeArray(a)\n% Normalizes array a. This means that the minimum value will become 0 and\n% the maximum value 1.\n%\n% a: Input array.\n%\n% b: Normalized output array\n%\n% Jasper Uijlings - 2013\n\nminVal = min(a(:));\nmaxVal = max(a(:));\n\ndiffVal = maxVal - minVal;\n\nb = a - minVal;\nif diffVal ~= 0\n b = b ./ diffVal;\nend\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SelectiveSearchCodeIJCV/Dependencies/NormalizeArray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7466025667380239}} {"text": "function z = polyval2(p,x,y)\n% POLYVAL2 \n% ---------\n%\n% Evaluate a 2D polynomial\n% By SS Rogers (2006)\n%\n% Usage\n% ------\n% Z = POLYVAL2(P,X,Y) returns the value of a 2D polynomial P evaluated at (X,Y). P\n% is a vector of length (N+1)*(N+2)/2 containing the polynomial coefficients in\n% ascending powers:\n%\n% P = [p00 p10 p01 p20 p11 p02 p30 p21 p12 p03...]\n%\n% e.g. For a 3rd order fit, polyval2.m evaluates the matrix equation:\n%\n% Z = V*P or\n%\n% 2 2 3 2 2 3\n% Z = [1 x y x xy y x x y x y y ] [p00\n% p10\n% p01\n% p20\n% p11\n% p02\n% p30\n% p21\n% p12\n% p03]\n%\n% *Note:* P is not in the format of standard Matlab 1D polynomials.\n%\n% X and Y should be vectors; the polynomial is evaluated at all\n% points (X,Y).\n%\n% Class support for inputs P,X,Y:\n% float: double, single\n\nx=x(:);\ny=y(:);\nlx=length(x);\nly=length(y);\nlp=length(p);\npts=lx*ly;\n\ny=y*ones(1,lx);\nx=ones(ly,1)*x';\nx = x(:);\ny = y(:);\n\nn=(sqrt(1+8*length(p))-3)/2;\n% Check input is a vector\nif ~(isvector(p) || mod(n,1)==0 || lx==ly)\n error('MATLAB:polyval2:InvalidP',...\n 'P must be a vector of length (N+1)*(N+2)/2, where N is order. X and Y must be same size.');\nend\n\n% Construct weighted Vandermonde matrix.\nV=zeros(pts,lp);\nV(:,1) = ones(pts,1);\nordercolumn=1;\nfor order = 1:n\n for ordercolumn=ordercolumn+(1:order)\n V(:,ordercolumn) = x.*V(:,ordercolumn-order);\n end\n ordercolumn=ordercolumn+1;\n V(:,ordercolumn) = y.*V(:,ordercolumn-order-1);\nend\n\nz=V*p';\nz=reshape(z,ly,lx);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13719-2d-weighted-polynomial-fitting-and-evaluation/polyfitweighted2/polyval2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7465812270048474}} {"text": "function [Mout, RHSout] = combineBC2D(BC, Meq, RHSeq)\n%COMBINEBC This function combines the boundary condition equations with the\n%main physical model equations, and delivers the matrix of coefficient and\n%RHS to be solved for the internal cells.\n%\n% SYNOPSIS:\n% [Mout, RHSout] = combineBC2D(BC, Meq, RHSeq)\n%\n% PARAMETERS:\n%\n%\n% RETURNS:\n%\n%\n% EXAMPLE:\n%\n% SEE ALSO:\n%\n\n% extract data from the mesh structure\nNxy = BC.domain.dims;\nNx = Nxy(1); Ny = Nxy(2);\nG=reshape(1:(Nx+2)*(Ny+2), Nx+2, Ny+2);\ndx = BC.domain.cellsize.x;\ndy = BC.domain.cellsize.y;\n\n% define the RHS column vector\nms = size(Meq);\nM = Meq;\nRHS = RHSeq;\n\n% Assign values to the boundary condition matrix and the RHS vector based\n% on the BC structure\n% top boundary\nj=Ny+2;\ni=2:Nx+1;\ntop = reshape(sub2ind(ms, G(i,j-1), G(i,j-1)), Nx,1); % top boundary cells\ntopN = reshape(sub2ind(ms, G(i,j-1), G(i,j)), Nx, 1); % north cells to top boundary cells\nM(top) = M(top)-((BC.top.b/2 - BC.top.a/dy(end))./(BC.top.b/2 + BC.top.a/dy(end))).*M(topN);\nRHS(G(i,j-1)) = RHS(G(i,j-1))-M(topN).*BC.top.c./(BC.top.b/2 + BC.top.a/dy(end));\n\n% Bottom boundary\nj=1;\ni=2:Nx+1;\nbottom = reshape(sub2ind(ms, G(i,j+1), G(i,j+1)), Nx,1); % bottom boundary cells\nbottomS = reshape(sub2ind(ms, G(i,j+1), G(i,j)), Nx, 1); % south cells to bottom boundary cells\nM(bottom) = M(bottom)-((BC.bottom.b/2 + BC.bottom.a/dy(1))./(BC.bottom.b/2 - BC.bottom.a/dy(1))).*M(bottomS);\nRHS(G(i,j+1)) = RHS(G(i,j+1))-M(bottomS).*BC.bottom.c./(BC.bottom.b/2 - BC.bottom.a/dy(1));\n\n% Right boundary\ni=Nx+2;\nj=2:Ny+1;\nright = reshape(sub2ind(ms, G(i-1,j), G(i-1,j)), Ny,1); % right boundary cells\nrightE = reshape(sub2ind(ms, G(i-1,j), G(i,j)), Ny, 1); % east cells to right boundary cells\nM(right) = M(right)-((BC.right.b/2 - BC.right.a/dx(end))./(BC.right.b/2 + BC.right.a/dx(end)))'.*M(rightE);\nRHS(G(i-1,j)) = RHS(G(i-1,j))-M(rightE).*(BC.right.c./(BC.right.b/2 + BC.right.a/dx(end)))';\n\n% Left boundary\ni = 1;\nj=2:Ny+1;\nleft = reshape(sub2ind(ms, G(i+1,j), G(i+1,j)), Ny,1); % left boundary cells\nleftW = reshape(sub2ind(ms, G(i+1,j), G(i,j)), Ny, 1); % west cells to left boundary cells\nM(left) = M(left)-((BC.left.b/2 + BC.left.a/dx(1))./(BC.left.b/2 - BC.left.a/dx(1)))'.*M(leftW);\nRHS(G(i+1,j)) = RHS(G(i+1,j))-M(leftW).*(BC.left.c./(BC.left.b/2 - BC.left.a/dx(1)))';\n\nMout = M(G(2:end-1,2:end-1), G(2:end-1,2:end-1));\nRHSout = RHS(reshape(G(2:end-1,2:end-1),Nx*Ny,1));\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Boundary/combineBC2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.746581217392314}} {"text": "function [ x, y, z, w ] = ld0194 ( )\n\n%*****************************************************************************80\n%\n%% LD0194 computes the 194 point Lebedev angular grid.\n%\n% Modified:\n%\n% 14 September 2010\n%\n% Author:\n%\n% Dmitri Laikov\n%\n% Reference:\n%\n% Vyacheslav Lebedev, Dmitri Laikov,\n% A quadrature formula for the sphere of the 131st\n% algebraic order of accuracy,\n% Russian Academy of Sciences Doklady Mathematics,\n% Volume 59, Number 3, 1999, pages 477-481.\n%\n% Parameters:\n%\n% Output, real X(N), Y(N), Z(N), W(N), the coordinates\n% and weights of the points.\n%\n n = 0;\n x = zeros(194,1);\n y = zeros(194,1);\n z = zeros(194,1);\n w = zeros(194,1);\n a = 0.0;\n b = 0.0;\n v = 0.1782340447244611E-02;\n [ n, x, y, z, w ] = gen_oh ( 1, n, a, b, v, x, y, z, w );\n v = 0.5716905949977102E-02;\n [ n, x, y, z, w ] = gen_oh ( 2, n, a, b, v, x, y, z, w );\n v = 0.5573383178848738E-02;\n [ n, x, y, z, w ] = gen_oh ( 3, n, a, b, v, x, y, z, w );\n a = 0.6712973442695226;\n v = 0.5608704082587997E-02;\n [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n a = 0.2892465627575439;\n v = 0.5158237711805383E-02;\n [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n a = 0.4446933178717437;\n v = 0.5518771467273614E-02;\n [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n a = 0.1299335447650067;\n v = 0.4106777028169394E-02;\n [ n, x, y, z, w ] = gen_oh ( 4, n, a, b, v, x, y, z, w );\n a = 0.3457702197611283;\n v = 0.5051846064614808E-02;\n [ n, x, y, z, w ] = gen_oh ( 5, n, a, b, v, x, y, z, w );\n a = 0.1590417105383530;\n b = 0.8360360154824589;\n v = 0.5530248916233094E-02;\n [ n, x, y, z, w ] = gen_oh ( 6, n, a, b, v, x, y, z, 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/sphere_lebedev_rule/ld0194.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7465021766676396}} {"text": "function const_pts = rectQAM_const(M)\n% \n\n% M-PAM bit/symbol ordering\n[bo so] = PAM_Gray_Code;\n\nk = log2(M);\nI = 2^ceil(k/2);\nQ = 2^floor(k/2);\n\n% Produce PAM constellation points for in-phase and quadrature\nI_t = -(I-1):2:I-1;\nQ_t = Q-1:-2:-(Q-1);\n\n% Re-order based on the PAM Gray mapping\nfor i=1:length(I_t)\n I_pts(so{log2(I)}(i)+1) = I_t(i);\nend\nfor i=1:length(Q_t)\n Q_pts(so{log2(Q)}(i)+1) = Q_t(i);\nend\n\nfor i=0:M-1\n MSBs = floor(i/I);\n LSBs = i-MSBs*I;\n QAM_I(i+1) = I_pts(LSBs+1);\n QAM_Q(i+1) = Q_pts(MSBs+1);\nend\n\nconst_pts=complex(QAM_I,QAM_Q);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22316-communication-systems-reference-curves/QAM_BER/_oldmyQAM_const.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7465021700993036}} {"text": "%% Author: epokh\n%% Website: www.epokh.org/drupy\n%% This software is under GPL\n\n%%Function description:\n%%Transformation of the end effector frame following the Euler angles\n%%in closed form\n%%input: rotation angles along y,z,y axis expressed in degrees\n\nfunction [EulerMat]=Euler(fi1,theta,fi2)\n\nEulerMat=[cosd(fi1)*cosd(theta)*cosd(fi2)-sind(fi1)*sind(fi2),-cosd(fi1)*cosd(theta)*sind(fi2)-sind(fi1)*cosd(fi2),cosd(fi1)*sind(theta),0;\n sind(fi1)*cosd(theta)*cosd(fi2)+cosd(fi1)*sind(fi2),-sind(fi1)*cosd(theta)*sind(fi2)+cosd(fi1)*cosd(fi2),sind(fi1)*sind(theta),0;\n -sind(theta)*cosd(fi2),sind(theta)*sind(fi2),cosd(theta),0;\n 0 ,0 ,0 ,1;];\n \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/14886-robotic-toolbox/Euler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7464885952806832}} {"text": "function [xECEF,MInv]=ENU2ECEF(plhOrigin,xENU,a,f)\n%%ENU2ECEF Convert from a local East-North-Up (ENU) Cartesian cooridnate\n% system to an Earth-centered Earth-fixed (ECEF) Cartesian\n% coordinate system. The alignment of the coordinate axes with the\n% reference ellipsoid is the one used in common standards such as\n% that used by the DoD's WGS-84 standard and the International\n% Earth Rotation and Reference Systems Service's (IERS)\n% international terrestrial reference frame (ITRF). The global\n% ECEF z-axis is North.\n%\n%INPUTS: plhOrigin A 3X1 point in [latitude;longitude; ellipsoidal height]\n% coordinates with respect to a reference ellipsoid\n% parameterized by a and f, derving as the origin of the local\n% ENU coordinate system. Latitude and longitude are given in\n% radians North and East.\n% xENU A 3XnumPts collection of 3D Cartesian points in the local ENU\n% coordinate system that should be converted to a global ECEF\n% coordinate system.\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 this\n% argument is omitted, the value in Constants.WGS84Flattening\n% is used.\n%\n%OUTPUTS: xECEF A 3XnumPts matrix of the points in xENU converted to ECEF\n% coordinates.\n% MInv A rotation matrix such that rotates a point from ENU to\n% ECEF coordinates.\n%\n%The ENU coordinate system is a common local tangent plane cooridnate\n%system. Here, we take \"up\" to be that described by a reference ellipsoid\n%and not true gravitational \"up\". This limits the accuracy of the local\n%coordinate system.\n%\n%The conversions are mentioned in [1].\n%\n%EXAMPLE:\n%Here, we convert 3 points in a local ENU tangent-plane coordinate system\n%to ECEF and then to ellipsoidal coordinates. In the ENU coordinate system,\n%the points are offset in the North, East, and up directions. One will see\n%that in ellipsoidal coordinates, as compared to the origin, there are\n%respective offsets in latitude (with no change in longitude), longitude\n%(with no change in latitude) and heigh (with no change in latitude or\n%longitude).\n% lat=19.7241*(pi/180);\n% lon=-155.0868*(pi/180);\n% height=0;\n% plhPoint=[lat;lon;height];%Around Hilo, Hawaii.\n% xENU=[0, 1e3, 0;\n% 1e3, 0, 0;\n% 0, 0, 1e3];\n% xECEF=ENU2ECEF(plhPoint,xENU);\n% latLonHeight=Cart2Ellipse(xECEF);\n% diffVals=bsxfun(@minus,latLonHeight,plhPoint);\n% %Convert angles to degrees\n% diffVals(1:2,:)=diffVals(1:2,:)*(180/pi);\n% %One can see the change in latitude on the first point, the change in\n% %longitude on the second point, and no change in laittude or longitude in\n% %the third point.\n% diffVals(1:2,:)\n% %The change in height with the third point is the full kilometer. The\n% %changes with the other points is just due to the tangent point\n% %approximation and are much smaller.\n% diffVals(3,:)\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"Simulating aerial targets in 3D accounting for the\n% Earth's curvature,\" Journal of Advances in Information Fusion, vol.\n% 10, no. 1, Jun. 2015.\n%\n%September 2020 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(a))\n a=Constants.WGS84SemiMajorAxis;\nend\n\nif(nargin<4||isempty(f))\n f=Constants.WGS84Flattening;\nend\n\nMInv=getENUAxes(plhOrigin,false,a,f);\noriginCart=ellips2Cart(plhOrigin,a,f);\n\nnumPts=size(xENU,2);\nxECEF=zeros(3,numPts);\nfor k=1:numPts\n xECEF(:,k)=xENU(1,k)*MInv(:,1)+xENU(2,k)*MInv(:,2)+xENU(3,k)*MInv(:,3);\nend\n\n%Correct for the origin shift.\nxECEF=bsxfun(@plus,xECEF,originCart);\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/ENU2ECEF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.746484089355187}} {"text": "function [invA]=invltod(A,n)\n\n\n\n\n\n\n% computes the inverse of a n*n lower triangular matrix with ones on the main diagonal\n% uses result (XXX) from Appendix (XXX)\n\n\n% first obtain the B matrix from A\nB=sparse(tril(A,-1));\n\n% compute the summation term\nsumm=sparse(n,n);\nprodt=speye(n);\nfor ii=1:n-1\nprodt=prodt*B;\nsumm=summ+(-1)^ii*prodt;\nend\n\n% compute the inverse of A\ninvA=full(speye(n)+summ);\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/invltod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297807787538, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7464840871422771}} {"text": "function buckling_spring_theta ( l_num, theta_num )\n\n%*****************************************************************************80\n%\n%% BUCKLING_SPRING_THETA plots LAMBDA(L,THETA) and MU(L,THETA) lines for fixed L.\n%\n% Discussion:\n%\n% This routine fixes L and plots LAMBDA and MU as functions of THETA.\n%\n% Usage:\n%\n% buckling_spring_theta ( l_num, theta_num )\n%\n% * l_num is the number of L values along each THETA line;\n% * theta_num is the number of THETA lines to draw.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 October 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer L_NUM, the number of values of L,\n% which controls the smoothness of each line.\n% A value of 101 is plenty.\n%\n% Input, integer THETA_NUM, the number of values of THETA, \n% which sets the number of lines to be drawn.\n% A value of 101 is plenty.\n%\n l_lo = 0.25;\n l_hi = 1.75;\n\n theta_lo = - 3 * pi / 8;\n theta_hi = + 3 * pi / 8;\n\n for j = 1 : l_num\n\n if ( l_num == 1 )\n L = 0.5 * ( l_lo + l_hi );\n else\n L = ( ( l_num - j ) * l_lo ...\n + ( j - 1 ) * l_hi ) ...\n / ( l_num - 1 );\n end\n\n for i = 1 : theta_num\n\n if ( theta_num == 1 )\n theta = 0.5 * ( theta_lo + theta_hi );\n else\n theta = ( ( theta_num - i ) * theta_lo ...\n + ( i - 1 ) * theta_hi ) ...\n / ( theta_num - 1 );\n end\n\n lambda(i,j) = ( 1 - L ) * cos ( theta ) + theta * sin ( theta ) / 4 / L;\n mu(i,j) = - theta * cos ( theta ) / 2 / L + 2 * ( 1 - L ) * sin ( theta );\n\n end\n\n end\n\n plot ( lambda, mu )\n%\n% Limit the plot range.\n% Suppress this command to see the whole plot.\n%\n axis ( [ 0.1 0.9 -0.07 0.07 ] );\n%\n% Label the plot.\n%\n xlabel ( '\\lambda(L,\\theta)' );\n ylabel ( '\\mu(L,\\theta)' );\n title ( 'Each line is a fixed value of L' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/buckling_spring/buckling_spring_theta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7464831904696654}} {"text": "% DOC\n%\n% Files\n% afemdoc - Adaptive Finite Element Method\n% amgdoc - ALGEBRAIC MULTIGRID METHOD\n% amgdoctest1 - AMG TEST I: DIFFERENT MESHES\n% amgdoctest2 - AMG TEST II: Different boundary conditions\n% amgdoctest3 - AMG TEST III: Robustness to time discretization\n% amgtest - test algebraic mutligrid solver\n% amgtest2 - AMG TEST II: Different boundary conditions\n% auxstructuredoc - Auxiliary Mesh Data Structure\n% bddoc - Data Structure: Boundary Conditions\n% bisectdoc - Bisection in Two Dimensions\n% coarsenAMGdoc - Coarsening for Algebraic Multigrid\n% coarsendoc - COARSENING in TWO DIMENSIONS\n% coloringdoc - Coloring Vertices of a Graph\n% dof3edgedoc - Data Structure: Lowest Order Edge Element\n% dofdoc - Data Sturcture for Degree of Freedom (DOF) \n% dofedgedoc - Dofedge in Two Dimensions\n% dofP2doc - Data Structure: P2 Quadratic Element\n% fastcoding - Vectorization\n% femcontent - Finite Element Methods\n% femdoc - Finite Element Methods\n% ifem - Display HTML documentation in the MATLAB web browser.\n% introduction - Introduction of iFEM\n% Maxwell1doc - Equation: Maxwell Equation Discretized by Edge Element\n% Maxwell1testdoc - Edge Element Discretization of Maxwell Equations: Linear Element\n% Maxwell2doc - Equation: Maxwell equation Quadratic Element in 3D\n% Maxwell2testdoc - Edge Element Discretization of Maxwell Equations\n% Maxwelldoc - Equation: Maxwell Equation Discretized by Edge Element\n% MaxwellNeumanBCdoc - Local Labeling of DOFs\n% Maxwelltestdoc - Edge Element Discretization of Maxwell Equations\n% meshamrdoc - Adaptive Mesh Refinement/Coarsening\n% meshbasicdoc - Basic Data Structure representing a Mesh\n% meshdoc - Mesh\n% meshoptdoc - Mesh Smoothing and Optimization\n% mgdoc - MULTIGRID on BISECTION GRIDS\n% mixFEMsolverdoc - Mixed FEM solver\n% Poisson3BDM1doc - Equation: Poisson Equation Discretized by $BDM_1$ Element in 3D\n% Poisson3RT0doc - Equation: Poisson Equation Discretized by $RT_0$ Element in 3D\n% PoissonBDM1doc - Equation: Poisson Equation Discretized by $BDM_1$ Element in 2D\n% PoissonRT0doc - Equation: Poisson Equation Discretized by $RT_0$ Element in 2D\n% sc3doc - Simplicial Complex in Three Dimensions\n% scdoc - Simplicial Complex in Three Dimensions\n% simplicialcomplexdoc - Simplicial Complex in 3D\n% solverdoc - Multigrid Method\n% sparsematrixdoc - Vectorization using Sparse Matrices\n% uniformrefine3doc - 3-D Red Refinement\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/doc/Contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.7464831693194192}} {"text": "function [h_1d,h_2d] = create_h(sigma_h, size_h, opt, mode)\n\nif sigma_h > opt.M || sigma_h > opt.N\n error('blur kernel must be smaller than image');\nend\n\nif mode == 1\n x = linspace(-size_h/2, size_h/2, size_h);\n h_1d = exp(-x.^2 / (2 * sigma_h^2)); % 1D Guassian filter kernel\n h_1d = h_1d / sum(h_1d); % normalize\n h_2d = kron(h_1d',h_1d);\nelseif mode == 2\n h_2d = ones(size_h,size_h) / (size_h*size_h);\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/SRAlgorithms/BayesianVSR/functions/create_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810525948928, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.746471083141616}} {"text": "% Generate Figure 6 of the \"Deep Scattering Spectrum\" paper.\n\n% Load the signal.\nx = wavread('chord_signal.wav');\n\n% Prepare the filters and scattering operators.\nfilt_opt.filter_type = {'gabor_1d','morlet_1d'};\nfilt_opt.B = [4 4];\nfilt_opt.Q = 4*filt_opt.B; \nfilt_opt.J = T_to_J([256 32768],filt_opt);\n\nscat_opt.oversampling = 3;\nscat_opt.M = 2;\n\nWop = wavelet_factory_1d(length(x), filt_opt, scat_opt);\n\n% Compute scattering coefficients.\n[S, U] = scat(x, Wop);\n\n% Renormalize coefficients.\nepsilon = 1e-3;\nS = renorm_scat(S, epsilon);\nS = renorm_1st(S, x, Wop{2}, epsilon);\n\nS = resample_scat(S, 8, false);\nU = resample_scat(U, 6, false);\n\n% Compute the logarithm.\nS = log_scat(S, 1e-3);\nU = log_scat(U, 1e-3);\n\n% Display scalogram U{2}, first-order coefficients S{2} and second-order\n% coefficients S{3} for j1 = 58.\nfigure(6);\nclf;\nset(gcf,'Units','pixels','Position',[200 200 560 420]);\nscattergram(U{2}, [], S{2}, [], S{3}, 58);\nsubplot(3,1,1);\nset(gca,'XTick',[],'YTick',[]);\nsubplot(3,1,2);\nset(gca,'XTick',[],'YTick',[]);\nsubplot(3,1,3);\nset(gca,'XTick',[],'YTick',[]);\ncolormap(jet);\n\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/papers/DSS/DSS_Figure6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7464259699263751}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n\n%Fourier Transfrom and inverse Fourier Transfrom of various functions \n% the order of the operations is a little different \n%from the order that they appear on the book \n\n\n%F{exp(-t^2)}\nsyms t w\nx=exp(-t^2);\nfourier(x)\n\nint(x*exp(-j*w*t),t,-inf,inf)\n\n\n%F^-1{1/(1+j*w)}\nX=1/(1+j*w);\nifourier(X)\n\nX=1/(1+j*w);\nifourier(X,t)\n\nsyms n\nX=1/(1+j*w);\nifourier(X,n)\n\n\n%F{exp(-t)*u(t)}\nsyms t w\nx=exp(-t)*heaviside(t);\nX=fourier(x,w)\n\n\n%F{1}\nx=1;\nfourier(x,w)\nsyms s\nfourier(x,s)\nfourier(x)\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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/6/c62.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763572, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7464259685499296}} {"text": "% Compute the closeness centrality for every vertex: 1/sum(dist to all other nodes)\n%\n% INPUTs: adjacency matrix, nxn\n% OUTPUTs: vector of closeness centralities, nx1\n%\n% Source: social networks literature (example: Wasserman, Faust, \"Social Networks Analysis\")\n% Other routines used: simpleDijkstra.m \n% GB: last updated, Sep 28, 2012\n\nfunction C=closeness(adj)\n\nC=zeros(length(adj),1); % initialize closeness vector\n\nfor i=1:length(adj); C(i)=1/sum( simpleDijkstra(adj,i) ); end", "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/closeness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768651485395, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7464004380864094}} {"text": "clear all\n\nnInst = 500;\nnVars = 200;\nX = randn(nInst,nVars);\nw = randn(nVars,1);\ny = sign(X*w + randn(nInst,1));\n\nw_init = zeros(nVars,1);\nfunObj = @(w)LogisticLoss(w,X,y);\n\nfprintf('\\nRunning Steepest Descent\\n');\noptions.Method = 'sd';\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;\n\nfprintf('\\nRunning Cyclic Steepest Descent\\n');\noptions.Method = 'csd';\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;\n\nfprintf('\\nRunning Conjugate Gradient\\n');\noptions.Method = 'cg';\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;\n\nfprintf('\\nRunning Scaled Conjugate Gradient\\n');\noptions.Method = 'scg';\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;\n\nfprintf('\\nRunning Preconditioned Conjugate Gradient (Diagonal preconditioner)\\n');\noptions.Method = 'pcg';\noptions.precFunc = @LogisticDiagPrecond;\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;\n\nfprintf('\\nRunning Preconditioned Conjugate Gradient (L-BFGS preconditioner)\\n');\noptions.Method = 'pcg';\noptions.precFunc = [];\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;\n\nfprintf('\\nRunning Hessian-Free Newton w/ numerical Hessian-Vector products\\n');\noptions.Method = 'newton0';\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;\n\nfprintf('\\nRunning Preconditioned Hessian-Free Newton w/ numerical Hessian-Vector products (Diagonal preconditioner)\\n');\noptions.Method = 'pnewton0';\noptions.precFunc = @LogisticDiagPrecond;\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;\n\nfprintf('\\nRunning Preconditioned Hessian-Free Newton w/ numerical Hessian-Vector products (L-BFGS preconditioner)\\n');\noptions.Method = 'pnewton0';\noptions.precFunc = [];\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;\n\nfprintf('\\nRunning Hessian-Free Newton w/ analytic Hessian-Vector products\\n');\noptions.Method = 'newton0';\noptions.HvFunc = @LogisticHv;\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;\n\nfprintf('\\nRunning Preconditioned Hessian-Free Newton w/ analytic Hessian-Vector products (Diagonal preconditioner)\\n');\noptions.Method = 'pnewton0';\noptions.HvFunc = @LogisticHv;\noptions.precFunc = @LogisticDiagPrecond;\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;\n\nfprintf('\\nRunning Preconditioned Hessian-Free Newton w/ analytic Hessian-Vector products (L-BFGS preconditioner)\\n');\noptions.Method = 'pnewton0';\noptions.precFunc = [];\noptions.HvFunc = @LogisticHv;\nminFunc(@LogisticLoss,w_init,options,X,y);\npause;", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/minFunc_2012/logisticExample/example_minFunc_LR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7464004247345764}} {"text": "function K=kronSym(A,B)\n%%KRONSYM Take the symmetric Kronecker product of the matrices A and B. The\n% standard Kronecker product of two real, square matrices A and B,\n% one can write the following relation with respect to any real\n% square matrix S:\n% kron(A,B)*vec(S)==vec(B*S*A')\n% However, the symmetric Kronecker product is such that for any two\n% real square matrices A and B and a square SYMMETRIC matrix S, one\n% can write\n% kronSym(A,B)*vech(S,sqrt(2))==vech((1/2)*(B*S*A'+A*S*B'),sqrt(2))\n% Whereas is A and B are nXn, the standard kronecker product is\n% n^2Xn^2, the symmetric Kronecker product is\n% (n*(n+1)/2)X(n*(n+1)/2).\n%\n%INPUTS: A, B Two real nXn matrices. They need not be square.\n%\n%OUTPUTS: K The (n*(n+1)/2)X(n*(n+1)/2) symmetric Kronecker product of A\n% and B.\n%\n%Symmetric Kronecker products are discussed in the appendix of [1], where\n%they play a role in the implementation of a semidefinite programming\n%algorithm.\n%\n%The symmetric Kronecker product is implemented by noting that in the\n%identity\n%kronSym(A,B)*vech(S,sqrt(2))==vech((1/2)*(B*S*A'+A*S*B'),sqrt(2)), if S is\n%a symmetric matrix where on or below the main diagonal there is only a\n%single nonzero element, then one effectively selects a column of\n%kronSym(A,B). To get an unscaled column of kronSym(A,B), the nonzero\n%element should be 1 if it is on the main diagonal and it should be\n%1/sqrt(2) for elements below (and above) the main diagonal due to the\n%sqrt(2) scaling in the vech command. Basically, a simple implementation\n%would be \n% n=size(A,1);\n% prodDim=n*(n+1)/2;\n% \n% K=zeros(prodDim,prodDim);\n% SelMat=zeros(n,n);\n% for curEl=1:prodDim\n% [row,col]=vechInd2Sub(n,curEl);\n% if(row==col)\n% SelMat(row,col)=1;\n% else%row>col\n% SelMat(row,col)=1/sqrt(2);\n% SelMat(col,row)=1/sqrt(2);\n% end\n% K(:,curEl)=vech((1/2)*(B*SelMat*A'+A*SelMat*B'),sqrt(2));\n% \n% SelMat(row,col)=0;\n% SelMat(col,row)=0;\n% end\n%However, that is rather slow. Thus, this implementation tries to directly\n%write the elements of the output matrix K. \n%\n%REFERENCES:\n%[1] F. Alizadeh, J.-P. A. Haeberly, and M. L. Overton, \"Primal-dual\n% interior-point methods for semidefinite programming: Convergence\n% rates, stability and numerical results,\" SIAM Journal on Optimization,\n% vol. 8, no. 3, pp. 746-768, 1998.\n%\n%February 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%The columns of K are indexed using (i1,i2) and the rows are indexed using\n%(j1,j2).\nn=size(A,1);\nprodDim=n*(n+1)/2;\n\nK=zeros(prodDim,prodDim);\nsqrt2=sqrt(2);\ndblSqrt2=2*sqrt2;\nfor i1=1:n\n col=i1+(i1-1)*(2*n-i1)/2;\n for j1=1:n\n row=j1+(j1-1)*(2*n-j1)/2;\n \n K(row,col)=(A(j1,i1)*B(j1,i1)+B(j1,i1)*A(j1,i1))/2;\n for j2=(j1+1):n\n row=row+1;\n \n K(row,col)=(A(j1,i1)*B(j2,i1)+B(j1,i1)*A(j2,i1))/sqrt2;\n end\n end\n \n for i2=(i1+1):n\n col=col+1;\n for j1=1:n\n row=j1+(j1-1)*(2*n-j1)/2;\n \n K(row,col)=(A(j1,i1)*B(j1,i2)+A(j1,i2)*B(j1,i1)+B(j1,i1)*A(j1,i2)+B(j1,i2)*A(j1,i1))/dblSqrt2; \n for j2=(j1+1):n\n row=row+1;\n \n K(row,col)=(A(j1,i1)*B(j2,i2)+A(j1,i2)*B(j2,i1)+B(j1,i1)*A(j2,i2)+B(j1,i2)*A(j2,i1))/2;\n end\n end\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/Basic_Matrix_Operations/kronSym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7463857002453699}} {"text": "function m = nanmean(x,dim)\n%NANMEAN Mean value, ignoring NaNs.\n% M = NANMEAN(X) returns the sample mean of X, treating NaNs as missing\n% values. For vector input, M is the mean value of the non-NaN elements\n% in X. For matrix input, M is a row vector containing the mean value of\n% non-NaN elements in each column. For N-D arrays, NANMEAN operates\n% along the first non-singleton dimension.\n%\n% NANMEAN(X,DIM) takes the mean along dimension DIM of X.\n%\n% See also MEAN, NANMEDIAN, NANSTD, NANVAR, NANMIN, NANMAX, NANSUM.\n\n% Copyright 1993-2004 The MathWorks, Inc.\n% $Revision: 1.1.8.1 $ $Date: 2010/03/16 00:15:50 $\n\n% Find NaNs and set them to zero\nnans = isnan(x);\nx(nans) = 0;\n\nif nargin == 1 % let sum deal with figuring out which dimension to use\n % Count up non-NaNs.\n n = sum(~nans);\n n(n==0) = NaN; % prevent divideByZero warnings\n % Sum up non-NaNs, and divide by the number of non-NaNs.\n m = sum(x) ./ n;\nelse\n % Count up non-NaNs.\n n = sum(~nans,dim);\n n(n==0) = NaN; % prevent divideByZero warnings\n % Sum up non-NaNs, and divide by the number of non-NaNs.\n m = sum(x,dim) ./ n;\nend\n\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/wavedet/nanmean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8539127529517044, "lm_q1q2_score": 0.7463856981720465}} {"text": "function [xpeak, ypeak, max_f] = findpeak(f,subpixel)\n%FINDPEAK Find extremum of matrix.\n% [XPEAK,YPEAK,MAX_F] = FINDPEAK(F,SUBPIXEL) finds the extremum of F,\n% MAX_F, and its location (XPEAK, YPEAK). F is a matrix. MAX_F is the maximum\n% absolute value of F, or an estimate of the extremum if a subpixel\n% extremum is requested.\n%\n% SUBPIXEL is a boolean that controls if FINDPEAK attempts to estimate the\n% extremum location to subpixel precision. If SUBPIXEL is false, FINDPEAK\n% returns the coordinates of the maximum absolute value of F and MAX_F is\n% max(abs(F(:))). If SUBPIXEL is true, FINDPEAK fits a 2nd order\n% polynomial to the 9 points surrounding the maximum absolute value of\n% F. In this case, MAX_F is the absolute value of the polynomial evaluated\n% at its extremum.\n%\n% Note: Even if SUBPIXEL is true, there are some cases that result\n% in FINDPEAK returning the coordinates of the maximum absolute value\n% of F:\n% * When the maximum absolute value of F is on the edge of matrix F.\n% * When the coordinates of the estimated polynomial extremum would fall\n% outside the coordinates of the points used to constrain the estimate.\n\n% Copyright 1993-2004 The MathWorks, Inc.\n% \n\n% get absolute peak pixel\n[max_f, imax] = max(abs(f(:)));\n[ypeak, xpeak] = ind2sub(size(f),imax(1));\n \nif ~subpixel || ...\n xpeak==1 || xpeak==size(f,2) || ypeak==1 || ypeak==size(f,1) % on edge\n return % return absolute peak\n \nelse\n % fit a 2nd order polynomial to 9 points \n % using 9 pixels centered on irow,jcol \n u = f(ypeak-1:ypeak+1, xpeak-1:xpeak+1);\n u = u(:);\n x = [-1 -1 -1 0 0 0 1 1 1]';\n y = [-1 0 1 -1 0 1 -1 0 1]'; \n\n % u(x,y) = A(1) + A(2)*x + A(3)*y + A(4)*x*y + A(5)*x^2 + A(6)*y^2\n X = [ones(9,1), x, y, x.*y, x.^2, y.^2];\n \n % u = X*A\n A = X\\u;\n\n % get absolute maximum, where du/dx = du/dy = 0\n x_offset = (-A(3)*A(4)+2*A(6)*A(2)) / (A(4)^2-4*A(5)*A(6));\n y_offset = -1 / ( A(4)^2-4*A(5)*A(6))*(A(4)*A(2)-2*A(5)*A(3));\n\n if abs(x_offset)>1 || abs(y_offset)>1\n % adjusted peak falls outside set of 9 points fit,\n return % return absolute peak\n end\n \n % return only one-tenth of a pixel precision\n x_offset = round(10*x_offset)/10;\n y_offset = round(10*y_offset)/10; \n \n xpeak = xpeak + x_offset;\n ypeak = ypeak + y_offset; \n \n % Calculate extremum of fitted function\n max_f = [1 x_offset y_offset x_offset*y_offset x_offset^2 y_offset^2] * A;\n max_f = abs(max_f);\n \nend\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/REG/reg_fft/findpeak.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7463209578599639}} {"text": "function area = polygonArea3d(poly, varargin)\n%POLYGONAREA3D Area of a 3D polygon\n%\n% AREA = polygonArea3d(POLY)\n% POLY is given as a N-by-3 array of vertex coordinates. The resulting\n% area is positive.\n% Works also for polygons given as a cell array of polygons.\n%\n% Example\n% % area of a simple 3D square \n% poly = [10 30 20;20 30 20;20 40 20;10 40 20];\n% polygonArea3d(poly)\n% ans =\n% 100\n%\n% % Area of a 3D mesh\n% [v f] = createCubeOctahedron;\n% polygons = meshFacePolygons(v, f);\n% areas = polygonArea3d(polygons);\n% sum(areas)\n% ans =\n% 18.9282\n%\n% See also\n% polygons3d, triangleArea3d, polygonArea, polygonCentroid3d\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2012-02-24, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012 INRA - Cepia Software Platform.\n\n% HISTORY\n% 2013-08-20 add support for multiple polygons\n\n% Check multiple polygons\nif iscell(poly) || sum(sum(isnan(poly))) > 0\n % split the polygons into a cell array\n polygons = splitPolygons3d(poly);\n nPolys = length(polygons);\n \n % compute area of each polygon\n area = zeros(nPolys, 1);\n for i = 1:nPolys\n area(i) = polygonArea3d(polygons{i});\n end\n \n return;\nend\n\n% put the first vertex at origin (reducing computation errors for polygons\n% far from origin)\nv0 = poly(1, :);\npoly = bsxfun(@minus, poly, v0);\n\n% indices of next vertices\nN = size(poly, 1);\niNext = [2:N 1];\n\n% compute cross-product of each elementary triangle formed by origin and\n% two consecutive vertices\ncp = cross(poly, poly(iNext,:), 2);\n\n% choose one of the triangles as reference for the normal direction\nvn = vectorNorm(cp);\n[tmp, ind] = max(vn); %#ok\ncpRef = cp(ind,:);\n\n% compute the sign of the area of each triangle\n% (need to compute the sign explicitely, as the norm of the cross product\n% does not keep orientation within supporting plane)\nsign_i = sign(dot(cp, repmat(cpRef, N, 1), 2));\n\n% compute area of each triangle, using sign correction\narea_i = vectorNorm3d(cp) .* sign_i;\n\n% sum up individual triangles area\narea = sum(area_i) / 2;\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom3d/polygonArea3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7463209578599638}} {"text": "function cpu_timing ( n )\n\n%*****************************************************************************80\n%\n%% CPU_TIMING measures execution time with CPUTIME.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 March 2008\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CPU_TIMING:\\n' );\n fprintf ( 1, ' MATLAB has a built in command called CPUTIME,\\n' );\n fprintf ( 1, ' which measures the CPU time elapsed so far.\\n' );\n fprintf ( 1, ' The difference of two readings measures the work done lately.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TASK #1:\\n' )\n fprintf ( 1, ' Multiply two random dense matices of order N\\n' );\n fprintf ( 1, ' using MATLAB''s A*B operation.\\n' );\n \n A = rand ( n, n );\n B = rand ( n, n );\n\n t1 = cputime ( );\n C = A * B;\n t2 = cputime ( );\n\n f = n * n * n;\n w = f / 1000000;\n s = t2 - t1;\n r = w / s;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' MegaFLOPs = %d\\n', w );\n fprintf ( 1, ' Elapsed CPU time = %f\\n', s );\n fprintf ( 1, ' Rate = %f\\n', r );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TASK #2:\\n' )\n fprintf ( 1, ' Multiply two random dense matices of order N\\n' );\n fprintf ( 1, ' using explicit loops.\\n' );\n \n A = rand ( n, n );\n B = rand ( n, n );\n\n t1 = cputime ( );\n for i = 1 : n\n for k = 1 : n\n C(i,k) = 0;\n for j = 1 : n\n C(i,k) = C(i,k) + A(i,j) * B(j,k);\n end\n end\n end\n t2 = cputime ( );\n\n f = n * n * n;\n w = f / 1000000;\n s = t2 - t1;\n r = w / s;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' MegaFLOPs = %d\\n', w );\n fprintf ( 1, ' Elapsed CPU time = %f\\n', s );\n fprintf ( 1, ' Rate = %f\\n', 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/matlab/cpu_timing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7463209416307144}} {"text": "function cvx_optval = det_rootn( X )\n\n%DET_ROOTN nth-root of the determinant of an SPD matrix.\n% For a square matrix X, DET_ROOTN(X) returns\n% POW(DET(X),1/(size(X,1))\n% if X is symmetric (real) or Hermitian (complex) and positive semidefinite,\n% and -Inf otherwise.\n%\n% This function can be used in many convex optimization problems that call for\n% LOG(DET(X)) instead. For example, if the objective function contains nothing\n% but LOG(DET(X)), it can be replaced with DET_ROOTN(X), and the same optimal \n% point will be produced.\n%\n% Disciplined convex programming information:\n% DET_ROOTN is concave and nonmonotonic; therefore, when used in\n% CVX specifications, its argument must be affine.\n\nerror( nargchk( 1, 1, nargin ) );\nif ndims( X ) > 2 || size( X, 1 ) ~= size( X, 2 ),\n error( 'Second argument must be a square matrix.' );\nend\nerr = X - X';\nX = 0.5 * ( X + X' );\nif norm( err, 'fro' ) > 8 * eps * norm( X, 'fro' ),\n cvx_optval = -Inf;\nelse\n [R,p] = chol(X);\n if p > 0,\n cvx_optval = geo_mean(eig(full(X)));\n else\n cvx_optval = geo_mean(diag(R)).^2;\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", "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/det_rootn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7462806123551733}} {"text": "function yc = pwl_approx_1d ( nd, xd, yd, nc, xc )\n\n%*****************************************************************************80\n%\n%% PWL_APPROX_1D determines the control values for a PWL approximant.\n%\n% Discussion:\n%\n% The piecewise linear approximant is defined by NC control pairs \n% (XC(I),YC(I)) and approximates ND data pairs (XD(I),YD(I)).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 October 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ND, the number of data points.\n% ND must be at least 1.\n%\n% Input, real XD(ND,1), the data points.\n%\n% Input, real YD(ND,1), the data values.\n%\n% Input, integer NC, the number of control points.\n% NC must be at least 1.\n%\n% Input, real XC(NC,1), the control points.\n%\n% Output, real YC(NC,1), the control values.\n%\n\n%\n% Define the NDxNC linear system that determines the control values.\n%\n a = pwl_approx_1d_matrix ( nd, xd, yd, nc, xc );\n%\n% Solve the system.\n%\n yc = a \\ yd;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/pwl_approx_1d/pwl_approx_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.746280606724197}} {"text": "% peq.m - Parametric EQ with matching gain at Nyquist frequency\n% Author: Sophocles J. Orfanidis, \n% Usage: [b, a] = peq(G0, G, w0, Dw, NdB)\n%\n% G0 = reference gain at DC in dB\n% G = boost/cut gain in dB\n% GB = bandwidth gain in dB\n%\n% w0 = center frequency in Hz\n% Dw = bandwidth in Hz\n% NdB = amount of db less than the peak/notch gain as the bandwidth frequencies \n% b = [b0, b1, b2] = numerator coefficients\n% a = [1, a1, a2] = denominator coefficients\n\n% Modified by Arvind using the equations from IIR Filter Design Chapter in\n% the book\nfunction [b, a, beta] = peq(G0, G, w0, Dw, NdB)\n\n%Convert from Decibels to real values\nGB = G * NdB;\nG = (10^(G/20));\nGB = (10^(GB/20));\nG0 = (10^(G0/20));\n\n%Convert absolute frequencies to rads/sec\n%w0 = w0*2*pi/fs;\n%Dw = Dw*2*pi/fs;\n\nbeta = sqrt((GB^2-G0^2)/(G^2-GB^2)) * tan(Dw/2);\nb = [(G0+G*beta)/(1+beta) -(2*G0*cos(w0))/(1+beta) (G0-G*beta)/(1+beta)];\na = [1 -(2*cos(w0))/(1+beta) (1-beta)/(1+beta)];\n\n\n%***********************\n% double beta;\n% \n% beta = sqrt((GB[0]^2-G0[0]^2)/(G^2[0]-GB[0]^2)) * tan(Dw[0]/2)\n% Num[0] = (G0[0]+G[0]*beta)/(1+beta);\n% Num[1] = -(2*G0[0]*cos(w0[0]))/(1+beta) ;\n% Num[2] = (G0[0]-G[0]*beta)/(1+beta);\n% \n% Den[0] = 1;\n% Den[1] = -(2*cos(w0[0]))/(1+beta);\n% Den[2] = (1-beta)/(1+beta);\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/1963-3-band-parametric-equalizer/peq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250325, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7462600986201664}} {"text": "%% Transform Compression JPEG\n\n% JPEG Baseline Encoder\n\n% Jorge Calderon \n% University Of Antioquia\n% Created: November 2012\n% Modified: January 2013\n% Copyright 2012\n% All rights reserved\n\n%% Clean Workplace\n\nclear all;\nclose all;\nclc;\n\n%% Initialize Variables\n\ncheck = 0;\nstream=[];\n\nDCTQ=[...\n 16 11 10 16 24 40 51 61;...\n 12 12 14 19 26 58 60 55;...\n 14 13 16 24 40 57 69 56;...\n 14 17 22 29 51 87 80 62;...\n 18 22 37 56 68 109 103 77;...\n 24 36 55 64 81 194 113 92;...\n 49 64 78 87 103 121 120 101;...\n 72 92 95 98 112 100 103 99];\n\nz=[...\n 9 2 3 10 17 25 18 11 4 5 12 19 26 ...\n 33 41 34 27 20 13 6 7 14 21 28 35 ...\n 42 49 57 50 43 36 29 22 15 8 16 23 ...\n 30 37 44 51 58 59 52 45 38 31 24 32 ...\n 39 46 53 60 61 54 47 40 48 55 62 63 56 64];\n\n%% Read Image\n\nwhile check<1\n [img_in pathname]=uigetfile({'*.bmp;*.tif','Image(*.bmp,*.tif)'},'Select Uncompressed Image','Multiselect','off');\n if img_in>0\n cd(pathname)\n image = double(imread(img_in));\n [row, col, dim] = size(image);\n if col 0, compute and print knots and weights. Print moments check.\n% = 0, compute knots and weights.\n% < 0, compute and print knots and weights.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Compute the Gauss quadrature formula.\n%\n [ t, wts ] = cdgqf ( nt, kind, alpha, beta );\n%\n% Exit if no print required.\n%\n if ( lo == 0 )\n return\n end\n\n key = 1;\n mop = 2 * nt;\n m = mop + 1;\n mmex = max ( 2 * nt + 3, 1 );\n%\n% All knots have multiplicity = 1.\n%\n mlt = zeros(nt,1);\n mlt(1:nt) = 1;\n%\n% NDX(I) = I.\n%\n ndx = ( 1 : nt );\n\n w = zeros(m,1);\n\n chkqfs ( t, wts, mlt, nt, nt, ndx, key, mop, mmex, ...\n kind, alpha, beta, lo, 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/toms655/cgqfs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7460266925529367}} {"text": "function learningConvergence\n\nk = 10;\niter = 1:200;\n\nlblRate = LowerBoundLipshitzFirstOrder(iter);\nlbscRate = lowerBoundStronglyConvexFirstOrder(iter,k);\nsRate = subgradientConvergence(iter);\nnRate = stronglyConvexNesterovConvergence(iter,k);\nqRate = quadraticConvergence(iter,1/k);\nlgRate = LipschitzGradientConvergence(iter);\nscRate = stronglyConvexGradientConvergence(iter,k);\n\ncolors = {\n [0.9290, 0.6940, 0.1250];\t \t\n [0, 0.4470, 0.7410];\n \t[0.8500, 0.3250, 0.0980];\n [0, 0.4470, 0.7410];\n [0.8500, 0.3250, 0.0980];\n \t[0.4940, 0.1840, 0.5560];\t \t\n \t[0.4660, 0.6740, 0.1880];\t \t\n \t[0.3010, 0.7450, 0.9330]};\nstyle = {'-';'--';'--';'-';'-';'-';'-';}; \n\nrates = [sRate;lblRate;lbscRate;lgRate;scRate;nRate;qRate];\n\nfigure(1)\nsubplot(1,2,1);\nhold on\nfor i = 1:size(rates,1)\n plot(iter,rates(i,:),'Color',colors{i},'LineStyle',style{i});\nend\nlegend('Subgradient','LowerBound Lipshitz','LowerBound Strongly Convex', 'Lipschitz Diff Gradient','StronglyConvex Diff Gradient','Strongly Convex Diff Nesterov','Quadratic Diff')\n\nfigure(1)\nsubplot(1,2,2);\nhold on\nfor i = 1:size(rates,1)\nh = plot(iter,rates(i,:),'Color',colors{i},'LineStyle',style{i});\nset(gca,'yscale','log');\nend\n\n\nlegend('Subgradient','LowerBound Lipshitz','LowerBound Strongly Convex', 'Lipschitz Diff Gradient','StronglyConvex Diff Gradient','Strongly Convex Diff Nesterov','Quadratic Diff')\n\n\nend\n\nfunction rate = subgradientConvergence(x)\n\nrate = 1./sqrt(x);\n\nend\n\nfunction rate = LowerBoundLipshitzFirstOrder(x)\n\nrate = 1./(x + 1).^2;\n\nend\n\n\n\nfunction rate = LipschitzGradientConvergence(x)\n\nrate = 1./(x + 1);\n\nend\n\nfunction rate = stronglyConvexGradientConvergence(x,k)\n\nrate = (((k) - 1)/((k)+1)).^(x);\nend\n\n\nfunction rate = quadraticConvergence(x,k)\n\nrate = k.^(2.^x);\n\nend\n\n\nfunction rate = lowerBoundStronglyConvexFirstOrder(x,k)\n\nrate = ((sqrt(k) - 1)/(sqrt(k) + 1)).^(2*x);\n\nend\n\n\nfunction rate = stronglyConvexNesterovConvergence(x,k)\n\nrate = ((sqrt(k) - 1)/(sqrt(k)+1)).^(x);\n\nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/ImageProcessing/Old/learningConvergence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.746026690552515}} {"text": "function value = r8_lgmc ( x )\n\n%*****************************************************************************80\n%\n%% R8_LGMC evaluates the log gamma correction factor for an R8 argument.\n%\n% Discussion:\n%\n% For 10 <= X, compute the log gamma correction factor so that\n%\n% log ( gamma ( x ) ) = log ( sqrt ( 2 * pi ) )\n% + ( x - 0.5 ) * log ( x ) - x\n% + r8_lgmc ( x )\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 correction factor.\n%\n persistent algmcs\n persistent nalgm\n persistent xbig\n persistent xmax\n\n if ( isempty ( nalgm ) )\n\n algmcs = [ ...\n +0.1666389480451863247205729650822, ...\n -0.1384948176067563840732986059135E-04, ...\n +0.9810825646924729426157171547487E-08, ...\n -0.1809129475572494194263306266719E-10, ...\n +0.6221098041892605227126015543416E-13, ...\n -0.3399615005417721944303330599666E-15, ...\n +0.2683181998482698748957538846666E-17, ...\n -0.2868042435334643284144622399999E-19, ...\n +0.3962837061046434803679306666666E-21, ...\n -0.6831888753985766870111999999999E-23, ...\n +0.1429227355942498147573333333333E-24, ...\n -0.3547598158101070547199999999999E-26, ...\n +0.1025680058010470912000000000000E-27, ...\n -0.3401102254316748799999999999999E-29, ...\n +0.1276642195630062933333333333333E-30 ]';\n\n nalgm = r8_inits ( algmcs, 15, r8_mach ( 3 ) );\n xbig = 1.0 / sqrt ( r8_mach ( 3 ) );\n xmax = exp ( min ( log ( r8_mach ( 2 ) / 12.0 ), ...\n - log ( 12.0 * r8_mach ( 1 ) ) ) );\n end\n\n if ( x < 10.0 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_LGMC - Fatal error!\\n' );\n fprintf ( 1, ' X must be at least 10.\\n' );\n error ( 'R8_LGMC - Fatal error!' )\n\n elseif ( x < xbig )\n\n value = r8_csevl ( 2.0 * ( 10.0 / x ) ...\n * ( 10.0 / x ) - 1.0, algmcs, nalgm ) / x;\n\n elseif ( x < xmax )\n\n value = 1.0 / ( 12.0 * x );\n\n else\n\n value = 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/fn/r8_lgmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7459822585880623}} {"text": "function [ a, q, lambda, seed ] = r8symm_test ( n, lambda_mean, lambda_dev, ...\n seed )\n\n%*****************************************************************************80\n%\n%% R8SYMM_TEST determines a symmetric matrix with a certain eigenstructure.\n%\n% Discussion:\n%\n% An R8SYMM is a real symmetric matrix stored using full storage, and\n% using R8 arithmetic.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real LAMBDA_MEAN, the mean value of the normal\n% distribution from which the eigenvalues will be chosen.\n%\n% Input, real LAMBDA_DEV, the standard deviation of the normal\n% distribution from which the eigenvalues will be chosen.\n%\n% Input/output, integer SEED, a seed for the random\n% number generator.\n%\n% Output, real A(N,N), the test matrix.\n%\n% Output, real Q(N,N), the eigenvector matrix.\n%\n% Output, real LAMBDA(N), the eigenvalue vector.\n%\n \n%\n% Choose the eigenvalues LAMBDA.\n%\n [ lambda, seed ] = r8vec_normal ( n, lambda_mean, lambda_dev, seed );\n%\n% Get a random orthogonal matrix Q.\n%\n [ q, seed ] = r8mat_orth_uniform ( n, seed );\n%\n% Set A = Q * Lambda*I * Q'.\n%\n a = q * diag ( lambda ) * q';\n\n return\nend\n", "meta": {"author": "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_eigen/r8symm_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7459822503455228}} {"text": "function a=v_polygonarea(p)\n%V_POLYGONAREA Calculate the area of a polygon\n%\n% Inputs:\n% P(n,2) is the polygon vertices\n%\n% Outputs:\n% A is teh area of teh polygon\n%\n% The area is positive if the vertices go anti-clockwise around the polygon.\n%\n\n% Copyright (C) Mike Brookes 2009\n% Version: $Id: v_polygonarea.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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\np(end+1,:)=p(1,:); % append an extra point\na=0.5*sum((p(1:end-1,1)-p(2:end,1)).*(p(1:end-1,2)+p(2:end,2)),1);\nif ~nargout\n plot(p(:,1),p(:,2),'b-');\n mnx=[1.05 -0.05;-0.05 1.05]*[min(p);max(p)];\n set(gca,'xlim',mnx(:,1)','ylim',mnx(:,2)');\n title(sprintf('Area = %.2g',a));\nend\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_polygonarea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7459822445840629}} {"text": "% Figure 3.30e Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%\n\nclf;\nnum=1;\na=.5;\n\nzeta =1;\nden2=[1/(zeta*a) 1];\nden1=[1 2*zeta 1];\nden=conv(den1,den2);\nt=0:.1:10;\ny1=step(num,den,t);\n\nzeta =.7;\nden2=[1/(zeta*a) 1];\nden1=[1 2*zeta 1];\nden=conv(den1,den2);\ny2=step(num,den,t);\n\nzeta =.5;\nden2=[1/(zeta*a) 1];\nden1=[1 2*zeta 1];\nden=conv(den1,den2);\ny3=step(num,den,t);\n\naxis([1 10 .1 .9])\nplot(t,y1,'-',t,y2,'--',t,y3,'-.'),grid\ntitle('Fig. 3.30e Step response with extra pole, \\alpha= .5')\nxlabel('\\omega_n t')\nylabel('y(t)')\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig3_30e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.745982242523428}} {"text": "function [G]=gsp_low_stretch_tree(k)\n%GSP_LOW_STRETCH_TREE Initialize a low stretch tree\n% Usage: G = gsp_low_stretch_tree(k);\n% G = gsp_low_stretch_tree();\n%\n% Input parameters:\n% k : 2^k points on each side of the grid of vertices. (default 6)\n% Output parameters:\n% G : Graph structure.\n%\n% 'gsp_create_low_stretch_tree(k)' initializes a graph structure containing\n% the weighted adjacency matrix (G.W), the number of vertices (G.N), the \n% plotting coordinates (G.coords), the plotting coordinate limits \n% (G.limits), and the root of a low stretch tree on a grid of points.\n% There are $2^k$ points on each side of the grid, and therefore $2^{2k}$ \n% total vertices. The edge weights are all equal to 1.\n%\n% Example:::\n%\n% G = gsp_low_stretch_tree(3);\n% paramplot.show_edges = 1;\n% gsp_plot_graph(G,paramplot);\n%\n% See also: gsp_graph\n\n\n% Author : David I Shuman, Nathanael Perraudin\n\nif nargin < 1\n k = 6; \nend\n\nii=[2 3 1 1 4 3];\njj=[1 1 2 3 3 4];\n\nXCoords=[1, 2, 1, 2];\nYCoords=[1, 1, 2, 2];\n\nfor p=2:k\n % create the indicies of the weight matrice\n ii_new=[ii,ii+4^(p-1),ii+2*4^(p-1),ii+3*4^(p-1)];\n ii_new_middle=[4^(p-1),4^(p-1),4^(p-1)+(4^p+2)/3,5/3*4^(p-1)+1/3,4^(p-1)+(4^p+2)/3,3*4^(p-1)+1];\n ii=[ii_new,ii_new_middle];\n\n jj_new=[jj,jj+4^(p-1),jj+2*4^(p-1),jj+3*4^(p-1)]; \n jj_new_middle=[5/3*4^(p-1)+1/3,4^(p-1)+(4^p+2)/3,3*4^(p-1)+1,4^(p-1),4^(p-1),4^(p-1)+(4^p+2)/3];\n jj=[jj_new,jj_new_middle];\n \n % Create Coords\n YCoords=repmat(YCoords,1,2);\n YCoords_new=[YCoords,YCoords+2^(p-1)];\n YCoords=YCoords_new;\n\n XCoords_new=[XCoords,XCoords+2^(p-1)];\n XCoords=repmat(XCoords_new,1,2);\nend\n\nG.W=sparse(ii,jj,ones(size(ii)));\nG.coords=[XCoords',YCoords'];\n\nG.limits=[0,2^k+1,0,2^k+1];\nG.N=(2^k)^2;\nG.root=4^(k-1);\n\nG.plotting.edge_width=1.25;\nG.plotting.vertex_size=75;\n\nG.type = 'low strech tree';\n\nG = gsp_graph_default_parameters(G);\n\n\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/graphs/gsp_low_stretch_tree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7459822424393389}} {"text": "function y=rdct(x,n,a,b)\n%RDCT Discrete cosine transform of real data Y=(X,N,A,B)\n% Data is truncated/padded to length N.\n%\n% This routine is equivalent to multiplying by the matrix\n%\n% rdct(eye(n)) = diag([sqrt(2)*B/A repmat(2/A,1,n-1)]) * cos((0:n-1)'*(0.5:n)*pi/n)\n%\n% Default values of the scaling factors are A=sqrt(2N) and B=1 which\n% results in an orthogonal matrix. Other common values are A=1 or N and/or B=1 or sqrt(2). \n% If b~=1 then the columns are no longer orthogonal.\n%\n% see IRDCT for the inverse transform\n\n% BUG: in line 51 we should do chopping after transform and not before\n\nfl=size(x,1)==1;\nif fl x=x(:); end\n[m,k]=size(x);\nif nargin<2 n=m;\nend\nif nargin<4 b=1; \n if nargin<3 a=sqrt(2*n);\n end\n end\nif n>m x=[x; zeros(n-m,k)];\nelseif n,\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%% Set defaults:\nif nargin < 2 || isempty(tau)\n tau = 'ac';\nend\n\n%-------------------------------------------------------------------------------\n% Can set the time lag, tau, to be 'ac' or 'mi':\nif strcmp(tau,'ac')\n tau = CO_FirstCrossing(y,'ac',0,'discrete');\n % tau is first zero crossing of the autocorrelation function\nelseif strcmp(tau,'mi')\n tau = CO_FirstMin(y,'mi');\n % tau is the first minimum of the automutual information function\nend\nif isnan(tau)\n error('No valid setting for time delay. (Is the time series too short?)');\nend\n\n%-------------------------------------------------------------------------------\n% Compute trev quantities:\n\nyn = y(1:end-tau);\nyn1 = y(1+tau:end); % yn, tau steps ahead\n\n% The trev expression used in TSTOOL:\nout.raw = mean((yn1-yn).^3)/(mean((yn1-yn).^2))^(3/2);\n\n% The magnitude\nout.abs = abs(out.raw);\n\n% The numerator\nout.num = mean((yn1-yn).^3);\nout.absnum = abs(out.num);\n\n% The denominator\nout.denom = (mean((yn1-yn).^2))^(3/2);\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/CO_trev.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7458569809959179}} {"text": "function best_weights = GetBestMixingWeight(stand_dev_of_variables)\n% Best mixing of random variables with common mean\n% and built-in constraint\n% best_weights = GetBestMixingWeight(stand_dev_of_variables)\n%\n% Input argument\n% stand_dev_of_variables: standard deviation of each variable\n%\n% Output argument\n% best_weights: best set of weights for mixing random variables\n\n% Copyright 2016 Google Inc. All Rights Reserved.\n% Author: hidekik@google.com (Hideki Kawahara)\n\nnarginchk(1, 1);\nn_variables = length(stand_dev_of_variables);\nH = ones(n_variables - 1, n_variables - 1) * ...\n stand_dev_of_variables(n_variables) ^ 2;\nH = H + diag(stand_dev_of_variables(1 : n_variables - 1) .^ 2);\nv = ones(n_variables - 1, 1) * stand_dev_of_variables(n_variables) ^ 2;\na = H \\ v;\nbest_weights = [a; 1 - sum(a)];\nend\n", "meta": {"author": "google", "repo": "yang_vocoder", "sha": "45787d4bbbb5b36617424b95c19430ced277db23", "save_path": "github-repos/MATLAB/google-yang_vocoder", "path": "github-repos/MATLAB/google-yang_vocoder/yang_vocoder-45787d4bbbb5b36617424b95c19430ced277db23/GetBestMixingWeight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.745853053213254}} {"text": "function [LS,LD,I] = isolines(V,F,S,iso)\n % ISOLINES compute a list of isolines for a scalar field S defined on the\n % mesh (V,F)\n %\n % [LS,LD,I] = isolines(V,F,S,iso)\n %\n % Inputs:\n % V #V by dim list of vertex positions\n % F #F by 3 list of triangle indices\n % S #V list of scalar values defined on V\n % iso #iso list of iso values\n % Outputs:\n % LS #L by dim list of isoline start positions\n % LD #L by dim list of isoline destination positions\n % I #L list of indices into iso revealing corresponding iso value\n %\n % alternative: tracing isolines should result in smaller plot data (every\n % vertex only appears once\n %\n % Example:\n % iso = linspace(min(S),max(S),10);\n % [LS,LD] = isolines(V,F,S,iso);\n % colormap(jet(numel(iso)-1));\n % tsurf(F,V,'CData',S,fphong);\n % hold on;\n % plot([LS(:,1) LD(:,1)]',[LS(:,2) LD(:,2)]', ...\n % 'Color','k','LineWidth',10);\n % hold off;\n %\n\n % make sure iso is a ROW vector\n iso = iso(:)';\n % number of isolines\n niso = numel(iso);\n\n % number of domain positions\n n = size(V,1);\n % number of dimensions\n dim = size(V,2);\n\n % number of faces\n m = size(F,1);\n\n % Rename for convenience\n S1 = S(F(:,1),:);\n S2 = S(F(:,2),:);\n S3 = S(F(:,3),:);\n\n % t12(i,j) reveals parameter t where isovalue j falls on the line from\n % corner 1 to corner 2 of face i\n t12 = bsxfun(@rdivide,bsxfun(@minus,iso,S1),S2-S1);\n t23 = bsxfun(@rdivide,bsxfun(@minus,iso,S2),S3-S2);\n t31 = bsxfun(@rdivide,bsxfun(@minus,iso,S3),S1-S3);\n\n % replace values outside [0,1] with NaNs\n t12( (t12<-eps)|(t12>(1+eps)) ) = NaN;\n t23( (t23<-eps)|(t23>(1+eps)) ) = NaN;\n t31( (t31<-eps)|(t31>(1+eps)) ) = NaN;\n\n % masks for line \"parallel\" to 12\n l12 = ~isnan(t23) & ~isnan(t31);\n l23 = ~isnan(t31) & ~isnan(t12);\n l31 = ~isnan(t12) & ~isnan(t23);\n\n % find non-zeros (lines) from t23 to t31\n [F12,I12,~] = find(l12);\n [F23,I23,~] = find(l23);\n [F31,I31,~] = find(l31);\n % indices directly into t23 and t31 corresponding to F12 and I12\n %ti12 = sub2ind(size(l12),F12,I12);\n %ti23 = sub2ind(size(l23),F23,I23);\n %ti31 = sub2ind(size(l31),F31,I31);\n % faster sub2ind\n ti12 = F12+(I12-1)*size(l12,1);\n ti23 = F23+(I23-1)*size(l23,1);\n ti31 = F31+(I31-1)*size(l31,1);\n\n % compute actual position values\n LS = [ ...\n ... % average of vertex positions between 2 and 3\n bsxfun(@times,1-t23(ti12), V(F(F12,2),:)) + ...\n bsxfun(@times, t23(ti12), V(F(F12,3),:)) ...\n ; ... % average of vertex positions between 2 and 3\n bsxfun(@times,1-t31(ti23), V(F(F23,3),:)) + ...\n bsxfun(@times, t31(ti23), V(F(F23,1),:)) ...\n ;... % average of vertex positions between 2 and 3\n bsxfun(@times,1-t12(ti31), V(F(F31,1),:)) + ...\n bsxfun(@times, t12(ti31), V(F(F31,2),:)) ...\n ];\n LD = [...\n ... % hcat with average of vertex positions between 3 and 1\n bsxfun(@times,1-t31(ti12), V(F(F12,3),:)) + ...\n bsxfun(@times, t31(ti12), V(F(F12,1),:)) ...\n ;... % hcat with average of vertex positions between 3 and 1\n bsxfun(@times,1-t12(ti23), V(F(F23,1),:)) + ...\n bsxfun(@times, t12(ti23), V(F(F23,2),:)) ...\n ;... % hcat with average of vertex positions between 3 and 1\n bsxfun(@times,1-t23(ti31), V(F(F31,2),:)) + ...\n bsxfun(@times, t23(ti31), V(F(F31,3),:)) ...\n ];\n\n % I is just concatenation of each I12\n I = [I12;I23;I31];\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/isolines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7458499311761116}} {"text": "function [w] = projectSimplex(v)\n% Computest the minimum L2-distance projection of vector v onto the probability simplex\nnVars = length(v);\nmu = sort(v,'descend');\nsm = 0;\nfor j = 1:nVars\n sm = sm+mu(j);\n if mu(j) - (1/j)*(sm-1) > 0\n row = j;\n sm_row = sm;\n end\nend\ntheta = (1/row)*(sm_row-1);\nw = max(v-theta,0);", "meta": {"author": "rbgirshick", "repo": "voc-dpm", "sha": "c0b88564bd668bcc6216bbffe96cb061613be768", "save_path": "github-repos/MATLAB/rbgirshick-voc-dpm", "path": "github-repos/MATLAB/rbgirshick-voc-dpm/voc-dpm-c0b88564bd668bcc6216bbffe96cb061613be768/external/minConf/minConf/projectSimplex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7458218669515694}} {"text": "function [C,T]=hungarian(A)\n% HUNGARIAN - Solve the assignment problem using the Hungarian method.\n% \n% Usage: >> [C,T]=hungarian(A)\n%\n% Inputs:\n% A - a square (correlation/distance/cost) matrix.\n% C - the optimal assignment (closest row/col pairs)\n% T - the total (minimized) cost of the optimal assignment. \n%\n% Author: Niclas Borlin, 1996\n\n% Adapted from the FORTRAN IV code in Carpaneto and Toth, \"Algorithm 548:\n% Solution of the assignment problem [H]\", ACM Transactions on\n% Mathematical Software, 6(1):104-111, 1980.\n%\n% v1.0 96-06-14. Niclas Borlin, niclas@cs.umu.se.\n% Department of Computing Science, Ume University,\n% Sweden.\n%\n% NOTE: A substantial effort was put into this code. If you use it for a\n% publication or otherwise, please include an acknowledgement and notify\n% me by email. /Niclas\n\n[m,n]=size(A);\n\nif (m~=n)\n error('HUNGARIAN: Cost matrix must be square!');\nend\n\n% Save original cost matrix.\norig=A;\n\n% Reduce matrix.\nA=hminired(A);\n\n% Do an initial assignment.\n[A,C,U]=hminiass(A);\n\n% Repeat while we have unassigned rows.\nwhile (U(n+1))\n % Start with no path, no unchecked zeros, and no unexplored rows.\n LR=zeros(1,n);\n LC=zeros(1,n);\n CH=zeros(1,n);\n RH=[zeros(1,n) -1];\n \n % No labelled columns.\n SLC=[];\n \n % Start path in first unassigned row.\n r=U(n+1);\n % Mark row with end-of-path label.\n LR(r)=-1;\n % Insert row first in labelled row set.\n SLR=r;\n \n % Repeat until we manage to find an assignable zero.\n while (1)\n % If there are free zeros in row r\n if (A(r,n+1)~=0)\n % ...get column of first free zero.\n l=-A(r,n+1);\n \n % If there are more free zeros in row r and row r in not\n % yet marked as unexplored..\n if (A(r,l)~=0 && RH(r)==0)\n % Insert row r first in unexplored list.\n RH(r)=RH(n+1);\n RH(n+1)=r;\n \n % Mark in which column the next unexplored zero in this row\n % is.\n CH(r)=-A(r,l);\n end\n else\n % If all rows are explored..\n if (RH(n+1)<=0)\n % Reduce matrix.\n [A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR);\n end\n \n % Re-start with first unexplored row.\n r=RH(n+1);\n % Get column of next free zero in row r.\n l=CH(r);\n % Advance \"column of next free zero\".\n CH(r)=-A(r,l);\n % If this zero is last in the list..\n if (A(r,l)==0)\n % ...remove row r from unexplored list.\n RH(n+1)=RH(r);\n RH(r)=0;\n end\n end\n \n % While the column l is labelled, i.e. in path.\n while (LC(l)~=0)\n % If row r is explored..\n if (RH(r)==0)\n % If all rows are explored..\n if (RH(n+1)<=0)\n % Reduce cost matrix.\n [A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR);\n end\n \n % Re-start with first unexplored row.\n r=RH(n+1);\n end\n \n % Get column of next free zero in row r.\n l=CH(r);\n \n % Advance \"column of next free zero\".\n CH(r)=-A(r,l);\n \n % If this zero is last in list..\n if(A(r,l)==0)\n % ...remove row r from unexplored list.\n RH(n+1)=RH(r);\n RH(r)=0;\n end\n end\n \n % If the column found is unassigned..\n if (C(l)==0)\n % Flip all zeros along the path in LR,LC.\n [A,C,U]=hmflip(A,C,LC,LR,U,l,r);\n % ...and exit to continue with next unassigned row.\n break;\n else\n % ...else add zero to path.\n \n % Label column l with row r.\n LC(l)=r;\n \n % Add l to the set of labelled columns.\n SLC=[SLC l];\n \n % Continue with the row assigned to column l.\n r=C(l);\n \n % Label row r with column l.\n LR(r)=l;\n \n % Add r to the set of labelled rows.\n SLR=[SLR r];\n end\n end\nend\n\n% Calculate the total cost.\nT=sum(orig(logical(sparse(C,1:size(orig,2),1))));\n\n\nfunction A=hminired(A)\n%HMINIRED Initial reduction of cost matrix for the Hungarian method.\n%\n%B=assredin(A)\n%A - the unreduced cost matris.\n%B - the reduced cost matrix with linked zeros in each row.\n\n% v1.0 96-06-13. Niclas Borlin, niclas@cs.umu.se.\n\n[m,n]=size(A);\n\n% Subtract column-minimum values from each column.\ncolMin=min(A);\nA=A-colMin(ones(n,1),:);\n\n% Subtract row-minimum values from each row.\nrowMin=min(A')';\nA=A-rowMin(:,ones(1,n));\n\n% Get positions of all zeros.\n[i,j]=find(A==0);\n\n% Extend A to give room for row zero list header column.\nA(1,n+1)=0;\nfor k=1:n\n % Get all column in this row. \n cols=j(k==i)';\n % Insert pointers in matrix.\n A(k,[n+1 cols])=[-cols 0];\nend\n\n\nfunction [A,C,U]=hminiass(A)\n%HMINIASS Initial assignment of the Hungarian method.\n%\n%[B,C,U]=hminiass(A)\n%A - the reduced cost matrix.\n%B - the reduced cost matrix, with assigned zeros removed from lists.\n%C - a vector. C(J)=I means row I is assigned to column J,\n% i.e. there is an assigned zero in position I,J.\n%U - a vector with a linked list of unassigned rows.\n\n% v1.0 96-06-14. Niclas Borlin, niclas@cs.umu.se.\n\n[n,np1]=size(A);\n\n% Initialize return vectors.\nC=zeros(1,n);\nU=zeros(1,n+1);\n\n% Initialize last/next zero \"pointers\".\nLZ=zeros(1,n);\nNZ=zeros(1,n);\n\nfor i=1:n\n % Set j to first unassigned zero in row i.\n\tlj=n+1;\n\tj=-A(i,lj);\n\n % Repeat until we have no more zeros (j==0) or we find a zero\n\t% in an unassigned column (c(j)==0).\n \n\twhile (C(j)~=0)\n\t\t% Advance lj and j in zero list.\n\t\tlj=j;\n\t\tj=-A(i,lj);\n\t\n\t\t% Stop if we hit end of list.\n\t\tif (j==0)\n\t\t\tbreak;\n\t\tend\n\tend\n\n\tif (j~=0)\n\t\t% We found a zero in an unassigned column.\n\t\t\n\t\t% Assign row i to column j.\n\t\tC(j)=i;\n\t\t\n\t\t% Remove A(i,j) from unassigned zero list.\n\t\tA(i,lj)=A(i,j);\n\n\t\t% Update next/last unassigned zero pointers.\n\t\tNZ(i)=-A(i,j);\n\t\tLZ(i)=lj;\n\n\t\t% Indicate A(i,j) is an assigned zero.\n\t\tA(i,j)=0;\n\telse\n\t\t% We found no zero in an unassigned column.\n\n\t\t% Check all zeros in this row.\n\n\t\tlj=n+1;\n\t\tj=-A(i,lj);\n\t\t\n\t\t% Check all zeros in this row for a suitable zero in another row.\n\t\twhile (j~=0)\n\t\t\t% Check the in the row assigned to this column.\n\t\t\tr=C(j);\n\t\t\t\n\t\t\t% Pick up last/next pointers.\n\t\t\tlm=LZ(r);\n\t\t\tm=NZ(r);\n\t\t\t\n\t\t\t% Check all unchecked zeros in free list of this row.\n\t\t\twhile (m~=0)\n\t\t\t\t% Stop if we find an unassigned column.\n\t\t\t\tif (C(m)==0)\n\t\t\t\t\tbreak;\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t% Advance one step in list.\n\t\t\t\tlm=m;\n\t\t\t\tm=-A(r,lm);\n\t\t\tend\n\t\t\t\n\t\t\tif (m==0)\n\t\t\t\t% We failed on row r. Continue with next zero on row i.\n\t\t\t\tlj=j;\n\t\t\t\tj=-A(i,lj);\n\t\t\telse\n\t\t\t\t% We found a zero in an unassigned column.\n\t\t\t\n\t\t\t\t% Replace zero at (r,m) in unassigned list with zero at (r,j)\n\t\t\t\tA(r,lm)=-j;\n\t\t\t\tA(r,j)=A(r,m);\n\t\t\t\n\t\t\t\t% Update last/next pointers in row r.\n\t\t\t\tNZ(r)=-A(r,m);\n\t\t\t\tLZ(r)=j;\n\t\t\t\n\t\t\t\t% Mark A(r,m) as an assigned zero in the matrix . . .\n\t\t\t\tA(r,m)=0;\n\t\t\t\n\t\t\t\t% ...and in the assignment vector.\n\t\t\t\tC(m)=r;\n\t\t\t\n\t\t\t\t% Remove A(i,j) from unassigned list.\n\t\t\t\tA(i,lj)=A(i,j);\n\t\t\t\n\t\t\t\t% Update last/next pointers in row r.\n\t\t\t\tNZ(i)=-A(i,j);\n\t\t\t\tLZ(i)=lj;\n\t\t\t\n\t\t\t\t% Mark A(r,m) as an assigned zero in the matrix . . .\n\t\t\t\tA(i,j)=0;\n\t\t\t\n\t\t\t\t% ...and in the assignment vector.\n\t\t\t\tC(j)=i;\n\t\t\t\t\n\t\t\t\t% Stop search.\n\t\t\t\tbreak;\n\t\t\tend\n\t\tend\n\tend\nend\n\n% Create vector with list of unassigned rows.\n\n% Mark all rows have assignment.\nr=zeros(1,n);\nrows=C(C~=0);\nr(rows)=rows;\nempty=find(r==0);\n\n% Create vector with linked list of unassigned rows.\nU=zeros(1,n+1);\nU([n+1 empty])=[empty 0];\n\n\nfunction [A,C,U]=hmflip(A,C,LC,LR,U,l,r)\n%HMFLIP Flip assignment state of all zeros along a path.\n%\n%[A,C,U]=hmflip(A,C,LC,LR,U,l,r)\n%Input:\n%A - the cost matrix.\n%C - the assignment vector.\n%LC - the column label vector.\n%LR - the row label vector.\n%U - the \n%r,l - position of last zero in path.\n%Output:\n%A - updated cost matrix.\n%C - updated assignment vector.\n%U - updated unassigned row list vector.\n\n% v1.0 96-06-14. Niclas Borlin, niclas@cs.umu.se.\n\nn=size(A,1);\n\nwhile (1)\n % Move assignment in column l to row r.\n C(l)=r;\n \n % Find zero to be removed from zero list..\n \n % Find zero before this.\n m=find(A(r,:)==-l);\n \n % Link past this zero.\n A(r,m)=A(r,l);\n \n A(r,l)=0;\n \n % If this was the first zero of the path..\n if (LR(r)<0)\n % remove row from unassigned row list and return.\n U(n+1)=U(r);\n U(r)=0;\n return;\n else\n \n % Move back in this row along the path and get column of next zero.\n l=LR(r);\n \n % Insert zero at (r,l) first in zero list.\n A(r,l)=A(r,n+1);\n A(r,n+1)=-l;\n \n % Continue back along the column to get row of next zero in path.\n r=LC(l);\n end\nend\n\n\nfunction [A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR)\n%HMREDUCE Reduce parts of cost matrix in the Hungerian method.\n%\n%[A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR)\n%Input:\n%A - Cost matrix.\n%CH - vector of column of 'next zeros' in each row.\n%RH - vector with list of unexplored rows.\n%LC - column labels.\n%RC - row labels.\n%SLC - set of column labels.\n%SLR - set of row labels.\n%\n%Output:\n%A - Reduced cost matrix.\n%CH - Updated vector of 'next zeros' in each row.\n%RH - Updated vector of unexplored rows.\n\n% v1.0 96-06-14. Niclas Borlin, niclas@cs.umu.se.\n\nn=size(A,1);\n\n% Find which rows are covered, i.e. unlabelled.\ncoveredRows=LR==0;\n\n% Find which columns are covered, i.e. labelled.\ncoveredCols=LC~=0;\n\nr=find(~coveredRows);\nc=find(~coveredCols);\n\n% Get minimum of uncovered elements.\nm=min(min(A(r,c)));\n\n% Subtract minimum from all uncovered elements.\nA(r,c)=A(r,c)-m;\n\n% Check all uncovered columns..\nfor j=c\n % ...and uncovered rows in path order..\n for i=SLR\n % If this is a (new) zero..\n if (A(i,j)==0)\n % If the row is not in unexplored list..\n if (RH(i)==0)\n % ...insert it first in unexplored list.\n RH(i)=RH(n+1);\n RH(n+1)=i;\n % Mark this zero as \"next free\" in this row.\n CH(i)=j;\n end\n % Find last unassigned zero on row I.\n row=A(i,:);\n colsInList=-row(row<0);\n if (length(colsInList)==0)\n % No zeros in the list.\n l=n+1;\n else\n l=colsInList(row(colsInList)==0);\n end\n % Append this zero to end of list.\n A(i,l)=-j;\n end\n end\nend\n\n% Add minimum to all doubly covered elements.\nr=find(coveredRows);\nc=find(coveredCols);\n\n% Take care of the zeros we will remove.\n[i,j]=find(A(r,c)<=0);\n\ni=r(i);\nj=c(j);\n\nfor k=1:length(i)\n % Find zero before this in this row.\n lj=find(A(i(k),:)==-j(k));\n % Link past it.\n A(i(k),lj)=A(i(k),j(k));\n % Mark it as assigned.\n A(i(k),j(k))=0;\nend\n\nA(r,c)=A(r,c)+m;\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/miscfunc/hungarian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654264, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7458145824881695}} {"text": "function [ vX, mX ] = SolveLsL1Admm( vX, mA, vY, paramLambda, sSolverParams )\n% ----------------------------------------------------------------------------------------------- %\n%[ vX ] = SolveProxTvAdmm( vY, mD, paramLambda, numIterations )\n% Solves the L1 Norm Regualrized Least Squares using Alternating\n% Direction Method of Multipliers (ADMM) Method.\n% Basically solves the problem given by:\n% $$ \\arg \\min_{ x \\in \\mathbb{R}^{n} } \\frac{1}{2} {\\left\\| A x - y \\right|}_{2}^{2} + \\lambda {\\left\\| x \\right\\|}_{1} $$\n% Input:\n% - vX - Optimization Vector.\n% The vector to be optimized. Initialization of\n% the iterative process.\n% Structure: Vector (n X 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - mA - Input Matirx.\n% The model matrix.\n% Structure: Matrix (m X n).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - vY - Measurements 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% - paramRho - The Rho Parameter.\n% Sets the weight of the equality constraint.\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 ADMM - https://en.wikipedia.org/wiki/Augmented_Lagrangian_method#Alternating_direction_method_of_multipliers.\n% Remarks:\n% 1. Using vanilla ADMM with no optimization of the parameter or\n% smoothing.\n% 2. For high values of `paramLambda` it will require many iterations.\n% Known Issues:\n% 1. C\n% TODO:\n% 1. D\n% Release Notes:\n% - 1.0.000 05/08/2021 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\narguments\n vX (:, 1) {mustBeFloat, mustBeReal}\n mA (:, :) {mustBeFloat, mustBeReal}\n vY (:, 1) {mustBeFloat, mustBeReal}\n paramLambda (1, 1) {mustBeFloat, mustBeReal, mustBePositive}\n sSolverParams.paramRho (1, 1) {mustBeNumeric, mustBeReal, mustBePositive} = 5\n sSolverParams.numIterations (1, 1) {mustBeNumeric, mustBeReal, mustBePositive, mustBeInteger} = 100\nend\n\nMAT_TYPE_SKINNY = 1;\nMAT_TYPE_FAT = 2;\n\nif(size(mA, 1) >= size(mA, 2))\n matType = MAT_TYPE_SKINNY;\nelse\n matType = MAT_TYPE_FAT;\nend\n\nparamRho = sSolverParams.paramRho;\nnumIterations = sSolverParams.numIterations;\n\nmX = zeros(size(mA, 2), numIterations);\n\n% Caching facotirzation\nmC = MatrixFactorize(mA, paramRho, matType);\nvAy = mA.' * vY;\n\nvZ = ProxL1(vX, paramLambda / paramRho);\nvU = vX - vZ;\n\nmX(:, 1) = vX;\n\nfor ii = 2:numIterations\n \n vQ = vAy + (paramRho * (vZ - vU));\n \n % Matrix Inversion Lemma\n switch(matType)\n case(MAT_TYPE_SKINNY)\n vX = mC \\ vQ;\n case(MAT_TYPE_FAT)\n vX = (vQ / paramRho) - ((mA.' * (mC \\ (mA * vQ))) / (paramRho * paramRho));\n end\n \n vZ = ProxL1(vX + vU, paramLambda / paramRho);\n vU = vU + vX - vZ;\n \n mX(:, ii) = vX;\n \nend\n\n\nend\n\n\nfunction [ mC ] = MatrixFactorize( mA, paramRho, matType )\n\nMAT_TYPE_SKINNY = 1;\nMAT_TYPE_FAT = 2;\n\nswitch(matType)\n case(MAT_TYPE_SKINNY)\n mI = speye(size(mA, 2)); \n mC = decomposition((mA.' * mA) + (paramRho * mI), 'chol');\n case(MAT_TYPE_FAT)\n mI = speye(size(mA, 1));\n mC = decomposition(mI + ((1 / paramRho) * (mA * mA.')), 'chol');\nend\n\n\nend\n\n\nfunction [ vX ] = ProxL1( vX, lambdaFactor )\n\n% Soft Thresholding\nvX = max(vX - lambdaFactor, 0) + min(vX + lambdaFactor, 0);\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/SignalProcessing/Q76626/SolveLsL1Admm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7457835006930069}} {"text": "%DELTA2TR Convert differential motion to SE(3) homogeneous transform\n%\n% T = DELTA2TR(D) is a homogeneous transform (4x4) representing differential \n% motion D (6x1). \n%\n% The vector D=(dx, dy, dz, dRx, dRy, dRz) represents infinitessimal translation\n% and rotation, and is an approximation to the instantaneous spatial velocity \n% multiplied by time step.\n%\n% Reference::\n% - Robotics, Vision & Control: Second Edition, P. Corke, Springer 2016; p67.\n%\n% See also tr2delta, SE3.delta.\n\n% Copyright (C) 1993-2019 Peter I. Corke\n%\n% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n% of the Software, and to permit persons to whom the Software is furnished to do\n% so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%\n% https://github.com/petercorke/spatial-math\n\nfunction delta = delta2tr(d)\n d = d(:);\n delta = eye(4,4) + [skew(d(4:6)) d(1:3); 0 0 0 0];\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/delta2tr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7457282134313689}} {"text": "function X = PQRFFT (x, N, ifn)\n% Calculate the DFT of a real N-point sequence or the inverse\n% DFT corresponding to a real N-point sequence.\n% ifn > 0, forward transform\n% input x(n) - N real values\n% output X(k) - The first N/2+1 points are the real\n% parts of the transform, the next N/2-1 points\n% are the imaginary parts of the transform. However\n% the imaginary part for the first point and the\n% middle point which are known to be zero are not\n% stored.\n% ifn < 0, inverse transform\n% input X(k) - The first N/2+1 points are the real\n% parts of the transform, the next N/2-1 points\n% are the imaginary parts of the transform. However\n% the imaginary part for the first point and the\n% middle point which are known to be zero are not\n% stored. \n% output x(n) - N real values\n\n% P. Kabal $Revision: 1.1 $ $Date: 2003/12/07 13:34:11 $\n\nif (ifn > 0)\n X = fft (x, N);\n XR = real(X(0+1:N/2+1));\n XI = imag(X(1+1:N/2-1+1));\n X = [XR XI];\nelse\n xR = [x(0+1:N/2+1)];\n xI = [0 x(N/2+1+1:N-1+1) 0];\n x = complex ([xR xR(N/2-1+1:-1:1+1)], [xI -xI(N/2-1+1:-1:1+1)]);\n X = real (ifft (x, N));\nend\n", "meta": {"author": "stephencwelch", "repo": "Perceptual-Coding-In-Python", "sha": "2993f57570663768c02745019185091a23f021fe", "save_path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python", "path": "github-repos/MATLAB/stephencwelch-Perceptual-Coding-In-Python/Perceptual-Coding-In-Python-2993f57570663768c02745019185091a23f021fe/PEAQPython/PQevalAudioMATLAB/PQevalAudio/Misc/PQRFFT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.7456993686443671}} {"text": "%% this is an implementation of kalman filter using belief propagation.\n% author: Shuang Wang\n% email: shw070@ucsd.edu\n% Division of Biomedical Informatics, University of California, San Diego.\n\nclear;\naddpath(genpath('.'));\n%%\n% x_k = A x_t-1 + q; N(0, V_Q);\n% y_k = B x_k + w; N(0, V_W);\n% x_1 ~ N(mu_0, V_0);\n\n%% generating fake data.\ns = RandStream('mt19937ar','Seed',4);\nRandStream.setGlobalStream(s);\nT = 40;\nx = zeros(2, T);\ny = zeros(2, T);\nd_y = size(y, 1);\nd_x = size(x, 1);\nmu_0 = [4; 4];\nV_0 = [1, 0\n 0, 1];\nV_Q = [0.1, 0\n 0, 0.3];\nV_W = [0.05, 0\n 0, 0.1];\nA = [ 1, 0.04\n 0.02, 1];\nB = [1, 0\n 0, 1];\n\n x(:, 1) = mvnrnd(mu_0, V_0, 1)';\n y(:, 1) = B * x(:, 1) + mvnrnd([0, 0], V_W, 1)';\n for t = 2:T\n x(:, t) = A * x(:, t-1) + mvnrnd([0, 0], V_Q, 1)';\n y(:, t) = B * x(:, t) + mvnrnd([0, 0], V_W, 1)';\n end\n \n[msg, varNode_x, factorNode_x, factorNode_y, belief] = initializeMessage(T, mu_0, V_0, d_x, y, B, V_W);\n \nfor bp_iter = 1:2*T\n %% variable node update\n for i = 1:T\n if (i < T)\n msg{varNode_x{i}.backwardNeighborMsgID}.toFactorNode ...\n = GaussianMultiply(msg{varNode_x{i}.forwardNeighborMsgID}.toVarNode,...\n msg{varNode_x{i}.lowerNeighborMsgID}.toVarNode);\n \n msg{varNode_x{i}.forwardNeighborMsgID}.toFactorNode ...\n = GaussianMultiply(msg{varNode_x{i}.backwardNeighborMsgID}.toVarNode,...\n msg{varNode_x{i}.lowerNeighborMsgID}.toVarNode);\n else\n msg{varNode_x{i}.backwardNeighborMsgID}.toFactorNode = msg{varNode_x{i}.lowerNeighborMsgID}.toVarNode;\n end\n end\n \n %% factor node update\n for i = 2:T\n msg{factorNode_x{i}.forwardNeighborMsgID}.toVarNode.mu ...\n = A * msg{factorNode_x{i}.backwardNeighborMsgID}.toFactorNode.mu;\n if(~isempty(msg{factorNode_x{i}.backwardNeighborMsgID}.toFactorNode.V))\n msg{factorNode_x{i}.forwardNeighborMsgID}.toVarNode.V ...\n = A * msg{factorNode_x{i}.backwardNeighborMsgID}.toFactorNode.V * (A') + V_Q;\n msg{factorNode_x{i}.forwardNeighborMsgID}.toVarNode.iV = [];\n else\n msg{factorNode_x{i}.forwardNeighborMsgID}.toVarNode.V = [];\n tmp_iAtiviA = (A')\\msg{factorNode_x{i}.backwardNeighborMsgID}.toFactorNode.iV/A;\n msg{factorNode_x{i}.forwardNeighborMsgID}.toVarNode.iV ...\n = tmp_iAtiviA -(eye(d_x) + tmp_iAtiviA*V_Q)\\tmp_iAtiviA*V_Q*tmp_iAtiviA;\n end\n msg{factorNode_x{i}.backwardNeighborMsgID}.toVarNode.mu ...\n = A\\msg{factorNode_x{i}.forwardNeighborMsgID}.toFactorNode.mu;\n if(~isempty(msg{factorNode_x{i}.forwardNeighborMsgID}.toFactorNode.V))\n msg{factorNode_x{i}.backwardNeighborMsgID}.toVarNode.iV = [];\n msg{factorNode_x{i}.backwardNeighborMsgID}.toVarNode.V ...\n = A\\(msg{factorNode_x{i}.forwardNeighborMsgID}.toFactorNode.V + V_Q)/(A');\n else\n tmp_iv = msg{factorNode_x{i}.forwardNeighborMsgID}.toFactorNode.iV;\n msg{factorNode_x{i}.backwardNeighborMsgID}.toVarNode.V = [];\n msg{factorNode_x{i}.backwardNeighborMsgID}.toVarNode.iV ...\n = (A')*(tmp_iv -(eye(d_x) + tmp_iv*V_Q)\\tmp_iv*V_Q*tmp_iv)*A;\n end\n end\nend % bp_iter\n\n%% update belief\nfor i = 1:T\n belief{i} = GaussianMultiply(msg{varNode_x{i}.backwardNeighborMsgID}.toFactorNode,...\n msg{varNode_x{i}.backwardNeighborMsgID}.toVarNode);\n mu_tmp_sm(:,i) = belief{i}.mu;\nend\n%%\nfigure(1); clf;\nplot(x(1, :), x(2, :), '.'); hold on;\nplot(y(1, :), y(2, :), 'ro'); hold on;\nplot(mu_tmp_sm(1, :), mu_tmp_sm(2, :), 'g*'); hold on;\nh = legend('Hidden state', 'observation', 'kalman smoother');\nset(h, 'box', 'off', 'location', 'best');\nfprintf('SAD:x_z = %f\\n', sum(abs((y(:) - x(:)))));\nfprintf('SAD:kf_sm_z = %f\\n', sum(abs((mu_tmp_sm(:) - x(:)))));", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39661-implementations-of-kalman-filter-using-both-message-passing-algorithm-and-standard-matrix-operations/BP_kalmanFilter/Demo_KalmanFilter_BP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7456736181302029}} {"text": "% AUTHOR : CHANDAN KUMAR\n% SUBJECT: COMPUTER GRAPHICS AND SOLID MODELLING.\n% TITLE : LINE CLIPPING ALGORITHM (CYRUS BECK )\n% DATE : 31/08/09\nfunction lineclip()\nclc, clear all;\nx = input('Give coord[ x0 y0 x1 y1]: ');\nv = input('Give Viewport coord[vx0 vy0 vx1 vy1]: '); \nd = [(x(3)-x(1)) (x(4)-x(2)) -(x(3)-x(1)) -(x(4)-x(2))]; \nfor i = 1:4\n if (i==1)||(i==3)\n j =1;\n else\n j =2;\n end\n t(i) = (v(i)-x(j))/d(j);\nend\ntl = min(t(1),t(3));\nti = max(t(2),t(4));\n \nz(1) = x(1) +d(1)*ti ; % x coord of clipped line\nz(3) = x(1) +d(1)*tl ; % end X coord of clipped line\nz(2) = x(2) +d(2)*ti ;\nz(4) = x(2) +d(2)*tl ;\n\nplot([z(1) z(3)] ,[z(2) z(4)],'r-','LineWidth',2); % Plots Clipped line\nhold on,grid on\nplot([v(1) v(1)] ,[v(2) v(4)],'b-','LineWidth',2); % Plots Viewport\nplot([x(1) z(3)],[x(2) z(4)],'k-'); % Plots Unclipped line\nlegend('Clipped line','Viewport','Unclipped line',3)\nplot([z(1) x(3)],[z(2) x(4)],'k-'); % Plots Unclipped line\nplot([v(1) v(3)] ,[v(2) v(2)],'b-','LineWidth',2); % Plots Viewport\nplot([v(3) v(3)] ,[v(2) v(4)],'b-','LineWidth',2); % Plots Viewport\nplot([v(1) v(3)] ,[v(4) v(4)],'b-','LineWidth',2); % Plots Viewport\naxis([v(1)-1 v(3)+1 v(2)-1 v(4)+1]);\ntitle('Line clipping by Cyrus Beck algorithm')", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/25528-line-clipping/lineclip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129329, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7456736095793585}} {"text": "function a = myiswt2(swc, lo_r, hi_r)\n% ISWT2 Inverse discrete stationary wavelet transform 2-D.\n% ISWT2 performs a multilevel 2-D stationary wavelet\n% reconstruction using either a specific orthogonal wavelet\n% ('wname', see WFILTERS for more information) or specific\n% reconstruction filters (Lo_r and Hi_r).\n%\n% Filters lo_r and hi_r must be normalized by dividing by sqrt(2)\n% (necessary for implmentation of Stationary Discrete WT)\n%\n% For X = MYISWT2(swc,Lo_r,Hi_r)\n% swc contains H(1:N) V(1:N) D(1:N) A(N)\n% lo_r is the reconstruction low-pass filter.\n% hi_r is the reconstruction high-pass filter.\n%\n% See also IDWT2, SWT2, WAVEREC2.\n\n% based on iswt2.m\n% Sathish Ramani, October 11, 2009\n\n%% Set DWT_Mode to 'per'.\nold_modeDWT = dwtmode('status','nodisp');\nmodeDWT = 'per';\ndwtmode(modeDWT,'nodisp');\n\n%% Load coefficients\nn = (size(swc, 3)-1)/3; %% Number of levels\nh = swc(:,:,1:n);\nv = swc(:,:,n+1:2*n);\nd = swc(:,:,2*n+1:3*n);\na = swc(:,:,3*n+1);\n\n[rx, cx, dump] = size(h);\nfor k = n:-1:1\n\tstep = 2^(k-1);\n\tlast = step;\n\tfor first1 = 1:last\n\t\tiRow = first1:step:rx;\n\t\tlR = length(iRow);\n\t\tfor first2 = 1:last\n\t\t\tiCol = first2:step:cx;\n\t\t\tlC = length(iCol);\n\t\t\tsR = iRow;\n\t\t\tsC = iCol;\n\t\t\ta(iRow,iCol) = idwt2LOC(a(sR,sC), h(sR,sC,k), v(sR,sC,k), d(sR,sC,k), ...\n\t\t\t\tlo_r, hi_r, [lR lC]);\n\t\tend\n\tend\nend\n\n% Restore DWT_Mode.\ndwtmode(old_modeDWT, 'nodisp');\n\n\n%===============================================================%\n% INTERNAL FUNCTIONS\n%===============================================================%\nfunction y = idwt2LOC(a, h, v, d, lo_r, hi_r, sy)\n\ny = upconvLOC(a,lo_r,lo_r,sy) ... % Approximation\n\t+ upconvLOC(h,hi_r,lo_r,sy) ... % Horizontal Detail\n\t+ upconvLOC(v,lo_r,hi_r,sy) ... % Vertical Detail\n\t+ upconvLOC(d,hi_r,hi_r,sy); % Diagonal Detail\n\n%---------------------------------------------------------------%\nfunction y = upconvLOC(x, f1, f2, s)\n\nlf = length(f1);\n% y = dyadup(x,'mat',0,1);\ny = x;\ny = wextend('2D', 'per', y, [lf/2,lf/2]);\ny = wconv2('col', y, f1);\ny = wconv2('row', y, f2);\ny = wkeep2(y, s, [lf lf]);\n%===============================================================%\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/penalty/myiswt2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7456500580393648}} {"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\nfunction pathS = MC_BS(S0,r,d,T,sigma,NTime,NSim,NBatches)\n%\n% Path discretization in a Black-Scholes 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% NBatches number of batches\n\nDelta = T/NTime; % The discretisation step\n\npathS = zeros(NSim,NTime+1,NBatches);\nlnS1 = zeros(NSim,NTime+1); % init the logspot price path\nlnS1(:,1)=log(S0*exp(-d*T)); % adjust due to dividend yield\n\nomega = (r-d-0.5*sigma^2) * Delta;\n\nfor l = 1:NBatches\n dW = randn(NSim,NTime); % precompute all randoms\n\n for i=2:NTime+1\n lnS1(:,i) = lnS1(:,i-1) + omega + sigma* sqrt(Delta)*dW(:,i-1);\n end\n pathS(:,:,l) = exp(lnS1);\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_BS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7456453562181117}} {"text": "function npartitions = partn_enum ( n, nmax )\n\n%*****************************************************************************80\n%\n%% PARTN_ENUM enumerates the partitions of N with maximum element NMAX.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 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 integer to be partitioned.\n% Normally N must be positive, but for this routine any\n% N is allowed.\n%\n% Input, integer NMAX, the maximum element in the partition.\n% Normally, 1 <= NMAX <= N is required,\n% but for this routine any value of NMAX is allowed.\n%\n% Output, integer NPARTITIONS is the number of partitions of N\n% with maximum element NMAX.\n%\n if ( n <= 0 )\n\n npartitions = 0;\n\n elseif ( nmax <= 0 || n < nmax )\n\n npartitions = 0;\n\n else\n\n offset = 1;\n\n p = npart_table ( n, nmax );\n\n npartitions = p(n+offset,nmax+offset);\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/combo/partn_enum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7455472888627616}} {"text": "function value = sphere_unit_monomial_nd ( n, p )\n\n%*****************************************************************************80\n%\n%% SPHERE_UNIT_MONOMIAL_ND integrates a monomial on a unit sphere in ND.\n%\n% Integration region:\n%\n% Points X(1:N) such that\n%\n% Sum ( X(1:N)**2 ) == 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gerald Folland,\n% How to Integrate a Polynomial Over a Sphere,\n% American Mathematical Monthly,\n% Volume 108, May 2001, pages 446-448.\n%\n% Parameters:\n%\n% Input, integer N, the dimension of the space.\n%\n% Input, integer P(N), the exponents of X(1) through X(N) in the monomial.\n% The exponents P(N) must be nonnegative.\n%\n% Output, real SPHERE_UNIT_MONOMIAL_ND, the integral of\n% X1**P(1)*X2**P(2)*...*XN**P(N) over the unit sphere.\n%\n for i = 1 : n\n if ( mod ( p(i), 2 ) == 1 )\n value = 0.0E+00;\n return\n end\n end\n\n temp = 0.0E+00;\n arg2 = 0.0E+00;\n\n for i = 1 : n\n arg1 = ( p(i) + 1 ) / 2.0E+00;\n temp = temp + gammaln ( arg1 );\n arg2 = arg2 + arg1;\n end\n temp = temp - gammaln ( arg2 );\n\n value = 2.0E+00 * exp ( temp );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/sphere_unit_monomial_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7455472869161148}} {"text": "%% Machine Learning Online Class - Exercise 1: Linear Regression\n\n% Instructions\n% ------------\n% \n% This file contains code that helps you get started on the\n% linear exercise. You will need to complete the following functions \n% in this exericse:\n%\n% warmUpExercise.m\n% plotData.m\n% gradientDescent.m\n% computeCost.m\n% gradientDescentMulti.m\n% computeCostMulti.m\n% featureNormalize.m\n% normalEqn.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% x refers to the population size in 10,000s\n% y refers to the profit in $10,000s\n%\n\n%% Initialization\nclear ; close all; clc\n\n%% ==================== Part 1: Basic Function ====================\n% Complete warmUpExercise.m \nfprintf('Running warmUpExercise ... \\n');\nfprintf('5x5 Identity Matrix: \\n');\nwarmUpExercise()\n\n%fprintf('Program paused. Press enter to continue.\\n');\n%pause;\n\n\n%% ======================= Part 2: Plotting =======================\nfprintf('Plotting Data ...\\n')\ndata = load('ex1data1.txt');\nX = data(:, 1); y = data(:, 2);\nm = length(y); % number of training examples\n\n% Plot Data\n% Note: You have to complete the code in plotData.m\nplotData(X, y);\n\n%fprintf('Program paused. Press enter to continue.\\n'); pause;\n\n%% =================== Part 3: Gradient descent ===================\nfprintf('Running Gradient Descent ...\\n')\n\nX = [ones(m, 1), data(:,1)]; % Add a column of ones to x\ntheta = zeros(2, 1); % initialize fitting parameters\n\n% Some gradient descent settings\niterations = 1500;\nalpha = 0.01;\n\n% compute and display initial cost\ncomputeCost(X, y, theta)\n\n% run gradient descent\ntheta = gradientDescent(X, y, theta, alpha, iterations);\n\n% print theta to screen\nfprintf('Theta found by gradient descent: ');\nfprintf('%f %f \\n', theta(1), theta(2));\n\n% Plot the linear fit\nhold on; % keep previous plot visible\nplot(X(:,2), X*theta, '-')\nlegend('Training data', 'Linear regression')\nhold off % don't overlay any more plots on this figure\n\n% Predict values for population sizes of 35,000 and 70,000\npredict1 = [1, 3.5] *theta;\nfprintf('For population = 35,000, we predict a profit of %f\\n',...\n predict1*10000);\npredict2 = [1, 7] * theta;\nfprintf('For population = 70,000, we predict a profit of %f\\n',...\n predict2*10000);\n\n%fprintf('Program paused. Press enter to continue.\\n'); pause;\n\n%% ============= Part 4: Visualizing J(theta_0, theta_1) =============\nfprintf('Visualizing J(theta_0, theta_1) ...\\n')\n\n% Grid over which we will calculate J\ntheta0_vals = linspace(-10, 10, 100);\ntheta1_vals = linspace(-1, 4, 100);\n\n% initialize J_vals to a matrix of 0's\nJ_vals = zeros(length(theta0_vals), length(theta1_vals));\n\n% Fill out J_vals\nfor i = 1:length(theta0_vals)\n for j = 1:length(theta1_vals)\n\t t = [theta0_vals(i); theta1_vals(j)]; \n\t J_vals(i,j) = computeCost(X, y, t);\n end\nend\n\n\n% Because of the way meshgrids work in the surf command, we need to \n% transpose J_vals before calling surf, or else the axes will be flipped\nJ_vals = J_vals';\n% Surface plot\nfigure;\nsurf(theta0_vals, theta1_vals, J_vals)\nxlabel('\\theta_0'); ylabel('\\theta_1');\n\n% Contour plot\nfigure;\n% Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100\ncontour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))\nxlabel('\\theta_0'); ylabel('\\theta_1');\nhold on;\nplot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);\n", "meta": {"author": "worldveil", "repo": "coursera-ml", "sha": "94e205b01ec3a47c0d777943194d12fa130f4685", "save_path": "github-repos/MATLAB/worldveil-coursera-ml", "path": "github-repos/MATLAB/worldveil-coursera-ml/coursera-ml-94e205b01ec3a47c0d777943194d12fa130f4685/linear-regression/code/ex1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7455472732369963}} {"text": "function p = predictOneVsAll(all_theta, X)\n%PREDICT Predict the label for a trained one-vs-all classifier. The labels \n%are in the range 1..K, where K = size(all_theta, 1). \n% p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions\n% for each example in the matrix X. Note that X contains the examples in\n% rows. all_theta is a matrix where the i-th row is a trained logistic\n% regression theta vector for the i-th class. You should set p to a vector\n% of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2\n% for 4 examples) \n\nm = size(X, 1);\nnum_labels = size(all_theta, 1);\n\n% You need to return the following variables correctly \np = zeros(size(X, 1), 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters (one-vs-all).\n% You should set p to a vector of predictions (from 1 to\n% num_labels).\n%\n% Hint: This code can be done all vectorized using the max function.\n% In particular, the max function can also return the index of the \n% max element, for more information see 'help max'. If your examples \n% are in rows, then, you can use max(A, [], 2) to obtain the max \n% for each row.\n% \n\nfor c = 1:m\n\tone_example = X(c,:);\n\t[max_value, max_index] = max(all_theta * one_example');\n\tp(c,1) = max_index;\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "sfvsfv", "repo": "Mathematical-modeling", "sha": "cef1a3688246851f067777b3599b1b3831d3d948", "save_path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling", "path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling/Mathematical-modeling-cef1a3688246851f067777b3599b1b3831d3d948/matlab吴恩达机器学习/machine-learning-ex3/ex3/predictOneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.8856314677809304, "lm_q1q2_score": 0.7455472695331082}} {"text": "function gb=gabor_fn(bw,gamma,psi,lambda,theta)\n% bw = bandwidth, (1)\n% gamma = aspect ratio, (0.5)\n% psi = phase shift, (0)\n% lambda= wave length, (>=2)\n% theta = angle in rad, [0 pi)\n \nsigma = lambda/pi*sqrt(log(2)/2)*(2^bw+1)/(2^bw-1);\nsigma_x = sigma;\nsigma_y = sigma/gamma;\n\nsz=fix(8*max(sigma_y,sigma_x));\nif mod(sz,2)==0, sz=sz+1;end\n\n% alternatively, use a fixed size\n% sz = 60;\n \n[x y]=meshgrid(-fix(sz/2):fix(sz/2),fix(sz/2):-1:fix(-sz/2));\n% x (right +)\n% y (up +)\n\n% Rotation \nx_theta=x*cos(theta)+y*sin(theta);\ny_theta=-x*sin(theta)+y*cos(theta);\n \ngb=exp(-0.5*(x_theta.^2/sigma_x^2+y_theta.^2/sigma_y^2)).*cos(2*pi/lambda*x_theta+psi);\nimshow(gb/2+0.5);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23253-gabor-filter/Gabor Filter/gabor_fn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741268224331, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7455440226562653}} {"text": "function F = tempCompCurve(x,Tdata)\n%% Calculate Temperature Curve given Resistor and Thermistor Values\n% Copyright (c) 2012, MathWorks, Inc.\n%% Input voltage\nVin = 1.1;\n\n%% Thermistor Calculations\n% Values in x: R1 R2 R3 R4 RTH1(T_25degc) Beta1 RTH2(T_25degc) Beta2\n% Thermistors are represented by:\n% Room temperature is 25degc: T_25\n% Standard value is at 25degc: RTHx_25\n% RTHx is the thermistor resistance at various temperature\n% RTH(T) = RTH(T_25degc) / exp (Beta * (T-T_25)/(T*T_25)))\nT_25 = 298.15;\nT_off = 273.15;\nBeta1 = x(6);\nBeta2 = x(8);\nRTH1 = x(5) ./ exp(Beta1 * ((Tdata+T_off)-T_25)./((Tdata+T_off)*T_25));\nRTH2 = x(7) ./ exp(Beta2 * ((Tdata+T_off)-T_25)./((Tdata+T_off)*T_25));\n\n%% Define equivalent circuits for parallel R's and RTH's\nR1_eq = x(1)*RTH1./(x(1)+RTH1);\nR3_eq = x(3)*RTH2./(x(3)+RTH2);\n\n%% Calculate voltages at Point B\nF = Vin * (R3_eq + x(4))./(R1_eq + x(2) + R3_eq + x(4));", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35810-optimal-component-selection-using-the-mixed-integer-genetic-algorithm/Thermistor_MixedIntegerGA/tempCompCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995762509215, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7455233024255357}} {"text": "% Isoparametric Formulation Implementation\n% clear memory\nclear all\n\n%% Physical Parameters\n% numberElements: number of elements\nnumberElements = 6; \n\n% Initial Area\nA = 12.5e-4; % m^2\n\n% Modulus of elasticity\nE = 2e11; % N/m^2\n\n% Length of bar\nLtotal = 1.5; % m \n\n%% Exact solutions\nxx = 0:0.1:1.5;\ndisplacements_exact = (40000*xx.^3/3-45000)/(E*A);\nstress_exact = (40000*xx.^2)/A;\n\nfigure(3)\n\n% Displacements\nsubplot(1,2,1); hold on;\nplot(xx,displacements_exact,'-r'); \n\n% Stress\nsubplot(1,2,2); hold on;\n\nplot(xx,stress_exact,'-r'); \n\ntest = [1 2 4 8];\nfor numberElements = test\n\n% Build nodes coordinates and middle points,\ndelta_x = Ltotal/numberElements;\ni = 0:numberElements; \nx = delta_x*i';x_mid = (x(2:end)-x(1:end-1))/2 + x(1:end-1);\n\n% Length of each element\nL = x(2:end)-x(1:end-1); \n \n%% Build Elements\n% numberNodes: number of nodes\nnumberNodes = numberElements + 1;\n\n% generation of coordinates and connectivities\nelementNodes = zeros(numberElements,2); \nelementNodes(1,:) = [1,2]; \nfor i = 2:numberElements \n elementNodes(i,:) = elementNodes(i-1,:) + 1; \nend\nnodeCoordinates = x;\n\n% for structure:\n % displacements: displacement vector\n % force : force vector\n % stiffness: stiffness matrix\nforce=zeros(numberNodes,1);\nstiffness=zeros(numberNodes,numberNodes); \n% computation of the system stiffness matrix and force vector\nfor e=1:numberElements; \n % elementDof: element degrees of freedom (Dof)\n elementDof=elementNodes(e,:) ;\n detJacobian=L(e)/2;\n invJacobian=1/detJacobian;\n ngp = 2;\n [w,xi]=gauss1d(ngp);\n xc=0.5*(nodeCoordinates(elementDof(1))+nodeCoordinates(elementDof(2)));\n for ip=1:ngp;\n [shape,naturalDerivatives]=shapeFunctionL2(xi(ip)); \n B=naturalDerivatives*invJacobian;\n stiffness(elementDof,elementDof)=...\n stiffness(elementDof,elementDof)+ B'*B*w(ip)*detJacobian*E*A;\n force(elementDof) = force(elementDof)+...\n -80000*(xc+detJacobian*xi(ip))*shape'*detJacobian*w(ip);\n end\nend \n \n%% BCs and solution\n% prescribed dofs\nprescribedDof = find(nodeCoordinates == 1.5); % fixed at node x = 1.5 m\n% solution\nGDof=numberNodes;\ndisplacements=solution(GDof,prescribedDof,stiffness,force);\n% output displacements/reactions\noutputDisplacementsReactions(displacements,stiffness, ...\n numberNodes,prescribedDof,force)\n\n%% Stress\nstress = zeros(numberElements,1);\nfor e=1:numberElements; \n stress(elementNodes(e,:)) = E*B*displacements(elementNodes(e,:));\nend\n\n\n%% plot figures\n\nswitch numberElements\n case 1\n line='r*--';\n case 2\n line='g*--';\n case 4\n line='k*--';\n case 8\n line='m*--';\nend\n\n% Displacements\nsubplot(1,2,1); plot(nodeCoordinates,displacements,line)\n\n% Stress\nsubplot(1,2,2); stairs(nodeCoordinates,stress,line)\n\nend %end for\nsubplot(1,2,1); legend('Exact','NEL=1','NEL=2','NEL=4','NEL=8',2); hold off\nsubplot(1,2,2); legend('Exact','NEL=1','NEL=2','NEL=4','NEL=8',2); hold off", "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/FEM/BarIsoParametric/HWproblem2dIso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7454508759407814}} {"text": "% \n% Implementation of Bertsekas' auction algorithm [1] for a very fast \n% solution of the linear assignment problem, i.e. it is able \n% to solve a 1000-by-1000 problem in ~1.5s.\n%\n% In practice, with respect to running time, the auction algorithm \n% outperforms the Kuhn-Munkres (or Hungarian) algorithm significantly. \n% The auction algorithm has average run-time complexity O(N^2*log(N)) and \n% worst-case complexity O(N^3), whereas the Kuhn-Munkres algorithm has \n% average- and worst-case complexity O(N^3).\n%\n% Note that only global optima are found for integer-valued benefit matrices. \n% For real-valued benefit matrices a scaling of the values needs to be applied\n% by multiplication with a large number. This scaling factor depends on the\n% desired accuracy, as the global solution is found for the integral part\n% of the benefit matrix, whilst there is no guarantee that the fractional part \n% of the benefits are properly taken into account. However, in practical cases \n% it seems advantageous to not round the resulting benefit matrix and retain \n% the fractional parts in the benefit matrix. Also note that larger scalings \n% of the benefit matrix increase the run-time, so a problem-specific trade-off \n% between runtime and accuracy must be chosen.\n%\n% Runtime can be slightly decreased by installing the FastSet library,\n% available on \n% http://www.levmuchnik.net/Content/ProgrammingTips/MatLab/FastSet/FastSet.html\n%\n% Input:\n% A N-by-N benefit matrix (higher\n% values indicate a better match)\n% [epsilon] Initial value of epsilon (optional)\n% [epsilonDecreaseFactor] Decreas factor of epsilon\n% (optional)\n%\n% Output:\n% assignments Resulting assignments\n% [prices] Prices used during auctions\n% (optional)\n%\n% Example: See the function test() below for a usage example.\n% Typically only the benefit matrix A is given as input and the\n% first output argument is relevant. epsilon and\n% epsilonDecreaseFactor can be used to heuristically adapt\n% runtime. The example below can also be used for testing\n% whether a sufficient amount of scaling has been performed.\n% This is done by solving the assignment problem using CVX\n% (available on http://cvxr.com/cvx/download/ ) and comparing\n% its result to the solution with the auction algorithm.\n% \n%\n% [1]\tBertsekas, D.P. 1998. Network Optimization Continuous and Discrete Models.\n%\n% Implementation by Florian Bernard ( f.bernardpi [at] gmail [dot] com )\n%\n% Created on 25/07/2014\n\nfunction [assignments, prices] = ...\n assignmentProblemAuctionAlgorithm(A, epsilon, epsilonDecreaseFactor)\n\nN = size(A,1);\nassignments = nan(N,1);\nprices = ones(N,1);\n\n% check which unique function we use\nif ( exist('fast_unique', 'file') ) \n % requires FastSet, available on \n % http://www.levmuchnik.net/Content/ProgrammingTips/MatLab/FastSet/FastSet.html\n uniqueFcn = @fast_unique;\nelse\n uniqueFcn = @unique;\nend\n\n% heuristic for setting epsilon\nA = A*(N+1);\nif ( ~exist('epsilon', 'var') || isempty(epsilon) )\n maxAbsA = max(abs(A(:)));\n epsilon = maxAbsA/25;\n% if ( sum(abs(A(:)) > 0.0001) > 0.7*N*N ) % non-sparse\n% ...\n% else\n% epsilon = 0.5*((N*maxVal)/5 + N*maxVal); % see page 260 in [1]\n% end\nend\n\nif ( ~exist('epsilonDecreaseFactor', 'var') )\n epsilonDecreaseFactor = 0.2;\nend\n\nwhile (epsilon >= 1) \n % the outer loop performs epsilon-scaling in order to speed up execution\n % time. In particular, an updated prices array is computed in each\n % round, which speeds up further rounds with lower values of epsilon.\n assignments = nan(N,1);\n while (any(isnan(assignments)))\n %% forward-auction algorithm\n %% bidding phase\n % find unassigned indices\n unassignedIdx = find(isnan(assignments));\n nUnassigned = numel(unassignedIdx);\n \n % find best and second best objects\n AijMinusPj = bsxfun(@minus, A(unassignedIdx,:), prices');\n\n [~,viIdx] = max(AijMinusPj, [], 2);\n\n for i=1:nUnassigned \n AijMinusPj(i,viIdx(i)) = -inf;\n end\n wi = max(AijMinusPj, [], 2);\n \n % compute bids\n bids = nan(nUnassigned,1);\n for i=1:nUnassigned \n bids(i) = A(unassignedIdx(i),viIdx(i)) - wi(i) + epsilon;\n end\n \n \n %% assignment phase\n objectsThatHaveBeenBiddedFor = uniqueFcn(viIdx);\n for uniqueObjIdx=1:numel(objectsThatHaveBeenBiddedFor)\n currObject = objectsThatHaveBeenBiddedFor(uniqueObjIdx);\n personssWhoGaveBidsForJ = find(viIdx==currObject);\n \n [prices(currObject), idx] = max(bids(personssWhoGaveBidsForJ));\n personWithHighestBid = unassignedIdx(personssWhoGaveBidsForJ(idx));\n \n % remove previous assignment and store new assignment (the person\n % with highest bid)\n assignments(assignments==currObject) = nan;\n assignments(personWithHighestBid) = currObject;\n \n end\n end\n epsilon = epsilon * epsilonDecreaseFactor; % refine epsilon\nend\nend\n\nfunction test()\nN = 1000;\n\nX = rand(N,3);\nreference = rand(N,3);\n\nA = X*reference';\n%% Apply Auction algorithm\ntic\n % scale A such that the integer version of A has sufficient accuracy\n % if S1 and P are not equal, the scaling factor needs to be increased\n scalingFactor = 10^6;\n Ascaled = A*scalingFactor;\n\n [assignments] = assignmentProblemAuctionAlgorithm(Ascaled);\n\n % create permutation matrix from assignments\n linIdx = sub2ind(size(A),assignments',1:size(A,1));\n P = sparse(size(A,1),size(A,2));\n P(linIdx) = 1;\ntoc\n\n%% Use CVX for checking correctness of result\n% (Useful in particular for non-integer matrices A)\n% Note that this is really slow as CVX needs to create the canonical form\n% of the LP before it can call Gurobi. Creating the canonical form by hand\n% and directly calling Gurobi is much faster.\nE = ones(N,1);\n\ntic\n cvx_begin % quiet\n cvx_solver gurobi % uncomment this line if Gurobi is not available\n variable S1(N,N) nonnegative;\n maximize (trace(S1*A));\n S1*E==E;\n E'*S1==E';\n cvx_end\ntoc\n\n% check if results are equal\nif ( sum(sum(full(S1)~=full(P))) == 0 )\n disp('Correct results using Auction algorithm');\nelse\n error('Incorrect results using Auction algorithm. You probably need to scale A by a larger factor!');\nend\nend\n", "meta": {"author": "OshriHalimi", "repo": "unsupervised_learning_of_dense_shape_correspondence", "sha": "440643d633a6db3f947ac71a247c8083cb3aeadc", "save_path": "github-repos/MATLAB/OshriHalimi-unsupervised_learning_of_dense_shape_correspondence", "path": "github-repos/MATLAB/OshriHalimi-unsupervised_learning_of_dense_shape_correspondence/unsupervised_learning_of_dense_shape_correspondence-440643d633a6db3f947ac71a247c8083cb3aeadc/Tools/PMF/assignmentProblemAuctionAlgorithm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7454450782428992}} {"text": "function [SNR] = bvpsnr(BVP, FS, HR, PlotTF)\n%BVPSNR Estimates the signal-to-noise ratio of the blood volume pulse\n% signal. Adapted from the method by G. de Haan, TBME, 2013.\n% SNR calculated as the ratio (in dB) of power contained within +/- 0.1 Hz\n% of the reference heart rate frequency and +/- 0.2 of its first\n% harmonic and sum of all other power between 0.5 and 4 Hz.\n% Adapted from the method by G. de Haan, TBME, 2013\n%\n% Inputs:\n% BVP = A BVP timeseries.\n% FS = The sample rate of the BVP time series (Hz/fps).\n% HR = The reference heart rate (Hz/fps).\n% PlotTF = Boolean to turn plotting results on or off.\n%\n% Outputs:\n% SNR = Blood Volume Pulse Signal-to-Noise Ratio.\n%\n% Daniel McDuff, Ethan Blackford, January 2019\n% Copyright (c)\n% Licensed under the MIT License and the RAIL AI License.\n\nHR_F=HR/60;\n\nNyquistF = FS/2;\nFResBPM = 0.5; %resolution (bpm) of bins in power spectrum used to determine PR and SNR\nN = (60*2*NyquistF)/FResBPM; %number of bins in power spectrum\n\n%% Construct Periodogram\n[Pxx,F] = periodogram(BVP,hamming(length(BVP)),N,FS);\nGTMask1 = (F >= HR_F-0.1)&(F <= HR_F+0.1);\nGTMask2 = (F >= HR_F*2-0.2)&(F <= HR_F*2+0.2);\nSPower = sum(Pxx(GTMask1|GTMask2));\nFMask2 = (F >= 0.5)&(F <= 4);\nAllPower = sum(Pxx(FMask2));\nSNR = pow2db(SPower/(AllPower-SPower));\n\n%% Optionally plot the power spectrum and regions used to calculate the SNR\nif(PlotTF)\n % Plot spower spectrum and SNR regions\n figure\n plot(F,pow2db(Pxx))\n title('Power Spectrum and SNR Regions')\n xlabel('Frequency (Hz)')\n ylabel('Power (dB)')\n xlim([0.5 4])\n ylimreg=ylim;\n hold on\n \n % HR peak\n %line([HR_F,HR_F],ylim,'Color','magenta','LineStyle','-.')\n \n % HR peak region\n line([HR_F-0.1,HR_F-0.1],ylim,'Color','red','LineStyle','--')\n line([HR_F+0.1,HR_F+0.1],ylim,'Color','red','LineStyle','--')\n \n % First harmonic\n line([HR_F*2-0.2,HR_F*2-0.2],ylim,'Color','red','LineStyle','--')\n line([HR_F*2+0.2,HR_F*2+0.2],ylim,'Color','red','LineStyle','--')\n \n % Overall power region\n line([0.5,0.5],ylim,'Color','black','LineStyle','-')\n line([4,4],ylim,'Color','black','LineStyle','-')\n \n % Adjust axes\n xlim([0 4.5])\n ylim(ylimreg);\nend\n\nend\n\n", "meta": {"author": "danmcduff", "repo": "iphys-toolbox", "sha": "65deeb46aea80c04009fe304a6612e4ef1497f08", "save_path": "github-repos/MATLAB/danmcduff-iphys-toolbox", "path": "github-repos/MATLAB/danmcduff-iphys-toolbox/iphys-toolbox-65deeb46aea80c04009fe304a6612e4ef1497f08/tools/bvpsnr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7453950323211332}} {"text": "function geometry_test1895 ( )\n\n%*****************************************************************************80\n%\n%% TEST1895 tests SPHERE_UNIT_AREA_ND, SPHERE_UNIT_AREA_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST1895:\\n' );\n fprintf ( 1, ' SPHERE_UNIT_AREA_ND evaluates the area of the unit\\n' );\n fprintf ( 1, ' sphere in N dimensions.\\n' );\n fprintf ( 1, ' SPHERE_UNIT_AREA_VALUES returns some test values.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' DIM_NUM Exact Computed\\n' );\n fprintf ( 1, ' Area Area\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, dim_num, area ] = sphere_unit_area_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n area2 = sphere_unit_area_nd ( dim_num );\n\n fprintf ( 1, ' %6d %10f %10f\\n', dim_num, area, area2 );\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_test1895.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.7453592311468198}} {"text": "function numgrad = computeNumericalGradient(J, theta)\n% numgrad = computeNumericalGradient(J, theta)\n% theta: a vector of parameters\n% J: a function that outputs a real-number. Calling y = J(theta) will return the\n% function value at theta. \n \n% Initialize numgrad with zeros\nnumgrad = zeros(size(theta));\n\n%% ---------- YOUR CODE HERE --------------------------------------\n% Instructions: \n% Implement numerical gradient checking, and return the result in numgrad. \n% (See Section 2.3 of the lecture notes.)\n% You should write code so that numgrad(i) is (the numerical approximation to) the \n% partial derivative of J with respect to the i-th input argument, evaluated at theta. \n% I.e., numgrad(i) should be the (approximately) the partial derivative of J with \n% respect to theta(i).\n% \n% Hint: You will probably want to compute the elements of numgrad one at a time. \n\nepsilon = 1e-4;\n\nfor i =1:length(numgrad)\n oldT = theta(i);\n theta(i)=oldT+epsilon;\n pos = J(theta);\n theta(i)=oldT-epsilon;\n neg = J(theta);\n numgrad(i) = (pos-neg)/(2*epsilon);\n theta(i)=oldT;\n if mod(i,100)==0\n fprintf('Done with %d\\n',i);\n end;\nend;\n\n%% ---------------------------------------------------------------\nend", "meta": {"author": "xuzhenqi", "repo": "cnn", "sha": "3b505ad0fc3bbb0cc5331d109702b6921fef2cb2", "save_path": "github-repos/MATLAB/xuzhenqi-cnn", "path": "github-repos/MATLAB/xuzhenqi-cnn/cnn-3b505ad0fc3bbb0cc5331d109702b6921fef2cb2/DebugTools/computeNumericalGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.7453592190049344}} {"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\nfor i=1:m,\n\tif sigmoid(X(i,:)*theta) >= 0.5,\n\t\tp(i) = 1;\n\telse\n\t\tp(i) = 0;\n\tend;\nend;\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "UtkarshPathrabe", "repo": "Machine-Learning-Stanford-University-Coursera", "sha": "0e5855855b5ddd475775b75bad69b47c2ebe84ef", "save_path": "github-repos/MATLAB/UtkarshPathrabe-Machine-Learning-Stanford-University-Coursera", "path": "github-repos/MATLAB/UtkarshPathrabe-Machine-Learning-Stanford-University-Coursera/Machine-Learning-Stanford-University-Coursera-0e5855855b5ddd475775b75bad69b47c2ebe84ef/Programming Exercises/machine-learning-ex2/ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.867035763237924, "lm_q1q2_score": 0.7453592035819404}} {"text": "function ds = dsegment ( p, pv )\n\n%*****************************************************************************80\n%\n%% DSEGMENT computes the distance of points to line segments.\n%\n% Discussion:\n%\n% This is a pure MATLAB version of the DSEGMENT routine.\n% Normally, the authors of DISTMESH recommend using a faster procedure\n% in which a MATLAB MEX interface is used to call a compiled C code.\n% But if that is not possible, you can fall back on this slower\n% version.\n%\n% Note that the line segments are defined by successive pairs of\n% vertices. In the very common case that the vertices represent\n% a polygon, it is necessary that the list be extended by repeating\n% the first vertex at the end; otherwise the definition of the\n% polygon, and the distance computation, will be incomplete.\n%\n% Licensing:\n%\n% (C) 2004 Per-Olof Persson. \n% See COPYRIGHT.TXT for details.\n%\n% Parameters:\n%\n% Input, real P(NP,2), a set of points.\n%\n% Input, real PV(NVS,2), a set of vertices. Sequential\n% pairs define NVS-1 line segments.\n%\n% Output, real DS(NP,NVS-1); DS(I,J) is the (unsigned) distance\n% of point P(I,:) from line segment PV(J,:)--PV(J+1,:).\n%\n nvs = size ( pv, 1 );\n np = size ( p, 1 );\n\n ds = zeros ( np,nvs-1);\n\n for iv = 1 : nvs-1\n for ip = 1 : np\n\n v(1:2) = [ pv(iv+1,1) - pv(iv,1), pv(iv+1,2) - pv(iv,2) ];\n\n w(1:2) = [ p(ip,1) - pv(iv,1), p(ip,2) - pv(iv,2) ];\n\n c1 = v * w';\n c2 = v * v';\n\n if ( c1 <= 0.0 )\n ds(ip,iv) = sqrt ( sum ( ( p(ip,1:2) - pv(iv,1:2) ).^2 ) );\n elseif ( c2 <= c1 )\n ds(ip,iv) = sqrt ( sum ( ( p(ip,1:2) - pv(iv+1,1:2) ).^2 ) );\n else\n ds(ip,iv) = sqrt ( sum ( ( p(ip,1:2) ...\n - pv(iv,1:2) - c1 / c2 * v(1:2) ).^2 ) );\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/distmesh/dsegment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213880824791, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.745316613873207}} {"text": "%wrap - Set radian angles in range [0,2pi] or [-pi,pi].\n%\n% USAGE\n%\n% y = wrap(x,range)\n%\n% x angles in radians\n% range optional: 1 for [-pi,pi] (default)\n% 2 for [0,2pi]\n%\n% SEE ALSO\n%\n% See also isradians.\n%\n\n% Copyright (C) 2010-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\nfunction y = wrap(x,range)\n\n% Check number of parameters\nif nargin < 1,\n error('Incorrect number of parameters (type ''help wrap'' for details).');\nend\n\nif nargin < 2,\n\trange = 1;\nend\n\nif ~isa(x,'double'), y = []; return; end\n\n% Determine angle in [0,2*pi]\ny = mod(x,2*pi);\n\n% Change range if necessary\nif range == 1,\n\tchange = y > pi;\n\ty(change) = y(change)-2*pi;\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/neuroscope/private/wrap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7453166036922827}} {"text": "%%%\n%> @brief computes the homogeneous transformation A of the pose vector v\n%> @param v pose vector\n%> @return A homogeneous transformation\n%> @author Giorgio Grisetti\n%%%\nfunction A = v2t(v)\n% V2T vector to homogeneous transformation\nc = cos(v(3));\ns = sin(v(3));\nA = [c, -s, v(1);\n s, c, v(2);\n 0 0 1];\nend", "meta": {"author": "versatran01", "repo": "graphslam", "sha": "c09bb80285e7356897b5cb39f236f84731bc976f", "save_path": "github-repos/MATLAB/versatran01-graphslam", "path": "github-repos/MATLAB/versatran01-graphslam/graphslam-c09bb80285e7356897b5cb39f236f84731bc976f/lsslam/v2t.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9621075690244281, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7452325417520554}} {"text": "function [A,B,D,E,I]=mdds(X)\n% gets A, B, D, E & I arrays for magnet driver\nN=2;U=3;M=1;Y=1;\nA1=zeros(U+N);B2=zeros(U+N,N+M);\n%\n% X = [R1 R2 R3 C1 C2]\n%\nR1=X(1);R2=X(2);R3=X(3);C1=X(4);C2=X(5);\n%\n% V1 V2 V3 iC1 iC2 column labels for A1\n% 1 2 3 4\t5\n%\nA1(1,1)=-1/R1;A1(1,4)=-1;A1(1,5)=-1; % From 1st equation\nA1(2,1)=1/R2;A1(2,2)=-1/R2;A1(2,4)=-1; % 2nd equation\nA1(3,3)=1;A1(3,4)=-R3;A1(3,5)=-R3; % V3 - iC1*R3 - iC2*R3 = 0\nA1(4,2)=1;A1(4,3)=-1; % V2 - V3 = E1\nA1(5,1)=1;A1(5,3)=-1; % V1 - V3 = E2\n%\nE1=1;E2=1;Ein=1;\n% E1 E2 Ein Column labels for B2\n% 1 2 3\nB2(4,1)=E1;\nB2(5,2)=E2;\nB2(1,3)=-Ein/R1;\n%\nP=diag([C1 C2]);\n%\n% Template statements (same for every circuit):\nV=A1\\B2;H=V(U+1:U+N,1:N+M);I=eye(N);\nAB=P\\H;A=AB(1:N,1:N);B=AB(1:N,N+1:N+M);\nD=V(Y:Y,1:N);E=V(Y:Y,N+1:N+M);\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2435-shortcut-state-space-circuit-analysis/Matlab_Files/mdds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561694652215, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.7451281324997501}} {"text": "function [q]=zn2fpd(input)\n% [q]=zn2fpd(input)\n% Ziegler-Nichols controller for 2nd order processes\n% This function computes parameters of the controller (q0, q1, q2, q3, q4).\n% Controller is based on forward rectangular method of discretization\n% replacing derivation by a four-point difference.\n% Transfer function of the controller is as follows:\n%\n% q0 + q1*z^-1 + q2*z^-2 + q3*z^-3 + q4*z^-4\n% G(z^-1) = --------------------------------------------\n% 1 - z^-1\n%\n% Transfer function of the controlled system is:\n%\n% b1*z^-1 + b2*z^-2 \n% Gs(z^-1) = -----------------------\n% 1 + a1*z^-1 + a2*z^-2\n%\n% Input: input ... input parameters\n% input(1) ... a1\n% input(2) ... b1\n% input(3) ... a2\n% input(4) ... b2\n% input(5) ... sample time T0\n% Output: qp ... controller parameters \n% qp(1) ... q0\n% qp(2) ... q1\n% qp(3) ... q2\n% qp(4) ... p1\n% qp(5) ... p2\n\na1 = input(1);\nb1 = input(2);\na2 = input(3);\nb2 = input(4);\nT0 = input(5);\n\n% compute ultimate gain and frequency\n[Kpu, Tu] = ultim([b1 b2],[a1 a2],T0);\n\nKp = 0.6*Kpu;\nTi = Tu/2;\nTd = Tu/8;\n\nq0 = Kp*(1 + T0/Ti + Td/(6*T0));\nq1 = Kp*(-1 + Td/(3*T0));\nq2 = Kp*(-Td/T0);\nq3 = Kp*(Td/(3*T0));\nq4 = Kp*(Td/(6*T0));\n\nq=[q0;q1;q2;q3;q4];", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8381-stcsl-standard-version/zn2fpd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377320263431, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.7450712460347797}} {"text": "function [EC,ec,degij] = edge_nei_overlap_bd(CIJ)\n%EDGE_NEI_OVERLAP_BD overlap amongst neighbors of two adjacent nodes\n%\n% [EC,ec,degij] = edge_nei_bd(CIJ);\n%\n% This function determines the neighbors of two nodes that are linked by \n% an edge, and then computes their overlap. Connection matrix must be\n% binary and directed. Entries of 'EC' that are 'inf' indicate that no\n% edge is present. Entries of 'EC' that are 0 denote \"local bridges\",\n% i.e. edges that link completely non-overlapping neighborhoods. Low\n% values of EC indicate edges that are \"weak ties\".\n%\n% If CIJ is weighted, the weights are ignored. Neighbors of a node can be\n% linked by incoming, outgoing, or reciprocal connections.\n%\n% Inputs: CIJ, directed (binary/weighted) connection matrix\n% \n% Outputs: EC, edge neighborhood overlap matrix\n% ec, edge neighborhood overlap per edge, in vector format\n% degij, degrees of node pairs connected by each edge\n%\n% Reference:\n%\n% Easley and Kleinberg (2010) Networks, Crowds, and Markets. \n% Cambridge University Press, Chapter 3\n%\n% Olaf Sporns, Indiana University, 2012\n\n[ik,jk,ck] = find(CIJ);\nlel = length(ck);\nN = size(CIJ,1);\n\n[~,~,deg] = degrees_dir(CIJ);\n\nec = zeros(1,lel);\ndegij = zeros(2,lel);\nfor e=1:lel\n neiik = setdiff(union(find(CIJ(ik(e),:)),find(CIJ(:,ik(e))')),[ik(e) jk(e)]);\n neijk = setdiff(union(find(CIJ(jk(e),:)),find(CIJ(:,jk(e))')),[ik(e) jk(e)]);\n ec(e) = length(intersect(neiik,neijk))/length(union(neiik,neijk));\n degij(:,e) = [deg(ik(e)) deg(jk(e))];\nend;\n\nff = find(CIJ);\nEC = 1./zeros(N);\nEC(ff) = ec; %#ok\n\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/edge_nei_overlap_bd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7450158282814744}} {"text": "function MD = mahalanobis(x,m,P)\n\n% MAHALANOBIS Mahalanobis distance\n% MD = MAHALANOBIS(X,M,P) computes the Mahalanobis distance from a point\n% X to a Gaussian of mean M and covariance P:\n%\n% MD = sqrt((X-M)'*inv(P)*(X-M));\n%\n% See also NEES.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nMD = sqrt((x-m)'/P*(x-m));\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/mahalanobis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7450104843337921}} {"text": "function [x, funVal, ValueL]=LeastR(A, y, z, opts)\n%\n%%\n% Function LeastR\n% Least Squares Loss with the L1-norm Regularization\n%\n%% Problem\n%\n% min 1/2 || A x - y||^2 + 1/2 rsL2 * ||x||_2^2 + z * ||x||_1\n%\n% By default, rsL2=0.\n% When rsL2 is nonzero, this corresponds to the well-know elastic net.\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 - L_1 norm regularization parameter (z >=0)\n% opts- Optional inputs (default value: opts=[])\n%\n%% Output parameters:\n% x- Solution\n% funVal- Function value during iterations\n%\n%% Copyright (C) 2009-2010 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 February 18, 2010.\n%\n%% Related papers\n%\n% [1] Jun Liu and Jieping Ye, Efficient Euclidean Projections\n% in Linear Time, ICML 2009.\n%\n% [2] Jun Liu and Jieping Ye, Sparse Learning with Efficient Euclidean\n% Projections onto the L1 Ball, Technical Report ASU, 2008.\n%\n%% Related functions\n% \n% sll_opts, initFactor, pathSolutionLeast\n% LeastC, nnLeastR, nnLeastC, \n%\n%%\n\n%% Verify and initialize the parameters\n%%\n\n% Verify the number of input parameters\nif (nargin <3)\n error('\\n Inputs: A, y and z should be specified!\\n');\nelseif (nargin==3)\n opts=[];\nend\n\n% Get the size of the matrix A\n[m,n]=size(A);% m -- sample size,n -- feature dimension%******************************\n\n% Verify the length of y\n%if(size(y,1) ~=m)%********************************\nif (length(y) ~=m)\n error('\\n Check the length of y!\\n');\nend\n\n% Verify the value of z\nif (z<0)\n error('\\n z should be nonnegative!\\n');\nend\n\n% run sll_opts to set default values (flags)\nopts=sll_opts(opts);\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%% Starting point initialization\n\n% compute AT y\nif (opts.nFlag==0)\n ATy=A'*y; %A-->mxn;y-->mxk****************************\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\n\n% L2 norm regularization\nif isfield(opts,'rsL2')\n rsL2=opts.rsL2;\n if (rsL2<0)\n error('\\n opts.rsL2 should be nonnegative!');\n end\nelse\n rsL2=0;\nend\n\n% L1 norm regularization\nif (opts.rFlag==0)\n lambda=z;\nelse % z here is the scaling factor lying in [0,1]\n if (z<0 || z>1)\n error('\\n opts.rFlag=1, and z should be in [0,1]');\n end\n\n lambda_max=max(abs(ATy));\n lambda=z*lambda_max;\n\n rsL2=rsL2*lambda_max; % the input rsL2 is a ratio of lambda_max\nend\n\n% initialize a starting point\nif opts.init==2\n %x=zeros(n,k);%*************************************\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) % If .init=0, we set x=ratio*x by \"initFactor\"\n % Please refer to the function initFactor for detail\n\n x_norm=sum(abs(x)); x_2norm=x'*x;%*****************************corresponding to L1norm,Fnorm\n if x_norm>=1e-6\n ratio=initFactor(x_norm, Ax, y, lambda,'LeastR', rsL2, x_2norm);\n x=ratio*x; Ax=ratio*Ax;\n end\nend\n\n%% The main program\n\n%% The Armijo Goldstein line search scheme + accelearted gradient descent\nif (opts.mFlag==0 && opts.lFlag==0)\n \n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1 + rsL2;\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 and alpha are used for computing the weight in forming search point\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 + rsL2 * s;%************************** +rsL2*s*inv(sigma)\n\n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n\n while (1)\n % let s walk in a step in the antigradient of s to get v\n % and then do the l1-norm regularized projection\n v=s-g/L;\n\n % L1-norm regularized projection\n x=sign(v).*max(abs(v)-lambda / L,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 - rsL2) * ||v||_2^2\n if(l_sum <= r_sum * (L-rsL2))\n break;\n else\n L=max(2*L, l_sum/r_sum + rsL2);\n % fprintf('\\n L=%5.6f',L);\n end\n end\n\n ValueL(iterStep)=L;\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 funVal(iterStep)=Axy'* Axy/2 + rsL2/2 * x'*x + sum(abs(x)) * lambda;\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 end\nend\n\n%% Reformulated problem + Nemirovski's scheme\n\n% .mFlag=1, and .lFlag=0\n% refomulate the problem as the constrained convex optimization\n% problem, and then apply Armijo Goldstein line search scheme\n\n% Problem:\n% min 1/2 || A x - y||^2 + 1/2 rsL2 * ||x||_2^2 + z * t' * 1\n% s.t. |x| <= t\n\nif(opts.mFlag==1 && opts.lFlag==0) \n \n bFlag=0; % this flag tests whether the gradient step only changes a little\n \n L=1 + rsL2;\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 t=abs(x); tp=t; \n % t is the upper bound of absolute value of x\n\n % alphap and alpha are used for computing the weight in forming search point\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; s_t= t + beta * (t -tp);\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 + rsL2 * s;\n\n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n tp=t;\n\n while (1)\n % let s walk in a step in the antigradient of s to get v\n % and then do the l1-norm regularized projection\n \n u=s-g/L;\n v= s_t - lambda / L;\n \n % projection\n [x, t]=ep1R(u, v, n);\n\n v=x-s; % the difference between the new approximate solution x\n % and the search point s\n \n v_t=t-s_t;\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 + v_t'*v_t; l_sum=Av'*Av + v'*v * rsL2;\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 + rsL2 * ||v||_2^2\n % <= L * (||v||_2^2 + ||v_t|| _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 ValueL(iterStep)=L;\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 funVal(iterStep)=Axy'* Axy/2 + rsL2/2 * x'*x + sum(t) * lambda;\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 + norm(t-tp)^2);\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=sqrt(xp'*xp + tp'*tp); norm_xxp=sqrt(xxp'*xxp+ norm(t-tp)^2);\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 end\n \nend\n\n\n%% adaptive line search\n\n% .mFlag=1, and .lFlag=1\n% refomulate the problem as the constrained convex optimization\n% problem, and then apply adaptive line search scheme\n\n% Problem:\n% min 1/2 || A x - y||^2 + 1/2 rsL2 * ||x||_2^2 + z * t' * 1\n% s.t. |x| <= t\n\nif(opts.mFlag==1 && opts.lFlag==1)\n \n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1 + rsL2;\n % We assume that the maximum eigenvalue of A'A is over 1\n \n gamma=1;\n % we shall set the value of gamma = L,\n % where L is appropriate for the starting point\n\n xp=x; Axp=Ax;\n % store x and Ax\n xxp=zeros(n,1);\n % the difference of x and xp \n t=abs(x); tp=t;\n % t is the upper bound of absolute value of x\n \n % compute AT Ax\n if (opts.nFlag==0)\n ATAx=A'*Ax;\n elseif (opts.nFlag==1)\n ATAx=A'*Ax - sum(Ax) * mu'; ATAx=ATAx./nu;\n else\n invNu=Ax./nu; ATAx=A'*invNu-sum(invNu)*mu';\n end\n \n % We begin the adaptive line search in the following\n %\n % Note that, in the line search, L and beta are changing\n \n for iterStep=1:opts.maxIter\n\n ATAxp=ATAx;\n % store ATAx to ATAxp\n\n if (iterStep~=1)\n % compute AT Ax\n if (opts.nFlag==0)\n ATAx=A'*Ax;\n elseif (opts.nFlag==1)\n ATAx=A'*Ax - sum(Ax) * mu'; ATAx=ATAx./nu;\n else\n invNu=Ax./nu; ATAx=A'*invNu-sum(invNu)*mu';\n end\n end\n\n %--------- Line Search for L begins\n while (1)\n if (iterStep~=1)\n alpha= (-gamma+ sqrt(gamma*gamma + 4* L * gamma)) / (2*L);\n beta= (gamma - gamma* alphap) / (alphap * gamma + alphap* L * alpha);\n % beta is the coefficient for generating search point s\n\n s=x + beta* xxp; s_t= t + beta * (t -tp);\n As=Ax + beta* (Ax-Axp);\n ATAs=ATAx + beta * (ATAx- ATAxp);\n % compute the search point s, A * s, and A' * A * s\n else\n alpha= (-1+ sqrt(5)) / 2;\n beta=0; s=x; s_t=t; As=Ax; ATAs=ATAx;\n end\n\n g=ATAs-ATy + rsL2 * s;\n % compute the gradient g\n \n % let s walk in a step in the antigradient of s \n u=s-g/L;\n v= s_t - lambda / L;\n\n % projection\n [xnew, tnew]=ep1R(u,v,n);\n\n v=xnew-s; % the difference between the new approximate solution x\n % and the search point s\n v_t=tnew-s_t;\n \n % compute A xnew\n if (opts.nFlag==0)\n Axnew=A* xnew;\n elseif (opts.nFlag==1)\n invNu=xnew./nu; mu_invNu=mu * invNu;\n Axnew=A*invNu -repmat(mu_invNu, m, 1);\n else\n Axnew=A*xnew-repmat(mu*xnew, m, 1); Axnew=Axnew./nu;\n end\n\n Av=Axnew -As;\n r_sum=v'*v + v_t'*v_t; l_sum=Av'*Av + v'*v * rsL2;\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 + rsL2 * ||v||_2^2\n % <= L * (||v||_2^2 + ||v_t|| _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 %--------- Line Search for L ends\n\n gamma=L* alpha* alpha; alphap=alpha;\n % update gamma, and alphap\n \n ValueL(iterStep)=L;\n\n tao=L * r_sum / l_sum;\n if (tao >=5)\n L=L*0.8;\n end\n % decrease the value of L\n\n xp=x; x=xnew; xxp=x-xp;\n Axp=Ax; Ax=Axnew;\n % update x and Ax with xnew and Axnew \n tp=t; t=tnew;\n % update tp and t \n \n Axy=Ax-y;\n funVal(iterStep)=Axy' * Axy/2 + rsL2/2 * x'*x + lambda * sum(t);\n % compute function value\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+ norm(t-tp)^2);\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=sqrt(xp'*xp + tp'*tp); norm_xxp=sqrt(xxp'*xxp+ norm(t-tp)^2);\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 end\nend\n\n\n%%\nif(opts.mFlag==0 && opts.lFlag==1)\n error('\\n The function does not support opts.mFlag=0 & opts.lFlag=1!');\nend", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Toolbox/SLEP_package_4.1/SLEP/functions/L1/L1R/LeastR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.8080672227971212, "lm_q1q2_score": 0.7449748219278151}} {"text": "function K = covCos(hyp, x, z, i)\n\n% Stationary covariance function for a sinusoid with period p in 1d:\n%\n% k(x,z) = sf^2*cos(2*pi*(x-z)/p)\n%\n% where the hyperparameters are:\n%\n% hyp = [ log(p)\n% log(sf) ]\n%\n% Note that covPeriodicNoDC converges to covCos as ell goes to infinity.\n%\n% Copyright (c) by James Robert Lloyd, 2013-08-05.\n%\n% See also COVFUNCTIONS.M, COVPERIODICNODC.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\n[n,D] = size(x);\nif D>1, error('Covariance is defined for 1d data only.'), end\np = exp(hyp(1));\nsf2 = exp(2*hyp(2));\n\n% precompute distances\nif dg % vector kxx\n K = zeros(size(x,1),1);\nelse\n if xeqz % symmetric matrix Kxx\n K = repmat(x,1,n) - repmat(x',n,1);\n else % cross covariances Kxz\n K = repmat(x,1,size(z,1)) - repmat(z',n,1);\n end\nend\n\nK = 2*pi*K/p;\nif nargin<4 % covariances\n K = sf2*cos(K);\nelse % derivatives\n if i==1\n K = sf2*sin(K).*K;\n elseif i==2\n K = 2*sf2*cos(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/covCos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7449747944817249}} {"text": "function R = ProjectToSO3(mat)\n% *** CHAPTER 3: RIGID-BODY MOTIONS ***\n% Takes mat: A matrix near SO(3) to project to SO(3).\n% Returns R representing the closest rotation matrix that is in SO(3).\n% This function uses singular-value decomposition (see\n% http://hades.mech.northwestern.edu/index.php/Modern_Robotics_Linear_Algebra_Review)\n% and is only appropriate for matrices close to SO(3).\n% Example Inputs:\n% \n% clear; clc;\n% mat = [ 0.675, 0.150, 0.720;\n% 0.370, 0.771, -0.511;\n% -0.630, 0.619, 0.472];\n% R = ProjectToSO3(mat)\n% \n% Output:\n% R =\n% 0.6790 0.1489 0.7189\n% 0.3732 0.7732 -0.5127\n% -0.6322 0.6164 0.4694\n\n[U, S, V] = svd(mat);\nR = U * V';\nif det(R) < 0\n % In this case the result may be far from mat.\n R = [R(:, 1: 2); -R(:, 3)];\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/ProjectToSO3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7449627533278218}} {"text": "% Compute the frequency range of the mel filterbank\n% Inputs:\n% start_freq: the lowerest linear frequency included in the calculation\n% linear_samp: sampling frequency\n% N_mel: number of mel banks used\n% Output: \n% bin_lower_edge: the lower edge linear frequency of each mel bank\n% bin_upper_edge: the upper edge linear frequency of each mel bank\n\nfunction [bin_lower_edge, bin_upper_edge] = mel_bank_range(start_freq, linear_samp, N_mel)\n\n% get the mel version of start frequency and linear sampling rate\nstart_mel = linear2mel(start_freq);\nsamp_mel = linear2mel(linear_samp/2);\n\n% slow implementation\nif 0\n for i=1:N_mel\n % find the lower edge linear frequency of the bank\n tmp_mel = (i-1)*(samp_mel-start_mel) / (N_mel+1);\n bin_lower_edge(i) = mel2linear(tmp_mel+start_mel);\n % find the upper edge linear frequency of the bank\n tmp_mel = (i+1)*(samp_mel-start_mel) / (N_mel+1);\n bin_upper_edge(i) = mel2linear(tmp_mel+start_mel);\n end\nelse\n % fast implementation\n i=1:N_mel;\n % find the lower edge linear frequency of the bank\n tmp_mel = (i-1)*(samp_mel-start_mel) / (N_mel+1);\n bin_lower_edge = mel2linear(tmp_mel+start_mel);\n % find the upper edge linear frequency of the bank\n tmp_mel = (i+1)*(samp_mel-start_mel) / (N_mel+1);\n bin_upper_edge = mel2linear(tmp_mel+start_mel);\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/signal/feature/mel_bank_range.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.7449572782344196}} {"text": "function r = dirrand(m,n)\n% DIRRAND - Uniform Dirichlet random vectors\n%\n% R = DIRRAND(M) returns vector of length M chosen from\n% Dirichlet(1,...,1) distribution.\n% R = DIRRAND(M,N) returns N such vectors in MxN matrix.\n%\n% References: Gelman, Carlin, Stern, Dunson, Vehtari & Rubin (2013),\n% Bayesian Data Analysis, third edition, p. 583.\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 n=1;\nend\n\n% Generate random numbers from Gamma(1,1) distribution...\nr=rand(m,n);\nr=-reallog(r);\n% ...and scale sum to unity\nrs=sum(r);\nfor i1=1:m\n r(i1,:)=r(i1,:)./rs;\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/dist/dirrand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7449572700279622}} {"text": "%% doubleContraction\n% Below is a demonstration of the features of the |doubleContraction| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |C=doubleContraction(A,B,subContract);|\n\n%% Description \n% This function performs a double contraction of two tensors |A| and |B| to\n% produce the output tensor |C|. The tensors are either both 3x3 second\n% order tensors or |A| is a 4th order 3x3x3x3 tensor. The optional 3rd\n% input |subContract| defines the indices to contract over for 4th order\n% tensors e.g. |subContract=[1 2]| would contract over the first 2 indices.\n% \n\n%% Examples \n% \n\n%% Double contraction of a 2nd-order and a 2nd-order tensor\n\n%%\n% Creating an example tensor. Here a tensor |A| with all zeros except for\n% the 3,3 component is created. Next a tensor |B| which, through double\n% contraction, can \"pick out\" this scalar value is created. Finally the\n% double contraction is performed illustrating this process. \n\n%Create example tensor A\nA=zeros(3,3); A(3,3)=pi; %Zeros with Azz=A33=pi\nR=euler2DCM([0.25*pi 0.25*pi 0]); %Rotation matrix\nA=R*A*R' %Rotated version of A\n\n% Create 'structure' tensor example B\nb=[0 0 1]*R.'; %Rotated Z vector\nB=b.'*b %Rotated \"structure\" tensor for vector b\n\n%%\n% Double contraction using |doubleContraction|\ns=doubleContraction(A,B)\n\n%% Double contraction of a 4th-order and a 2nd-order tensor\n\n%%\n% Example for Hooke's law of linear elasticity\n\n%Creating the 4th order linear elastic stiffness tensor\nI=eye(3,3); %The 2nd order identity tensor\nII1=dyadicProduct(I,I,1); %4th order base tensor 1 \nII3=dyadicProduct(I,I,3); %4th order base tensor 3\n\n%Parameters for Hooke's law\nmu=1; %The shear modulus\nlambda=5; %The lambda lame parameter\n\n%Compose stiffness tensor\nC=lambda.*II1+2.*mu.*II3; \n\n%Create strain tensor\nE=rand(3,3); E=E*E'\n\n%%\n% Double contraction using |doubleContraction|\nsubContract=[3 4];\nS=doubleContraction(C,E,subContract)\n\n%% Using symbolic variables\n\n%%\n% Example for Hooke's law of linear elasticity\n\n%Creating the 4th order linear elastic stiffness tensor\nI=eye(3,3); %The 2nd order identity tensor\nII1=dyadicProduct(I,I,1); %4th order base tensor 1 \nII3=dyadicProduct(I,I,3); %4th order base tensor 3\n\n%Parameters for Hooke's law\ntry\n syms mu lambda\ncatch\n mu=1; %The shear modulus\n lambda=5; %The lambda lame parameter\nend\n%Compose stiffness tensor\nC=lambda.*II1+2.*mu.*II3;\n\n%Display Voigt mapped version\nc=voigtMap(C)\n\n%Create strain tensor\nsyms E1_1 E2_2 E3_3 E1_2 E1_3 E2_3;\nE=[E1_1 E1_2 E1_3;...\n E1_2 E2_2 E2_3;...\n E1_3 E2_3 E3_3]\n\n%%\n% Double contraction using |doubleContraction|\n\nsubContract=[3 4];\nS=doubleContraction(C,E,subContract)\n\n%%\n% \n% <>\n% \n% _*GIBBON*_ \n% \n% \n% _Kevin Mattheus Moerman_, \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/HELP_doubleContraction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.744957268162255}} {"text": "% Fast community finding algorithm by M. Newman\n% Source: \"Fast algorithm for detecting community \n% structure in networks\", Mark Newman\n%\n% INPUTs: adjacency matrix, nxn\n% OUTPUTs: sequential group (cluster) formation, \n% modularity metric for each cluster breakdown\n%\n% Other functions used: numEdges.m\n% Note: To save the plot generated in this routine:\n% uncomment \"print newmanCommFast_example.pdf\"\n%\n% GB: last updated, Oct 12 2012\n\nfunction [groups_hist,Q]=newmanCommFast(adj)\n\ngroups={};\ngroups_hist={}; % a list of groups at each step\nQ=[];\nn=size(adj,1); % number of vertices\ngroups_hist{1}={};\n\nfor i=1:n\n groups{i}=i; % each node starts out as one community\n groups_hist{1}{i}=i;\nend\n\nQ(1) = Qfn(groups,adj);\n\nfor s=1:n-1 % all possible iterations\n \n \n dQ=zeros(length(groups));\n\n for i=1:length(groups)\n for j=i+1:length(groups)\n group_i=groups{i};\n group_j=groups{j};\n \n dQ(i,j)=0; % default\n \n % check if connected\n connected=0;\n if sum(sum(adj([group_i group_j],[group_i group_j])))>sum(sum(adj(group_i,group_i)))+sum(sum(adj(group_j,group_j)))\n\tconnected=1;\n end\n \n if connected && not(isempty(group_i)) && not(isempty(group_j))\n\t% join groups i and j?\n\tdQ(i,j)=deltaQ(groups,adj,i,j);\n end\n \n end\n end\n \n \n % pick max nonzero dQ\n dQ(find(dQ==0))=-Inf; \n [minv,minij]=max(dQ(:));\n \n [mini,minj]=ind2sub([size(dQ,1),size(dQ,1)],minij); % i and j corresponding to min dQ\n groups{mini}=sort([groups{mini} groups{minj}]);\n groups{minj}=groups{length(groups)}; % swap minj with last group\n groups=groups(1:length(groups)-1);\n \n groups_hist{length(groups_hist)+1}=groups; % save current snapshot\n Q(length(Q)+1) = Qfn(groups,adj);\n \nend % end of all iterations\n\nnum_modules=[];\nfor g=1:length(groups_hist)\n num_modules=[num_modules length(groups_hist{g})];\nend\n\nset(gcf,'Color',[1 1 1],'Colormap',jet);\nplot(num_modules,Q,'ko-')\nxlabel('number of modules / communities')\nylabel('modularity metric, Q')\n\n% print newmanCommFast_example.pdf\n\n\nfunction dQ=deltaQ(groups,adj,i,j)\n\n% computing the delta Q between two community configurations\n% dQ = 2(e_ij - ai*aj) or (Q_groups_(i,j)_merged - Q_original)\n% inputs: current community assignments: groups, adjacency matrix, i,j to be joined\n% outputs: delta Q value (real number)\n\n% $$$ Q1=Qfn(groups,adj);\n% $$$ groups{i}=[groups{i} groups{j}];\n% $$$ groups{j}=groups{length(groups)};\n% $$$ groups=groups(1:length(groups)-1);\n% $$$ Q2=Qfn(groups,adj);\n% $$$ dQ = Q2-Q1;\n\n% alternative dQ = 2(e_ij - ai*aj) from paper;\nnedges=numEdges(adj); % compute the total number of edges\ne_ii = numEdges( adj(groups{i},groups{i}) ) / nedges;\ne_jj = numEdges( adj(groups{j},groups{j}) ) / nedges;\ne_ij = numEdges( adj([groups{i} groups{j}],[groups{i} groups{j}]) ) / nedges - e_ii - e_jj;\n\na_i=sum(sum(adj(groups{i},:)))/nedges-e_ii;\na_j=sum(sum(adj(groups{j},:)))/nedges-e_jj;\n\ndQ = 2*(e_ij-a_i*a_j);\n\n\n\nfunction Q=Qfn(modules,adj) % ....... same as modularityMetric.m ........\n\n% Computing the modularity for the final module break-down\n% Defined as: Q=sum_over_modules_i (eii-ai^2) (eq 5) in Newman and Girvan.\n% eij = fraction of edges that connect community i to community j\n% ai=sum_j (eij)\n\nnedges=numEdges(adj); % compute the total number of edges\n\nQ = 0;\nfor m=1:length(modules) \n\n e_mm=numEdges(adj(modules{m},modules{m}))/nedges;\n a_m=sum(sum(adj(modules{m},:)))/nedges - e_mm; % counting e_mm only once\n \n Q = Q + (e_mm - a_m^2);\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/newmanCommFast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7449131002167129}} {"text": "function [ num_int, pi ] = plane_imp_triangle_int_3d ( a, b, c, d, t )\n\n%*****************************************************************************80\n%\n%% PLANE_IMP_TRIANGLE_INT_3D: intersection ( implicit plane, triangle ) in 3D.\n%\n% Discussion:\n%\n% The implicit form of a plane in 3D is:\n%\n% A * X + B * Y + C * Z + D = 0\n%\n% There may be 0, 1, 2 or 3 points of intersection returned.\n%\n% If two intersection points are returned, then the entire line\n% between them comprises points of intersection.\n%\n% If three intersection points are returned, then all points of\n% the triangle intersect the plane.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(3,3), the vertices of the triangle.\n%\n% Input, real A, B, C, D, the implicit plane parameters.\n%\n% Output, integer NUM_INT, the number of intersection points returned.\n%\n% Output, real PI(3,3), the intersection points.\n%\n dim_num = 3;\n num_int = 0;\n pi = [];\n%\n% Compute the signed distances between the vertices and the plane.\n%\n dist1 = a * t(1,1) + b * t(2,1) + c * t(3,1) + d;\n dist2 = a * t(1,2) + b * t(2,2) + c * t(3,2) + d;\n dist3 = a * t(1,3) + b * t(2,3) + c * t(3,3) + d;\n%\n% Consider any zero distances.\n%\n if ( dist1 == 0.0 )\n num_int = num_int + 1;\n pi(1:dim_num,num_int) = t(1:dim_num,1);\n end\n\n if ( dist2 == 0.0 )\n num_int = num_int + 1;\n pi(1:dim_num,num_int) = t(1:dim_num,2);\n end\n\n if ( dist3 == 0.0 )\n num_int = num_int + 1;\n pi(1:dim_num,num_int) = t(1:dim_num,3);\n end\n%\n% If 2 or 3 of the nodes intersect, we're already done.\n%\n if ( 2 <= num_int )\n return\n end\n%\n% If one node intersects, then we're done unless the other two\n% are of opposite signs.\n%\n if ( num_int == 1 )\n\n if ( dist1 == 0.0 )\n\n [ num_int, pi ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,2), t(1:dim_num,3), ...\n dist2, dist3, num_int, pi );\n\n elseif ( dist2 == 0.0 )\n\n [ num_int, pi ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,1), t(1:dim_num,3), ...\n dist1, dist3, num_int, pi );\n\n elseif ( dist3 == 0.0 )\n\n [ num_int, pi ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,1), t(1:dim_num,2), ...\n dist1, dist2, num_int, pi );\n\n end\n\n return\n\n end\n%\n% All nodal distances are nonzero, and there is at least one\n% positive and one negative.\n%\n if ( dist1 * dist2 < 0.0 & dist1 * dist3 < 0.0 )\n\n [ num_int, pi ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,1), t(1:dim_num,2), ...\n dist1, dist2, num_int, pi );\n\n [ num_int, pi ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,1), t(1:dim_num,3), ...\n dist1, dist3, num_int, pi );\n\n elseif ( dist2 * dist1 < 0.0 & dist2 * dist3 < 0.0 )\n\n [ num_int, pi ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,2), t(1:dim_num,1), ...\n dist2, dist1, num_int, pi );\n\n [ num_int, pi ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,2), t(1:dim_num,3), ...\n dist2, dist3, num_int, pi );\n\n elseif ( dist3 * dist1 < 0.0 & dist3 * dist2 < 0.0 )\n\n [ num_int, pi ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,3), t(1:dim_num,1), ...\n dist3, dist1, num_int, pi );\n\n [ num_int, pi ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,3), t(1:dim_num,2), ...\n dist3, dist2, num_int, pi );\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/plane_imp_triangle_int_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7449130989299824}} {"text": "function x=logistic(n,level,a,x0)\n%Syntax: x=logistic(n,level,a,x0)\n%________________________________\n%\n% Simulation of the Quadratic map.\n% x'=ax(1-x)\n%\n% x is the simulated time series.\n% n is the number of the simulated points.\n% level is the noise standard deviation divided by the standard deviation of the\n% noise-free time series. We assume Gaussian noise with zero mean.\n% a is the parameter.\n% x0 is the initial value for x.\n%\n%\n% Reference:\n%\n% May R M (1976): Simple mathematical modelswith very complicated dynamics. \n% Nature 261: 459-467\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% 17 Nov 2001\n\nif nargin<1 | isempty(n)==1\n n=500;\nelse\n % n must be scalar\n if sum(size(n))>2\n error('n must be scalar.');\n end\n % n must be positive\n if n<0\n error('n must be positive.');\n end\n % n must be an integer\n if round(n)-n~=0\n error('n must be an integer.');\n end\nend\n\nif nargin<2 | isempty(level)==1\n level=0;\nelse\n % level must be a scalar\n if sum(size(level))>2\n error('level must be scalar.');\n end\n % level must be positive\n if level<0\n error('level must be positive.');\n end\nend\n\nif nargin<3 | isempty(a)==1\n a=4;\nelse\n % a must be scalar\n if sum(size(a))>2\n error('a must be scalar.');\n end\nend\n\nif nargin<4 | isempty(x0)==1\n x0=0.1;\nelse\n % x0 must be scalar\n if sum(size(x0))>2\n error('x0 must be scalar.');\n end\nend\n\n\n% Initialize\nx(1,1)=a*x0*(1-x0);\n\n% Simulate\nfor i=2:n\n x(i,1)=a*x(i-1,1)*(1-x(i-1,1));\nend\n\n% Add normal white noise\nx=x+randn(n,1)*level*std(x);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/1597-chaotic-systems-toolbox/logistic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8311430478583169, "lm_q1q2_score": 0.7449130887005421}} {"text": "function [gradf, err] = tapas_riddersgradient(f, x, varargin)\n% Calculates the gradient of the function f at point x according to Ridders' method:\n%\n% Ridders, CJF. (1982). Accurate computation of F'(x) and F'(x) F''(x). Advances in Engineering\n% Software, 4(2), 75-6.\n%\n% INPUT:\n% f Function handle of a real function of n real variables which are passed as\n% *one* vector with n elements\n% x Point at which to differentiate f\n%\n% OUTPUT:\n% gradf Gradient of f at x (row vector)\n% err Error estimates (row vector)\n%\n% OPTIONS:\n% Optionally, the third argument of the function can be a structure containing further\n% settings for Ridder's method.\n%\n% varargin{1}.init_h Initial finite difference (default: 1)\n% varargin{1}.div Divisor used to reduce h on each step (default: 1.2)\n% varargin{1}.min_steps Minimum number of steps in h (default: 3)\n% varargin{1}.max_steps Maximum number of steps in h (default: 100)\n% varargin{1}.tf Terminate if last step worse than preceding by a factor of tf\n% (default: 2)\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is released under the terms of the GNU General Public Licence (GPL), version 3. You can\n% redistribute it and/or modify it under the terms of the GPL (either version 3 or, at your option,\n% any later version). For further details, see the file COPYING or .\n\n n = length(x);\n\n % Defaults\n options.init_h = 1;\n options.div = 1.2;\n options.min_steps = 3;\n options.max_steps = 100;\n options.tf = 2;\n gradf = NaN(1,n);\n err = NaN(1,n);\n \n % Overrides\n if nargin > 2\n options_ovr = varargin{1};\n\n if isfield(options_ovr,'init_h')\n options.init_h = options_ovr.init_h;\n end\n \n if isfield(options_ovr,'div')\n options.div = options_ovr.div;\n end\n \n if isfield(options_ovr,'min_steps')\n options.min_steps = options_ovr.min_steps;\n end\n \n if isfield(options_ovr,'max_steps')\n options.max_steps = options_ovr.max_steps;\n end\n \n if isfield(options_ovr,'tf')\n options.tf = options_ovr.tf;\n end\n end\n \n % Check if f and x match\n try\n f(x);\n catch err\n error('tapas:hgf:ridders:CannotEvalFun', 'Function cannot be evaluated at differentiation point.');\n end\n \n % Loop through argument variables\n for i = 1:n\n \n % Construct filehandle to be passed to riddersdiff\n fxih = @(xi) fxi(f,x,i,xi);\n \n % Calculate derivative\n [gradf(i), err(i)] = tapas_riddersdiff(fxih,x(i),options);\n end\nend\n\nfunction fxi = fxi(f,x,i,xi)\n xx = x;\n xx(i) = xi;\n fxi = f(xx);\nend\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_riddersgradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.8539127603871312, "lm_q1q2_score": 0.7449085632296031}} {"text": "function outsig=rampup(L,wintype)\n%RAMPUP Rising ramp function\n% Usage: outsig=rampup(L);\n%\n% `rampup(L)` will return a rising ramp function of length *L*. The\n% ramp is a sinusoide starting from zero and ending at one. The ramp\n% is centered such that the first element is always 0 and the last\n% element is not quite 1, such that the ramp fits with following ones.\n%\n% `rampup(L,wintype)` will use another window for ramping. This may be any\n% of the window types from |firwin|. Please see the help on |firwin| for\n% more information. The default is to use a piece of the Hann window.\n%\n% See also: rampdown, rampsignal, firwin\n\ncomplainif_argnonotinrange(nargin,1,2,mfilename);\n\nif nargin==1\n wintype='hann';\nend;\n \nwin=firwin(wintype,2*L,'inf');\noutsig=win(L+1:2*L);\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/sigproc/rampup.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7449085531063679}} {"text": "function [ r c ] = corner_ST( img,ptNum )\n%[ r c ] = corner_ST( img )\n%\tFind corner points in image using Shi-Tomasi method\n% IMG should be gray.R and C are the coordinates of corners(col vec)\n\nimg = im2double(img);\nh1 = fspecial('gauss',[6 6],1.5);\nhd = imfilter(h1,[-1 1],'rep');\nhd = hd(1:5,1:5); % use the HOG gradient\n% hd = [-1 0 1];\nimgdx = imfilter(img,hd,'rep');\nimgdy = imfilter(img,hd','rep');\n\nker = fspecial('gauss',[5 5],1.5); % weight of the patch\nimgdx2 = imfilter(imgdx.^2,ker,'rep');\nimgdxdy = imfilter(imgdx.*imgdy,ker,'rep');\nimgdy2 = imfilter(imgdy.^2,ker,'rep');\n\nA = zeros(2,2,numel(img));\nA(1,1,:) = imgdx2(:);\nA(1,2,:) = imgdxdy(:);\nA(2,1,:) = imgdxdy(:);\nA(2,2,:) = imgdy2(:);\nev = real(eig2(A));\n\nevTh = .1;\nminEv = min(ev,[],2);\nminEv = reshape(minEv,size(img));\nR = (minEv > evTh*max(max(minEv)));\n% fis(R)\n\nRmax = ordfilt2(minEv,9,ones(3));\nRcorner = (minEv == Rmax) & R; % non-maximal suppression\n% fis(Rcorner)\nI = find(Rcorner);\n\nif exist('ptNum','var') && nnz(Rcorner) > ptNum\n\tselEvs = minEv(I); % find the ptNum corners with the largest ev\n\t[~,I1] = sort(selEvs,'descend');\n\tI = I(I1(1:ptNum));\nend\n[r c] = ind2sub(size(img),I); % points' positions\n\nend\n\nfunction ev = eig2(a) % eigenvalue of a 2*2 matrix\nb = -(a(1,1,:)+a(2,2,:));\ndetA = a(1,1,:).*a(2,2,:)-a(1,2,:).*a(2,1,:);\ndelta = b.^2-4*detA;\nev = [-b+sqrt(delta),-b-sqrt(delta)]/2; \nev = reshape(ev,2,[])'; % N-by-2\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/30822-lucas-kanade-tracker-with-pyramid-and-iteration/LK Tracker/corner_ST.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7448949847697769}} {"text": "function [logbf,t] = spm_bms_ttest (y,prior)\n% Log Bayes Factor against null for one sample t-test\n% FORMAT [logbf,t] = spm_bms_ttest (y,prior)\n% \n% y [N x 1] data vector\n% prior 'jzs' (default), 'unit'\n%\n% logbf Log Bayes Factor \n% t t-statistic\n%\n% Default prior is 'jzs'. The different priors are described in\n% [1] Rouder et al. (2009) Psych Bull Rev, 16(2),225-237.\n%\n% These tests consider the quantity d = mean / standard deviation. \n% The unit information prior, 'unit', uses a zero mean unit variance \n% Gaussian prior over d (the prior variance of d, sig_d^2, is unity).\n%\n% The (Jeffreys-Zellner-Snow) JZS prior, 'jzs', uses a Cauchy over d \n% and an inverse chi^2 over sig_d^2.\n%_______________________________________________________________________\n% Copyright (C) 2014 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_bms_ttest.m 6038 2014-06-04 15:22:42Z will $\n\ntry \n pr=prior;\ncatch\n pr='jzs';\nend\n\nN=length(y);\nm=mean(y);\ns=std(y);\nsem=s/sqrt(N);\nt=m/sem;\nv=N-1;\n\nswitch pr,\n case 'unit',\n rs=1;\n case 'jzs',\n logbf = jzs_logbf(t,v,N);\n return\n otherwise\n disp('Unknown prior in bayes_ttest');\n return\nend\n\n% For Unit Information prior, 'unit':\n%\n% The minimum value of logbf obtains when t=0\n% This minimum value is logbf=-0.5*log(1+N*r)\n% For r=1 logbf=-3 can be gotten with N=405 samples.\n\n% See note 5 at end of [1]\nt2=t^2;\nnr=1+N*rs^2;\nlog_num=-0.5*N*log(1+t2/v);\nlog_denom1=-0.5*log(nr);\nlog_denom2=-0.5*N*log(1+t2/(nr*v));\n\nlogbf=log_num-log_denom1-log_denom2;\nlogbf=-logbf;\n\n\n%-------------------------------------------------------\nfunction [logbf] = jzs_logbf(t,v,N)\n% JZS Log Bayes factor \n%\n% See equation (1) in \n% Rouder et al. (2009) Psych Bull Rev, 16(2),225-237.\n\nt2=t^2;\nnum=(1+t2/v)^(-0.5*(v+1));\n\ngmax=1000;\ndenom=quad(@(g)jzs_integrand(g,t2,N,v),0,gmax);\n\nlogbf=log(num/denom);\nlogbf=-logbf;\n\n%--------------------------------------------------------\nfunction [j] = jzs_integrand(g,t2,N,v)\n\nng=1+N*g;\nt1=ng.^(-0.5);\nt2=(1+t2./(ng*v)).^(0.5*(v+1));\nt3=(2*pi)^(-0.5)*(g.^(-1.5)).*exp(-1./(2*g));\nj=t1.*t2.*t3;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_bms_ttest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7448587908811505}} {"text": "function [R,S]=rga(G)\n% RGA Relative Gain Array\n% \n% R=rga(G) returns the Relative Gain Array, R based on the gain matrix, G.\n%\n% For square matrix, G, R is the normal RGA, defined as follows:\n% R = inv(G') .* G \n% If G is nonsquare, R is the so called General RGA:\n% R = pinv(G') .* G\n% \n% The RGA is a very useful tool for control structure design. For a square\n% system (the number of inputs equals to the number of output), the RGA can\n% be used to find input-output pairs (one input to control one output).\n% There are many publications on how to pair input and output using the\n% RGA. The basic rule is:\n% 1. Avoid input and output pairs which have negative relative gains.\n% 2. Avoid input and output pairs which have large relative gains.\n% 3. Select input and output pairs which have the relative gain close to 1.\n% \n% Interestingly, if the RGA is repeatedly calculated based on R, i.e.\n%\n% R = rga(R);\n% \n% Eventualy, the RGA will converge to a selection (0,1)-matrix. With the\n% second output, \n%\n% [R,S] = rga(G) produces a selection matrix, S based on the repeated RGA.\n%\n% where S is (0,1) matrix with the same dimension as G. Each row and each\n% column of S have only one element of 1, but all others are 0. The element\n% of 1 indicates which input (column) should be used to pair which output\n% (row).\n% Note: The selection matrix, S, is only a recommendation. It may not\n% satisfy the rules stated above and may not be appropriate for some\n% systems.\n%\n% For nonsquare systems, the general RGA can also be used to select inputs\n% if the number of inputs is larger than the number of outputs, or to\n% choose outputs, if the system has more outputs than inputs. The second\n% output in this case gives the input (output) effectiveness, E.\n%\n% [R,E] = rga(G)\n%\n% Where E is a column vector corresponding to the input (output). Inputs\n% (outputs) with largest input (output) effectiveness are recommented to be\n% selected for the control system.\n%\n% By Yi Cao at Cranfield University on 7th March 2008\n%\n% References:\n%\n% 1. Bristol, E.H., On a new measure of interactions for multivariable process\n% control. IEEE Trans. Automatic Control, AC-11:133-134, 1966.\n% 2. Cao, Y and Rossiter, D, An input pre-screening technique for control\n% structure selection, Computers and Chemical Engineering, 21(6), pp.\n% 563-569, 1997.\n \n% Examples:\n%\n% Example 1: A random 5 x 5 matrix\n%{\nG = randn(5);\n[R,S] = rga(G)\n%}\n% Example 2: A random 5 x 10 matrix for input selection\n%{\nG = randn(5,10);\n[R,IE] = rga(G)\n%}\n% Example 3: A random 10 x 5 matrix for output selection\n%{\nG = randn(10,5);\n[R,OE] = rga(G)\n%}\n%\n\n\n% Check input and output\nerror(nargchk(1,1,nargin));\nerror(nargoutchk(0,2,nargout));\n\n% The RGA\nR=pinv(G.').*G;\nif nargout<2\n return\nend\n\n[m,n]=size(G);\n% The square case\nif n==m\n S=R;\n while norm(round(S)-S)>1e-9\n S(S<0)=0;\n S = inv(S.').*S;\n end\n return\nend\n\n% The nonsquare case\nS = sqrt(sum(R))';\nif m>n\n S = sqrt(sum(R,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/19096-relative-gain-array/rga.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7448587884267801}} {"text": "%% LSHAPESTOKES Poiseuille flow in a L-shaped domain\n%\n% Stokes equations on the square [-1,1]^2. \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% See also squareStokes, StokesP2P1\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all; clear all;\n%% Parameters\nmaxIt = 4; N = zeros(maxIt,1); \nerru = zeros(maxIt,1); errp = zeros(maxIt,1);\n\n%% Generate an initial mesh \n[node,elem] = squaremesh([-1 1 -1 1], 0.25);\nbdFlag = setboundary(node,elem,'Dirichlet');\n\n%% PDE and options\npde = Stokesdata1;\n\n%% Finite Element Method \nfor k = 1:maxIt\n % solve the equation\n [u,p,edge,A] = StokesP2P1(node,elem,pde,bdFlag);\n N(k) = length(u)+length(p);\n if N(k) < 2e3 % show solution for small size\n figure(1); showresult(node,elem,p); \n end\n % compute error\n uI = pde.exactu([node; (node(edge(:,1),:)+node(edge(:,2),:))/2]);\n erru(k) = sqrt((u-uI(:))'*A*(u-uI(:)));\n errp(k) = getL2error(node,elem,pde.exactp,p);\n % refine mesh\n [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\nend\n\n%% Plot convergence rates\nfigure(2); clf;\nshowrate2(N,erru,2,'-*','||Du_I-Du_h||',N,errp,2,'k-+','|| p - p_h||');", "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/2D/LshapeStokes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.8152324915965391, "lm_q1q2_score": 0.7448587867795848}} {"text": "function p=legendrep(m,x)\n% function which construct Legendre polynomial Pm(x)\n% where M is the degree of polynomial and X is the variable. \n% Result - P is the char string that should be evaluated EVAL(P)\n% Example:\n% P=legendrep(2,'cos(theta)') will produce\n% P='(3*cos(theta).^2 -1)/2' which then can be evaluated as\n% theta=0.3; P=legendrep(2,'cos(theta)'); Lp=eval(P); produce\n% Lp = 0.8690\n% For Matlab R14 the following example can be used:\n% x=-5:.1:5; p=legendrep(5,'x .*cos(x)'); xp = eval(p); \n% figure; plot(x, xp, 'r.-'); grid\n\n%% References: \n% Gradshteyn, Ryzhik \"Table of Integrals Series and Products\", 6th ed., p.973\n% \n%__________________________________________________\n% \tSergei Koptenko, Resonant Medical Inc., Toronto \n%\tsergei.koptenko@resonantmedical.com \n%______________March/30/2004_______________________\n%%\nswitch m\ncase 0\n p='1'; return\ncase 1\n p=x; return\ncase 2\n p=['(3*' x '.^2 -1)/2']; return\ncase 3\n p=['(5*' x '.^3 - 3 *' x ')/2']; return\ncase 4\n p=['(35 *' x '.^4 - 30 * ' x '.^2 + 3)/8']; return\ncase 5\n p=['( 63 * ' x '.^5 - 70 * ' x '.^3 + 15 *' x ' )/8']; return\ncase 6\n p=['(231 *' x '.^6 - 315 * ' x '.^4 + 105 * ' x '.^2 -5)/16']; return\n case 7\n p=['(429 * ' x '.^7 - 693 * ' x '.^5 +315 * ' x '.^3 -35 *' x ' )/16']; return\ncase 8\n p=['(6435 *' x '.^8 -12012 *' x '.^6 + 6930 * ' x '.^4 -1260 * ' x '.^2 +35)/128']; return\ncase 9\n p=['(12155 * ' x '.^9 -25740 * ' x '.^7 +18018 * ' x '.^5 -4620 * ' x '.^3 +315 *' x ' )/128'];\n return\ncase 10\n p=['(46189 *' x '.^10 -109395 *' x '.^8 +90090 *' x '.^6 -30030 * ' x '.^4 +3465 * ' x '.^2 -63)/256'];\n return\ncase 11\n p=['(88179 * ' x '.^11 -230945 * ' x '.^9 +218790 * ' x '.^7 -90090 * ' x '.^5 +15015 * ' x '.^3 -693 *' x ' )/256'];\n return \ncase 12\n p=['(676039 *' x '.^12 -1939938 *' x '.^10 +2078505 *' x '.^8 -1021020 *' x '.^6 +225225 * ' x '.^4 -18018 * ' x '.^2 +231)/1024'];\n return\n \notherwise\n iii=m-10; %shift counter \n pp=strvcat(legendrep(11,x),legendrep(12,x)); % get last two members\n for ii=3:1:iii, % Begin construct from 13th member \n p_ii=[num2str(1/(ii)) ' * (' num2str(2*ii-1) ' * ' x '.*(' ...\n deblank(pp(ii-1,:)) ')-' num2str(ii-1) '.*(' deblank(pp(ii-2,:)) '))'];\n pp=strvcat(pp, p_ii);\n end\np=deblank(pp(iii,:)); % remove traiing blanks\n return\nend\n\nreturn\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/4710-legendre-polynomial-pmx/legendrep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7448587862414677}} {"text": "function [A,b] = parallax(n)\n%PARALLAX Stellar parallax problem with 28 fixed, real observations.\n%\n% [A,b] = parallax(n)\n%\n% Stellar parallax problem with 28 fixed, real observations.\n%\n% The underlying problem is a Fredholm integral equation of the\n% first kind with kernel\n% K(s,t) = (1/sigma*sqrt(2*pi))*exp(-0.5*((s-t)/sigma)^2) ,\n% and it is discretized by means of a Galerkin method with n\n% orthonormal basis functions. The right-hand side consists of\n% a measured distribution function of stellar parallaxes, and its\n% length is fixed, m = 26. The exact solution, which represents\n% the true distribution of stellar parallaxes, in not known.\n\n% Reference: W. M. Smart, \"Stellar Dynamics\", Cambridge University Press,\n% 1938; p. 30.\n\n% Discretized by Galerkin method with orthonormal box functions;\n% 2-D integration is done by means of the computational molecule:\n% 1 4 1\n% 4 16 4\n% 1 4 1\n\n% Per Christian Hansen, IMM, 09/16/92.\n\n% Initialization.\na = 0; b = 0.1; m = 26; sigma = 0.014234;\nhs = 0.130/m; hx = (b-a)/n; hsh = hs/2; hxh = hx/2;\nss = (-0.03 + [0:m-1]'*hs)*ones(1,n);\nxx = ones(m,1)*(a + [0:n-1]*hx);\n\n% Set up the matrix.\nA = 16*exp(-0.5*((ss+hsh - xx-hxh)/sigma).^2);\nA = A + 4*(exp(-0.5*((ss+hsh - xx )/sigma).^2) + ...\n exp(-0.5*((ss+hsh - xx-hx )/sigma).^2) + ...\n exp(-0.5*((ss - xx-hxh)/sigma).^2) + ...\n exp(-0.5*((ss+hs - xx-hxh)/sigma).^2));\nA = A + (exp(-0.5*((ss - xx )/sigma).^2) + ...\n exp(-0.5*((ss+hs - xx )/sigma).^2) + ...\n exp(-0.5*((ss - xx-hx )/sigma).^2) + ...\n exp(-0.5*((ss+hs - xx-hx )/sigma).^2));\nA = sqrt(hs*hx)/(36*sigma*sqrt(2*pi))*A;\n\n% Set up the normalized right-hand side.\nb = [3;7;7;17;27;39;46;51;56;50;43;45;43;32;33;29;...\n 21;12;17;13;15;12;6;6;5;5]/(sqrt(hs)*640);", "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/parallax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7448587808962949}} {"text": "function [Y, spectrum] = sllle_wg(G, d)\n%SLLLE_WG Solves the Locally Linear Embedding from weight graph\n%\n% $ Syntax $\n% - Y = sllle_wg(G, d)\n% - [Y, spectrum] = sllle_wg(G, d)\n%\n% $ Arguments $\n% - G: The weights graph\n% - d: The dimension of the embedding\n% - Y: The sample coordinates in the embedded space\n% - spectrum: The spectrum of the embeded space dimensions\n%\n% $ Description $\n% - Y = sllle_wg(G, d) solves the locally linear embedding from\n% a given weight graph. G should be a graph of n nodes, where\n% the edge value from i-th node to j-th node, means the weights\n% on the i-th sample in constructing the j-th sample, (or the\n% construction of i-th sample to the j-th sample). \n% Y is solved by taking the eigenvectors of (I - W)(I - W)^T, \n% corresponding to the (d+1) smallest eigenvalues, and discarding \n% the smallest one. In our output, the dimension is sorted in the \n% ascending order of eigenvalues.\n%\n% - [Y, spectrum] = sllle_wg(G, d) also returns the spectrum of the\n% corresponding dimensions, a column vector of the corresponding\n% eigenvalues.\n%\n% $ Remarks $\n% - The dimension d should be strictly less than n.\n%\n% $ History $\n% - Created by Dahua Lin, on Sep 11st, 2006\n%\n\n%% parse and verify input\n\nif nargin < 2\n raise_lackinput('sllle_wg', 2);\nend\n\ngi = slgraphinfo(G, {'square'});\nif ~gi.valued\n error('sltoolbox:invalidarg', 'The graph G should be a valued graph');\nend\nif isnumeric(G)\n W = G;\nelse\n W = sladjmat(G, 'sparse', true);\nend\n\nn = gi.n;\nif d >= n\n error('sltoolbox:invalidarg', 'd should be strictly less than n');\nend\n\n%% compute\n\nif issparse(W)\n M = speye(n) - W;\nelse\n M = eye(n) - W;\nend\nclear W;\nM = M * M';\n\n[spectrum, Y] = slsymeig(M, d+1, 'ascend');\nclear M;\nspectrum = spectrum(2:d+1);\nY = Y(:, 2:d+1);\nY = Y';\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/manifold/sllle_wg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7448587804927073}} {"text": "function cnt = countcover(sz,blocksize,stepsize)\n%COUNTCOVER Covering of signal samples by blocks\n% CNT = COUNTCOVER(SZ,BLOCKSIZE,STEPSIZE) assumes a p-dimensional signal\n% of size SZ=[N1 N2 ... Np] covered by (possibly overlapping) blocks of\n% size BLOCKSIZE=[M1 M2 ... Mp]. The blocks start at position (1,1,..,1)\n% and are shifted between them by steps of size STEPSIZE=[S1 S2 ... Sp].\n% COUNTCOVER returns a matrix the same size as the signal, containing in\n% each entry the number of blocks covering that sample.\n%\n% See also IM2COLSTEP, COL2IMSTEP, IM2COL.\n\n\n% Ron Rubinstein\n% Computer Science Department\n% Technion, Haifa 32000 Israel\n% ronrubin@cs\n%\n% August 2008\n\n\ncnt = ones(sz);\nfor k = 1:length(sz)\n \n % this code is modified from function NDGRID, so it computes one\n % output argument of NDGRID at a time (to conserve memory)\n ids = (1:sz(k))';\n s = sz; s(k) = [];\n ids = reshape(ids(:,ones(1,prod(s))),[length(ids) s]);\n ids = permute(ids,[2:k 1 k+1:length(sz)]);\n \n cnt = cnt .* max( min(floor((ids-1)/stepsize(k)),floor((sz(k)-blocksize(k))/stepsize(k))) - ...\n max(ceil((ids-blocksize(k))/stepsize(k)),0) + 1 , 0 );\nend\n", "meta": {"author": "tiepvupsu", "repo": "DICTOL", "sha": "1a0361aa35c32d70525d06910d0e9b87997ff246", "save_path": "github-repos/MATLAB/tiepvupsu-DICTOL", "path": "github-repos/MATLAB/tiepvupsu-DICTOL/DICTOL-1a0361aa35c32d70525d06910d0e9b87997ff246/LCKSVD/ksvdbox/private/countcover.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7447316774511572}} {"text": "function [x1,x2,nS]=bracket(S,x0,d,problem,stepsize)\n% Bracket the minimum (or maximum) of the objective function\n% in the search direction.\n%\n% [x1,x2,nS]=bracket(S,x0,d,problem,stepsize)\n%\n% S: objective function\n% x0: initial point\n% d: search direction vector\n% problem: (-1): minimum (default), (1): maximum\n% stepsize: initial stepsize (default = 0.01*norm(d))\n% [x1,x2]: unsorted lower and upper limits\n% nS: number of objective function evaluations\n\n% Copyright (c) 2001 by LASIM-DEQUI-UFRGS\n% $Revision: 1.0 $ $Date: 2001/07/04 21:45:10 $\n% Argimiro R. Secchi (arge@enq.ufrgs.br)\n\n if nargin < 3,\n error('bracket requires three input arguments');\n end\n if nargin < 4,\n problem=-1;\n end\n if nargin < 5,\n stepsize=0.01*norm(d);\n end\n\n d=d(:);\n x0=x0(:);\n j=0; nS=1;\n y0=feval(S,x0)*problem;\n \n while j < 2,\n x=x0+stepsize*d;\n y=feval(S,x)*problem;\n nS=nS+1;\n \n if y0 >= y,\n stepsize=-stepsize;\n j=j+1;\n else\n while y0 < y,\n stepsize=2*stepsize;\n y0=y;\n x=x+stepsize*d;\n y=feval(S,x)*problem;\n nS=nS+1;\n end \n j=1;\n break;\n end\n end\n \n x2=x;\n x1=x0+stepsize*(j-1)*d;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15072-unconstrained-optimization-using-powell/bracket.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7446765548805016}} {"text": "clear; clc;\n% P2.4\nx = [1,-2,4,6,-5,8,10];\nn = [-4:2];\n\n% P2.4a\n[x11,n11] = sigshift(x,n,-2);\n[x12,n12] = sigshift(x,n,4);\n[x1,n1] = sigadd(3*x11,n11,x12,n12);\n[x1,n1] = sigadd(x1,n1,-2*x,n);\n[xe,xo,m] = evenodd(x1,n1);\nfigure(1);\nsubplot(2,2,1); stem(n1,x1,'ko'); title('Original Sequence')\nxlabel('n'); ylabel('x(n)');\nsubplot(2,2,2); stem(m,xe,'ko'); title('Even Part')\nxlabel('n'); ylabel('xe(n)');\nsubplot(2,2,4); stem(m,xo,'ko'); title('Odd Part')\nxlabel('n'); ylabel('xo(n)');\n\n% P2.4b\n[x21,n21] = sigshift(x,n,-5);\n[x22,n22] = sigshift(x,n,-4);\n[x2,n2] = sigadd(5*x21,n21,4*x22,n22);\n[x2,n2] = sigadd(x2,n2,3*x,n);\n[xe,xo,m] = evenodd(x2,n2);\nfigure(2);\nsubplot(2,2,1); stem(n2,x2,'ko'); title('Original Sequence')\nxlabel('n'); ylabel('x(n)');\nsubplot(2,2,2); stem(m,xe,'ko'); title('Even Part')\nxlabel('n'); ylabel('xe(n)');\nsubplot(2,2,4); stem(m,xo,'ko'); title('Odd Part')\nxlabel('n'); ylabel('xo(n)');\n\n% P2.4c\n[x31,n31] = sigshift(x,n,-4);\n[x32,n32] = sigshift(x,n,1);\n[x33,n33] = sigmult(x31,n31,x32,n32);\n[x31,n31] = sigfold(x,n); [x31,n31] = sigshift(x31,n31,2);\n[x32,n32] = sigmult(x31,n31,x,n);\n[x3,n3] = sigadd(x33,n33,x32,n32);\n[xe,xo,m] = evenodd(x3,n3);\nfigure(3);\nsubplot(2,2,1); stem(n3,x3,'ko'); title('Original Sequence')\nxlabel('n'); ylabel('x(n)');\nsubplot(2,2,2); stem(m,xe,'ko'); title('Even Part')\nxlabel('n'); ylabel('xe(n)');\nsubplot(2,2,4); stem(m,xo,'ko'); title('Odd Part')\nxlabel('n'); ylabel('xo(n)');\n\n% P2.4d\n[x41,n41] = sigshift(x,n,-2);\nx42 = cos(0.1*pi*n);\n[x42,n42] = sigmult(x42,n,x41,n41);\nx43 = 2*exp(0.5*n);\n[x41,n41] = sigmult(x43,n,x,n);\n[x4,n4] = sigadd(x42,n42,x41,n41);\n[xe,xo,m] = evenodd(x4,n4);\nfigure(4);\nsubplot(2,2,1); stem(n4,x4,'ko'); title('Original Sequence')\nxlabel('n'); ylabel('x(n)');\nsubplot(2,2,2); stem(m,xe,'ko'); title('Even Part')\nxlabel('n'); ylabel('xe(n)');\nsubplot(2,2,4); stem(m,xo,'ko'); title('Odd Part')\nxlabel('n'); ylabel('xo(n)');\n\n% P2.4e\nx5 = zeros(size(n));\nfor k = 1:5,\n [x51,n51] = sigshift(x,n,k);\n x52 = n.*x51;\n x5 = sigadd(x5,n51,x52,n51);\nend\n[xe,xo,m] = evenodd(x5,n51);\nfigure(5);\nsubplot(2,2,1); stem(n51,x5,'ko'); title('Original Sequence')\nxlabel('n'); ylabel('x(n)');\nsubplot(2,2,2); stem(m,xe,'ko'); title('Even Part')\nxlabel('n'); ylabel('xe(n)');\nsubplot(2,2,4); stem(m,xo,'ko'); title('Odd Part')\nxlabel('n'); ylabel('xo(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/16323-ingle-proakis-chapter-2-solutions/P204.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.744675578335095}} {"text": "function x = inv_digamma(y,niter)\n% INV_DIGAMMA Inverse of the digamma function.\n%\n% inv_digamma(y) returns x such that digamma(x) = y.\n\n% a different algorithm is provided by Paul Fackler:\n% http://www.american.edu/academic.depts/cas/econ/gaussres/pdf/loggamma.src\n\n% Newton iteration to solve digamma(x)-y = 0\nx = exp(y)+1/2;\ni = find(y <= -2.22);\nx(i) = -1./(y(i) - digamma(1));\n\n% never need more than 5 iterations\nif nargin < 2\n niter = 5;\nend\nfor iter = 1:niter\n x = x - (digamma(x)-y)./trigamma(x);\nend\nreturn\n\n% test\ny = -3:0.01:0.1;\nx = digamma(inv_digamma(y));\nmax(abs(x-y))\nmax(abs(x-y)./inv_digamma(y))\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/inv_digamma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7446755582140769}} {"text": "function [LIFT] = Lift2D()\n\n% function [LIFT] = Lift2D()\n% Purpose : Compute surface to volume lift term for DG formulation\n\nGlobals2D;\nEmat = zeros(Np, Nfaces*Nfp);\n\n% face 1\nfaceR = r(Fmask(:,1));\nV1D = Vandermonde1D(N, faceR); \nmassEdge1 = inv(V1D*V1D');\nEmat(Fmask(:,1),1:Nfp) = massEdge1;\n\n% face 2\nfaceR = r(Fmask(:,2));\nV1D = Vandermonde1D(N, faceR);\nmassEdge2 = inv(V1D*V1D');\nEmat(Fmask(:,2),Nfp+1:2*Nfp) = massEdge2;\n\n% face 3\nfaceS = s(Fmask(:,3));\nV1D = Vandermonde1D(N, faceS); \nmassEdge3 = inv(V1D*V1D');\nEmat(Fmask(:,3),2*Nfp+1:3*Nfp) = massEdge3;\n\n% inv(mass matrix)*\\I_n (L_i,L_j)_{edge_n}\nLIFT = V*(V'*Emat);\nreturn\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes2D/Lift2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947055100816, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7445908058358035}} {"text": "function [ num_int, pint ] = halfspace_imp_triangle_int_3d ( a, b, c, d, t )\n\n%*****************************************************************************80\n%\n%% HALFSPACE_IMP_TRIANGLE_INT_3D: intersection ( implicit halfspace, triangle ) in 3D.\n%\n% Discussion:\n%\n% The implicit form of a half-space in 3D may be described as the set\n% of points (X,Y,Z) on or \"above\" an implicit plane:\n%\n% 0 <= A * X + B * Y + C * Z + D\n%\n% The triangle is specified by listing its three vertices.\n%\n% The intersection may be described by the number of vertices of the\n% triangle that are included in the halfspace, and by the location of\n% points between vertices that separate a side of the triangle into\n% an included part and an unincluded part.\n%\n% 0 vertices, 0 separators (no intersection)\n% 1 vertex, 0 separators (point intersection)\n% 2 vertices, 0 separators (line intersection)\n% 3 vertices, 0 separators (triangle intersection)\n%\n% 1 vertex, 2 separators, (intersection is a triangle)\n% 2 vertices, 2 separators, (intersection is a quadrilateral).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, C, D, the parameters that define the\n% implicit plane, which in turn define the implicit halfspace.\n%\n% Input, real T(3,3), the vertices of the triangle.\n%\n% Output, integer NUM_INT, the number of intersection points returned,\n% which will always be between 0 and 4.\n%\n% Output, real PINT(3,4), the coordinates of the NUM_INT\n% intersection points. The points will lie in sequence on the triangle.\n% Some points will be vertices, and some may be separators.\n%\n\n%\n% Compute the signed distances between the vertices and the plane.\n%\n dist1 = a * t(1,1) + b * t(2,1) + c * t(3,1) + d;\n dist2 = a * t(1,2) + b * t(2,2) + c * t(3,2) + d;\n dist3 = a * t(1,3) + b * t(2,2) + c * t(3,3) + d;\n%\n% Now we can find the intersections.\n%\n [ num_int, pint ] = halfspace_triangle_int_3d ( t, dist1, dist2, dist3 );\n\n return\nend\n", "meta": {"author": "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/halfspace_imp_triangle_int_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7445184007249466}} {"text": "% ======================================================== % \n% Files of the Matlab programs included in the book: %\n% Xin-She Yang, Nature-Inspired Metaheuristic Algorithms, %\n% Second Edition, Luniver Press, (2010). www.luniver.com %\n% ======================================================== % \n\n% -------------------------------------------------------- %\n% Firefly Algorithm for constrained optimization using %\n% for the design of a spring (benchmark) % \n% by Xin-She Yang (Cambridge University) Copyright @2009 %\n% -------------------------------------------------------- %\n\nfunction fa_ndim\n% parameters [n N_iteration alpha betamin gamma]\npara=[20 500 0.5 0.2 1];\n\nhelp fa_ndim.m\n\n% Simple bounds/limits for d-dimensional problems\nd=15;\nLb=zeros(1,d);\nUb=2*ones(1,d);\n\n% Initial random guess\nu0=Lb+(Ub-Lb).*rand(1,d);\n\n[u,fval,NumEval]=ffa_mincon(@cost,u0,Lb,Ub,para);\n\n% Display results\nbestsolution=u\nbestojb=fval\ntotal_number_of_function_evaluations=NumEval\n\n%%% Put your own cost/objective function here --------%%%\n%% Cost or Objective function\n function z=cost(x)\n% Exact solutions should be (1,1,...,1) \nz=sum((x-1).^2);\n\n%%% End of the part to be modified -------------------%%%\n\n%%% --------------------------------------------------%%%\n%%% Do not modify the following codes unless you want %%%\n%%% to improve its performance etc %%%\n% -------------------------------------------------------\n% ===Start of the Firefly Algorithm Implementation ======\n% Lb = lower bounds/limits\n% Ub = upper bounds/limits\n% para == optional (to control the Firefly algorithm)\n% Outputs: nbest = the best solution found so far\n% fbest = the best objective value\n% NumEval = number of evaluations: n*MaxGeneration\n% Optional:\n% The alpha can be reduced (as to reduce the randomness)\n% ---------------------------------------------------------\n\n% Start FA\nfunction [nbest,fbest,NumEval]...\n =ffa_mincon(fhandle,u0, Lb, Ub, para)\n% Check input parameters (otherwise set as default values)\nif nargin<5, para=[20 500 0.25 0.20 1]; end\nif nargin<4, Ub=[]; end\nif nargin<3, Lb=[]; end\nif nargin<2,\ndisp('Usuage: FA_mincon(@cost,u0,Lb,Ub,para)');\nend\n\n% n=number of fireflies\n% MaxGeneration=number of pseudo time steps\n% ------------------------------------------------\n% alpha=0.25; % Randomness 0--1 (highly random)\n% betamn=0.20; % minimum value of beta\n% gamma=1; % Absorption coefficient\n% ------------------------------------------------\nn=para(1); MaxGeneration=para(2);\nalpha=para(3); betamin=para(4); gamma=para(5);\n\n% Total number of function evaluations\nNumEval=n*MaxGeneration;\n\n% Check if the upper bound & lower bound are the same size\nif length(Lb) ~=length(Ub),\n disp('Simple bounds/limits are improper!');\n return\nend\n\n% Calcualte dimension\nd=length(u0);\n\n% Initial values of an array\nzn=ones(n,1)*10^100;\n% ------------------------------------------------\n% generating the initial locations of n fireflies\n[ns,Lightn]=init_ffa(n,d,Lb,Ub,u0);\n\n% Iterations or pseudo time marching\nfor k=1:MaxGeneration, %%%%% start iterations\n\n% This line of reducing alpha is optional\n alpha=alpha_new(alpha,MaxGeneration);\n\n% Evaluate new solutions (for all n fireflies)\nfor i=1:n,\n zn(i)=fhandle(ns(i,:));\n Lightn(i)=zn(i);\nend\n\n% Ranking fireflies by their light intensity/objectives\n[Lightn,Index]=sort(zn);\nns_tmp=ns;\nfor i=1:n,\n ns(i,:)=ns_tmp(Index(i),:);\nend\n\n%% Find the current best\nnso=ns; Lighto=Lightn;\nnbest=ns(1,:); Lightbest=Lightn(1);\n\n% For output only\nfbest=Lightbest;\n\n% Move all fireflies to the better locations\n[ns]=ffa_move(n,d,ns,Lightn,nso,Lighto,nbest,...\n Lightbest,alpha,betamin,gamma,Lb,Ub);\n\nend %%%%% end of iterations\n\n% -------------------------------------------------------\n% ----- All the subfunctions are listed here ------------\n% The initial locations of n fireflies\nfunction [ns,Lightn]=init_ffa(n,d,Lb,Ub,u0)\n % if there are bounds/limits,\nif length(Lb)>0,\n for i=1:n,\n ns(i,:)=Lb+(Ub-Lb).*rand(1,d);\n end\nelse\n % generate solutions around the random guess\n for i=1:n,\n ns(i,:)=u0+randn(1,d);\n end\nend\n\n% initial value before function evaluations\nLightn=ones(n,1)*10^100;\n\n% Move all fireflies toward brighter ones\nfunction [ns]=ffa_move(n,d,ns,Lightn,nso,Lighto,...\n nbest,Lightbest,alpha,betamin,gamma,Lb,Ub)\n% Scaling of the system\nscale=abs(Ub-Lb);\n\n% Updating fireflies\nfor i=1:n,\n% The attractiveness parameter beta=exp(-gamma*r)\n for j=1:n,\n r=sqrt(sum((ns(i,:)-ns(j,:)).^2));\n % Update moves\nif Lightn(i)>Lighto(j), % Brighter and more attractive\n beta0=1; beta=(beta0-betamin)*exp(-gamma*r.^2)+betamin;\n tmpf=alpha.*(rand(1,d)-0.5).*scale;\n ns(i,:)=ns(i,:).*(1-beta)+nso(j,:).*beta+tmpf;\n end\n end % end for j\n\nend % end for i\n\n% Check if the updated solutions/locations are within limits\n[ns]=findlimits(n,ns,Lb,Ub);\n\n% This function is optional, as it is not in the original FA\n% The idea to reduce randomness is to increase the convergence,\n% however, if you reduce randomness too quickly, then premature\n% convergence can occur. So use with care.\nfunction alpha=alpha_new(alpha,NGen)\n% alpha_n=alpha_0(1-delta)^NGen=10^(-4);\n% alpha_0=0.9\ndelta=1-(10^(-4)/0.9)^(1/NGen);\nalpha=(1-delta)*alpha;\n\n% Make sure the fireflies are within the bounds/limits\nfunction [ns]=findlimits(n,ns,Lb,Ub)\nfor i=1:n,\n % Apply the lower bound\n ns_tmp=ns(i,:);\n I=ns_tmpUb;\n ns_tmp(J)=Ub(J);\n % Update this new move\n ns(i,:)=ns_tmp;\nend\n\n%% ==== End of Firefly Algorithm implementation ======\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/29693-firefly-algorithm/fa_ndim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7445183952022536}} {"text": "% Fig. 8.19 Feedback Control of Dynamic Systems, 5e \n% Franklin, Powell, Emami\n%\n\nclear all;\nclose all;\n\nnumGs=1;\ndenGs=[1 0 0]; % s^2\n\nnumDs=.81*[1 .2];\ndenDs=[1 2];\n\nnumC=conv(numGs,numDs);\ndenC=conv(denGs,denDs);\n\n[numCL,denCL]=feedback(numC,denC,1,1);\ndamp(denCL)\n\ntf=30;\nt=0:.2:tf;\ny=step(numCL,denCL,t);\n\naxis([0 30 0 1.5])\nplot(t,y),grid\nhold on\n\n% discrete designs\n\nT=1;\n[numGz,denGz]=c2dm(numGs,denGs,T,'zoh');\n\nnumDz1=[.389 -.319];\ndenDz1=[1 -.135];\n\nnumDz2=.374*[1 -.85];\ndenDz2=[1 0];\n\nnumz1=conv(numGz,numDz1);\ndenz1=conv(denGz,denDz1);\n\nnumz2=conv(numGz,numDz2);\ndenz2=conv(denGz,denDz2);\n\n[numCLz1,denCLz1]=feedback(numz1,denz1,1,1);\n[numCLz2,denCLz2]=feedback(numz2,denz2,1,1);\n\nddamp(denCLz1,T)\nddamp(denCLz2,T)\n\nN=tf/T+1;\ntd=0:1:tf;\nyd1=dstep(numCLz1,denCLz1,N);\nyd2=dstep(numCLz2,denCLz2,N);\nplot(td,yd1,'-',td,yd1,'*')\nplot(td,yd2,'-',td,yd2,'o')\ntext(10,.55,'----------- continuous design')\ntext(10,.75,'*----*----* discrete equivalent design')\ntext(10,.65,'o----o----o discrete design')\ntitle('Fig. 8.19 Step responses of the various design methods')\nxlabel('Time (sec)')\nylabel('Plant output')\nhold off\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig8_19.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002491, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7445183875232072}} {"text": "function a = laguerre ( n )\n\n%*****************************************************************************80\n%\n%% LAGUERRE returns the LAGUERRE matrix.\n%\n% Example:\n%\n% N = 8\n%\n% 1 . . . . . . .\n% 1 -1 . . . . . .\n% 2 -4 1 . . . . . / 2\n% 6 -18 9 -1 . . . . / 6\n% 24 -96 72 -16 1 . . . / 24\n% 120 -600 600 -200 25 -1 . . / 120\n% 720 -4320 5400 -2400 450 -36 1 . / 720\n% 5040 -35280 52920 -29400 7350 -882 49 -1 / 5040\n%\n% Properties:\n%\n% A is generally not symmetric: A' /= A.\n%\n% A is lower triangular.\n%\n% The columns of A alternate in sign.\n%\n% A(I,1) = 1\n% A(I,I) = (-1)^(I-1) / (I-1)!.\n%\n% LAMBDA(I) = (-1)^(I-1) / (I-1)!.\n%\n% det ( A ) = product ( 1 <= I <= N ) (-1)^(I-1) / (I-1)!\n%\n% The I-th row contains the coefficients of the Laguerre\n% polynomial of degree I-1.\n%\n% The family of matrices is nested as a function of N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz, Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n if ( n <= 0 )\n a = [];\n return\n end\n\n a(1,1) = 1.0;\n\n if ( n == 1 )\n return\n end\n\n a(2,1) = 1.0;\n a(2,2) = -1.0;\n\n if ( n == 2 )\n return\n end\n\n for i = 3 : n\n for j = 1 : n\n if ( j == 1 )\n a(i,j) = ( ( 2 * i - 3 ) * a(i-1,j) ...\n + ( - i + 2 ) * a(i-2,j) ) ...\n / ( i - 1 );\n else\n a(i,j) = ( ( 2 * i - 3 ) * a(i-1,j) ...\n - ( 1 ) * a(i-1,j-1) ...\n + ( - i + 2 ) * a(i-2,j) ) ...\n / ( i - 1 );\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/laguerre.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.8267118026095991, "lm_q1q2_score": 0.7444785939573009}} {"text": "% function thetaOpt = StochasticGradientDescent (gradFunc, theta0, maxiter)\n% runs gradient descent until convergence, returning the optimal parameters thetaOpt.\n%\n% Inputs:\n% gradFunc function handle to a function [cost, grad] = gradFunc(theta, i)\n% that computes the LR cost / objective function and the gradient \n% of the negative log likelihood of the ith data instance, given \n% parameters theta.\n% theta0 initial value of theta to start gradient descent from.\n% maxIter number of iterations to run SGD for.\n%\n% Output:\n% thetaOpt optimal value of theta.\n%\n%\n% Note - function handles may be new to some of you. Briefly, function handles\n% are a way of passing a function to another function as an argument. The\n% syntax for calling a function handle is exactly the same as for calling any\n% other function. \n%\n% For more information, refer to the official documentation:\n% Matlab - http://www.mathworks.com/help/techdoc/matlab_prog/f2-38133.html\n% Octave - http://www.gnu.org/software/octave/doc/interpreter/Function-Handles.html\n%\n% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n\n\nfunction thetaOpt = StochasticGradientDescent (gradFunc, theta0, maxIter)\n\n % The grader will accept all answers that are near enough\n % to the optimal value, so don't worry about being off by one \n % iteration etc.\n \n thetaOpt = zeros(size(theta0));\n\n %%%%%%%%%%%%%%\n %%% Student code\n for i = 1:maxIter\n\t [cost, grad] = gradFunc(theta0,i);\n\t theta0 = theta0 - (0.1)*(grad)/(1+sqrt(i));\n end\n thetaOpt = theta0;\n %%%%%%%%%%%\n\nend\n\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/7.CRF Learning for OCR/StochasticGradientDescent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7444785829921166}} {"text": "function z = mutInfo(x, y)\n% Compute mutual information I(x,y) of two discrete variables x and y.\n% Input:\n% x, y: two integer vector of the same length \n% Output:\n% z: mutual information z=I(x,y)\n% Written by Mo Chen (sth4nth@gmail.com).\nassert(numel(x) == numel(y));\nn = numel(x);\nx = reshape(x,1,n);\ny = reshape(y,1,n);\n\nl = min(min(x),min(y));\nx = x-l+1;\ny = y-l+1;\nk = max(max(x),max(y));\n\nidx = 1:n;\nMx = sparse(idx,x,1,n,k,n);\nMy = sparse(idx,y,1,n,k,n);\nPxy = nonzeros(Mx'*My/n); %joint distribution of x and y\nHxy = -dot(Pxy,log2(Pxy));\n\nPx = nonzeros(mean(Mx,1));\nPy = nonzeros(mean(My,1));\n\n% entropy of Py and Px\nHx = -dot(Px,log2(Px));\nHy = -dot(Py,log2(Py));\n% mutual information\nz = Hx+Hy-Hxy;\nz = max(0,z);", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter01/mutInfo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422213778251, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7444233239986211}} {"text": "clear; clc;\n\n%% DFT filter bank\nN = 8; % number of subbands\nK = 16; % overlapping factor\nL = 2*K*N; % length of analysis filters\n\nhopt = fir1(L-1,1/N); % prototype filter\n[H,F] = make_bank_DFT(hopt,N);\nH = sqrt(N)*H; % analysis section\nF = sqrt(N)*F; % synthesis section\n\n%% signals in the DFT filter bank\nxn = sin(2*pi*0.01*(0:1000));\nITER = length(xn);\nyn = zeros(ITER,1);\nx = zeros(length(H),1);\nb = zeros(length(F),1);\n\n%% analysis and synthesis filter banks implementation\nfor n = 1:ITER\n x = [xn(n); x(1:end-1)];\n % block transformation is performed once for every N input samples\n if mod(n,N) == 0\n x_D = H.'*x;\n % =====================\n % insert subband processing here\n % =====================\n b = F*x_D + b;\n end\n yn(n) = real(b(1));\n b = [b(2:end); 0];\nend\n\n%% plot input and output signal\nfigure;\nplot(0:length(xn)-1, xn); hold on;\nplot(0:length(yn)-1, yn, 'r:');\nxlabel('Time index, n'); ylabel('Amplitude');\n\n\n%{\n %% plot frequency response\nDFTpoint = 4096;\n[Hz,w] = FreqResp(H, DFTpoint); \nHz = Hz.';\nfigure;\nsubplot(3,1,[1 2]); hold on;\nfor k = 1:N\n if mod(k,2) == 0\n plot(w/pi,20*log10(abs(Hz(k,:))));\n else\n plot(w/pi,20*log10(abs(Hz(k,:))),':');\n end\nend\ntitle('frequency response'); \n%}\n", "meta": {"author": "CharlesThaCat", "repo": "acoustic-interference-cancellation", "sha": "edb394499ea6f9c96445a3e9613bd64a854c289e", "save_path": "github-repos/MATLAB/CharlesThaCat-acoustic-interference-cancellation", "path": "github-repos/MATLAB/CharlesThaCat-acoustic-interference-cancellation/acoustic-interference-cancellation-edb394499ea6f9c96445a3e9613bd64a854c289e/Subband processing/Book/After reading Chapter 2 -- Design Analysis & Synthesis Filter bank/DFTFilterBank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7444088814560544}} {"text": "%% runCoordinateDescent.m\n\n% This test file implements the Coordinate Descent solver. The code builds\n% a synthetic formulation of the Phase Retrieval problem, b = |Ax| and\n% computes an estimate to x. The code finally plots a convergence curve\n% and also makes a scatter plot of the true vs recovered solution.\n\n% PAPER TITLE:\n% Coordinate Descent Algorithms for Phase Retrieval\n\n% ARXIV LINK:\n% https://arxiv.org/abs/1706.03474\n\n\n% 1) Each test script starts out by defining the length of the unknown\n% signal, n and the number of measurements, m. These mesurements can be\n% made complex by setting the isComplex flag to be true.\n%\n% 2) We then build the test problem by invoking the function\n% 'buildTestProblem' which generates random gaussian measurements according\n% to the user's choices in step(1). The function returns the measurement \n% matrix 'A', the true signal 'xt' and the measurements 'b0'.\n%\n% 3) We set the options for the PR solver. For example, the maximum\n% number of iterations, the tolerance value, the algorithm and initializer\n% of choice. These options are controlled by setting the corresponding\n% entries in the 'opts' struct. Please see the user guide for a complete \n% list of options.\n%\n% 4) We solve the phase retrieval problem by running the following line \n% of code:\n% >> [x, outs, opts] = solvePhaseRetrieval(A, A', b0, n, opts)\n% This solves the problem using the algorithm and initialization scheme\n% specified by the user in the struct 'opts'.\n%\n% 5) Determine the optimal phase rotation so that the recovered solution\n% matches the true solution as well as possible.\n%\n% 6) Report the relative reconstruction error. Plot residuals (a measure\n% of error) against the number of iterations and plot the real part of the \n% recovered signal against the real part of the original signal.\n\n\n% PhasePack by Rohan Chandra, Ziyuan Zhong, Justin Hontz, Val McCulloch,\n% Christoph Studer, & Tom Goldstein \n% Copyright (c) University of Maryland, 2017\n%% -----------------------------START----------------------------------\n\n\nclc\nclear\nclose all\n\nn = 100; % Dimension of unknown vector\nm = 8 * n; % Number of measurements\nisComplex = true; % If the signal and measurements are complex\n\n%% Build a random test problem\nfprintf('Building test problem...\\n');\n[A, xt, b0] = buildTestProblem(m, n, isComplex);\n\n% Options\nopts = struct;\nopts.initMethod = 'Truncatedspectral';\n% opts.initMethod = 'optimalspectral';\nopts.algorithm = 'CoordinateDescent';\nopts.isComplex = isComplex;\nopts.maxIters = 500000;\nopts.tol = 1e-6;\nopts.verbose = 2;\n\n\n%% Try to recover x\nfprintf('Running algorithm...\\n');\n[x, outs, opts] = solvePhaseRetrieval(A, A', b0, n, opts);\n\n%% Determine the optimal phase rotation so that the recovered solution\n% matches the true solution as well as possible. \nalpha = (x'*xt)/(x'*x);\nx = alpha * x;\n\n%% Determine the relative reconstruction error. If the true signal was \n% recovered, the error should be very small - on the order of the numerical\n% accuracy of the solver.\nreconError = norm(xt-x)/norm(xt);\nfprintf('relative recon error = %d\\n', reconError);\n\n% Plot a graph of error(definition depends on if opts.xt is provided) versus\n% the number of iterations.\nplotErrorConvergence(outs, opts)\n\n% Plot a graph of the recovered signal x against the true signal xt.\nplotRecoveredVSOriginal(x,xt);\n\n\n\n", "meta": {"author": "tomgoldstein", "repo": "phasepack-matlab", "sha": "aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9", "save_path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab", "path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab/phasepack-matlab-aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9/examples/runCoordinateDescent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7444088658128613}} {"text": "function K = covMaterniso(d, hyp, x, z, i)\n\n% Matern covariance function with nu = d/2 and isotropic distance measure. For\n% d=1 the function is also known as the exponential covariance function or the \n% Ornstein-Uhlenbeck covariance in 1d. The covariance function is:\n%\n% k(x^p,x^q) = sf^2 * f( sqrt(d)*r ) * exp(-sqrt(d)*r)\n%\n% with f(t)=1 for d=1, f(t)=1+t for d=3 and f(t)=1+t+t²/3 for d=5.\n% Here r is the distance sqrt((x^p-x^q)'*inv(P)*(x^p-x^q)), P is ell times\n% the unit matrix and sf2 is the signal variance. The hyperparameters are:\n%\n% hyp = [ log(ell)\n% log(sf) ]\n%\n% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2010-09-10.\n%\n% See also COVFUNCTIONS.M.\n\nif nargin<3, K = '2'; return; end % report number of parameters\nif nargin<4, z = []; end % make sure, z exists\nxeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode\n\nell = exp(hyp(1));\nsf2 = exp(2*hyp(2));\nif all(d~=[1,3,5]), error('only 1, 3 and 5 allowed for d'), end % degree\n\nswitch d\n case 1, f = @(t) 1; df = @(t) 1; % df(t) = f(t)-f'(t)\n case 3, f = @(t) 1 + t; df = @(t) t;\n case 5, f = @(t) 1 + t.*(1+t/3); df = @(t) t.*(1+t)/3;\nend\n m = @(t,f) f(t).*exp(-t); dm = @(t,f) df(t).*exp(-t).*t;\n\n% precompute distances\nif dg % vector kxx\n K = zeros(size(x,1),1);\nelse\n if xeqz % symmetric matrix Kxx\n K = sq_dist(sqrt(d)/ell*x');\n else % cross covariances Kxz\n K = sq_dist(sqrt(d)/ell*x',sqrt(d)/ell*z');\n end\nend\n\nif nargin<5 % covariances\n K = sf2*m(sqrt(K),f);\nelse % derivatives\n if i==1\n K = sf2*dm(sqrt(K),f);\n elseif i==2\n K = 2*sf2*m(sqrt(K),f);\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/covMaterniso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7444088621958111}} {"text": "function p = mvnormpdfln(x, m, S, V)\n% MVNORMPDFLN log of multivariate normal density.\n% See MVNORMPDF for argument description.\n\nlog2pi = 1.83787706640935;\n[d, n] = size(x);\nif nargin == 1\n dx = x;\nelseif isempty(m)\n dx = x;\nelse\n % m specified\n sz = size(m);\n if sz(1) ~= d\n error('rows(m) ~= rows(x)')\n end\n nm = sz(2);\n if nm == 1\n dx = x - repmat(m,1,n);\n elseif n == 1\n dx = repmat(x,1,nm) - m;\n elseif nm == n\n dx = x - m;\n else\n error('incompatible number of columns in x and m')\n end\nend\nif nargin < 3\n % unit variance\n p = -0.5*(d*log2pi + col_sum(dx.*dx));\n return\nend\nhave_inv = 0;\nif nargin == 3\n % standard deviation given\n if d == 1\n dx = dx./S;\n p = (-log(S) -0.5*log2pi) - 0.5*(dx.*dx);\n return;\n end\n if S(2,1) ~= 0\n error('S is not upper triangular')\n end\n if any(size(S) ~= [d d])\n error('S is not the right size')\n end\nelse\n if ischar(V)\n if strcmp(V,'inv')\n % inverse stddev given\n iS = S;\n have_inv = 1;\n else\n error('unknown directive')\n end\n elseif ischar(S) \n if strcmp(S,'inv')\n % inverse variance given\n if d == 1\n\tiS = sqrt(V);\n else\n\tiS = chol(V);\n end\n have_inv = 1;\n else\n error('unknown directive')\n end\n else\n % variance given\n if d == 1\n S = sqrt(V);\n else\n S = chol(V);\n end\n end\nend\nif have_inv\n if d == 1\n dx = iS .* dx;\n logdetiS = log(iS);\n else\n dx = iS*dx;\n logdetiS = sum(log(diag(iS)));\n end\nelse\n if d == 1\n dx = dx./S;\n logdetiS = -log(S);\n else\n dx = solve_tril(S',dx);\n %dx = S'\\dx;\n logdetiS = -sum(log(diag(S)));\n end\nend\np = (logdetiS -0.5*d*log2pi) -0.5*col_sum(dx.*dx);\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+lightspeed/mvnormpdfln.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7444088606810343}} {"text": "% Local Regression and Likelihood, Figure 6.1.\n%\n% Derivative (local slope) estimation, for the Old Faithful Geyser Data.\n% The 'deriv' argument specifies derivative estimation,\n% 'deriv',1 First-order derivative.\n% 'deriv',[1 1] Second-order derivative.\n% 'deriv',2 For bivariate fits, partial deriv. wrt second variable.\n% 'deriv',[1 2] Mixed second-order derivative.\n%\n% Density estimation is done on the log-scale. That is, the estimate\n% is of g(x) = log(f(x)), where f(x) is the density.\n%\n% The relation between derivatives is therefore\n% f'(x) = f(x)g'(x) = g'(x)exp(g(x)).\n% To estimate f'(x), we must estimate g(x) and g'(x) (fit1 and fit2 below),\n% evaluate on a grid of points (p1 and p2), and apply the back-transformation.\n%\n% Disclaimer: I don't consider derivative estimation from noisy data\n% to be a well-defined problem. Use at your own risk.\n%\n% Author: Catherine Loader\n%\n% NEED: m argument passed to lfmarg().\n\nload geyser;\nfit1 = locfit(geyser,'alpha',[0.1 0.6],'ll',1,'ur',6);\nfit2 = locfit(geyser,'alpha',[0.1 0.6],'ll',1,'ur',6,'deriv',1);\nz = lfmarg(fit1);\np1 = predict(fit1,z);\np2 = predict(fit2,z);\nfigure('Name','fig6_1: slope estimation: Old faithful data' );\nplot(z{1},p2.*exp(p1));\nxlabel('Eruption Duration (Minutes)');\nylabel('Density Derivative');\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/locfit/Book/fig6_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7444088579912643}} {"text": "function pyramid_exactness ( quad_filename, degree_max )\n\n%*****************************************************************************80\n%\n%% MAIN is the main program for PYRAMID_EXACTNESS.\n%\n% Discussion:\n%\n% This program investigates the polynomial exactness of a quadrature\n% rule for the pyramid.\n%\n% The integration region is:\n% \n% - ( 1 - Z ) <= X <= 1 - Z\n% - ( 1 - Z ) <= Y <= 1 - Z\n% 0 <= Z <= 1.\n%\n% When Z is zero, the integration region is a square lying in the (X,Y) \n% plane, centered at (0,0,0) with \"radius\" 1. As Z increases to 1, the \n% radius of the square diminishes, and when Z reaches 1, the square has \n% contracted to the single point (0,0,1).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 July 2009\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PYRAMID_EXACTNESS\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Investigate the polynomial exactness of\\n' );\n fprintf ( 1, ' a quadrature rule for the pyramid.\\n' );\n%\n% Get the quadrature file root name:\n%\n if ( 1 <= nargin )\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PYRAMID_EXACTNESS:\\n' );\n\n quad_filename = input ( ' Enter the \"root\" name of the quadrature files.' );\n\n end\n%\n% Create the names of:\n% the quadrature X file;\n% the quadrature W file;\n%\n quad_x_filename = strcat ( quad_filename, '_x.txt' );\n quad_w_filename = strcat ( quad_filename, '_w.txt' );\n%\n% The second command line argument is the maximum degree.\n%\n if ( 2 <= nargin )\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PYRAMID_EXACTNESS:\\n' );\n\n degree_max = input ( ' Please enter the maximum total degree to check.' );\n\n end\n%\n% Summarize the input.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PYRAMID_EXACTNESS: User input:\\n' );\n fprintf ( 1, ' Quadrature rule X file = \"%s\".\\n', quad_x_filename );\n fprintf ( 1, ' Quadrature rule W file = \"%s\".\\n', quad_w_filename );\n fprintf ( 1, ' Maximum total degree to check = %d', degree_max );\n%\n% Read the X file.\n%\n [ dim_num, order ] = r8mat_header_read ( quad_x_filename );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension = %d\\n', dim_num );\n fprintf ( 1, ' Number of points = %d\\n', order );\n\n if ( dim_num ~= 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PYRAMID_EXACTNESS - Fatal error!\\n' );\n fprintf ( 1, ' The quadrature abscissas must be 3 dimensional.\\n' );\n error ( 'PYRAMID_EXACTNESS - Fatal error!' );\n end\n\n x = r8mat_data_read ( quad_x_filename, dim_num, order );\n%\n% Read the W file.\n%\n [ dim_num2, order2 ] = r8mat_header_read ( quad_w_filename );\n\n if ( dim_num2 ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PYRAMID_EXACTNESS - Fatal error!\\n' );\n fprintf ( 1, ' The quadrature weight file should have exactly\\n');\n fprintf ( 1, ' one value on each line.\\n' );\n error ( 'PYRAMID_EXACTNESS - Fatal error!' );\n end\n\n if ( order2 ~= order )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PYRAMID_EXACTNESS - Fatal error!\\n' );\n fprintf ( 1, ' The quadrature weight file should have exactly\\n' );\n fprintf ( 1, ' the same number of lines as the abscissa file.\\n' );\n error ( 'PYRAMID_EXACTNESS - Fatal error!' );\n end\n\n w = r8mat_data_read ( quad_w_filename, 1, order );\n%\n% Explore the monomials.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Error Degree Exponents\\n' );\n fprintf ( 1, '\\n' );\n\n for degree = 0 : degree_max\n\n expon = [];\n more = 0;\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ expon, more, h, t ] = comp_next ( degree, dim_num, expon, more, h, t );\n\n v = monomial_value ( dim_num, order, expon, x );\n\n quad = pyra_unit_volume ( ) * w(1:order) * v(1:order)';\n\n exact = pyra_unit_monomial ( expon );\n\n quad_error = abs ( quad - exact );\n\n fprintf ( 1, ' %24.16f %2d ', quad_error, degree );\n for dim = 1 : dim_num\n fprintf ( 1, '%3d', expon(dim) );\n end\n fprintf ( 1, '\\n' );\n\n if ( ~more )\n break\n end\n\n end\n\n fprintf ( 1, '\\n' );\n\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PYRAMID_EXACTNESS:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\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 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% There are 28 compositions of 6 into three parts. This routine will\n% produce those compositions in the following order:\n%\n% I A\n% - ---------\n% 1 6 0 0\n% 2 5 1 0\n% 3 4 2 0\n% 4 3 3 0\n% 5 2 4 0\n% 6 1 5 0\n% 7 0 6 0\n% 8 5 0 1\n% 9 4 1 1\n% 10 3 2 1\n% 11 2 3 1\n% 12 1 4 1\n% 13 0 5 1\n% 14 4 0 2\n% 15 3 1 2\n% 16 2 2 2\n% 17 1 3 2\n% 18 0 4 2\n% 19 3 0 3\n% 20 2 1 3\n% 21 1 2 3\n% 22 0 3 3\n% 23 2 0 4\n% 24 1 1 4\n% 25 0 2 4\n% 26 1 0 5\n% 27 0 1 5\n% 28 0 0 6\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 02 July 2008\n%\n% Author:\n%\n% FORTRAN77 original 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 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 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 value = monomial_value ( dim_num, point_num, expon, x )\n\n%*****************************************************************************80\n%\n%% MONOMIAL_VALUE evaluates a monomial.\n%\n% Discussion:\n%\n% This routine evaluates a monomial of the form\n%\n% product ( 1 <= dim <= dim_num ) x(dim)^expon(dim)\n%\n% where the exponents are nonnegative integers. Note that\n% if the combination 0^0 is encountered, it should be treated\n% as 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 May 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer POINT_NUM, the number of points at which the\n% monomial is to be evaluated.\n%\n% Input, integer EXPON(DIM_NUM), the exponents.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the point coordinates.\n%\n% Output, real VALUE(POINT_NUM), the value of the monomial.\n%\n value(1:point_num) = 1.0;\n\n for dim = 1 : dim_num\n if ( 0 ~= expon(dim) )\n value(1:point_num) = value(1:point_num) .* x(dim,1:point_num).^expon(dim);\n end\n end\n\n return\nend\nfunction value = pyra_unit_monomial ( expon )\n\n%*****************************************************************************80\n%\n%% PYRA_UNIT_MONOMIAL: monomial integral in a unit pyramid.\n%\n% Discussion:\n%\n% This routine returns the integral of\n%\n% product ( 1 <= I <= 3 ) X(I)^EXPON(I)\n%\n% over the unit pyramid.\n%\n% The unit pyramid is defined as:\n%\n% - ( 1 - Z ) <= X <= 1 - Z\n% - ( 1 - Z ) <= Y <= 1 - Z\n% 0 <= Z <= 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 April 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Arthur Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971,\n% ISBN: 0130438936,\n% LC: QA311.S85.\n%\n% Parameters:\n%\n% Input, integer EXPON(3), the exponents.\n%\n% Output, real VALUE, the integral of the monomial.\n%\n value = 0.0;\n\n if ( mod ( expon(1), 2 ) == 0 && mod ( expon(2), 2 ) == 0 )\n\n i_hi = 2 + expon(1) + expon(2);\n\n for i = 0 : i_hi\n value = value + r8_mop ( i ) * r8_choose ( i_hi, i ) / ( i + expon(3) + 1 );\n end\n\n value = value * 2.0 / ( expon(1) + 1 ) * 2.0 / ( expon(2) + 1 );\n\n end\n\n return\nend\nfunction value = pyra_unit_volume ( )\n\n%*****************************************************************************80\n%\n%% PYRA_UNIT_VOLUME_3D returns the volume of a unit pyramid.\n%\n% Discussion:\n%\n% A pyramid with square base can be regarded as the upper half of a\n% 3D octahedron.\n%\n% The integration region:\n%\n% - ( 1 - Z ) <= X <= 1 - Z\n% - ( 1 - Z ) <= Y <= 1 - Z\n% 0 <= Z <= 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 31 March 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real VALUE, the volume of the pyramid.\n%\n value = 4.0 / 3.0;\n\n return\nend\nfunction value = r8_choose ( n, k )\n\n%*****************************************************************************80\n%\n%% R8_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% 31 March\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, real 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 value = 0;\n elseif ( mn == 0 )\n value = 1;\n else\n mx = max ( k, n - k );\n value = mx + 1;\n for i = 2 : mn\n value = ( value * ( mx + i ) ) / i;\n end\n end\n\n return\nend\nfunction value = r8_mop ( i )\n\n%*****************************************************************************80\n%\n%% R8_MOP returns the I-th power of -1 as an R8 value.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 07 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, the power of -1.\n%\n% Output, real R8_MOP, the I-th power of -1.\n%\n if ( mod ( i, 2 ) == 0 )\n value = + 1.0;\n else\n value = - 1.0;\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% Discussion:\n%\n% An R8MAT is an array of R8's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 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% Discussion:\n%\n% An R8MAT is an array of R8's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 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 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% 19 April 2009\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/pyramid_exactness/pyramid_exactness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802373309982, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7444088519781924}} {"text": "function y = gaussian_response(rect_size, sigma)\n%GAUSSIAN_RESPONSE create the (fixed) target response of the correlation filter response\n [i1, i2] = circ_grid(rect_size(1), rect_size(2));\n y = exp(-(i1.^2 + i2.^2) / (2 * sigma^2));\nend\n", "meta": {"author": "bertinetto", "repo": "cfnet", "sha": "971e7922b7f0f9140e0d995b598e8d97dece277c", "save_path": "github-repos/MATLAB/bertinetto-cfnet", "path": "github-repos/MATLAB/bertinetto-cfnet/cfnet-971e7922b7f0f9140e0d995b598e8d97dece277c/src/util/gaussian_response.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9643214450208031, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.744305227044141}} {"text": "function loglik = RicianLogLik(meas, signals, sig)\n% Computes the log likelihood of the measurements given the model signals\n% for the Rician noise model.\n%\n% loglik = RicianLogLik(meas, signals, sig) returns the likelihood of\n% measuring meas given the signals and the noise standard deviation sig. \n%\n% meas are the measurements\n%\n% signals are computed from a model\n%\n% sig is the standard deviation of the Gaussian distributions underlying\n% the Rician distribution.\n%\n% author: Daniel C Alexander (d.alexander@ucl.ac.uk)\n%\n\nsumsqsc = (signals.^2 + meas.^2)./(2*sig.^2);\nscp = meas.*signals./(sig.^2);\nlb0 = logbesseli0(scp);\nlogliks = - 2*log(sig) - sumsqsc + log(signals) + lb0;\nloglik = sum(logliks);\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/RicianLogLik.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7442719027502049}} {"text": "function N = nees(x,m,P)\n\n% NEES Normalized Estimation Error Squared.\n% N = NEES(X,M,P) computes the Normalized Estimation Error Squared given\n% true state X and a Gaussian estimate of mean M and covariance P:\n%\n% NEES = (X-M)'*inv(P)*(X-M);\n%\n% See also MAHALANOBIS.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nN = (x-m)'/P*(x-m);\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/nees.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.7442718960355666}} {"text": "% Figure 10.11 Feedback Control of Dynamic Systems, 6e\n% Franklin, Powell, Emami\n%\n% fig10_11.m is a script to generate Fig. 10.11 \n% the frequency response of the notch network\nclf;\nnnotch=[1/.81 0 1] ;\ndnotch=[1/625 2/25 1];\n% define frequency range\nw=logspace(-1,1);\nw(36)=1;\nsubplot(211)\nw=logspace(-1,1);\nw(24)=0.89;\n% compute Bode\n[magn phn]=bode(nnotch,dnotch,w);\n% phn=php-360*ones(phn);\nmagn1=[magn, ones(size(magn))];\nsubplot(211); loglog(w,magn1); grid;\nxlabel('\\omega (rad/sec)');\nylabel('Magnitude');\ntitle('Fig. 10.11 Bode plot of a notch filter')\nsubplot(212); semilogx(w,phn); grid;\nxlabel('\\omega (rad/sec)');\nylabel('Phase (deg)');\n%Bode grid\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/fig10_11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.7442160149889179}} {"text": "function fd1d_heat_explicit_test03 ( )\n\n%*****************************************************************************80\n%\n%% FD1D_HEAT_EXPLICIT_TEST03 does a simple test problem.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 30 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD1D_HEAT_EXPLICIT_TEST03:\\n' );\n fprintf ( 1, ' Compute an approximate solution to the time-dependent\\n' );\n fprintf ( 1, ' one dimensional heat equation:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' dH/dt - K * d2H/dx2 = f(x,t)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Run a simple test case.\\n' );\n%\n% Heat coefficient.\n%\n k = k_test03 ( );\n%\n% X_NUM is the number of equally spaced nodes to use between 0 and 1.\n%\n x_num = 21;\n x_min = -5.0;\n x_max = +5.0;\n dx = ( x_max - x_min ) / ( x_num - 1 );\n x = linspace ( x_min, x_max, x_num );\n%\n% T_NUM is the number of equally spaced time points between 0 and 10.0.\n%\n t_num = 81;\n t_min = 0.0;\n t_max = 4.0;\n dt = ( t_max - t_min ) / ( t_num - 1 );\n t = linspace ( t_min, t_max, t_num );\n%\n% Get the CFL coefficient.\n%\n cfl = fd1d_heat_explicit_cfl ( k, t_num, t_min, t_max, x_num, x_min, x_max );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of X nodes = %d\\n', x_num );\n fprintf ( 1, ' X interval is [%f,%f]\\n', x_min, x_max );\n fprintf ( 1, ' X spacing is %f\\n', dx );\n fprintf ( 1, ' Number of T values = %d\\n', t_num );\n fprintf ( 1, ' T interval is [%f,%f]\\n', t_min, t_max );\n fprintf ( 1, ' T spacing is %f\\n', dt );\n fprintf ( 1, ' Constant K = %g\\n', k );\n fprintf ( 1, ' CFL coefficient = %g\\n', cfl );\n%\n% Running the code produces an array H of temperatures H(t,x),\n% and vectors x and t.\n%\n\n hmat = zeros ( x_num, t_num );\n\n for j = 1 : t_num\n if ( j == 1 )\n h = ic_test03 ( x_num, x, t(j) );\n h = bc_test03 ( x_num, x, t(j), h );\n else\n h = fd1d_heat_explicit ( x_num, x, t(j-1), dt, cfl, @rhs_test03, @bc_test03, h );\n end\n hmat(1:x_num,j) = h(1:x_num);\n end\n%\n% Plot the data.\n%\n figure ( 3 )\n [ tmat, xmat ] = meshgrid ( t, x );\n mesh ( tmat, xmat, hmat );\n title ( 'H(X,T) for TEST03 computed by FD1D\\_HEAT\\_EXPLICIT' );\n xlabel ( '<-- Time -->' );\n ylabel ( '<-- X -->' );\n zlabel ( '<-- H(X,T) -->' );\n%\n% Write the data to files.\n%\n r8mat_write ( 'h_test03.txt', x_num, t_num, hmat );\n r8vec_write ( 't_test03.txt', t_num, t );\n r8vec_write ( 'x_test03.txt', x_num, x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' H(X,T) written to \"h_test03.txt\"\\n' );\n fprintf ( 1, ' T values written to \"t_test03.txt\"\\n' );\n fprintf ( 1, ' X values written to \"x_test3.txt\"\\n' );\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fd1d_heat_explicit/fd1d_heat_explicit_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7442069362256801}} {"text": "function krn = spm_smoothkern(fwhm,x,t)\n% Generate a Gaussian smoothing kernel\n% FORMAT krn = spm_smoothkern(fwhm,x,t)\n% fwhm - full width at half maximum\n% x - position\n% t - either 0 (nearest neighbour) or 1 (linear).\n% [Default: 1]\n%\n% krn - value of kernel at position x\n%__________________________________________________________________________\n%\n% For smoothing images, one should really convolve a Gaussian with a sinc\n% function. For smoothing histograms, the kernel should be a Gaussian\n% convolved with the histogram basis function used. This function returns\n% a Gaussian convolved with a triangular (1st degree B-spline) basis \n% function (by default). A Gaussian convolved with a hat function (0th \n% degree B-spline) can also be returned.\n%\n% Note that the convolution kernel returned by this function differ from\n% the ones that other packages currently use for Gaussian smoothing -\n% particularly when the FWHM is small compared with the voxel dimensions.\n% The fact that SPM does it differently from other software does not mean\n% that it is wrong.\n%__________________________________________________________________________\n% Copyright (C) 2005-2011 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_smoothkern.m 7460 2018-10-29 15:55:12Z john $\n\n\nif nargin<3, t = 1; end\n\n% Variance from FWHM\ns = (fwhm/sqrt(8*log(2)))^2+eps;\n\n% The simple way to do it. Not good for small FWHM\n% krn = (1/sqrt(2*pi*s))*exp(-(x.^2)/(2*s));\n\nif t==0\n % Gaussian convolved with 0th degree B-spline\n % int(exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= -0.5..0.5)\n w1 = 1/sqrt(2*s);\n krn = 0.5*(erf(w1*(x+0.5))-erf(w1*(x-0.5)));\n krn(krn<0) = 0;\n\nelseif t==1\n % Gaussian convolved with 1st degree B-spline\n % int((1-t)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= 0..1)\n % +int((t+1)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t=-1..0)\n w1 = 0.5*sqrt(2/s);\n w2 = -0.5/s;\n w3 = sqrt(s/2/pi);\n krn = 0.5*(erf(w1*(x+1)).*(x+1) + erf(w1*(x-1)).*(x-1) - 2*erf(w1*x ).* x)...\n +w3*(exp(w2*(x+1).^2) + exp(w2*(x-1).^2) - 2*exp(w2*x.^2));\n krn(krn<0) = 0;\n\nelse\n error('Only defined for nearest neighbour and linear interpolation.');\n % This should probably be based on https://arxiv.org/pdf/1608.05854.pdf:\n % Martin TB, Prunet S, Drissen L. Optimal fitting of Gaussian-apodized\n % or under-resolved emission lines in Fourier transform spectra\n % providing new insights on the velocity structure of NGC 6720. Monthly\n % Notices of the Royal Astronomical Society. 2016 Sep 14;463(4):4223-38.\n % (thanks for the pointer Guillaume).\nend\n\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_smoothkern.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7441955015327942}} {"text": "% rouwenhorst approximates and AR(1) process with a Markov chain\n% \n% ::\n% \n% [Thetai,y]=rouwenhorst(mu,rho,sigma)\n% [Thetai,y]=rouwenhorst(mu,rho,sigma,N)\n% [Thetai,y]=rouwenhorst(mu,rho,sigma,N,p)\n% [Thetai,y]=rouwenhorst(mu,rho,sigma,N,p,q)\n% \n% Args:\n% \n% mu (numeric): unconditonal mean of the ar(1) process\n% rho [numeric): autoregressive coefficient\n% sigma (numeric): standard deviation of the shock\n% N (numeric | {2}): number of states of the markov chain\n% p (numeric | {.5*(1+rho)}): first parameter of the procedure\n% q (numeric | {.5*(1+rho)}): second parameter of the procedure\n% \n% Returns:\n% :\n% \n% - **Thetai** [numeric] : NxN transition matrix\n% - **y** [numeric] : vector of nodes or states\n% \n% Note:\n% \n% - The process is assumed to be of the form\n% x_t-mu=rho*(x_{t-1}-mu)+sigma*error_term where error_term ~ N(0,1)\n% \n% Reference:\n% \n% - Karen A. Kopecky, Richard M. H. Suen (2010): \"Finite state\n% Markov-chain approximations to highly persistent processes\". Review of\n% Economic Dynamics 13, pp 701-714\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/+ar1_approximation/rouwenhorst.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7441954980320372}} {"text": "% SOSDEMO4 --- Matrix Copositivity\n% Section 3.4 of SOSTOOLS User's Manual\n% \n\nclear; echo on;\nsyms x1 x2 x3 x4 x5;\nvartable = [x1; x2; x3; x4; x5];\n\n% The matrix under consideration\nJ = [1 -1 1 1 -1;\n -1 1 -1 1 1;\n 1 -1 1 -1 1;\n 1 1 -1 1 -1;\n -1 1 1 -1 1];\n\n% =============================================\n% First, initialize the sum of squares program\n\nprog = sosprogram(vartable); % No decision variables.\n\n% =============================================\n% Next, define SOSP constraints\n\n% Constraint : r(x)*J(x) - p(x) = 0\nJ = [x1^2 x2^2 x3^2 x4^2 x5^2]*J*[x1^2; x2^2; x3^2; x4^2; x5^2];\nr = x1^2 + x2^2 + x3^2 + x4^2 + x5^2;\n\nprog = sosineq(prog,r*J);\n\n% =============================================\n% And call solver\nprog = sossolve(prog);\n\n% =============================================\n% Program is feasible. The matrix J is copositive.\n\necho off\n\n\n\n\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/SOSTOOLS.300/SOSTOOLS.300/demos/sosdemo4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7441954886424936}} {"text": "function fx = edcheb ( x, coef, npl )\n\n%*****************************************************************************80\n%\n%% EDCHEB evaluates the derivative of a Chebyshev series at a point.\n%\n% Discussion:\n%\n% This routine evaluates the derivative of a Chebyshev series \n% at a point in [-1,+1].\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 ( kind = 8 ) X, the evaluation point.\n% -1 <= X <= +1.\n%\n% Input, real ( kind = 8 ) COEF(NPL), the Chebyshev series.\n%\n% Input, integer ( kind = 4 ) NPL, the number of terms in the \n% Chebyshev series.\n%\n xjp2 = 0.0;\n xjpl = 0.0;\n bjp2 = 0.0;\n bjpl = 0.0;\n n = npl - 1;\n\n for k = 1 : n\n j = npl - k;\n dj = j;\n xj = 2.0 * coef(j+1) * dj + xjp2;\n bj = 2.0 * x * bjpl - bjp2 + xj;\n bf = bjp2;\n bjp2 = bjpl;\n bjpl = bj;\n xjp2 = xjpl;\n xjpl = xj;\n end\n\n fx = 0.5 * ( bj - bf );\n\n return\nend\n", "meta": {"author": "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/edcheb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7441344573439863}} {"text": "function backtrack_binary_rc_test01 ( )\n\n%*****************************************************************************80\n%\n%% BACKTRACK_BINARY_RC_TEST01 seeks binary powers that have a given sum.\n%\n% Discussion:\n%\n% We consider the binary powers 1, 2, 4, ... 2^(n-1).\n%\n% We wish to select some of these powers, so that the sum is equal\n% to a given target value. We are actually simply seeking the binary\n% representation of an integer.\n%\n% A partial solution is acceptable if it is less than the target value.\n%\n% We list the powers in descending order, so that the bactracking\n% procedure makes the most significant choices first, thus quickly\n% eliminating many unsuitable choices.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 December 2013\n%\n% Author:\n%\n% John Burkardt\n%\n n = 8;\n test_num = 3;\n targets = [ 73, 299, -3 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BACKTRACK_BINARY_RC_TEST01\\n' );\n fprintf ( 1, ' Use BACKBIN_RC to find the binary expansion of\\n' );\n fprintf ( 1, ' an integer between 0 and 255.\\n' );\n fprintf ( 1, ' The choices are 0/1 for the 8 digits.\\n' );\n\n for test = 1 : test_num\n\n target = targets(test);\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' TARGET = %d\\n', target );\n call_num = 0;\n reject = 0;\n n2 = -1;\n choice = [];\n\n while ( 1 )\n\n [ n2, choice ] = backbin_rc ( n, reject, n2, choice );\n call_num = call_num + 1;\n\n if ( n2 == -1 )\n fprintf ( 1, ' Termination without solution.\\n' );\n break\n end\n%\n% Evaluate the integer determined by the choices.\n%\n factor = 1;\n for i = n : -1 : n2 + 1\n factor = factor * 2;\n end\n\n result = 0;\n for i = 1 : n2\n result = result * 2 + choice(i);\n end\n\n result = result * factor;\n%\n% If the integer is too big, then we reject it, and\n% all the related integers formed by making additional choices.\n%\n reject = ( target < result );\n%\n% If we hit the target, then in this case, we can exit because\n% the solution is unique.\n%\n if ( result == target )\n break\n end\n\n end\n\n fprintf ( 1, ' Number of calls = %d\\n', call_num );\n fprintf ( 1, ' Binary search space = %d\\n', 2 ^ n );\n fprintf ( 1, ' ' );\n for i = 1 : n\n fprintf ( 1, '%2d', choice(i) );\n end\n fprintf ( 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/backtrack_binary_rc/backtrack_binary_rc_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.8774767858797979, "lm_q1q2_score": 0.7440720231510717}} {"text": "function legendre_polynomial_test04 ( )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_POLYNOMIAL_TEST04 tests P_QUADRATURE_RULE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEGENDRE_POLYNOMIAL_TEST04:\\n' );\n fprintf ( 1, ' P_QUADRATURE_RULE computes the quadrature rule\\n' );\n fprintf ( 1, ' associated with P(n,x)\\n' );\n\n n = 5;\n [ x, w ] = p_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 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 = x .^ e;\n end\n q = w' * f;\n q_exact = p_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/legendre_polynomial/legendre_polynomial_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.877476800298183, "lm_q1q2_score": 0.7440720218920914}} {"text": "function test07()\n% function test07()\n%\n% Computes a robust mean of angles\n%\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 % Generate the data\n N = 250;\n theta_true = pi*(2*rand(1)-1);\n thetas = zeros(N,1);\n p_true = .25;\n for i = 1 : N\n if rand(1) < p_true\n thetas(i) = theta_true + .3*randn(1);\n else\n thetas(i) = pi*(2*rand(1)-1);\n end\n end\n X = [cos(thetas') ; sin(thetas)'];\n \n % Pick the manifold\n problem.M = spherefactory(2);\n\n % Parameters\n p = p_true;\n kappa = 3;\n c2 = besseli(0, 2*kappa);\n \n % Define the problem cost function\n problem.cost = @cost;\n function [val store] = cost(x, store)\n \n if ~isfield(store, 'fi')\n store.fi = (p/c2)*exp(2*kappa*X'*x);\n end\n fi = store.fi;\n \n val = -sum(log(fi + (1-p)));\n \n end\n\n % And its gradient\n problem.grad = @grad;\n function [g store] = grad(x, store)\n \n if ~isfield(store, 'fi')\n store.fi = (p/c2)*exp(2*kappa*X'*x);\n end\n fi = store.fi;\n \n g = -X*(2*kappa*(fi./(fi+(1-p))));\n g = g - (x'*g)*x;\n \n end\n \n % Check differentials consistency.\n % checkgradient(problem);\n\n % Solve with trust-regions and FD approximation of the Hessian\n warning('off', 'manopt:getHessian:approx');\n \n % Test many random initial guess\n% best_cost = inf;\n% best_x = [];\n% for i = 1 : 5\n% [x cst] = trustregions(problem);\n% if cst < best_cost\n% best_cost = cst;\n% best_x = x;\n% end\n% end\n% theta_found = angle(best_x(1)+1i*best_x(2));\n\n % Do a histogram of the data and select the initial guess as the peak\n [freqs, bins] = hist(thetas, 30);\n [~, ind] = max(freqs);\n x0 = [cos(bins(ind)) ; sin(bins(ind))];\n x = trustregions(problem, x0);\n theta_found = angle(x(1)+1i*x(2));\n \n fprintf('True theta: %g\\nHist theta: %g\\nFound theta: %g\\n', theta_true, angle(x0(1)+1i*x0(2)), theta_found);\n \n subplot(2,1,1);\n hist(thetas, 30);\n xlim([-pi pi]);\n \n th = linspace(-pi, pi);\n fth = zeros(size(th));\n for i = 1 : length(th)\n fth(i) = cost([cos(th(i));sin(th(i))], struct());\n end\n subplot(2,1,2);\n plot(th, -fth);\n xlim([-pi pi]);\n \n% keyboard;\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/tests/test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7440720214156573}} {"text": "function outputarray = linarray(start,spacing,numpoints)\n% outputarray = linarray(start,spacing,numpoints)\n% \n% The function linarray generates an row vector based on a start value, a\n% spacing, and a number of points. For example: linarray(1,.1,5) returns:\n% [1.0000 1.1000 1.2000 1.3000 1.4000]\n%\n% 3/2/11 (c) James F. Mack\n\noutputarray = [start:spacing:start+(numpoints-1)*spacing];", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/36124-linarray-alternative-to-linspace/linarray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7440720194525628}} {"text": "function [rhsHx, rhsHy, rhsHz, rhsEx, rhsEy, rhsEz] = MaxwellRHS3D(Hx,Hy,Hz,Ex,Ey,Ez)\n\n% function [rhsHx, rhsHy, rhsHz, rhsEx, rhsEy, rhsEz] = MaxwellRHS3D(Hx,Hy,Hz,Ex,Ey,Ez)\n% Purpose : Evaluate RHS flux in 3D Maxwell equations\n\nGlobals3D;\n\n% storage for field differences at faces\ndHx = zeros(Nfp*Nfaces,K); dHy = dHx; dHz = dHx; \ndEx = zeros(Nfp*Nfaces,K); dEy = dEx; dEz = dEx; \n\n% form field differences at faces\ndHx(:) = Hx(vmapP)-Hx(vmapM); dEx(:) = Ex(vmapP)-Ex(vmapM);\t\ndHy(:) = Hy(vmapP)-Hy(vmapM); \tdEy(:) = Ey(vmapP)-Ey(vmapM);\t\ndHz(:) = Hz(vmapP)-Hz(vmapM); dEz(:) = Ez(vmapP)-Ez(vmapM); \n\n% make boundary conditions all reflective (Ez+ = -Ez-)\ndHx(mapB) = 0; dEx(mapB) = -2*Ex(vmapB); \ndHy(mapB) = 0; dEy(mapB) = -2*Ey(vmapB); \ndHz(mapB) = 0; dEz(mapB) = -2*Ez(vmapB);\n\nalpha=1; % => full upwinding\n\nndotdH = nx.*dHx + ny.*dHy + nz.*dHz;\nndotdE = nx.*dEx + ny.*dEy + nz.*dEz;\n\nfluxHx = -ny.*dEz + nz.*dEy + alpha*(dHx - ndotdH.*nx); \nfluxHy = -nz.*dEx + nx.*dEz + alpha*(dHy - ndotdH.*ny); \nfluxHz = -nx.*dEy + ny.*dEx + alpha*(dHz - ndotdH.*nz); \n\nfluxEx = ny.*dHz - nz.*dHy + alpha*(dEx - ndotdE.*nx); \nfluxEy = nz.*dHx - nx.*dHz + alpha*(dEy - ndotdE.*ny); \nfluxEz = nx.*dHy - ny.*dHx + alpha*(dEz - ndotdE.*nz); \n\n% evaluate local spatial derivatives\n[curlHx,curlHy,curlHz] = Curl3D(Hx,Hy,Hz);\n[curlEx,curlEy,curlEz] = Curl3D(Ex,Ey,Ez);\n\n% calculate Maxwell's right hand side\nrhsHx = -curlEx + LIFT*(Fscale.*fluxHx/2);\nrhsHy = -curlEy + LIFT*(Fscale.*fluxHy/2);\nrhsHz = -curlEz + LIFT*(Fscale.*fluxHz/2);\n\nrhsEx = curlHx + LIFT*(Fscale.*fluxEx/2);\nrhsEy = curlHy + LIFT*(Fscale.*fluxEy/2);\nrhsEz = curlHz + LIFT*(Fscale.*fluxEz/2);\nreturn;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes3D/MaxwellRHS3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.744031732240083}} {"text": "function D = EuDist2(fea_a,fea_b,bSqrt)\n% Euclidean Distance matrix\n% D = EuDist(fea_a,fea_b)\n% fea_a: nSample_a * nFeature\n% fea_b: nSample_b * nFeature\n% D: nSample_a * nSample_a\n% or nSample_a * nSample_b\n\n\nif ~exist('bSqrt','var')\n bSqrt = 1;\nend\n\n\nif (~exist('fea_b','var')) | isempty(fea_b)\n [nSmp, nFea] = size(fea_a);\n\n aa = sum(fea_a.*fea_a,2);\n ab = fea_a*fea_a';\n \n aa = full(aa);\n ab = full(ab);\n\n if bSqrt\n D = sqrt(repmat(aa, 1, nSmp) + repmat(aa', nSmp, 1) - 2*ab);\n D = real(D);\n else\n D = repmat(aa, 1, nSmp) + repmat(aa', nSmp, 1) - 2*ab;\n end\n \n D = max(D,D');\n D = D - diag(diag(D));\n D = abs(D);\nelse\n [nSmp_a, nFea] = size(fea_a);\n [nSmp_b, nFea] = size(fea_b);\n \n aa = sum(fea_a.*fea_a,2);\n bb = sum(fea_b.*fea_b,2);\n ab = fea_a*fea_b';\n\n aa = full(aa);\n bb = full(bb);\n ab = full(ab);\n\n if bSqrt\n D = sqrt(repmat(aa, 1, nSmp_b) + repmat(bb', nSmp_a, 1) - 2*ab);\n D = real(D);\n else\n D = repmat(aa, 1, nSmp_b) + repmat(bb', nSmp_a, 1) - 2*ab;\n end\n \n D = abs(D);\nend\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/nmf/LNMF/EuDist2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7439828814677669}} {"text": "function g = p42_g ( n, x )\n\n%*****************************************************************************80\n%\n%% P42_G evaluates the gradient 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% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real G(N), the gradient of the objective function.\n%\n g = zeros ( n, 1 );\n\n g(1) = 2.0 * ( x(1) - x(2) ) / ( 1.0 + ( x(1) - x(2) )^2 )^2;\n\n g(2) = 2.0 * ( x(2) - x(1) ) / ( 1.0 + ( x(1) - x(2) )^2 )^2 ...\n - 0.5 * pi * x(3) * cos ( 0.5 * pi * x(2) * x(3) );\n\n g(3) = - 0.5 * pi * x(2) * cos ( 0.5 * pi * x(2) * x(3) );\n\n if ( x(2) ~= 0.0 )\n\n arg = ( x(1) + 2.0 * x(2) + x(3) ) / x(2);\n term = exp ( - arg^2 );\n\n g(1) = g(1) + 2.0 * term * ( x(1) + 2.0 * x(2) + x(3) ) / x(2)^2;\n g(2) = g(2) - 2.0 * term * ( x(1) + 2.0 * x(2) + x(3) ) ...\n * ( x(1) + x(3) ) / x(2)^3;\n g(3) = g(3) + 2.0 * term * ( x(1) + 2.0 * x(2) + x(3) ) / x(2)^2;\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/p42_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7439167458935372}} {"text": "%% Introduction to *wavelet_layer_2d*\n% *wavelet_layer_2d* is computing the wavelet transform coefficient from \n% the coefficient of the previous layer. It should be applied iteratively\n% to an input signal.\n%\n%% Usage\n% [A, V] = *wavelet_layer_2d*(U, filters, options), documentation is given in\n% \n%\n%% Description\n% It is possible to create some wavelet filters with wavelet_factory_2d for \n% instance. The filters size have to be adapted to the size of the input\n% signal $x$. \nclear; close all; \n\nx = mandrill;\n\n% Create $ U[\\empty]x $\nU{1}.signal{1} = x;\nU{1}.meta.j = zeros(0,1);\nU{1}.meta.q = zeros(0,1);\nU{1}.meta.resolution=0;\nfilters = morlet_filter_bank_2d(size(x));\n\n% A corresponds to the output scattering coefficients, and V to the wavelet\n% coefficients.\n[A, V] = wavelet_layer_2d(U{1}, filters);\n\ncolormap gray\nsubplot(121)\nimagesc(real(V.signal{1}))\naxis off\ntitle('Real part of the first wavelet transform coefficient');\nsubplot(122)\nimagesc(imag(V.signal{1}))\naxis off\ntitle('Imaginary part of the first wavelet transform coefficient');\n\n\n%% Options\n% The options are the same as in *wavelet_2d*.\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/demo/core/demo_wavelet_layer_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7438992337288879}} {"text": "function param = copulaparam(type,tau)\n%COPULAPARAM Copula parameter, given Kendall's rank correlation.\n% RHO = COPULAPARAM('Gaussian',TAU) returns the linear correlation\n% parameter RHO corresponding to a Gaussian copula having Kendall's rank\n% correlation TAU. If TAU is a scalar correlation coefficient, RHO is a\n% scalar correlation coefficient corresponding to a bivariate copula. If\n% TAU is a P-by-P correlation matrix, RHO is a P-by-P correlation matrix\n% corresponding to a P-variate copula.\n%\n% RHO = COPULAPARAM('t',TAU) returns the linear correlation parameter RHO\n% corresponding to a t copula having Kendall's rank correlation TAU. If\n% TAU is a scalar correlation coefficient, RHO is a scalar correlation\n% coefficient corresponding to a bivariate copula. If TAU is a P-by-P\n% correlation matrix, RHO is a P-by-P correlation matrix corresponding to\n% a P-variate copula.\n% \n% ALPHA = COPULAPARAM(TYPE,TAU) returns the copula parameter ALPHA\n% corresponding to a bivariate Archimedean copula having Kendall's rank\n% correlation TAU. TYPE is one of 'Clayton', 'Frank', or 'Gumbel'.\n%\n% Example:\n% % Determine the linear correlation coefficient corresponding to a\n% % bivariate Gaussian copula having a rank correlation of -0.5\n% tau = -0.5\n% rho = copulaparam('gaussian',tau)\n%\n% % Generate dependent beta random values using that copula\n% u = copularnd('gaussian',rho,100)\n% b = betainv(u,2,2)\n%\n% % Verify that those pairs have a sample rank correlation approximately\n% % equal to tau\n% tau_sample = kendall(b)\n\n% Written by Peter Perkins, The MathWorks, Inc.\n% Revision: 1.0 Date: 2003/09/05\n% This function is not supported by The MathWorks, Inc.\n%\n% Requires MATLAB R13.\n\nif nargin < 2\n error('Requires two input arguments.');\nend\n\nswitch lower(type)\ncase {'gaussian' 't'}\n if ((numel(tau) == 1) && (tau < -1 | 1 < tau)) || ((numel(tau) ~= 1) && ~iscor(tau))\n error('TAU must be a correlation coefficient between -1 and 1, or a positive semidefinite correlation matrix.');\n end\n param = sin(tau.*pi./2);\n \ncase {'clayton' 'frank' 'gumbel'}\n if (numel(tau) ~= 1) || (tau < -1 | 1 < tau)\n error('TAU must be a correlation coefficient between -1 and 1.');\n end\n switch lower(type)\n case 'clayton'\n if tau < 0\n error('TAU must be nonnegative for the Clayton copula.');\n end\n param = 2*tau ./ (1-tau);\n case 'frank'\n if tau == 0\n param = 0;\n elseif abs(tau) < 1\n % There's no closed form for alpha in terms of tau, so alpha has to be\n % determined numerically.\n warn = warning('off','MATLAB:fzero:UndeterminedSyntax');\n param = fzero(@frankRootFun,sign(tau),[],tau);\n warning(warn);\n else\n param = sign(tau).*Inf;\n end\n case 'gumbel'\n if tau < 0\n error('TAU must be nonnegative for the Gumbel copula.');\n end\n param = 1 ./ (1-tau);\n end\n \notherwise\n error('Unrecognized copula type: ''%s''',type);\nend\n\n\nfunction err = frankRootFun(alpha,targetTau)\nif abs(alpha) < realmin\n tau = 0;\nelse\n tau = 1 + 4 .* (debye1(alpha)-1) ./ alpha;\nend\nerr = tau - targetTau;\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/copulaparam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7438476022666982}} {"text": "function asset_path_test ( )\n\n%*****************************************************************************80\n%\n%% ASSET_PATH_TEST tests ASSET_PATH.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ASSET_PATH_TEST:\\n' );\n fprintf ( 1, ' Demonstrate the simulation of an asset price path.\\n' );\n\n s0 = 2.0;\n mu = 0.1;\n sigma = 0.3;\n n = 100;\n t0 = 0.0;\n t1 = 1.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The asset price at time 0, S0 = %f\\n', s0 );\n fprintf ( 1, ' The asset expected growth rate MU = %f\\n', mu );\n fprintf ( 1, ' The asset volatility SIGMA = %f\\n', sigma );\n fprintf ( 1, ' The expiry date T1 = %f\\n', t1 );\n fprintf ( 1, ' The number of time steps N = %d\\n', n );\n\n s = asset_path ( s0, mu, sigma, t1, n );\n%\n% Plot.\n%\n figure ( 1 )\n t = ( linspace ( t0, t1, n + 1 ) )';\n plot ( t, s )\n grid on\n xlabel ( '<-- Time -->' )\n ylabel ( '<-- Value --> ' )\n title ( 'Simulated asset path' )\n%\n% Print a little.\n%\n r8vec_print_part ( n + 1, s, 10, ' Partial results:' );\n%\n% Write to a file.\n%\n output_filename = 'asset_path.txt';\n\n r8vec_write ( output_filename, n + 1, s );\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Full results written to \"%s\".\\n', output_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/black_scholes/asset_path_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7438017890689362}} {"text": "function x = r8vec_chebyspace ( n, a, b )\n\n%*****************************************************************************80\n%\n%% R8VEC_CHEBYSPACE creates a vector of Chebyshev spaced values in [A,B].\n%\n% Discussion:\n%\n% An R8VEC is a vector of R8's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 June 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, real A, B, the first and last entries.\n%\n% Output, real X(N,1), a vector of Chebyshev spaced data.\n%\n x = zeros ( n, 1 );\n\n if ( n == 1 )\n\n x(1) = ( a + b ) / 2.0;\n\n else\n\n for i = 1 : n\n\n theta = ( n - i ) * pi / ( n - 1 );\n\n c = cos ( theta );\n\n if ( mod ( n, 2 ) == 1 )\n if ( 2 * i - 1 == n )\n c = 0.0;\n end\n end\n\n x(i) = ( ( 1.0 - c ) * a ...\n + ( 1.0 + c ) * b ) ...\n / 2.0;\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/r8lib/r8vec_chebyspace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7437938351957574}} {"text": "function [ mO ] = ApplyLocalLinearKernel( mI, filterRadius, regFctr )\n% ----------------------------------------------------------------------------------------------- %\n%[ mOutputImage ] = ApplyLocalLinearFilter( mInputImage, filterRadius, regFctr )\n% Applying Linear Edge Preserving Smoothing Filter based on Local Linear (Affine) model.\n% Input:\n% - mI - Input Image.\n% Structure: Image Matrix (Single Channel).\n% Type: 'Single' / 'Double'.\n% Range: [0, 1].\n% - filterRadius - Filter Radius.\n% The filter radius.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, ...}.\n% - regFctr - Regularization Factor.\n% Regularize the local covariance (Variance).\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: (0, inf).\n% Output:\n% - mO - Output Image.\n% Structure: Image Matrix (Single Channel).\n% Type: 'Single' / 'Double'.\n% Range: [0, 1].\n% References:\n% 1. \"Guided Image Filtering\".\n% Remarks:\n% 1. This is basically estimating the Linear Function (Affine)\n% parameters for the Local Window. Namely, the ouput is a Linear\n% combination of the input Window and a DC Factor. The final step is\n% aggregation (Uniform) off all estimations of the parameters.\n% 2. Prefixes:\n% - 'v' - Vector.\n% - 'm' - Matrix.\n% - 't' - Tensor (Multi Dimension Matrix)\n% - 's' - Struct.\n% - 'c' - Cell Array.\n% 3. The calculation of the Local Variance might be negative due to\n% numerical diffuculties. If artifacts appear, this might be the\n% casue. Usually using matrices of type 'double' solves it.\n% 4. This implemnetation is `ApplyGuidedFilter` where the Guiding Image\n% is the Input Image.\n% 5. Speed otimizzation can be achived by wiser use of 'mNumEffPixels'.\n% Instead of dividing by it calculate its reciprocal once. Moreover,\n% it can be used only once in the aggregation process.\n% TODO:\n% 1. Create Multi Variable Linear Model.\n% 2. Some speed potimization could be made (Taking advantage of 'mNumEffPixels').\n% Release Notes:\n% - 1.0.000 05/01/2016 Royi Avital\n% * First release version\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\nBORDER_TYPE_CONSTANT = 1;\nBORDER_TYPE_CIRCULAR = 2;\nBORDER_TYPE_REPLICATE = 3;\nBORDER_TYPE_SYMMETRIC = 4;\n\nnumRows = size(mI, 1);\nnumCols = size(mI, 2);\n\nborderType = BORDER_TYPE_CONSTANT;\nborderValue = 0;\nnormalizeFlag = OFF;\n\nmNumEffPixels = ApplyBoxFilter(ones([numRows, numCols]), filterRadius, borderType, borderValue, normalizeFlag);\n\nmLocalMean = ApplyBoxFilter(mI, filterRadius, borderType, borderValue, normalizeFlag) ./ mNumEffPixels;\nmLocalMeanSquare = ApplyBoxFilter((mI .* mI), filterRadius, borderType, borderValue, normalizeFlag) ./ mNumEffPixels;\nmLocalCovariance = mLocalMeanSquare - (mLocalMean .* mLocalMean);\n\nmO = zeros([numRows, numCols]);\n\nfor jj = 1:numCols\n for ii = 1:numRows\n % The coordinate i, j are set.\n \n sumWeights = 0;\n \n % Running on the Neighborhood of the pixel\n for ll = -filterRadius:filterRadius\n for kk = -filterRadius:filterRadius\n \n jRowIdx = ii + kk;\n jColIdx = jj + ll;\n \n if((jColIdx >= 1) && (jColIdx <= numCols) && (jRowIdx >= 1) && (jRowIdx <= numRows))\n % Valid Pixel\n numPixels = 0;\n jPixelWeight = 0;\n \n % Running on Wk Window\n for nn = -filterRadius:filterRadius\n for mm = -filterRadius:filterRadius\n \n % K Index\n kRowIdx = jRowIdx + mm;\n kColIdx = jColIdx + nn;\n \n if((kColIdx >= 1) && (kColIdx <= numCols) && (kRowIdx >= 1) && (kRowIdx <= numRows) && (abs(kColIdx - jj) <= filterRadius) && (abs(kRowIdx - ii) <= filterRadius))\n \n numPixels = numPixels + 1;\n \n % Weight\n jPixelWeight = jPixelWeight + 1 + (((mI(ii, jj) - mLocalMean(kRowIdx, kColIdx)) * (mI(jRowIdx, jColIdx) - mLocalMean(kRowIdx, kColIdx))) / (mLocalCovariance(kRowIdx, kColIdx) + regFctr));\n end\n end\n end\n \n % jPixelWeight = jPixelWeight / (numPixels * numPixels);\n mO(ii, jj) = mO(ii, jj) + (jPixelWeight * mI(jRowIdx, jColIdx));\n \n sumWeights = sumWeights + jPixelWeight;\n \n end\n end\n end\n \n mO(ii, jj) = mO(ii, jj) / sumWeights;\n \n end\nend\n\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/SignalProcessing/Q42415/ApplyLocalLinearKernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7437938346243838}} {"text": "function scMove(Pos1,length,LinCol)\n%scMove : Move along the transmission line on smith chart to transform impedance\n%\n%\n% SYNOPSIS:\n% Transform a point to another one as one moves along a lossless transmission line on\n% smith chart.\n%\n% See also scDraw, scInv, scConCirc, scMatchCirc\n% \n% SYNTAX:\n% scMove(Pos1, length, Direction, LinCol)\n%\n% INPUT ARGUMENTS:\n% Pos1 : Starting point coordinates [r x] normalized\n% length : Length of the transmission line normalized to wavelength\n% LinCol : Color of the end-ray emanating from origin\n% Direction : Towards(+1) or away from the generator(-1) %%%%TO BE INCORPORATED YET.\n%\n% OUTPUT ARGUMENT:\n% none\n%\n% EXAMPLE:\n% The Command sequence \n% scDraw;\n% scMove([2 3],.3)\n% will draw a blank smith chart and will plot the point\n% corresponding to impedance (2+j*3)*Z_L and its transformed value\n% after moving 0.3*lambda towards the generator along the\n% transmission line\n%\n% Mohammad Ashfaq - (31-05-2000)\n% Mohammad Ashfaq - (13-04-2006) Modified (example included)\n%\n\nif nargin == 2\n LinCol = 'm';\nend\n\n r1 = Pos1(1);\n x1 = Pos1(2);\n [u1, v1] = scPOI(r1,x1);\n\n % MARK STARTING POINT\n scRay(Pos1);\n\n r = sqrt(u1^2+v1^2);\n Theta1 = atan2(v1,u1);\n length1 = (1-Theta1/pi)/4;\n length2 = length1 + length;\n Theta2 = (1-4*length2)*pi;\n u2 = r * cos(Theta2);\n v2 = r * sin(Theta2);\n\n % MARK END POINT\n plot(u2, v2,'r*')\n\n Theta2d = Theta2*180/pi;\n if (Theta2d<-180)\n Theta2d = 360 + Theta2d;\n elseif (Theta2d>180)\n Theta2d = 360 - Theta2d;\n end\n length2 = length2-floor(length2/.5)*.5;\n \n plot([0 u2],[0 v2],LinCol);\n plot([1.25*cos(Theta2) u2],[1.25*sin(Theta2) v2],'k');\n string = ['\\theta=', num2str(Theta2d,'%3.2f'), ' l/\\lambda=', num2str(length2, '%0.3f')];\n \n if abs(Theta2d)>90\n Theta2d = Theta2d+180;\n h = text(1.25*cos(Theta2),1.25*sin(Theta2), string);\n set(h,'rotation', Theta2d, 'Fontsize', 8, 'HorizontalAlignment','right');\n else\n h = text(1.25*cos(Theta2),1.25*sin(Theta2), string);\n set(h,'rotation', Theta2d, 'Fontsize', 8);\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/324-smithchart/scMove.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7437938306828888}} {"text": "function C= train_QDA(xTr, yTr, varargin)\n%TRAIN_QDA - Quadratic Discriminant Analysis \n%\n%Synopsis:\n% C = train_QDA(XTR, YTR)\n% C = train_QDA(XTR, YTR, PRIOR)\n%\n%Arguments:\n% XTR: DOUBLE [NxM] - Data matrix, with N feature dimensions, and M\n% training points/examples. \n% YTR: INT [CxM] - Class membership labels of points in X_TR. C by M matrix\n% of training labels, with C representing the number of\n% classes and M the number of training examples/points.\n% Y_TR(i,j)==1 if the point j belongs to class i.\n% PRIOR: DOUBLE - (default ones(nClasses, 1)/nClasses): Empirical class\n% priors\n%\n%Returns:\n% C: STRUCT - Trained classifier structure, with the hyperplane given by\n% fields C.w, C.b and C.sq\n%\n%See also:\n% APPLY_QDA\n\n\nif size(yTr,1)==1,\n nClasses= 2;\n clInd{1}= find(yTr==-1);\n clInd{2}= find(yTr==1);\n N= [length(clInd{1}) length(clInd{2})];\nelse\n nClasses= size(yTr,1);\n clInd= cell(nClasses,1);\n N= zeros(nClasses, 1);\n for ci= 1:nClasses,\n clInd{ci}= find(yTr(ci,:));\n N(ci)= length(clInd{ci});\n end\nend\n\nif nargin==2\n priorP= ones(nClasses,1)/nClasses;\nelse\n priorP= varargin{1};\nend\nif isequal(priorP, '*')\n priorP = N/sum(N);\nend\n \nd= size(xTr,1);\nC.w= zeros(d, nClasses);\nC.b= zeros(1, nClasses);\nC.sq= zeros(d, d, nClasses);\nfor ci= 1:nClasses,\n cli= clInd{ci};\n C.w(:,ci)= mean(xTr(:,cli), 2);\n yc= xTr(:,cli) - C.w(:,ci)*ones(1,N(ci));\n Sq= yc*yc';\n C.sq(:,:,ci)= Sq / (N(ci)-1);\nend\nC.b= zeros(1, nClasses);\nfor ci= 1:nClasses,\n S= C.sq(:,:,ci);\n S= pinv(S);\n C.sq(:,:,ci)= -0.5*S;\n C.b(ci)= -0.5*C.w(:,ci)' * S*C.w(:,ci) + ...\n 0.5*log(max([det(S),realmin])) + log(priorP(ci));\n C.w(:,ci)= S*C.w(:,ci);\nend\nC.b=C.b';\n\nif nClasses==2,\n sq(:,:)= C.sq(:,:,2) - C.sq(:,:,1);\n C.sq= sq;\n C.w= C.w(:,2)-C.w(:,1);\n C.b= C.b(2) - C.b(1);\nend\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/classification/train_QDA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7437938267413937}} {"text": "function pde = Stokesdata0\n\n%\nnu = 1;\npde = struct('f',@f,'g',@g,'exactp', @exactp, ...\n 'exactu', @exactu,'g_D', @g_D, 'nu', nu);\n\n function z = f(p) \n x = p(:,1); y = p(:,2);\n z(:,1) = -4*pi^2*(2*cos(2*pi*x)-1).*sin(2*pi*y)+x.^2;\n z(:,2) = 4*pi^2*(2*cos(2*pi*y)-1).*sin(2*pi*x);\n end\n\n function z = g(p)\n z = zeros(size(p,1),1);\n end\n\n function z = exactu(p)\n x = p(:,1); y = p(:,2);\n z(:,1) = (1-cos(2*pi*x)).*sin(2*pi*y); \n z(:,2) = -(1-cos(2*pi*y)).*sin(2*pi*x);\n end\n\n function z = exactp(p)\n x = p(:,1); % y = p(:,2);\n z = 1/3*x.^3;\n end\n\n function z = g_D(p) % Dirichlet boundary condition\n z = 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/Stokesdata0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7437228176579035}} {"text": "function b = isPointOnLine(point, line, varargin)\n%ISPOINTONLINE Test if a point belongs to a line.\n%\n% B = isPointOnLine(POINT, LINE)\n% with POINT being [xp yp], and LINE being [x0 y0 dx dy].\n% Returns 1 if point lies on the line, 0 otherwise.\n%\n% If POINT is an N-by-2 array of points, B is a N-by-1 array of booleans.\n%\n% If LINE is a N-by-4 array of line, B is a 1-by-N array of booleans.\n%\n% B = isPointOnLine(POINT, LINE, TOL)\n% Specifies the tolerance used for testing location on 3D line. Default value is 1e-14.\n%\n% See also \n% lines2d, points2d, isPointOnEdge, isPointOnRay, isLeftOriented\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2003-10-31\n% Copyright 2003-2022 INRA - TPV URPOI - BIA IMASTE\n\n% extract computation tolerance\ntol = 1e-14;\nif ~isempty(varargin)\n tol = varargin{1};\nend\n\n% test if lines are colinear, using third coordinate of 3D cross-product\n% same test as:\n% b = abs((xp-x0).*dy-(yp-y0).*dx)./hypot(dx, dy).^2 < tol;\nb = bsxfun(...\n @rdivide, abs(...\n bsxfun(@times, bsxfun(@minus, point(:,1), line(:,1)'), line(:,4)') - ...\n bsxfun(@times, bsxfun(@minus, point(:,2), line(:,2)'), line(:,3)')), ...\n (line(:,3).^2 + line(:,4).^2)') < tol;\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/geom2d/isPointOnLine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7437075556089618}} {"text": "function [gradISE,gradJhr,gradJrr]=GaussMixISEMeanGrads(w1,mu1,P1,w2,mu2,P2,PDFVals12,PDFVals22)\n%%GAUSSMIXISEMEANGRADS Compute the gradient of the non-normalized\n% integrated squared error (ISE) between two Gaussian mixture\n% PDFs with respect to the mean vectors of the individual\n% components of the second Gaussian mixture. This gradient\n% can arise when optimizing over the ISE with respect to the\n% means.\n%\n%INPUTS: w1 The N1X1 or 1XN1 vector of weights for the first Gaussian\n% mixture. All w1>0 and sum(w1)=1.\n% mu1 The xDimXN1 set of mean vectors for the first Gaussian mixture\n% distribution.\n% P1 The xDimXxDimXN1 set of positive definite covariance matrices\n% for the first Gaussian mixture distirbution.\n% w2, mu2, P2, The length N2, xDimXN2, and xDimXxDimXN2 set of weights,\n% mean vectors and positive-definite covariance matrices for the\n% second Gaussian mixture distribution.\n% PDFVals12 A matrix such that the value in element (i,j) is\n% N(mu1(:,i);mu2(:,j),P1(:,:,i)+P2(:,:,j)), where N indicates the\n% multivariate Gaussian PDF evaluated at the first argument with\n% the second and third arguments being the mean and covarince\n% matrix. This parameter is returned by computeGaussMixISE.\n% PDFVals22 A matrix such that the value in element (i,j) is\n% N(mu2(:,i);mu2(:,j),P2(:,:,i)+P2(:,:,j)). This parameter is\n% returned by computeGaussMixISE.\n%\n%OUTPUTS: gradISE The xDimXn2 set of derivatives of the ISE with respect to\n% the elements of q (the square roots of w2).\n% gradJhr, gradJrr In Chapter 3 of [1], the ISE is expressed in terms of\n% Jhr and Jrr terms. These are the xDimXn2 gradients of\n% those terms.\n%\n%Formule for gradJhr and gradJrr are Equation 3.34 in Section 3.3.3.2 of\n%[1]. They relate to the ISE via Equation 3.20. See the function\n%computeGaussMixISE to compute the ISE.\n%\n%EXAMPLE 1:\n%In this example with a scalar random variable, we verify that the gradient\n%obtained from this function is consistent with numerical differentiation.\n% w1=[0.03,0.18,0.12,0.19,0.02,0.16,0.06,0.1,0.08,0.06];\n% n1=length(w1);\n% mu1=[1.45,2.20,0.67,0.48,1.49,0.91,1.01,1.42,2.77,0.89];\n% P1=[0.0487,0.0305,0.1171,0.0174,0.0295,0.0102, 0.0323, 0.0380, 0.0115, 0.0679];\n% P1=reshape(P1,[1,1,n1]);\n% \n% %The second PDF is the first with the five least-weight components deleted.\n% w2=[0.18,0.12,0.19,0.16,0.1,0.08];\n% w2=w2/sum(w2);\n% n2=length(w2);\n% mu2=[2.20,0.67,0.48,0.91,1.42,2.77];\n% P2=[0.0305,0.1171,0.0174,0.0102,0.0380,0.0115];\n% P2=reshape(P2,[1,1,n2]);\n% \n% [ISEVal,PDFVals12,PDFVals22]=computeGaussMixISE(w1,mu1,P1,w2,mu2,P2);\n% \n% epsVal=1e-8;\n% gradISENumDiff=zeros(1,n2);\n% for j=1:n2\n% muCur=mu2;\n% muCur(1,j)=muCur(1,j)+epsVal;\n% \tISEValCur=computeGaussMixISE(w1,mu1,P1,w2,muCur,P2);\n% gradISENumDiff(1,j)=(ISEValCur-ISEVal)/epsVal;\n% end\n% gradISE=GaussMixISEMeanGrads(w1,mu1,P1,w2,mu2,P2,PDFVals12,PDFVals22);\n% RelErr=max(abs((gradISENumDiff-gradISE)./gradISENumDiff))\n%The relative error will be about 5.4042e-6, which indicates good numeric\n%agreement.\n%\n%EXAMPLE 2:\n%In this example with a bivariate distribution, we verify that the gradient\n%obtained from this function is consistent with numerical differentiation.\n% w1=[0.25;0.5;0.25];\n% mu1=zeros(2,2);\n% mu1(:,1)=[1;-1];\n% mu1(:,2)=[-1;1];\n% mu1(:,3)=[0;0];\n% P1=zeros(2,2,2);\n% P1(:,:,1)=[4/9, 14/45;\n% 14/45,4/9];\n% P1(:,:,2)=[4/9, 0;\n% 0, 4/9];\n% P1(:,:,3)=[2/9, -1/9;\n% -1/9, 3/9];\n% \n% %The second distribution just throws out the first component.\n% w2=w1(2:3);\n% w2=w2/sum(w2);\n% mu2=mu1(:,2:3);\n% P2=P1(:,:,2:3);\n% \n% n2=length(w2);\n% [ISEVal,PDFVals12,PDFVals22]=computeGaussMixISE(w1,mu1,P1,w2,mu2,P2);\n% \n% numDim=size(mu1,1);\n% epsVal=1e-8;\n% gradISENumDiff=zeros(numDim,n2);\n% for curDim=1:numDim\n% for j=1:n2\n% muCur=mu2;\n% muCur(curDim,j)=muCur(curDim,j)+epsVal;\n% ISEValCur=computeGaussMixISE(w1,mu1,P1,w2,muCur,P2);\n% gradISENumDiff(curDim,j)=(ISEValCur-ISEVal)/epsVal;\n% end\n% end\n% gradISE=GaussMixISEMeanGrads(w1,mu1,P1,w2,mu2,P2,PDFVals12,PDFVals22);\n% RelErr=max(max(abs((gradISENumDiff-gradISE)./gradISENumDiff)))\n%The relative error will be about 1.2876e-7, which indicates good numeric\n%agreement.\n%\n%REFERENCES:\n%[1] J. L. Williams, \"Gaussian mixture reduction for tracking multiple\n% maneuvering targets in clutter,\" Master's thesis, Air Force Institute\n% of Technology, Mar. 2003. [Online].\n% Available: http://www.dtic.mil/srch/doc?collection=t3&id=ADA415317\n%\n%May 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nNh=length(w1);\nNr=length(w2);\nxDim=size(mu1,1);\n\n%The formulae for the gradient of Jhr and Jrr are given in Equation 3.34 of\n%Section 3.3.3.2 of [1].\ngradJhr=zeros(xDim,Nr);\ngradJrr=zeros(xDim,Nr);\n\nfor j=1:Nr\n for i=1:Nh\n gradJhr(:,j)=gradJhr(:,j)+(P1(:,:,i)+P2(:,:,j))\\(mu2(:,j)-mu1(:,i))*PDFVals12(i,j)*w1(i);\n end\n gradJhr(:,j)=-w2(j)*gradJhr(:,j);\nend\n\nfor j=1:Nr\n for i=1:Nr\n gradJrr(:,j)=gradJrr(:,j)+(P2(:,:,i)+P2(:,:,j))\\(mu2(:,j)-mu2(:,i))*PDFVals22(i,j)*w2(i);\n end\n gradJrr(:,j)=-2*w2(j)*gradJrr(:,j);\nend\n\ngradISE=gradJrr-2*gradJhr;\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/GaussMixISEMeanGrads.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7436980529148861}} {"text": "function [n,V,p] = affine_fit(X,W)\n %Computes the plane that fits best (lest square of the normal distance\n %to the plane) a set of sample points.\n %INPUTS:\n %\n %X: a N by 3 matrix where each line is a sample point\n %\n %OUTPUTS:\n %\n %n : a unit (column) vector normal to the plane\n %V : a 3 by 2 matrix. The columns of V form an orthonormal basis of the\n %plane\n %p : a point belonging to the plane\n %\n %NB: this code actually works in any dimension (2,3,4,...)\n %Author: Adrien Leygue\n %Date: August 30 2013\n\n if nargin<2\n W = 1/size(X,1)*ones(size(X,1),1);\n end\n W = W(:)./sum(W);\n \n %the mean of the samples belongs to the plane\n p = sum(bsxfun(@times,W,X));\n \n %The samples are reduced:\n R = bsxfun(@times,bsxfun(@minus,X,p),W);\n %Computation of the principal directions if the samples cloud\n [V,D] = eig(R'*R);\n %Extract the output from the eigenvectors\n n = V(:,1);\n V = V(:,2:end);\nend\n\n% Copyright (c) 2013, Adrien Leygue\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", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/external/affine_fit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7436980356416919}} {"text": "function B = barymat(y, x, w, s, r, doFlip)\n%BARYMAT Barycentric Interpolation Matrix.\n% BARYMAT(Y, X, W), where Y is a column vector of length M and X and W are\n% column and row vectors of length N, respectively, returns the M*N matrix\n% which interpolates data from the grid X to the grid Y using the 2nd-kind\n% barycentric interpolation formula with barycentric weights W. If W is not\n% supplied it is assumed to be the weights for polynomial interpolation at a\n% 2nd-kind Chebyshev grid: W(j) = (-1)^j, W([1, N]) = 0.5*W([1, N]).\n%\n% BARYMAT(Y, X, W, S, R) is the same, where S = acos(Y) and R = acos(X). The\n% purpose of this is that Y(j) - X(k) can be more accurately computed in this\n% 'theta space'. This is sometimes referred to as the 'trig trick' in spectral\n% collocation. BARYMAT(Y, X, W, S, R, 1) also performs the 'flipping trick', \n% which takes advantage of the fact that the smaller entries in R and S can be\n% computed more accurately. Note that X and Y should be symmetric about zero\n% for this work, and it is assumed that S and R are sorted in descending\n% order.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( isempty(y) || isempty(x) )\n % Nothing to do here!\n B = []; \n return\nend\n\nif ( size(x, 2) > 1 || size(y, 2) > 1 )\n error('CHEBFUN:barymat:dims', 'Inputs should be column vectors.');\nend\n\n% Obtain lengths of inputs:\nN = length(x);\nM = length(y);\n\n% Nothing to do here!\nif ( M == N && all(x == y) ) \n B = eye(N); \n return\nend\n \n% Default to the Chebyshev barycentric weights:\nif ( nargin < 3 || isempty(w) ) \n w = ones(1, N); \n w(2:2:end) = -1; \n w([1, N]) = 0.5*w([1, N]);\nelse\n % Ensure w is a row vector:\n w = reshape(w, 1, N);\nend\n\n% Repmat(Y-X'):\nif ( nargin < 5 )\n B = bsxfun(@minus, y, x.'); \nelse\n % Use the 'trig trick' that y-x = cos(s)-cos(r) = 2*sin((s+r)/2)*sin((r-s)/2).\n B = 2*bsxfun(@(r, s) sin((s+r)/2).* sin((r-s)/2), r.', s);\nend\n\n% Construct the matrix:\nif ( M >= 500 && N >= 1000 ) % <-- Experimentally determined.\n % Testing shows BSXFUN is faster in this regime\n B = bsxfun(@rdivide, w, B); % w(k)/(y(j)-x(k))\n B = bsxfun(@rdivide, B, sum(B, 2)); % Normalisation.\nelse\n % Else use FOR loops\n for k = 1:N\n B(:,k) = w(k)./B(:,k); % w(k)/(y(j)-x(k))\n end\n c = 1./sum(B, 2); % Normalisation.\n for j = 1:M\n B(j,:) = B(j,:)*c(j);\n end\nend\n\n% Where points coincide there will be division by zeros (as with bary.m).\n% Replace these entries with the identity:\nB(isnan(B)) = 1;\n\n% Flipping trick:\nif ( nargin > 5 && doFlip )\n ii = logical(rot90(tril(ones(M, N)), 2)); \n ii = fliplr(ii);\n rot90D = rot90(B, 2);\n B(ii) = rot90D(ii);\n B(isnan(B)) = 1;\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/barymat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7436980314385462}} {"text": "%CORRECTMATCHES Refines coordinates of corresponding points\n%\n% [newPoints1, newPoints2] = cv.correctMatches(F, points1, points2)\n%\n% ## Input\n% * __F__ 3x3 fundamental matrix.\n% * __points1__ first set of 2D points. A numeric Nx2/Nx1x2/1xNx2 array or a\n% cell array of 2-element vectors `{[x,y], ...}` (floating-point precision).\n% * __points2__ second set of 2D points. Same size and type as `points1`.\n%\n% ## Output\n% * __newPoints1__ The optimized `points1`. Similar in shape to `points1`\n% (either Nx2/1xNx2 numeric array or cell array of 2D points).\n% * __newPoints2__ The optimized `points2`.\n%\n% The function implements the Optimal Triangulation Method (see [Hartley2004]\n% for details). For each given point correspondence `points1[i] <-> points2[i]`,\n% and a fundamental matrix `F`, it computes the corrected correspondences\n% `newPoints1[i] <-> newPoints2[i]` that minimize the geometric error:\n%\n% d(points1[i], newPoints1[i])^2 + d(points2[i], newPoints2[i])^2\n%\n% (where `d(a,b)` is the geometric distance between points `a` and `b`)\n% subject to the epipolar constraint\n%\n% newPoints2' * F * newPoints1 = 0\n%\n% ## References\n% [Hartley2004]:\n% > R.I. Hartley and A. Zisserman. \"Multiple View Geometry in Computer Vision\"\n% > Cambridge University Press, 2004.\n%\n% See also: cv.findFundamentalMat\n%\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/correctMatches.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7436930817876117}} {"text": "function jac = p17_jac ( neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P17_JAC evaluates the jacobian for problem p17.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NEQN, the number of equations.\n%\n% Input, real T, Y(NEQN), the arguments of the jacobian.\n%\n% Output, real JAC(NEQN,NEQN), the jacobian matrix.\n%\n jac = zeros ( neqn, neqn );\n\n d = ( sqrt ( ( y(1).^2 + y(2).^2 ) ) ).^5;\n\n jac(1,3) = 1.0;\n jac(2,4) = 1.0;\n jac(3,1) = ( 2.0 * y(1).^2 - y(2).^2 ) / d;\n jac(3,2) = 3.0 * y(1) * y(2) / d;\n jac(4,1) = 3.0 * y(1) * y(2) / d;\n jac(4,2) = ( - y(1).^2 + 2.0 * y(2).^2 ) / 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/test_ode/p17_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7436930815999445}} {"text": "function [ld, UC] = logdet(A, UC)\n\n% LOGDET The log of the determinant when argument is positive definite.\n% FORMAT\n% DESC returns the log determinant of a positive definite matrix. If\n% the matrix isn't quite positive definite the function adds 'jitter'\n% to make it positive definite and gives out a warning message (this\n% is done through JITCHOL).\n% ARG A : the input positive definite matrix for which the log\n% determinant is required.\n% RETURN d : the log determinant of A computed using Cholesky\n% decomposition.\n% RETURN U : the Cholesky decomposition of A.\n%\n% FORMAT\n% DESC returns the log determinant of a positive definite matrix given\n% the Cholesky decomposition of A. If jitter is used then the\n% amount of jitter used is returned. \n% ARG A : the input positive definite matrix for which the log\n% determinant is required.\n% ARG U : the Cholesky decomposition of A.\n% RETURN d : the log determinant of A computed using Cholesky\n% decomposition.\n% RETURN U : the Cholesky decomposition of A.\n% RETURN jitter : the amount of jitter added.\n%\n% SEEALSO : jitChol, pdinv, chol\n%\n% COPYRIGHT : Neil D. Lawrence, 2003, 2004, 2005, 2006\n\n% NDLUTIL\n\nif nargin < 2\n UC=[];\nend\n\n% Obtain a Cholesky decomposition.\nif isempty(UC)\n if nargout > 2\n [UC, jitter] = jitChol(A);\n else\n UC = jitChol(A);\n end\nend\n\nld = 2*sum(log(diag(UC)));\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ndlutil/logdet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7436930753785929}} {"text": "function [J grad] = nnCostFunction(nn_params, ...\n input_layer_size, ...\n hidden_layer_size, ...\n num_labels, ...\n X, y, lambda)\n%NNCOSTFUNCTION Implements the neural network cost function for a two layer\n%neural network which performs classification\n% [J grad] = NNCOSTFUNCTON(nn_params, hidden_layer_size, num_labels, ...\n% X, y, lambda) computes the cost and gradient of the neural network. The\n% parameters for the neural network are \"unrolled\" into the vector\n% nn_params and need to be converted back into the weight matrices. \n% \n% The returned parameter grad should be a \"unrolled\" vector of the\n% partial derivatives of the neural network.\n%\n\n% Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices\n% for our 2 layer neural network\nTheta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), ...\n hidden_layer_size, (input_layer_size + 1));\n\nTheta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), ...\n num_labels, (hidden_layer_size + 1));\n\n% Setup some useful variables\nm = size(X, 1);\n \n% You need to return the following variables correctly \nJ = 0;\nTheta1_grad = zeros(size(Theta1));\nTheta2_grad = zeros(size(Theta2));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should complete the code by working through the\n% following parts.\n%\n% Part 1: Feedforward the neural network and return the cost in the\n% variable J. After implementing Part 1, you can verify that your\n% cost function computation is correct by verifying the cost\n% computed in ex4.m\n\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n% Convert y from (1-10) class into num_labels vector\nyd = eye(num_labels);\ny = yd(y,:);\n \n%%% Map from Layer 1 to Layer 2\na1=X;\n% Coverts to matrix of 5000 examples x 26 thetas\nz2=X*Theta1';\n% Sigmoid function converts to p between 0 to 1\na2=sigmoid(z2);\n\n%%% Map from Layer 2 to Layer 3\n% Add ones to the h1 data matrix\na2=[ones(m, 1) a2];\n% Converts to matrix of 5000 exampls x num_labels \nz3=a2*Theta2';\n% Sigmoid function converts to p between 0 to 1\na3=sigmoid(z3);\n\n% Compute cost\n%logisf=(-y)'*log(a3)-(1-y)'*log(1-a3);\nlogisf=(-y).*log(a3)-(1-y).*log(1-a3); % Becos y is now a matrix, so use dot product, unlike above\n%J=((1/m).*sum(sum(logisf)));\t% This line is correct if there is no regularization\n% Try with ...\n% J=((1/m).*sum((logisf))); \n% That will give J in 10 columns (it has summed m samples), so need to sum again\n\n%% Regularized cost\nTheta1s=Theta1(:,2:end);\nTheta2s=Theta2(:,2:end);\nJ=((1/m).*sum(sum(logisf)))+(lambda/(2*m)).*(sum(sum(Theta1s.^2))+sum(sum(Theta2s.^2)));\n\n\n% Part 2: Implement the backpropagation algorithm to compute the gradients\n% Theta1_grad and Theta2_grad. You should return the partial derivatives of\n% the cost function with respect to Theta1 and Theta2 in Theta1_grad and\n% Theta2_grad, respectively. After implementing Part 2, you can check\n% that your implementation is correct by running checkNNGradients\n%\n% Note: The vector y passed into the function is a vector of labels\n% containing values from 1..K. You need to map this vector into a \n% binary vector of 1's and 0's to be used with the neural network\n% cost function.\n%\n% Hint: We recommend implementing backpropagation using a for-loop\n% over the training examples if you are implementing it for the \n% first time.\n%\n% Set all the D to zeros\ntridelta_1=0;\ntridelta_2=0;\n\n% Compute delta, tridelta and big D\n\tdelta_3=a3-y;\n z2=[ones(m,1) z2];\n\tdelta_2=delta_3*Theta2.*sigmoidGradient(z2);\n delta_2=delta_2(:,2:end);\n\ttridelta_1=tridelta_1+delta_2'*a1; % Same size as Theta1_grad (25x401)\n tridelta_2=tridelta_2+delta_3'*a2; % Same size as Theta2_grad (10x26)\n\tTheta1_grad=(1/m).*tridelta_1;\n Theta2_grad=(1/m).*tridelta_2;\n %Theta1_grad=0;\n\t%Theta2_grad=0;\n%end\n\n\n% Part 3: Implement regularization with the cost function and gradients.\n%\n% Hint: You can implement this around the code for\n% backpropagation. That is, you can compute the gradients for\n% the regularization separately and then add them to Theta1_grad\n% and Theta2_grad from Part 2.\n%\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n% -------------------------------------------------------------\n\n% =========================================================================\n\n% Unroll gradients\ngrad = [Theta1_grad(:) ; Theta2_grad(:)];\n\n\nend\n", "meta": {"author": "yhyap", "repo": "machine-learning-coursera", "sha": "fb33f0ad54ff2104660c86b0d26456b15029a798", "save_path": "github-repos/MATLAB/yhyap-machine-learning-coursera", "path": "github-repos/MATLAB/yhyap-machine-learning-coursera/machine-learning-coursera-fb33f0ad54ff2104660c86b0d26456b15029a798/mlclass-ex4/nnCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7436300672093812}} {"text": "function [model, L] = ppcaVb(X, q, prior)\n% Perform variatioanl Bayeisan inference for probabilistic PCA model. \n% Input:\n% X: d x n data matrix\n% q: dimension of target space\n% Output:\n% model: trained model structure\n% L: variantional lower bound\n% Reference: \n% Pattern Recognition and Machine Learning by Christopher M. Bishop \n% Written by Mo Chen (sth4nth@gmail.com).\n[m,n] = size(X);\nif nargin < 3\n a0 = 1e-4;\n b0 = 1e-4;\n c0 = 1e-4;\n d0 = 1e-4;\nelse\n a0 = prior.a;\n b0 = prior.b;\n c0 = prior.c;\n d0 = prior.d;\nend\n\nif nargin < 2\n q = m-1;\nend\ntol = 1e-6;\nmaxIter = 500;\nL = -inf(1,maxIter);\n\nmu = mean(X,2);\nXo = bsxfun(@minus, X, mu);\ns = dot(Xo(:),Xo(:));\nI = eye(q);\n% init parameters\na = a0+m/2;\nc = c0+m*n/2;\nEalpha = 1e-4;\nEbeta = 1e-4;\nEW = rand(q,m); \nEWo = bsxfun(@minus,EW,mean(EW,2));\nEWW = EWo*EWo'/m+EW*EW';\nfor iter = 2:maxIter \n% q(z)\n LZ = I+Ebeta*EWW;\n V = inv(chol(LZ)); % inv(LZ) = V*V';\n EZ = LZ\\EW*Xo*Ebeta;\n EZZ = n*(V*V')+EZ*EZ';\n KLZ = n*sum(log(diag(V))); % KLZ = 0.5*n*log(det(inv(LZ)));\n% q(w)\n LW = diag(Ealpha)+Ebeta*EZZ;\n V = inv(chol(LW)); % inv(LW) = V*V'; \n EW = LW\\EZ*Xo'*Ebeta;\n EWW = m*(V*V')+EW*EW';\n KLW = m*sum(log(diag(V))); % KLW = 0.5*n*log(det(inv(LW)));\n% q(alpha)\n b = b0+diag(EWW)/2;\n Ealpha = a./b;\n KLalpha = -sum(a*log(b));\n% q(beta)\n WZ = EW'*EZ;\n d = d0+(s-2*dot(Xo(:),WZ(:))+dot(EWW(:),EZZ(:)))/2;\n Ebeta = c/d;\n KLbeta = -c*log(d);\n% q(mu)\n% Emu = Ebeta/(lambda+n*Ebeta)*sum(X-WZ,2);\n\n% lower bound\n L(iter) = KLalpha+KLbeta+KLW+KLZ;\n if L(iter)-L(iter-1) < tol*abs(L(iter-1)); break; end \nend\nL = L(2:iter);\n\nmodel.Z = EZ;\nmodel.W = EW;\nmodel.apha = Ealpha;\nmodel.beta = Ebeta;\nmodel.a = a;\nmodel.b = b;\nmodel.c = c;\nmodel.d = d;\nmodel.mu = mu;", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter12/ppcaVb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.743630065864836}} {"text": "function ellipse_t = ellFit(x,y,axis_handle,colorStr)\n% Finds the best fit to an ellipse for the given set of points.\n% http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=3215&objectType=File \n%\n% Format: ellipse_t = ellFit( x,y, [axis_handle])\n%\n% Input: x,y - a set of points in 2 column vectors. AT LEAST 5 points are needed !\n% axis_handle - optional. a handle to an axis, at which the estimated ellipse \n% will be drawn along with it's axes\n%\n% Output: ellipse_t - structure that defines the best fit to an ellipse\n% a - sub axis (radius) of the X axis of the non-tilt ellipse\n% b - sub axis (radius) of the Y axis of the non-tilt ellipse\n% phi - orientation in radians of the ellipse (tilt)\n% X0 - center at the X axis of the non-tilt ellipse\n% Y0 - center at the Y axis of the non-tilt ellipse\n% X0_in - center at the X axis of the tilted ellipse\n% Y0_in - center at the Y axis of the tilted ellipse\n% long_axis - size of the long axis of the ellipse\n% short_axis - size of the short axis of the ellipse\n% status - status of detection of an ellipse\n%\n% Note: if an ellipse was not detected (but a parabola or hyperbola), then\n% an empty structure is returned\n%\n% Example: (Verify recovery)\n% a = 1.45; b = 3.2; theta = 0.15; radSpacing = 0.05;\n% [x,y] = ellipsePoints(a,b,theta,radSpacing);\n% figure(1), plot(x,y,'-'); axis equal\n% ellS = ellFit(x,y);\n% [ellS.a, ellS.b, ellS.phi]\n% [a, b, theta] \n%\n% a = 1.45; b = 3.2; theta = pi/5; radSpacing = 0.05;\n% [x,y] = ellipsePoints(a,b,theta,radSpacing);\n% figure(1), plot(x,y,'-'); axis equal\n% for ii=1:10\n% ellS = ellFit(x + randn(size(x))/5, y + randn(size(y))/5);\n% aHat(ii) = ellS.a; bHat(ii) = ellS.b; thetaHat(ii) = ellS.phi;\n% end\n% [mean(aHat), mean(bHat), mean(thetaHat)]\n%\n% ellS = ellFit(x,y,figure(1));\n\n%\n% =====================================================================================\n% Ellipse Fit using Least Squares criterion\n% =====================================================================================\n% We will try to fit the best ellipse to the given measurements. the mathematical\n% representation of use will be the CONIC Equation of the Ellipse which is:\n% \n% Ellipse = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f = 0\n% \n% The fit-estimation method of use is the Least Squares method (without any weights)\n% The estimator is extracted from the following equations:\n%\n% g(x,y;A) := a*x^2 + b*x*y + c*y^2 + d*x + e*y = f\n%\n% where:\n% A - is the vector of parameters to be estimated (a,b,c,d,e)\n% x,y - is a single measurement\n%\n% We will define the cost function to be:\n%\n% Cost(A) := (g_c(x_c,y_c;A)-f_c)'*(g_c(x_c,y_c;A)-f_c)\n% = (X*A+f_c)'*(X*A+f_c) \n% = A'*X'*X*A + 2*f_c'*X*A + N*f^2\n%\n% where:\n% g_c(x_c,y_c;A) - vector function of ALL the measurements\n% each element of g_c() is g(x,y;A)\n% X - a matrix of the form: [x_c.^2, x_c.*y_c, y_c.^2, x_c, y_c ]\n% f_c - is actually defined as ones(length(f),1)*f\n%\n% Derivation of the Cost function with respect to the vector of parameters \"A\" yields:\n%\n% A'*X'*X = -f_c'*X = -f*ones(1,length(f_c))*X = -f*sum(X)\n%\n% Which yields the estimator:\n%\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n% | A_least_squares = -f*sum(X)/(X'*X) ->(normalize by -f) = sum(X)/(X'*X) |\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n%\n% (We will normalize the variables by (-f) since \"f\" is unknown and can be accounted for later on)\n% \n% NOW, all that is left to do is to extract the parameters from the Conic Equation.\n% We will deal the vector A into the variables: (A,B,C,D,E) and assume F = -1;\n%\n% Recall the conic representation of an ellipse:\n% \n% A*x^2 + B*x*y + C*y^2 + D*x + E*y + F = 0\n% \n% We will check if the ellipse has a tilt (=orientation). The orientation is present\n% if the coefficient of the term \"x*y\" is not zero. If so, we first need to remove the\n% tilt of the ellipse.\n%\n% If the parameter \"B\" is not equal to zero, then we have an orientation (tilt) to the ellipse.\n% we will remove the tilt of the ellipse so as to remain with a conic representation of an \n% ellipse without a tilt, for which the math is more simple:\n%\n% Non tilt conic rep.: A`*x^2 + C`*y^2 + D`*x + E`*y + F` = 0\n%\n% We will remove the orientation using the following substitution:\n% \n% Replace x with cx+sy and y with -sx+cy such that the conic representation is:\n% \n% A(cx+sy)^2 + B(cx+sy)(-sx+cy) + C(-sx+cy)^2 + D(cx+sy) + E(-sx+cy) + F = 0\n%\n% where: c = cos(phi) , s = sin(phi)\n%\n% and simplify...\n%\n% x^2(A*c^2 - Bcs + Cs^2) + xy(2A*cs +(c^2-s^2)B -2Ccs) + ...\n% y^2(As^2 + Bcs + Cc^2) + x(Dc-Es) + y(Ds+Ec) + F = 0\n%\n% The orientation is easily found by the condition of (B_new=0) which results in:\n% \n% 2A*cs +(c^2-s^2)B -2Ccs = 0 ==> phi = 1/2 * atan( b/(c-a) )\n% \n% Now the constants c=cos(phi) and s=sin(phi) can be found, and from them\n% all the other constants A`,C`,D`,E` can be found.\n%\n% A` = A*c^2 - B*c*s + C*s^2 D` = D*c-E*s\n% B` = 2*A*c*s +(c^2-s^2)*B -2*C*c*s = 0 E` = D*s+E*c \n% C` = A*s^2 + B*c*s + C*c^2\n%\n% Next, we want the representation of the non-tilted ellipse to be as:\n%\n% Ellipse = ( (X-X0)/a )^2 + ( (Y-Y0)/b )^2 = 1\n%\n% where: (X0,Y0) is the center of the ellipse\n% a,b are the ellipse \"radiuses\" (or sub-axis)\n%\n% Using a square completion method we will define:\n% \n% F`` = -F` + (D`^2)/(4*A`) + (E`^2)/(4*C`)\n%\n% Such that: a`*(X-X0)^2 = A`(X^2 + X*D`/A` + (D`/(2*A`))^2 )\n% c`*(Y-Y0)^2 = C`(Y^2 + Y*E`/C` + (E`/(2*C`))^2 )\n%\n% which yields the transformations:\n% \n% X0 = -D`/(2*A`)\n% Y0 = -E`/(2*C`)\n% a = sqrt( abs( F``/A` ) )\n% b = sqrt( abs( F``/C` ) )\n%\n% And finally we can define the remaining parameters:\n%\n% long_axis = 2 * max( a,b )\n% short_axis = 2 * min( a,b )\n% Orientation = phi\n%\n%\n\nif notDefined('colorStr');\n colorStr = 'r';\nend\n% initialize\norientation_tolerance = 1e-3;\n\n% empty warning stack\nwarning( '' );\n\n% prepare vectors, must be column vectors\nx = x(:);\ny = y(:);\n\n% remove bias of the ellipse - to make matrix inversion more accurate. (will be added later on).\nmean_x = mean(x);\nmean_y = mean(y);\nx = x-mean_x;\ny = y-mean_y;\n\n% the estimation for the conic equation of the ellipse\nX = [x.^2, x.*y, y.^2, x, y ];\na = sum(X)/(X'*X);\n\n% check for warnings\nif ~isempty( lastwarn )\n disp( 'stopped because of a warning regarding matrix inversion' );\n ellipse_t = [];\n return\nend\n\n% extract parameters from the conic equation\n[a,b,c,d,e] = deal( a(1),a(2),a(3),a(4),a(5) );\n\n% remove the orientation from the ellipse\nif ( min(abs(b/a),abs(b/c)) > orientation_tolerance )\n \n orientation_rad = 1/2 * atan( b/(c-a) );\n cos_phi = cos( orientation_rad );\n sin_phi = sin( orientation_rad );\n [a,b,c,d,e] = deal(...\n a*cos_phi^2 - b*cos_phi*sin_phi + c*sin_phi^2,...\n 0,...\n a*sin_phi^2 + b*cos_phi*sin_phi + c*cos_phi^2,...\n d*cos_phi - e*sin_phi,...\n d*sin_phi + e*cos_phi );\n [mean_x,mean_y] = deal( ...\n cos_phi*mean_x - sin_phi*mean_y,...\n sin_phi*mean_x + cos_phi*mean_y );\nelse\n orientation_rad = 0;\n cos_phi = cos( orientation_rad );\n sin_phi = sin( orientation_rad );\nend\n\n% check if conic equation represents an ellipse\ntest = a*c;\nswitch (1)\ncase (test>0), status = '';\ncase (test==0), status = 'Parabola found'; warning( 'fit_ellipse: Did not locate an ellipse' );\ncase (test<0), status = 'Hyperbola found'; warning( 'fit_ellipse: Did not locate an ellipse' );\nend\n\n% if we found an ellipse return it's data\nif (test>0)\n \n % make sure coefficients are positive as required\n if (a<0), [a,c,d,e] = deal( -a,-c,-d,-e ); end\n \n % final ellipse parameters\n X0 = mean_x - d/2/a;\n Y0 = mean_y - e/2/c;\n F = 1 + (d^2)/(4*a) + (e^2)/(4*c);\n [a,b] = deal( sqrt( F/a ),sqrt( F/c ) ); \n long_axis = 2*max(a,b);\n short_axis = 2*min(a,b);\n\n % rotate the axes backwards to find the center point of the original TILTED ellipse\n R = [ cos_phi sin_phi; -sin_phi cos_phi ];\n P_in = R * [X0;Y0];\n X0_in = P_in(1);\n Y0_in = P_in(2);\n \n % pack ellipse into a structure\n ellipse_t = struct( ...\n 'a',a,...\n 'b',b,...\n 'phi',orientation_rad,...\n 'X0',X0,...\n 'Y0',Y0,...\n 'X0_in',X0_in,...\n 'Y0_in',Y0_in,...\n 'long_axis',long_axis,...\n 'short_axis',short_axis,...\n 'status','' );\nelse\n % report an empty structure\n ellipse_t = struct( ...\n 'a',[],...\n 'b',[],...\n 'phi',[],...\n 'X0',[],...\n 'Y0',[],...\n 'X0_in',[],...\n 'Y0_in',[],...\n 'long_axis',[],...\n 'short_axis',[],...\n 'status',status );\nend\n\n% check if we need to plot an ellipse with it's axes.\nif (nargin>2) && ~isempty( axis_handle ) && (test>0)\n \n % rotation matrix to rotate the axes with respect to an angle phi\n R = [ cos_phi sin_phi; -sin_phi cos_phi ];\n \n % the axes\n ver_line = [ [X0 X0]; Y0+b*[-1 1] ];\n horz_line = [ X0+a*[-1 1]; [Y0 Y0] ];\n new_ver_line = R*ver_line;\n new_horz_line = R*horz_line;\n \n % the ellipse\n theta_r = linspace(0,2*pi);\n ellipse_x_r = X0 + a*cos( theta_r );\n ellipse_y_r = Y0 + b*sin( theta_r );\n rotated_ellipse = R * [ellipse_x_r;ellipse_y_r];\n \n % draw\n hold_state = get( axis_handle,'NextPlot' );\n set( axis_handle,'NextPlot','add' );\n% plot( new_ver_line(1,:),new_ver_line(2,:),colorStr );\n% plot( new_horz_line(1,:),new_horz_line(2,:),colorStr );\n plot( rotated_ellipse(1,:),rotated_ellipse(2,:),colorStr );\n set( axis_handle,'NextPlot',hold_state );\nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/Stats/ellipse/ellFit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.7436300637110557}} {"text": "function determ = herndon_determinant ( n )\n\n%*****************************************************************************80\n%\n%% HERNDON_DETERMINANT returns the determinant of the Herndon matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real DETERM, the determinant.\n%\n determ = 6.0 / ( ( n + 1 ) * n * ( 5 - 2 * n ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/herndon_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7435992603554528}} {"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\n\nh = sigmoid(X*theta);\nids = find(h>=0.5);\np(ids) = 1;\nids = find(h<0.5);\np(ids) = 0;\n\n\n\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "1094401996", "repo": "machine-learning-coursera", "sha": "e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb", "save_path": "github-repos/MATLAB/1094401996-machine-learning-coursera", "path": "github-repos/MATLAB/1094401996-machine-learning-coursera/machine-learning-coursera-e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb/problem_sets/ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7435863807567106}} {"text": "function determ = wilk21_determinant ( n )\n\n%*****************************************************************************80\n%\n%% WILK21_DETERMINANT computes the determinant of the WILK21 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 N, the order of the matrix.\n%\n% Output, real DETERM, the determinant.\n%\n d = zeros ( n, 1 );\n\n for i = 1 : n\n d(i) = round ( abs ( i - ( n + 1 ) / 2 ) );\n end\n\n determ_nm1 = d(n);\n\n if ( n == 1 )\n determ = determ_nm1;\n return\n end\n\n determ_nm2 = determ_nm1;\n determ_nm1 = d(n-1) * d(n) - 1.0;\n\n if ( n == 2 )\n determ = determ_nm1;\n return\n end\n\n for i = n - 2 : -1 : 1\n\n determ = d(i) * determ_nm1 - determ_nm2;\n\n determ_nm2 = determ_nm1;\n determ_nm1 = determ;\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/wilk21_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.7435863729144211}} {"text": "function turnDir=turnOrientation(v1,v2,v3)\n%%TURNORIENTATION Given 3 two-dimensional vertices in order, determine\n% whether they form a left turn (go counterclockwise).\n% Such a determination is necessary for determining\n% whether a polygon is convex and plays a role in\n% finding the convex hull of a set of points.\n% \n%INPUTS: v1, v2, v3 A set of 3 2XN matrices, of N vertex sets in the order\n% [x;y] These are 2-dimensional vertices in order,\n% whereby one wishes to determine whether the angle\n% v1-v2-v3 is going counterclockwise (left) or clockwise\n% (right) for each set of vertices.\n%\n%OUTPUTS: turnDir An NX1 vector where the ith element is is 1 if the ith\n% set of vertices form a counterclockwise angle, -1 if\n% they are going clockwise and 0 if they are collinear or\n% if two of them coincide.\n% \n%An implementation is given ehre in Matlab. However, the implementation in\n%C++ might be more accurate, assuming that one's compilter implements the\n%long double datatype as an IEEE-754 souble extended precision datatype.\n%A notable exception is Microsoft's Visual Studio (as of 2017), which maps\n%long doubles to doubles (64 bits rather than the 80-bit size of Intel/\n%AMD floating point registers) as noted in \n%https://docs.microsoft.com/en-us/cpp/c-language/type-long-double\n%Additionally, the function exactSignOfSumCPP is used to provide the sign\n%of an error-free sum. Unfortunately, since the IEEE-754 double extended\n%precision datatype only provides a 64-bit mantissa, which is not much of\n%an extension over the 54-bit mantissa of a standard double precision\n%floating point number, and is not enough to assure no finite precision\n%rounding in the products that go into the sum, one cannot guarantee zero\n%finite precision errors in this function. On the other hand, if the\n%inputs are single-precision (promoted to doubles, since the function does\n%not take singles) floating point numbers, the result is exact.\n%\n%The cross product rule for 3D vectors a and b says that\n%norm(cross(a,b))=norm(a)*norm(b)*sin(theta)\n%where theta is the positive angle between the vectors. However, If the\n%vectors are 2D, (set the z-components to zero), then the cross product\n%only have one nonzero component in the z-direction and that component is\n%equal to det([a,b]) (for 2D a and b). The interesting thing now, is that\n%the sign of the determinant will tell you whether the subsequent vectors\n%are going counterclockwise or clockwise. This function returns -1 if the\n%vectors are going counterclockwise, 0 if they are exactly collinear and 1\n%if they are clockwise.\n%\n%The Matlab implementation can be used without a compilation. The compiled\n%version of the algorithm can be obtained using the \n%CompileCLibraries function.\n%\n%The algorithm is run in Matlab using the command format\n%turnDir=turnOrientation(v1,v2,v3);\n%\n%December 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n S=zeros(6,1);\n S(1)=v3(1)*v1(2);\n S(2)=v1(1)*v2(2);\n S(3)=v2(1)*v3(2);\n S(4)=-v3(1)*v2(2);\n S(5)=-v1(1)*v3(2);\n S(6)=-v2(1)*v1(2);\n\n turnDir=exactSignOfSum(S);\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/turnOrientation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7434810562206657}} {"text": "function xycoords = latlon2xy(latlon,centerpoint)\n % convert lat,lon list into x,y given a lat-lon centerpoint\n %\n %This function will take coordinates given in latitude and longitude\n %and convert them to and x,y coordinate system with x pointing east, y\n %pointing north.\n \n %The zero point will be set at the point given in centerpoint, where\n %centerpoint is entered as [lat lon].\n \n \n \n lat = latlon(:,1);\n lon = latlon(:,2);\n \n \n \n %Defining the y and x coordinates of each lat and lon\n \n y = deg2km(lat - centerpoint(1));\n \n x = deg2km(lon - centerpoint(2)).*cosd(lat);\n \n %Outputting a vector with column1 = x coords, column2 = y coords\n \n xycoords = [x(:) y(:)];\nend\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/src/thomas/etas/latlon2xy2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.7434590706803907}} {"text": "function out = nsamdf_nonlinear_measure(data,fs,winLenRel,shiftLenRel,lagRel,degree,doPlot)\n% nsamdf_nonlinear_measure computes the nonlinearity measure L through nsAMDF\n% (nonlinear average magnitude difference function), developed by:\n%\n% Ozkurt et al. (2020), \"Identification of nonlinear features in cortical and\n% subcortical signals of Parkinson's Disease patients via a novel efficient\n% measure\", Neuroimage.\n%\n% Please refer to and cite this paper if you utilize this function in your work.\n%\n%---INPUTS:\n%\n% data = One dimensional input time-series (it can be raw, but it is a good idea to low-pass filter it to get rid of high frequency nuisance)\n% For the neural data (LFP, MEG) in the aferomentioned paper, we\n% low-passed the raw data for 40 Hz. The data should be long enough for proper estimation of nonlinearity.\n%\n% winlen = window length (a long enough segment is important to estimate the nonlinearity)\n% We chose the window length as 14 sec., i.e., winlen = 14*fs\n%\n% shiftlen = This amounts to window length - overlap length btw windows\n% We chose it as half the window length, i.e., shiftlen = 0.5*winlen\n%\n% lag = TMaximum lag for nsAMDF, we chose it as 1 sec, i.e., lag = fs.\n%\n% fs = sampling frequency of the data\n%\n% degree = The chosen degree p should ideally be large enough to capture the highest order of nonlinearity within the data.\n% We chose p=7 for in our case of Parkinsonian data in the paper.\n%\n% doPlot = true to plot nsAMDF sequences, otherwise just assign it false\n%\n%---OUTPUTS:\n%\n% L: nonlinearity measure\n%\n% s2: normalized nsAMDF for the degree 2\n%\n% sd: normalized nsAMDF for the chosen degree greater than 2\n%\n%\n% Required subfunctions are NormedSingleCurveLengthWindowed.m & NormedSingleCurveLength.m\n%\n%\n% Authored by Tolga Esat Ozkurt, 2020. (tolgaozkurt@gmail.com)\n\n\n%-------------------------------------------------------------------------------\n% Set defaults:\n\nif nargin < 2\n fs = 1;\nend\nif nargin < 3\n winLenRel = 14;\nend\nwindowLength = winLenRel*fs;\nif nargin < 4\n shiftLenRel = 0.5;\nend\nshiftLength = shiftLenRel*windowLength;\nif nargin < 5\n lagRel = 1;\nend\nlag = fs*lagRel;\nif nargin < 6\n degree = 7;\nend\nif nargin < 7\n doPlot = false\nend\n\n%-------------------------------------------------------------------------------\n% nsAMDF for p=2:\ns2 = NormedSingleCurveLengthWindowed(data,windowLength,shiftLength,lag,fs,2);\nout.s2 = s2 ./ max(s2); % normalized\n\n% nsAMDF for p=degree:\nsd = NormedSingleCurveLengthWindowed(data,windowLength,shiftLength,lag,fs,degree);\nout.sd = sd ./ max(sd); % normalized\n\n% If you like, you can bandpass filter s2 and sd for the specific frequency band\n% of nonlinear effect both to compute L and plot them as such\n\nout.L = norm(s2 - sd);\n\n%-------------------------------------------------------------------------------\nif doPlot\n figure\n plot(s2,'b')\n hold on\n plot(sd,'g')\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/Toolboxes/nsamdf/nsamdf_nonlinear_measure.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7434544595305401}} {"text": "% dimension of ambient space\nn = 6;\n% number of subspaces = number of clusters\nns = 2;\n% dimensions of individual subspaces 1 and 2\nd1 = 2;\nd2 = 2;\n% number of signals in individual subspaces\ns1 = 10;\ns2 = 10;\n% total number of signals\nS = s1 + s2;\n% A random basis for first subspace;\nbasis1 = randn(n,d1);\n% coefficients for s1 vectors chosen randomly in subspace 1\ncoeffs1 = randn(d1,s1);\n% Random signals from first subspace\nX1 = basis1 * coeffs1;\n% A random basis for second subspace\nbasis2 = randn(n,d2);\n% coefficients for s2 vectors chosen randomly in subspace 2\ncoeffs2 = randn(d2,s2);\n% Random signals from first subspace\nX2 = basis2 * coeffs2;\n% Prepare the overall set of signals\nX = [X1 X2];\n% ground through clustering data\ntrue_labels = [1*ones(s1,1) ; 2*ones(s2,1)];\n% the largest dimension amongst all subspaces\nK = max(d1, d2);\nX = spx.norm.normalize_l2(X);\nC = spx.fast.gomp_spr(X, K, 2);\n\nsolver = spx.pursuit.single.OrthogonalMatchingPursuit(X, K);\nC2 = zeros(S, S);\nfor s=1:S\n solver.IgnoredAtom = s;\n result = solver.solve(X(:, s));\n C2(:, s) = result.z;\nend\nmax(C2 - C)\nmax(abs(X - X * C))\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/ssc_gomp/ex_gomp_spr_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.743454457163682}} {"text": "function r = invwishrand(S,nu);\n%INVWISHRND Random matrices from inverse Wishard distribution.\n%\n% R = INVWISHRAND(S,N) returns a matrix of random numbers chosen \n% from the central inverse Wishard distribution with parameters S and NU.\n%\n% S is a symmetric positive definite scale matrix\n% NU is degrees of freedom\n%\n% Note: E[R]=S*nu/(nu-k-1)\n%\n%\tSee also WISHRAND\n%\n% Copyright (c) 1999 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('Requires two input arguments.'); \nend;\n\n[d d2] = size(S);\nif d ~= d2\n error('Matrix S must be square');\nend\n\n[t,p]=chol(S);\nif p < 0\n error('Matrix S must be positive definite.');\nend\n\nr=inv(wishrand(inv(S),nu));\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/dist/invwishrand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7434544545295432}} {"text": "function y = sphere_characteristic ( m, n, x )\n\n%*****************************************************************************80\n%\n%% SPHERE_CHARACTERISTIC evaluates the characteristic function of a sphere.\n%\n% Discussion:\n%\n% The dimension of the sphere is arbitrary, and set by the input value M.\n%\n% The sphere is assumed to have center at the origin and radius 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points to check.\n%\n% Input, real X(M,N), the coordinates of points to be checked.\n%\n% Output, real Y(N,1), is 1 if the point is inside, 0 otherwise.\n%\n y = sqrt ( sum ( x.^2, 1 ) );\n\n y = y';\n\n y = ( y < 1.0 );\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/hypersphere_surface/sphere_characteristic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.8705972818382005, "lm_q1q2_score": 0.7434141087002032}} {"text": "% 高斯消去法 Gaussian_Elimination\nfunction [x] = my_ge(A, b)\n\n[m,n]=size(A);\nif (m~=n)\n fprintf('\\n Error: A 不是方阵!\\n'); return; \nend\n\nm = zeros(n);\n%消元过程\nfor k = 1:n-1\n for i = k+1:n\n m(i,k) = A(i,k)/A(k,k);\n A(i,:) = A(i,:) - m(i,k) * A(k,:);\n b(i) = b(i) - m(i,k) * b(k);\n end\nend\n%回代过程\nx(n) = b(n)/A(n,n);\nfor k = n-1 : -1 : 1\n summary = 0;\n for j = k+1 : n\n summary = summary + A(k,j) * x(j);\n end\n x(k) = (b(k) - summary) / A(k,k);\nend\n ", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第六章 线性方程组的直接法/my_ge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263736, "lm_q2_score": 0.785308578375437, "lm_q1q2_score": 0.7433704901022472}} {"text": "function [ lat, long ] = xy2latlong( x, y, ref_lat, ref_long )\n% converts cartesian coordinates x,y (in km) to lat/long\n% ref_lat and ref_long is the geodetic reference point for plane approximation of the earth surface\n\nearth_circumf = 40074;\n\nlat = (y * 360 / earth_circumf) + ref_lat;\nlong = ( (x*360) / (earth_circumf * cos(ref_lat*pi/180)) ) + ref_long;\n\nend\n\n", "meta": {"author": "DC9ST", "repo": "tdoa-evaluation-rtlsdr", "sha": "3e7791adca1179b0a0be715b240caa0ad01d09c7", "save_path": "github-repos/MATLAB/DC9ST-tdoa-evaluation-rtlsdr", "path": "github-repos/MATLAB/DC9ST-tdoa-evaluation-rtlsdr/tdoa-evaluation-rtlsdr-3e7791adca1179b0a0be715b240caa0ad01d09c7/functions/xy2latlong.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9465966702001758, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7433704877479771}} {"text": "function[varargout]=instmom(varargin)\n%INSTMOM Univariate and multivariate instantaneous moments.\n% don't need this because it really doesn't seep things up much from \n% using anatrans and instmome\n%\n% [A,OMEGA,UPSILON]=INSTMOM(X), where X is an analytic signal, computes \n% the amplitude A, instantaneous *radian* frequency OMEGA, and \n% instantaneous bandwidth assuming a unit sample rate. \n%\n% X is an array with the first dimension being \"time\". Thus, X can be a \n% matrix of analytic signals oriented as column vectors, or a 2- or 3-D \n% wavelet transform such as output by WAVETRANS.\n%\n% The output arrays are the same size as X. \n%\n% The instantaneous frequency, bandwidth, and curvature are defined as\n%\n% A = abs X\n% OMEGA = d/dt Im ln X = d/dt arg X\n% UPSILON = d/dt Re ln X = d/dt ln abs X \n% \n% where i=SQRT(-1) as usual.\n%\n% INSTMOM(X,DIM) computes the moments along dimension DIM, instead of \n% the default of computing the moments along the rows (DIM=1).\n%\n% For details, see \n% \n% Lilly & Olhede (2010), \"Bivariate instantaneous frequency and \n% bandwidth\", IEEE Trans. Sig. Proc., 58 (2), 591--603.\n% _____________________________________________________________________\n% \n% Sample interval\n%\n% INSTMOM(DT,...) uses sample interval DT, where DT is a scalar, for \n% computing time derivatives. DT=1 is the default.\n% _____________________________________________________________________\n% \n% Joint instantaneous moments\n%\n% INSTMOM can also calculate the joint instananeous moments of \n% multivariate signals, as defined in Lilly and Olhede (2010).\n%\n% [JA,JOMEGA,JUPSILON]=INSTMOM(X1,X2,...,XN,DIM) returns the *joint*\n% instantaneous moments calculated across the N signals X1,X2,... XN, \n% based on the univariate instantaneous moments along dimension DIM.\n%\n% The joint instantaneous amplitude JA is the root-mean-square of the \n% component amplitudes across dimension JDIM, while JOMEGA is power-\n% weighted average of the component instantaneous frequencies.\n%\n% For details and for the definition of the joint instantaneous bandwidth \n% JUPSILON, see Lilly and Olhede (2010).\n%\n% [JA,JOMEGA,JUPSILON]=INSTMOM(X,DIM,JDIM) also works, where the joint\n% instantaneous moments are calculated across dimensions JDIM of X.\n%\n% The joint instantaneous moments JA, JOMEGA, and JUPSILON then have the \n% same size as X, except along dimension JDIM where they have only one \n% entry. Note that DIM is no longer optional when JDIM is used.\n% _____________________________________________________________________\n% \n% Instantaneous curvature\n%\n% INSTMOM can also return the next-higher order instantaneous moment, \n% which is more rarely encountered. \n%\n% [A,OMEGA,UPSILON,XI]=INSTMOM(X) returns the instantaneous curvature XI,\n% defined as\n%\n% XI = d^2/dt^2 abs X / abs X + i d^2/dt^2 arg X\n% = UPSILON^2 + d/dt UPSILON + i d/dt OMEGA\n%\n% Similarly [JA,JOMEGA,JUPSILON,JXI]=INSTMOM(X,DIM,JDIM) returns the\n% joint instantaneous curvature JXI for the multivariate signal X.\n% \n% For details on the univariate and joint instantaneous curvature, see \n%\n% Lilly and Olhede (2012a), \"Analysis of modulated multivariate \n% oscillations\", IEEE Trans. Sig. Proc., 60 (2), 600--612. \n% _____________________________________________________________________\n%\n% Boundary conditions\n%\n% The first and last points must be treated differently, as the central \n% difference is not defined there. Three different methods can be used.\n%\n% INSTMOM(...,STR) specifies the method: STR= 'endpoint' (the default),\n% 'periodic', or 'nans'. See VDIFF for details. \n% _____________________________________________________________________\n%\n% 'instmom --f' generates some sample figures.\n%\n% Usage: [a,om]=instmom(x);\n% [a,om,up,xi]=instmom(dt,x);\n% [a,om,up,xi]=instmom(dt,x,dim);\n% [a,om,up,xi]=instmom(dt,x1,x2,x3,x4,dim);\n% [a,om,up,xi]=instmom(dt,x,dim,jdim);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2007--2019 J.M. Lilly --- type 'help jlab_license' for details\n\n\n% _____________________________________________________________________\n%\n% Higher-order modulation functions\n%\n% [OMEGA,RHO1,...RHON]=INSTMOM(X) also outputs the higher-order \n% instantaneous modulation functions. RHO1 is identical to the\n% bandwidth, and RHO2 is called the curvature.\n%\n% For details see \n%\n% Lilly and Olhede (2010). On the analytic wavelet transform.\n%\n% Note that the modulation functions are defined in their non-normalized \n% form, that is, not divided by powers of the instananeous frequency, \n% unlike in Lilly and Olhede (2010).\n%\n% _____________________________________________________________________\n\n\nif strcmpi(varargin{1}, '--t')\n instmom_test,return\nelseif strcmpi(varargin{1}, '--f')\n type makefigs_instmom\n makefigs_instmom;\n return\nend\n\nif length(varargin{1})==1\n dt=varargin{1};\n varargin=varargin(2:end);\nelse\n dt=1;\nend\n\n \nstr='endpoint';\ndim=1;\njdim=[];\nfor i=1:4\n if ischar(varargin{end})\n str=varargin{end};\n varargin=varargin(1:end-1);\n else\n if length(varargin{end})==1\n if length(varargin{end-1})==1 \n dim=varargin{end-1};\n jdim=varargin{end};\n varargin=varargin(1:end-2);\n else\n dim=varargin{end};\n varargin=varargin(1:end-1);\n end\n end\n end\nend\n\n\n\n\nN=length(varargin);\nif N==1\n x=varargin{1};\nelse\n jdim=lnsd(varargin{1})+1;\n sizex1=size(varargin{1});\n sizex1=sizex1(1:jdim-1);\n x=zeros([sizex1 N]);\n for i=1:N\n x=vindexinto(x,varargin{i},i,jdim);\n end\nend\n\n%Note: there are different ways to reasonably define the instantaneous\n%frequency as a vdiff of the signal. These differ greatly actually. \n%Diffing the unwrapped angle seems to give the best results. If you take \n%the Im of the diffed log, you will break the wavelet phase algorithm!\n\n%You definitely don't want to just do diff(x). This differences the real\n%and imaginary parts separately, which are themselves rapidly varying.\n \nom=vdiff(unwrap(angle(x),[],dim),dim,str)./dt;\nup=vdiff(log(abs(x)),dim,str)./dt; \neta=om-sqrt(-1)*up;\n\nvarargout{1}=abs(x);\nvarargout{2}=om;\nnmax=nargout-2;\n\n%I prefer this version, though difference is minor\n%if nmax>=1\n% varargout(3)=frac(1,abs(x)).*vdiff(vdiff(abs(x),1,str),1,str)./dt./dt+sqrt(-1)*vdiff(om,1,str)./dt; \n%end\n\nif nmax>=1\n etadiff=cell(nmax,1); \n polyargs=cell(nmax,1);\n bcell=cell(nmax,1);\n\n etadiff{1}=vdiff(eta,dim,str)./dt;\n polyargs{1}=up;\n\n for n=2:nmax\n etadiff{n}=vdiff(etadiff{n-1},dim,str)./dt;\n polyargs{n}=sqrt(-1)*etadiff{n-1};\n end\n\n temp=bellpoly(polyargs);\n for n=1:length(temp)\n varargout{n+2}=temp{n};\n end\nend\n\n%When JDIM is input, this tells me to output joint quantities\nif ~isempty(jdim)\n if nargout==1\n varargout{1}=jointmom(x,jdim); \n elseif nargout==2\n [varargout{1},varargout{2}]=jointmom(x,varargout{2},jdim);\n elseif nargout==3\n [varargout{1},varargout{2},varargout{3}]=jointmom(x,varargout{2},varargout{3},jdim);\n elseif nargout==4\n [varargout{1},varargout{2},varargout{3},varargout{4}]=jointmom(x,varargout{2},varargout{3},varargout{4},jdim);\n end\nend\n\n\nfunction[varargout]=jointmom(varargin)\n%JOINTMOM Joint instantaneous frequency, bandwidth, and curvature.\n%\n% OMEGAX=JOINTMOM(X,OMEGA,DIM) where X is an array of multiple analytic\n% signals and OMEGA is an array of their instantaneous frequencies, gives\n% the joint instaneous frequency OMEGAX averaged over dimension DIM.\n%\n% X is presumed to have time oriented in rows. The output matrix OMEGAX\n% are the same size as X except along dimension DIM, where the output\n% matrices will have length one. X and OMEGA are the same size.\n% \n% [OMEGAX,UPSILONX]=JOINTMOM(X,UPSILON,DIM) also works, where UPSILON \n% are the individual bandwidths, and UPSILONX is the joint quantity. \n% UPSILON is the same size as X and OMEGA.\n%\n% Finally [OMEGAX,UPSILONX,XIX]=JOINTMOM(X,UPSILON,XI,DIM) also returns \n% the joint instantaneous curvature XIX given individual curvatures XI.\n%\n% For details, see \n% \n% Lilly & Olhede (2010), \"Bivariate instantaneous frequency and \n% bandwidth\", IEEE Trans. Sig. Proc., 58 (2), 591--603.\n% \n% See also INSTMOM.\n%\n% Usage: [a,om]=jointmom(x,om,dim);\n% [a,om,up]=jointmom(x,om,up,dim);\n% [a,om,up,xi]=jointmom(x,om,xi,dim);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2009--2014 J.M. Lilly --- type 'help jlab_license' for details\n \n\n\ndim=varargin{end};\nx=varargin{1};\nvarargin=varargin(2:end-1);\n\n\nif ~isempty(varargin)\n om=varargin{1};\nend\nif length(varargin)>1\n upsilon=varargin{2};\nend\nif length(varargin)>2\n xi=varargin{3};\nend\n\nvarargout{1}=sqrt(vmean(abs(x).^2,dim));\nif nargout>1\n varargout{2}=vmean(om,dim,squared(x));\n ombar=vrep(varargout{2},size(x,dim),dim);\nend\nif nargout>2\n varargout{3}=sqrt(vmean(abs(upsilon+sqrt(-1)*(om-ombar)).^2,dim,squared(x)));\nend\nif nargout>3\n varargout{4}=sqrt(vmean(abs(xi+2*sqrt(-1)*upsilon.*(om-ombar)-(om-ombar).^2).^2,dim,squared(x)));\nend\nif nargout>4\n error('Sorry, INSTMOM only outputs the first two deviation vectors for joint moments.')\nend\n\n\nfunction[]=instmom_test\n\nload npg2006\nuse npg2006\n\n[a1,om1,up1,c1]=instmom(cv);\n[a2,om2,up2,c2]=instmom(permute(cv,[2 1]),2);\n\nreporttest('INSTMOM moments computed along different dimensions match', aresame([om1 up1 c1],[om2(:) up2(:) c2(:)])); \njointmom_test;\n\nfunction[]=jointmom_test\nload solomon\nuse solomon\n\n[x,z]=anatrans(x,z);\n\n[ax,omx,upx]=instmom(x);\n[az,omz,upz]=instmom(z);\n\nombar=frac(abs(x).^2.*omx+abs(z).^2.*omz,abs(x).^2+abs(z).^2);\nupbar=sqrt(frac(abs(x).^2.*(upx.^2+(omx-ombar).^2)+abs(z).^2.*(upz.^2+(omz-ombar).^2),abs(x).^2+abs(z).^2));\n\n[a,om,up]=instmom([x z],1,2);\n\nreporttest('INSTMOM joint moments using Solomon Islands frequency',aresame(om,ombar,1e-8))\nreporttest('INSTMOM joint moments using Solomon Islands bandwidth',aresame(up,upbar,1e-8))\n\n[a2,om2,up2]=instmom(x,z,1);\n\nreporttest('INSTMOM joint moments alternate form',aresame([a om up],[a2 om2 up2]))\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/jRidges/instmom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7433142379512783}} {"text": "function geometry_test035 ( )\n\n%*****************************************************************************80\n%\n%% TEST035 tests LINE_IMP_POINT_DIST_2D.\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 dim_num = 2;\n ntest = 3;\n\n atest = [ 2.0, 2.0, 2.0 ];\n btest = [ 5.0, 5.0, 5.0 ];\n ctest = [ 3.0, 3.0, 3.0 ];\n ptest = [ ...\n 0.0, 6.0; ...\n 0.0, 5.0; ...\n 0.0, 4.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST035\\n' );\n fprintf ( 1, ' LINE_IMP_POINT_DIST_2D finds the distance from\\n' );\n fprintf ( 1, ' a point X Y to a line A * X + B * Y + C = 0.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X Y A B C DIST\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : ntest\n\n a = atest(i);\n b = btest(i);\n c = ctest(i);\n p(1:dim_num) = ptest(1:dim_num,i);\n\n dist = line_imp_point_dist_2d ( a, b, c, p );\n\n fprintf ( 1, ' %8f %8f %8f %8f %8f %8f\\n', ...\n p(1:dim_num), a, b, c, dist );\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_test035.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7433003439079342}} {"text": "function d = distance(u, v)\n% Euclidean distance between u and v\n%\n% :Usage:\n% ::\n%\n% d = distance(u, v)\n%\n% :Inputs:\n%\n% **u** and **v:**\n% should be column vectors or matrices in k-dim space, where k is\n% the number of columns of u and v.\n%\n% if u is a single row, replicates u to size(v,1)\n\nif size(u,1) < size(v,1)\n u = repmat(u,size(v,1),1);\n if size(u,1) < size(v,1), error('Inputs must have same number of rows, or one row for 1st input!'),end\nend\n\ndelt = u - v;\nd = (sum(delt .^ 2,2)) .^.5;\n\nreturn\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/Misc_utilities/distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7433003404498866}} {"text": "function geometry_test179 ( )\n\n%*****************************************************************************80\n%\n%% TEST179 tests SOCCER_SIZE_3D and SOCCER_SHAPE_3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n dim_num = 3;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST179\\n' );\n fprintf ( 1, ' For the truncated icosahedron, or soccer ball,\\n' );\n fprintf ( 1, ' SOCCER_SIZE_3D returns dimension information;\\n' );\n fprintf ( 1, ' SOCCER_SHAPE_3D returns face and order information.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' We will use this information to compute the\\n' );\n fprintf ( 1, ' areas and centers of each face.\\n' );\n\n [ point_num, edge_num, face_num, face_order_max ] = soccer_size_3d ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of points = %d\\n', point_num );\n fprintf ( 1, ' Number of edges = %d\\n', edge_num );\n fprintf ( 1, ' Number of faces = %d\\n', face_num );\n fprintf ( 1, ' Maximum face order = %d\\n', face_order_max );\n\n [ point_coord, face_order, face_point ] = soccer_shape_3d ( ...\n point_num, face_num, face_order_max );\n%\n% Compute the area of each face.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Face Order Area\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : face_num\n\n for j = 1 : face_order(i)\n k = face_point(j,i);\n v(1:dim_num,j) = point_coord(1:dim_num,k);\n end\n\n [ area, normal ] = polygon_area_3d ( face_order(i), v );\n\n fprintf ( 1, ' %6d %5d %8f\\n', i, face_order(i), area );\n\n end\n%\n% Find the center of each face.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Face Center\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : face_num\n\n vave(1:dim_num) = 0.0;\n\n for j = 1 : face_order(i)\n k = face_point(j,i);\n vave(1:dim_num) = vave(1:dim_num) + point_coord(1:dim_num,k)';\n end\n\n vave(1:dim_num) = vave(1:dim_num) / face_order(i);\n\n fprintf ( 1, ' %6d %10f %10f %10f\\n', i, vave(1:dim_num) );\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_test179.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7433003387208628}} {"text": "%RPY2R Roll-pitch-yaw angles to SO(3) rotation matrix\n%\n% R = RPY2R(ROLL, PITCH, YAW, OPTIONS) is an SO(3) orthonornal rotation\n% matrix (3x3) equivalent to the specified roll, pitch, yaw angles angles.\n% These correspond to rotations about the Z, Y, X axes respectively. If\n% ROLL, PITCH, YAW are column vectors (Nx1) then they are assumed to\n% represent a trajectory and R is a three-dimensional matrix (3x3xN), where\n% the last index corresponds to rows of ROLL, PITCH, YAW.\n%\n% R = RPY2R(RPY, OPTIONS) as above but the roll, pitch, yaw angles are\n% taken from the vector (1x3) RPY=[ROLL,PITCH,YAW]. If RPY is a matrix\n% (Nx3) then R is a three-dimensional matrix (3x3xN), where the last index\n% corresponds to rows of RPY which are assumed to be [ROLL,PITCH,YAW].\n%\n% Options::\n% 'deg' Compute angles in degrees (radians default)\n% 'xyz' Rotations about X, Y, Z axes (for a robot gripper)\n% 'zyx' Rotations about Z, Y, X axes (for a mobile robot, default)\n% 'yxz' Rotations about Y, X, Z axes (for a camera)\n% 'arm' Rotations about X, Y, Z axes (for a robot arm)\n% 'vehicle' Rotations about Z, Y, X axes (for a mobile robot)\n% 'camera' Rotations about Y, X, Z axes (for a camera)\n%\n% Note::\n% - Toolbox rel 8-9 has XYZ angle sequence as default.\n% - ZYX order is appropriate for vehicles with direction of travel in the X\n% direction. XYZ order is appropriate if direction of travel is in the Z\n% direction.\n% - 'arm', 'vehicle', 'camera' are synonyms for 'xyz', 'zyx' and 'yxz'\n% respectively.\n%\n% See also TR2RPY, EUL2TR.\n\n% Copyright (C) 1993-2019 Peter I. Corke\n%\n% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n% of the Software, and to permit persons to whom the Software is furnished to do\n% so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%\n% https://github.com/petercorke/spatial-math\n\nfunction R = rpy2r(roll, varargin)\n opt.order = {'zyx', 'xyz', 'yxz', 'arm', 'vehicle', 'camera'};\n opt.deg = false;\n [opt,args] = tb_optparse(opt, varargin);\n \n % unpack the arguments\n if numcols(roll) == 3\n\t\tpitch = roll(:,2);\n\t\tyaw = roll(:,3);\n\t\troll = roll(:,1);\n\telseif nargin >= 3\n pitch = args{1};\n yaw = args{2};\n else\n error('SMTB:rpy2r:badarg', 'bad arguments')\n end\n\n % optionally convert from degrees\n if opt.deg\n d2r = pi/180.0;\n roll = roll * d2r;\n pitch = pitch * d2r;\n yaw = yaw * d2r;\n end\n\n switch opt.order\n case {'xyz', 'arm'}\n % XYZ order\n if numrows(roll) == 1\n R = rotx(yaw) * roty(pitch) * rotz(roll);\n else\n R = zeros(3,3,numrows(roll));\n for i=1:numrows(roll)\n R(:,:,i) = rotx(yaw(i)) * roty(pitch(i)) * rotz(roll(i));\n end\n end\n case {'zyx', 'vehicle'}\n % ZYX order\n if numrows(roll) == 1\n R = rotz(yaw) * roty(pitch) * rotx(roll);\n else\n R = zeros(3,3,numrows(roll));\n for i=1:numrows(roll)\n R(:,:,i) = rotz(yaw(i)) * roty(pitch(i)) * rotx(roll(i));\n end\n end\n \n case {'yxz', 'camera'}\n % YXZ order\n if numrows(roll) == 1\n R = roty(yaw) * rotx(pitch) * rotz(roll);\n else\n R = zeros(3,3,numrows(roll));\n for i=1:numrows(roll)\n R(:,:,i) = roty(yaw(i)) * rotx(pitch(i)) * rotz(roll(i));\n end\n end\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/rpy2r.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7433003359861572}} {"text": "function [f, lineSegs, theta] = fov(A, pref)\n%FOV Field of values (numerical range) of matrix A.\n% F = FOV(A), where A is a square matrix, returns a CHEBFUN F with domain [0\n% 2*pi]. The image F([0 pi]) is a curve describing the extreme points of the\n% boundary of the field of values A, a convex region in the complex plane. \n%\n% For a generic matrix, the boundary of the field of values is smooth and all\n% boundary points are extreme points. If A is normal, the field of values is\n% the convex hull of the eigenvalues of A, so the extreme points consist only\n% of the eigenvalues and hence F has one constant piece for each eigenvalue,\n% so it is not continuous on [0, 2*pi].\n% \n% The numerical abscissa of A is equal to max(real(F)), though this is much\n% better computed as max(real(eig(A + A')))/2.\n%\n% The algorithm used is that of C. R. Johnson, Numerical determination of the\n% field of values of a general complex matrix, SIAM J. Numer. Anal. 15 (1978),\n% 595-602.\n%\n% F = FOV(A, PREF) allows the preferences in the CHEBFUNPREF structure PREF to\n% be used in constructing F. Note that PREF.splitting will always be set to\n% TRUE by FOV and the domain will always be [0, 2*pi].\n%\n% [F, LINESEGS, THETA] = FOV(A) also returns a quasimatrix LINESEGS whose\n% columns are CHEBFUN objects defining the line segments connecting up the\n% extreme points and a vector THETA specifying the values in [0, 2*pi] where\n% the discontinuities in F occur.\n%\n% Example 1 (smooth boundary)\n% A = randn(5);\n% F = fov(A);\n% hold off, plot(F, '-b')\n% e = eig(A);\n% hold on, plot(e, '*k'), hold off, axis equal\n%\n% Example 2 (boundary has a corner)\n% A = [0 1 0 ; 0 0 0 ; 0 0 1];\n% [F, lineSegs] = fov(A);\n% plot(F, '-b'), hold on\n% plot(lineSegs, '-r')\n% e = eig(A);\n% plot(complex(e), '*k'), hold off, axis equal\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( nargin < 2 )\n % Obtain preferences:\n pref = chebfunpref();\nend\n\n% Set splitting to 'on' and the domain to [0, 2*pi].\npref.splitting = true;\npref.domain = [0, 2*pi];\n\n% Construct a CHEBFUN of the FOV curve, and try to merge any unnecessary\n% breakpoints out of the result:\nf = chebfun(@(theta) fovCurve(theta, A), pref);\nf = merge(f);\n\nif ( nargout == 1 )\n return\nend\n\n%% LINESEGS - implemented by Michael Overton\n% Look for possible discontinuities at any break points. The boundary of the\n% field of values may have corners, but it is continuous: hence the need\n% sometimes for linear interpolation connecting up the sets of extreme points.\n\nends = f.domain; % Break points are between 0 and 2*pi.\ndelta = 1e-14; % Must be bigger than machine precision but not much \n % bigger: if it is too small spurious line segments will\n % have tiny length, which hardly matters. \nif ( any(diff(ends) < delta) )\n delta = min(diff(ends))/3;\nend\nm = length(ends) - 1; % Number of pieces\n\n% Get the values to the left and right of break points. The first break point is\n% zero, which wraps around to 2*pi and needs special treatment. Exclude the\n% right end point 2*pi.\nlVal = feval(f, ends(1:end-1), 'left'); % Values to left of break points.\nlVal(1) = feval(f, ends(end), 'left'); % Value to left of 2*pi.\nrVal = feval(f, ends(1:end-1), 'right'); % Values to right of break points.\n\n% Determine which points correspond to discontinuities:\ntol = 10*delta*max(abs([lVal, rVal]), [], 2);\ndiscont = abs(lVal - rVal) > tol;\n\n% Define additional CHEBFUNs for the line segments joining discontinuities.\n% (First idea was to do this by inserting tiny intervals with steep slopes into\n% the CHEBFUN f, but this leads to loss of accuracy.) Each column of lineSegs\n% represents a line in the complex plane connecting the points lVal(j) and\n% rVal(j) to each other, along with the corresponding theta value in [0,2*pi].\ntheta = ends(discont);\nlineSegs = chebfun([lVal(discont) ; rVal(discont)], [-1 1], 'tech', @chebtech2);\n\nend\n\nfunction z = fovCurve(theta, A)\nz = NaN(size(theta));\nfor j = 1:length(theta)\n r = exp(1i*theta(j));\n B = r*A;\n H = (B + B')/2;\n [X, D] = eig(H);\n [ignored, k] = max(diag(D));\n v = X(:,k);\n z(j) = v'*A*v/(v'*v);\nend\nend\n\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/fov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7431987974411212}} {"text": "function [all_theta] = oneVsAll(X, y, num_labels, lambda)\n%ONEVSALL trains multiple logistic regression classifiers and returns all\n%the classifiers in a matrix all_theta, where the i-th row of all_theta \n%corresponds to the classifier for label i\n% [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels\n% logisitc regression classifiers and returns each of these classifiers\n% in a matrix all_theta, where the i-th row of all_theta corresponds \n% to the classifier for label i\n\n% Some useful variables\nm = size(X, 1);\nn = size(X, 2);\n\n% You need to return the following variables correctly \nall_theta = zeros(num_labels, n + 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should complete the following code to train num_labels\n% logistic regression classifiers with regularization\n% parameter lambda. \n%\n% Hint: theta(:) will return a column vector.\n%\n% Hint: You can use y == c to obtain a vector of 1's and 0's that tell use \n% whether the ground truth is true/false for this class.\n%\n% Note: For this assignment, we recommend using fmincg to optimize the cost\n% function. It is okay to use a for-loop (for c = 1:num_labels) to\n% loop over the different classes.\n%\n% fmincg works similarly to fminunc, but is more efficient when we\n% are dealing with large number of parameters.\n%\n% Example Code for fmincg:\n%\n% % Set Initial theta\n% initial_theta = zeros(n + 1, 1);\n% \n% % Set options for fminunc\n% options = optimset('GradObj', 'on', 'MaxIter', 50);\n% \n% % Run fmincg to obtain the optimal theta\n% % This function will return theta and the cost \n% [theta] = ...\n% fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...\n% initial_theta, options);\n%\n\n\ninitial_theta = zeros(n + 1, 1);\noptions = optimset('GradObj', 'on', 'MaxIter', 50);\n\n\nfor c=1:num_labels\n \n y1 = (y==c);\n [theta] = ...\n\tfmincg(@(t)(lrCostFunction(t, X, y1, lambda)), initial_theta, options);\n\n all_theta(c,:) = theta;\n\n \n \n \n \nend;\n\n\n\n\n\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "1094401996", "repo": "machine-learning-coursera", "sha": "e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb", "save_path": "github-repos/MATLAB/1094401996-machine-learning-coursera", "path": "github-repos/MATLAB/1094401996-machine-learning-coursera/machine-learning-coursera-e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb/problem_sets/ex3/oneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7431987934259048}} {"text": "function [Q fcnEvals iter] = adaptiveSimpson(fcn, a, b, varargin)\n% adaptiveSimpson - Numerically evaluate integral, adaptive Simpson quadrature. \n%\n% function [Q fcnEvals iter] = adaptiveSimpson(fcn, a, b, varargin)\n%\n% (c) Matthias Conrad and Nils Papenberg (2007-08-03)\n% \n% Authors: \n% Matthias Conrad (e-mail: conrad@tiaco.de)\n% Nils Papenberg (e-mail: papenber@math.uni-luebeck.de)\n%\n% Version:\n%\t\tRelease date: 2008-08-12 Version: 1.2\n% MATLAB Version 7.5.0.338 (R2007b)\n%\n% Description:\n% The adaptive Simpson algorithm programmed in an iterative not recursive\n% manner\n%\n% Input arguments:\n% fcn - function to be integrated\n% a - first point of interval\n% b - final point of interval\n% #varargin - further options of algorithm\n% tol - tolerance accuracy of quadrature [ 1e-6 ]\n% parts - initial number of partitions [ 2 ]\n% maxFcnEvals - maximal number of function evaluations allowed [ 20000 ]\n% maxParts - maximal number of partitions allowed [ 8000 ]\n%\n% Output arguments:\n% Q - numerical integral of function fcn on [a,b]\n% fcnEvals - number of function evaluations\n% iter - number of iterations\n%\n% Details:\n% This function behavior is similar to of Matlab integrated function \"quadv\".\n% \n% Example:\n% Q = adaptiveSimpson(@(x) [-cos(50*x); sin(x)], 0, pi, 'tol', 1e-6)\n%\n% References:\n% [1] Gander, W. & Gautschi, W. Adaptive Quadrature - Revisited\n% Eidgenoessische technische Hochschule Zuerich, 2000.\n\n% check scalar limits of interval\nif ~isscalar(a) || ~isscalar(b)\n error('Matlab:adaptiveSimpson:Limits',...\n 'The limits of integration must be scalars.');\nend\n\n% default values\ntol = 1e-6; parts = 2; maxFcnEvals = 20000; maxParts = 8000;\n\n% rewrite default options if needed\nfor j = 1 : length(varargin) / 2\n eval([varargin{2 * j - 1},'=varargin{',int2str(2 * j),'};']);\nend\n\n% initial values, termination constant (incl. quadr factor 15), parts of interval and integral value\ntol = 15 * tol; m = parts; parts = 4 * parts + 1; Q = 0;\niter = 0; fcnEvals = 0; maxResolution = 0; minH = eps(b - a) / 1024;\npoleWarning = 0;\n\n% check if interval has infinite boundaries, in case substitute function\nif ~isfinite(a) || ~isfinite(b)\n warning('Matlab:adaptiveSimpson:infiniteInterval',...\n 'The integral has an infinite interval; proceed with a substitution of function on finite interval.')\n if ~isfinite(a) && isfinite(b)\n [Q fcnEvals iter] = adaptiveSimpson(fcn, 0, b, varargin);\n fcn = @(t) infiniteLeft(t, fcn);\n a = 0; b = 1;\n elseif isfinite(a) && ~isfinite(b)\n [Q fcnEvals iter] = adaptiveSimpson(fcn, a, 0, varargin);\n fcn = @(t) infiniteRight(t, fcn);\n a = 0; b = 1;\n else\n fcn = @(t) infiniteBoth(t, fcn);\n a = - pi / 2; b = pi / 2;\n end\nend\n\n% choice of initial evaluation points\nt = [a + (b - a) / m * (kron(ones(1,m), [0, 0.27158, 0.72842]) + kron(0: m - 1, [1 1 1])), b];\nH = diff(t);\nt = [t(1:end-1); t(1:end-1) + H/4; t(1:end-1) + H/2; t(1:end-1) + 3 * H/4;];\nt = [t(:);b]';\n\n% initialize equidistant mesh and dimension of fcn\ny = fcn(t); fcnEvals = fcnEvals + length(y); n = size(y,1);\n\n% avoid infinities at start point of interval\nif any(~isfinite(y(:,1)))\n y(:,1) = fcn(a + eps(superiorfloat(a,b)) * (b - a));\n fcnEvals = fcnEvals + 1;\n poleWarning = 1;\nend\n\n% avoid infinities at end point of interval\nif any(~isfinite(y(:, end)))\n y(:, end) = fcn(b - eps(superiorfloat(a,b)) * (b - a));\n fcnEvals = fcnEvals + 1;\n poleWarning = 1;\nend\n\n% poles at initial points\nif ~isempty(find(~isfinite(max(abs(y))))), poleWarning = 1; end\n\n% initialize interval boundaries and values\nA = t(1:4:end-1); yA = y(:, 1:4:end-1);\nB = t(5:4:end); yB = y(:, 5:4:end);\nC = t(3:4:end-1); yC = y(:, 3:4:end-1);\nD = t(2:4:end-1); yD = y(:, 2:4:end-1);\nE = t(4:4:end-1); yE = y(:, 4:4:end-1);\n\n% adaptive Simpson iteration\nwhile 1\n\n % number of iteration\n iter = iter + 1;\n\n % Simpson formulas (on rough and fine grid)\n Q1 = kron(H, ones(n,1)) / 6 .* (yA + 4 * yC + yB);\n Q2 = kron(H, ones(n,1)) / 12 .* (yA + 4 * yD + 2 * yC + 4 * yE + yB);\n\n % difference of Simpson formulas\n diffQ = Q2 - Q1; diffQ(find(isnan(diffQ))) = 0;\n\n % intervals which do not fulfill termination criterion\n idx = find(max(abs(diffQ), [], 1) > tol);\n\n % intervals fulfill termination criterion\n idxQ = setdiff(1:length(A), idx);\n\n % check stop criterions\n STOP1 = isempty(idx); % check regular termination\n STOP2 = fcnEvals > maxFcnEvals; % check maximal function evaluations\n STOP3 = 2 * length(idx) > maxParts; % check maximal partition\n\n % regular termination\n if STOP1\n Q = Q + sum(Q2 + diffQ / 15, 2);\n break\n end\n\n % check if maximal resolution reached\n idxH = find(abs(H) < minH);\n if ~isempty(idxH)\n Q = Q + sum(Q2(idxH) + diffQ(idxH) / 15, 2);\n idx = setdiff(idx, idxH);\n idxQ = setdiff(idxQ, idxH);\n maxResolution = 1;\n % termination criterion\n if isempty(idx), break, end\n end\n\n % maximal function evaluations reached\n if STOP2\n warning('Matlab:adaptiveSimpson:MaxEvaluations',...\n 'The maximal number of function evaluations reached; singularity likely.')\n Q = Q + sum(Q2 + diffQ / 15, 2);\n break\n end\n\n % maximal partition reached\n if STOP3\n warning('Matlab:adaptiveSimpson:parts',...\n 'The maximal number of parts reached.')\n Q = Q + sum(Q2 + diffQ / 15, 2);\n break\n end\n\n % update quadrature value\n Q = Q + sum(Q2(:,idxQ) + diffQ(:,idxQ) / 15, 2);\n\n % update A, B, and C\n t = zeros(1, 2*length(idx));\n t(1:2:end) = A(idx); t(2:2:end) = C(idx); A = t;\n t(1:2:end) = C(idx); t(2:2:end) = B(idx); B = t;\n t(1:2:end) = D(idx); t(2:2:end) = E(idx); C = t;\n\n % update yA, yB, and yC\n y = zeros(n, 2*length(idx));\n y(:,1:2:end) = yA(:,idx); y(:,2:2:end) = yC(:,idx); yA = y;\n y(:,1:2:end) = yC(:,idx); y(:,2:2:end) = yB(:,idx); yB = y;\n y(:,1:2:end) = yD(:,idx); y(:,2:2:end) = yE(:,idx); yC = y;\n\n % update interval length\n H = B - A;\n\n % update D and E by interval bisection\n D = (A + H / 4); E = (A + 3 * H / 4);\n\n % calculate yD and yE\n y = fcn([D,E]); fcnEvals = fcnEvals + 4 * length(idx);\n\n % poles at new points\n if ~isempty(find(~isfinite(max(abs(y))))), poleWarning = 1; end\n\n % assign new values ob yD and yE\n yD = y(:,1:end/2); yE = y(:,end/2+1: end);\n\nend\n\n% display warnings\nif any(~isfinite(Q))\n warning('Matlab:adaptiveSimpson:Infinite',...\n 'The Quadrature of the function reached infinity or is Not-a-Number.')\nend\nif maxResolution\n warning('Matlab:adaptiveSimpson:MaxResolution',...\n 'The maximal resolution of partial interval reached; singularity likely.')\nend\nif poleWarning\n warning('Matlab:adaptiveSimpson:PoleDetection',...\n 'A detection of a pole; singularity likely.')\nend\n\nreturn\n\n% substitute function interval [-inf, 0] on [0, 1]\nfunction f = infiniteLeft(t, fcn)\nf = fcn(log(t));\nf = f ./ kron(ones(size(f,1),1), t);\nreturn\n\n% substitute function interval [0, inf] on [0, 1]\nfunction f = infiniteRight(t, fcn)\nf = fcn(-log(t));\nf = f ./ kron(ones(size(f,1),1), t);\nreturn\n\n% substitute function interval [-inf, inf] on [-pi / 2, pi / 2]\nfunction f = infiniteBoth(t, fcn)\nf = fcn(tan(t));\nf = f ./ kron(ones(size(f,1),1), cos(t).^2);\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/21013-iterative-adaptive-simpson-and-lobatto-quadrature/adaptiveSimpson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7431987795733739}} {"text": "function [imgw, imgwr, map] = tpswarp(img, outDim, Zp, Zs, interp)\n%\n% Description: Thin-Plane spline warping of the input image (img) to\n% output image (imgw). The warping is defined by a set of reference points\n% (Zp=[Xp Yp]) on the [img] image and a set of corresponding points (Zs)\n% on the (imgw) image. The warping will translate Zp in img to Zs in imgw.\n%\n% Input:\n% img - input image\n% outDim - Output canvas ([W H])\n% Zp - landmark in img\n% Zs - landmark in canvas\n% interp.method - interpolation mode('nearest', 'invdist', 'none')\n% interp.radius - Max radius for nearest neighbor interpolation or\n% Radius of inverse weighted interpolation\n% interp.power - power for inverse weighted interpolation\n%\n% Output:\n% imgw - warped image with no holes\n% imgwr - warped image with holes\n% map - Map of the canvas with 0 indicating holes and 1 indicating pixel\n%\n% Reference:\n% F.L. Bookstein, \"Principal Warps: Thin-Plate splines and the\n% decomposition of deformations\", IEEE Transaction on Pattern Analysis and\n% Machine Intelligence, Vol. 11, No. 6, June 1989\n%\n% Author: Fitzgerald J Archibald\n% Date: 07-Apr-09\n\n%% Initialization\nNPs = size(Zp,1); % number of landmark points\n\nimgH = size(img,1); % height\nimgW = size(img,2); % width\n\noutH = outDim(2);\noutW = outDim(1);\n\n% landmark in input\nXp = Zp(:,1)';\nYp = Zp(:,2)';\n\n% landmark in output (homologous)\nXs = Zs(:,1)';\nYs = Zs(:,2)';\n\n%% Algebra of Thin-plate splines\n\n% Compute thin-plate spline mapping [W|a1 ax ay] using landmarks\n[wL]=computeWl(Xp, Yp, NPs);\nwY = [Xs(:) Ys(:); zeros(3,2)]; % Y = ( V| 0 0 0)' where V = [G] where G is landmark homologous (nx2) ; Y is col vector of length (n+3)\nwW = inv(wL)*wY; % (W|a1 ax ay)' = inv(L)*Y\n\n% Thin-plate spline mapping (Map all points in the plane)\n% f(x,y) = a1 + ax * x + ay * y + SUM(wi * U(|Pi-(x,y)|)) for i = 1 to n\n[Xw, Yw]=tpsMap(wW, imgH, imgW, Xp, Yp, NPs);\n\n%% Warping\n\n% input grid for warping\n[X Y] = meshgrid(1:imgH,1:imgW); % HxW\n\n% Nearest neighbor or inverse distance weighted based interpolation\n[imgw,imgwr,map] = interp2d(X(:), Y(:), img, Xw, Yw, outH, outW, interp);\n\nreturn\n\n%% [L] = [[K P];[P' 0]]\n% np - number of landmark points\n% (xp, yp) - coordinate of landmark points\nfunction [wL]=computeWl(xp, yp, np)\n\nrXp = repmat(xp(:),1,np); % 1xNp to NpxNp\nrYp = repmat(yp(:),1,np); % 1xNp to NpxNp\n\nwR = sqrt((rXp-rXp').^2 + (rYp-rYp').^2); % compute r(i,j)\n\nwK = radialBasis(wR); % compute [K] with elements U(r)=r^2 * log (r^2)\nwP = [ones(np,1) xp(:) yp(:)]; % [P] = [1 xp' yp'] where (xp',yp') are n landmark points (nx2)\nwL = [wK wP;wP' zeros(3,3)]; % [L] = [[K P];[P' 0]]\n\nreturn\n\n\n%% Mapping: f(x,y) = a1 + ax * x + ay * y + SUM(wi * U(|Pi-(x,y)|)) for i = 1 to n\n% np - number of landmark points\n% (xp, yp) - coordinate of landmark points\nfunction [Xw, Yw]=tpsMap(wW, imgH, imgW, xp, yp, np)\n\n[X Y] = meshgrid(1:imgH,1:imgW); % HxW\nX=X(:)'; % convert to 1D array by reading columnwise (NWs=H*W)\nY=Y(:)'; % convert to 1D array (NWs)\nNWs = length(X); % total number of points in the plane\n\n% all points in plane\nrX = repmat(X,np,1); % Np x NWs\nrY = repmat(Y,np,1); % Np x NWs\n\n% landmark points\nrxp = repmat(xp(:),1,NWs); % 1xNp to Np x NWs\nryp = repmat(yp(:),1,NWs); % 1xNp to Np x NWs\n\n% Mapping Algebra\nwR = sqrt((rxp-rX).^2 + (ryp-rY).^2); % distance measure r(i,j)=|Pi-(x,y)|\n\nwK = radialBasis(wR); % compute [K] with elements U(r)=r^2 * log (r^2)\nwP = [ones(NWs,1) X(:) Y(:)]'; % [P] = [1 x' y'] where (x',y') are n landmark points (nx2)\nwL = [wK;wP]'; % [L] = [[K P];[P' 0]]\n\nXw = wL*wW(:,1); % [Pw] = [L]*[W]\nYw = wL*wW(:,2); % [Pw] = [L]*[W]\n\nreturn\n\n%% k=(r^2) * log(r^2)\nfunction [ko]=radialBasis(ri)\n\nr1i = ri;\nr1i(find(ri==0))=realmin; % Avoid log(0)=inf\nko = 2*(ri.^2).*log(r1i);\n\nreturn\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24315-warping-using-thin-plate-splines/tpsWarp/tpswarp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7431402842546774}} {"text": "function prob_test011 ( )\n\n%*****************************************************************************80\n%\n%% TEST011 tests BETA, GAMMA.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST011\\n' );\n fprintf ( 1, ' BETA evaluates the Beta function;\\n' );\n fprintf ( 1, ' GAMMA evaluates the Gamma function.\\n' );\n\n a = 2.2;\n b = 3.7;\n\n beta1 = beta ( a, b );\n beta2 = gamma ( a ) * gamma ( b ) / gamma ( a + b );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Argument A = %14f\\n', a );\n fprintf ( 1, ' Argument B = %14f\\n', b );\n fprintf ( 1, ' Beta(A,B) = %14f\\n', beta1 );\n fprintf ( 1, ' (Expected value = 0.0454 )\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Gamma(A)*Gamma(B)/Gamma(A+B) = %14f\\n', beta2 );\n\n return\nend\n", "meta": {"author": "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_test011.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7431402774603084}} {"text": "function jac = p30_jac ( neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P30_JAC evaluates the jacobian for problem p30.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NEQN, the number of equations.\n%\n% Input, real T, Y(NEQN), the arguments of the jacobian.\n%\n% Output, real JAC(NEQN,NEQN), the jacobian matrix.\n%\n jac = zeros ( neqn, neqn );\n\n csum = 0.0;\n for i = 1 : 19\n csum = csum + i.^(4.0/3.0);\n end\n\n pprime = 0.0;\n for i = 1 : 19\n pprime = pprime + ( 4.0 / 3.0 ) * r8_cube_root ( t - i );\n end\n\n jac(1,1) = pprime / csum;\n\n return\nend\n", "meta": {"author": "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_ode/p30_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8376199613065411, "lm_q1q2_score": 0.7431402724640797}} {"text": "function [H] = rotate(f)\n\n% ROTATE returns the homogenous coordinate transformation matrix\n% corresponding to a rotation around the x, y and z-axis. The direction of\n% the rotation is according to the right-hand rule.\n%\n% Use as\n% [H] = rotate(R)\n% where\n% R [rx, ry, rz] in degrees\n% H corresponding homogenous transformation matrix\n%\n% Note that the order in which the rotations are performs matters. The\n% rotation is first done around the z-axis, then the y-axis and finally the\n% x-axis.\n\n% Copyright (C) 2000-2005, Robert Oostenveld\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\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%\n% $Id$\n\nif numel(f)~=3\n ft_error('incorrect input vector');\nend\n\n% convert degrees to radians\nf = f*pi/180;\n\n% get the individual angles (in radians)\nrx = f(1);\nry = f(2);\nrz = f(3);\n\n% precompute the sin/cos values of the angles\ncX = cos(rx);\ncY = cos(ry);\ncZ = cos(rz);\nsX = sin(rx);\nsY = sin(ry);\nsZ = sin(rz);\n\n% according to Roger Woods' http://bishopw.loni.ucla.edu/AIR5/homogenous.html\n% it should be this, but I cannot reproduce his rotation matrix\n% H = eye(4,4);\n% H(1,1) = cZ*cY + sZ*sX*sY;\n% H(1,2) = sZ*cY - cZ*sX*sY;\n% H(1,3) = cX*sY;\n% H(2,1) = -sZ*cX;\n% H(2,2) = cZ*cX;\n% H(2,3) = sX;\n% H(3,1) = sZ*sX*cY - cZ*sY;\n% H(3,2) = -cZ*sX*cY - sZ*sY;\n% H(3,3) = cX*cY;\n\n% instead, the following rotation matrix does work according my\n% expectations. It rotates according to the right hand rule and first\n% rotates around z, then y and then x axis\nH = [\n cZ*cY, -sZ*cY, sY, 0\n cZ*sY*sX+sZ*cX, -sZ*sY*sX+cZ*cX, -cY*sX, 0\n -cZ*sY*cX+sZ*sX, sZ*sY*cX+cZ*sX, cY*cX, 0\n 0, 0, 0, 1\n];\n\nif 0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The following code can be used to construct the combined rotation matrix\n% for either xyz or zyx ordering (using the MATLAB symbolic math toolbox)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n syms sX sY sZ cX cY cZ\n % this is for only rotating around x\n Rx = [\n 1 0 0 0\n 0 cX -sX 0\n 0 sX cX 0\n 0 0 0 1\n ];\n % this is for only rotating around y\n Ry = [\n cY 0 sY 0\n 0 1 0 0\n -sY 0 cY 0\n 0 0 0 1\n ];\n % this is for only rotating around z\n Rz = [\n cZ -sZ 0 0\n sZ cZ 0 0\n 0 0 1 0\n 0 0 0 1\n ];\n % combine them\n Rzyx = Rz * Ry * Rx % rotate around x, y, then z\n Rxyz = Rx * Ry * Rz % rotate around z, y, then x\nend\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/rotate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7431329826268086}} {"text": "function [rhsQ] = CurvedEulerRHS2D(Q, time, SolutionBC, fluxtype)\n\n% function [rhsQ] = CurvedEulerRHS2D(Q, time, SolutionBC, fluxtype)\n% Purpose: compute right hand side residual for the compressible Euler \n% gas dynamics equations\n\nGlobals2D;\n\n% 1.1 Interpolate solution to cubature nodes \ncQ = zeros(cub.Ncub, K, 4);\nfor n=1:4, cQ(:,:,n) = cub.V*Q(:,:,n); end;\n\n% 1.2 Evaluate flux function at cubature nodes\ngamma = 1.4;\n[F,G,rho,u,v,p] = EulerFluxes2D(cQ, gamma);\n\n% 1.3 Compute volume terms (dphidx, F) + (dphidy, G)\nrhsQ = zeros(Np, K, 4);\nfor n=1:4\n ddr = (cub.Dr')*(cub.W.*(cub.rx.*F(:,:,n) + cub.ry.*G(:,:,n)));\n dds = (cub.Ds')*(cub.W.*(cub.sx.*F(:,:,n) + cub.sy.*G(:,:,n)));\n rhsQ(:,:,n) = ddr + dds;\nend\n\n% 2.1 SURFACE TERMS (using Gauss nodes on element faces)\nnx = gauss.nx; ny = gauss.ny; \nmapW = gauss.mapW; mapI = gauss.mapI; mapO = gauss.mapO; mapB = gauss.mapB; mapC = gauss.mapC;\n\n% 2.2 Interpolate solution to Gauss surface nodes\ngQM = zeros(gauss.NGauss*Nfaces, K, 4); gQP = zeros(gauss.NGauss*Nfaces, K, 4);\nfor n=1:4\n gQ = gauss.interp*Q(:,:,n);\n gQM(:,:,n) = gQ(gauss.mapM); gQP(:,:,n) = gQ(gauss.mapP);\nend \n\n% 2.3 Apply boundary conditions to '+' traces\nif(~isempty(SolutionBC))\n gQP = feval(SolutionBC, gauss.x, gauss.y, gauss.nx, gauss.ny, gauss.mapI, ...\n gauss.mapO, gauss.mapW, gauss.mapC, gQP, time);\nend\n\n% 2.4 Evaluate surface flux functions with stabilization\nswitch fluxtype\n case {'LF'}\n [flux] = EulerLF2D (nx, ny, gQM, gQP, gamma); \n case {'Roe'}\n [flux] = EulerRoe2D(nx, ny, gQM, gQP, gamma); \n case {'HLL'}\n [flux] = EulerHLL2D(nx, ny, gQM, gQP, gamma); \n case {'HLLC'}\n [flux] = EulerHLLC2D(nx, ny, gQM, gQP, gamma); \nend\n\n% 2.5 Compute surface integral terms\nfor n=1:4\n rhsQ(:,:,n) = rhsQ(:,:,n) - gauss.interp'*(gauss.W.*flux(:,:,n));\nend\n\n% 3.1 Multiply by inverse mass matrix\nfor n=1:4\n % 3.1.a Multiply straight sided elements by inverse mass matrix\n rhsQ(:,straight, n) = V*V'*(rhsQ(:,straight, n)./J(:,straight));\n\n % 3.1.b Multiply curvilinear elements by custom inverse mass matrices\n Ncurved = length(curved);\n for m=1:Ncurved\n k = curved(m);\n mmCHOL = cub.mmCHOL(:,:,k);\n rhsQ(:,k,n) = mmCHOL\\(mmCHOL'\\rhsQ(:,k,n));\n end\nend\nreturn;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/CFD2D/CurvedEulerRHS2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388754, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7431204681234429}} {"text": "\nfunction [A, AH, normA] = MakeTransforms(type, N, params)\n\n% [A, AH] = MakeTransforms(type, N, params)\n% with A AH = I\n%\n% INPUT\n% N : signal length\n% type : type of transform can be 'DFT' or 'STFT'\n% params : parameters for transform\n%\n% For DFT, params = [Nfft]\n% Nfft = number of DFT coefficients, Nfft >= N\n% Nfft/N is over-sampling factor\n%\n% For STFT, params = [R, Nfft]\n% R = length of frame\n% Nfft = number of DFT coefficients, Nfft >= R\n%\n% For DCT, params = [Ndct]\n% Ndct = number of DCT coefficients, Ndct >= N\n% Ndct/N is over-sampling factor\n%\n% For STDCT, params = [R, Ndct]\n% R = length of frame\n% Ndct = number of DCT coefficients, Ndct >= R\n%\n% OUTPUT\n% A, AH : function handles for transform\n% AH is the conjugate transpose of A\n% Note: input to AH must be a row vector of length N\n\n% DFT : Discrete Fourier transform with zero-padding\n% STFT : Short-time Fourier transform\n% DCT : Discrete cosine transform with zero-padding\n% STDCT : Short-time DCT\n\nswitch type\n case '2D-CDWT'\n [Faf, Fsf] = FSfarras;\n [af, sf] = dualfilt1;\n AH = @(x) cplxdual2D(x,params(1),Faf,af);\n A = @(x) icplxdual2D(x,params(1),Fsf,sf);\n \n normA = 1;\n \n case 'DWT'\n [h0, h1, g0, g1] = daubf(params(2)); % Get filters\n AH = @(x) udwt(x, params(1), h0, h1);\n A = @(x) iudwt(x, params(1), g0, g1);\n normA = 1;\n case '2D-DWT'\n [Faf, Fsf] = FSfarras;\n [af, sf] = dualfilt1;\n AH = @(x) dualtree2D(x,params(1), Faf, af);\n A = @(x) idualtree2D(x,params(1), Fsf, sf);\n \n normA = 1;\n case 'DFT'\n\n % over-sampled DFT (oversampling factor = Nfft/N)\n Nfft = params(1);\n truncate = @(x, N) x(1:N);\n AH = @(x) fft(x, Nfft)/sqrt(Nfft);\n A = @(X) truncate(ifft(X), N)*sqrt(Nfft);\n \n normA = sqrt(N/Nfft);\n\n case 'STFT'\n \n R = params(1);\n M = params(2);\n K = params(3);\n Nfft = params(4);\n AH = @(x) pSTFT2(x, R, M, K, Nfft);\n A = @(x) ipSTFT2(x,R,M,K,N); \n\n normA = sqrt(R/(M*Nfft));\n\n case 'DCT'\n\n % over-sampled DFT (oversampling factor = Nfft/N)\n Ndct = params(1);\n truncate = @(x, N) x(1:N);\n AH = @(x) dct(x, Ndct);\n A = @(X) truncate(idct(X), N);\n \n normA = sqrt(N/Ndct);\n \n case 'STDCT'\n \n R = params(1);\n M = params(2);\n K = params(3);\n Ndct = params(4);\n AH = @(x) stdct(x, R,M,K, Ndct);\n A = @(x) istdct(x, R,M,K, N); \n\n normA = sqrt(R/(2*Ndct));\n\nend\n\n% x = randn(1, N); % assuming row vector ! ! !\n% \n% % Verify perfect reconstruction property of transform 1 (A*AH = I)\n% c = AH(x);\n% err = x - A(c)';\n% re = max(abs(err(:))); % should be zero\n% fprintf('Reconstruction error = %f\\n', re)\n% \n% % Verify Parseval energy identity\n% E = sum(abs(x(:)).^2);\n% E1 = sum(abs(c(:)).^2); % should be unity\n% fprintf('Energy ratio = %f\\n', E/E1)\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_Proximal/Denoising/MakeTransforms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7431204636793266}} {"text": "function [power] = VBA_power(type, alpha, Estat, dof)\n% // VBA toolbox //////////////////////////////////////////////////////////\n%\n% [power] = VBA_power(type, alpha, Estat, dof)\n% Statistical power of a t- or F-test\n%\n% IN:\n% - type: type of test. Can be set to 't' or 'F'.\n% - alpha: statistical significance level\n% - Estat: expected effect size (z-score for a t-test, F value for an\n% F-test)\n% - dof: degrees of freedom\n%\n% OUT:\n% - power: ensuing statistical power\n%\n% /////////////////////////////////////////////////////////////////////////\n\n% ensure numerical stability\ndof(isinf(dof)) = 1e8;\ndof(dof==0) = 1e-8;\n\nswitch type\n case 't'\n tcritic = VBA_spm_invTcdf (1 - alpha, dof);\n power = 1 - VBA_spm_Tcdf (tcritic - Estat, dof);\n case 'F'\n Fcritic = VBA_spm_invFcdf (1 - alpha, dof(1), dof(2));\n power = 1-VBA_ncfcdf (Fcritic, dof(1), dof(2), Estat); \n otherwise\n disp('*** VBA_power: ''type'' argument can only be ''t'' or ''F''')\n power = [];\n return\nend\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/utils/VBA_power.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133565584851, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7430300099205636}} {"text": "function lorenza\n% Lorenz convection model \n\nsigma = 16; rho = 45.92; beta = 4; % parameters \nN = 1000; % no. of time steps\nspan = 0.05; % inner iteration span\nAbsTol = 1.e-5; % absolute tolerance for ODE solver\nRelTol = 1.e-5; % relative tolerance for ODE solver\n\nH = figure; set(H,'DefaultLineLineWidth',1.0);\noptions = odeset('RelTol',RelTol,'AbsTol',ones(1,3)*AbsTol);\nu0 = [1;1;1];\nfor i = 1:N\n [t,u] = ode45(@lornz,[0 span],u0,odeset,beta,rho,sigma);\n hold on; \n plot(u(:,1),u(:,2),'r'); \n u0 = u(end,:); \nend\n\ntitle('Attractor of Lorenz System');\nxlabel('Component 1'); ylabel('Component 2');\naxis off; hold off;\n\nfunction dydt = lornz(t,y,beta,rho,sigma)\ndydt = [sigma*(y(2)-y(1)); rho*y(1)-y(2)-y(1)*y(3); y(1)*y(2)-beta*y(3)];", "meta": {"author": "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/lorenza.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7430299976405729}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% intlinear.m\n%\n%[A,B] = intlinear(x,y)\n%\n% Does de linear regression (least mean squares) for given (x,y).\n% Returns A and B, with meaning y = A + B*x.\n\nfunction [A,B] = intlinear(x,y)\n\nmx = mean(x); my = mean(y);\nmx2 = mean(x.^2); my2 = mean(y.^2);\nmxy = mean(x.*y);\nA = (mx2*my-mx*mxy)/(mx2-mx^2);\nB = (mxy - (mx*my))/(mx2-mx^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/11392-acmus-room-acoustic-parameters/intlinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.952574122783325, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.7430010429934738}} {"text": "function cond = condition_sample1 ( n, a, m )\n\n%*****************************************************************************80\n%\n%% CONDITION_SAMPLE1 estimates the L1 condition number of a matrix.\n%\n% Discussion:\n%\n% A naive sampling method is used.\n%\n% Only \"forward\" sampling is used, that is, we only look at results\n% of the form y=A*x.\n%\n% Presumably, solving systems A*y=x would give us a better idea of\n% the inverse matrix.\n%\n% Moreover, a power sequence y1 = A*x, y2 = A*y1, ... and the same for\n% the inverse might work better too.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 October 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the dimension of the matrix.\n%\n% Input, real A(N,N), the matrix.\n%\n% Input, integer M, the number of samples to use.\n%\n% Output, real COND, an estimate of the L1 condition number.\n%\n a_norm = 0.0;\n ainv_norm = 0.0;\n seed = 123456789;\n\n for i = 1 : m\n\n [ x, seed ] = r8vec_uniform_unit ( n, seed );\n x_norm = norm ( x, 1 );\n ax = a * x;\n ax_norm = norm ( ax, 1 );\n\n if ( ax_norm == 0.0 )\n cond = 0.0;\n return\n end\n\n a_norm = max ( a_norm, ax_norm / x_norm );\n ainv_norm = max ( ainv_norm, x_norm / ax_norm );\n\n end\n\n cond = a_norm * ainv_norm;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/condition/condition_sample1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8499711775577735, "lm_q1q2_score": 0.7429404512733251}} {"text": "function b = r8pbu_ml ( n, mu, a_lu, x )\n\n%*****************************************************************************80\n%\n%% R8PBU_ML multiplies a vector times a matrix that was factored by R8PBU_FA.\n%\n% Discussion:\n%\n% The R8PBU storage format is for a symmetric positive definite band matrix.\n%\n% To save storage, only the diagonal and upper triangle of A is stored,\n% in a compact diagonal format that preserves columns.\n%\n% The diagonal is stored in row MU+1 of the array.\n% The first superdiagonal in row MU, columns 2 through N.\n% The second superdiagonal in row MU-1, columns 3 through N.\n% The MU-th superdiagonal in row 1, columns MU+1 through N.\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, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, integer MU, the number of superdiagonals of the matrix.\n% MU must be at least 0 and no more than N-1.\n%\n% Input, real A_LU(MU+1,N), the matrix, as factored by R8PBU_FA.\n%\n% Input, real X(N), the vector to be multiplied by A.\n%\n% Output, real B(N), the product A * x.\n%\n b(1:n) = x(1:n);\n%\n% Multiply U * X = Y.\n%\n for k = 1 : n\n\n ilo = max ( 1, k - mu );\n for i = ilo : k - 1\n b(i) = b(i) + a_lu(mu+1+i-k,k) * b(k);\n end\n\n b(k) = a_lu(mu+1,k) * b(k);\n\n end\n%\n% Multiply L * Y = B.\n%\n for k = n : -1 : 1\n\n jhi = min ( k + mu, n );\n for j = k + 1 : jhi\n b(j) = b(j) + a_lu(mu+1+k-j,j) * b(k);\n end\n\n b(k) = a_lu(mu+1,k) * b(k);\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/r8pbu_ml.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7429375345229271}} {"text": "% This function compute the instantaneous frequency from phase spectrogram\n% Input: \n% phase: D x T matrix of phase spectrogram, where D is FFT-bin number and\n% T is number of frames. \n% Output: \n% instantaneous frequency of the size size as phase. \n% The implementation is based on equation (3) of \n% Krawczyk, Martin, and Timo Gerkmann. \"STFT Phase Reconstruction in \n% Voiced Speech for an Improved Single-Channel Speech Enhancement.\" (2014).\n%\n% Author: Xiong Xiao, Nanyang Tech. Univ., Singapore. \n% Created: 06 Jan 2015\n% Last modified: 06 Jan 2015\n%\nfunction [instan_freq] = comp_instan_freq(phase)\n\nphase_delta = phase(:,2:end) - phase(:,1:end-1);\nphase_delta = [phase(:,1) phase_delta];\n\n[dim, nFr] = size(phase_delta);\n\nphase_delta_vec = reshape(phase_delta, dim*nFr, 1);\nphase_delta_vec = get_principal_value(phase_delta_vec);\ninstan_freq = reshape(phase_delta_vec, dim, nFr);\n\n\n\nif 0 \n subplot(3,1,1); imagesc(phase); title('Phase'); colorbar;\n subplot(3,1,2); imagesc(phase_delta); title('Phase delta');colorbar;\n subplot(3,1,3); imagesc(instan_freq); title('Phase delta principal value - Instantaneous frequency');colorbar;\nend\n\nend\n\nfunction phase_delta_vec = get_principal_value(phase_delta_vec)\nidx = find(phase_delta_vec>pi);\nphase_delta_vec(idx) = phase_delta_vec(idx) - 2*pi;\n\nidx = find(phase_delta_vec<-pi);\nphase_delta_vec(idx) = phase_delta_vec(idx) + 2*pi;\n\nend\n", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/signal/phase/comp_instan_freq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7428150284496488}} {"text": "% GAUSSIAN_DLOGPDF_COV - The gradient of the log pdf of a multivariate\n% normal distribution with respect to the covariance\n% matrix.\n%\n% Computes the gradient of the logarithm of the multivariate normal\n% probability density function N(Y|MU,COV), where Y is the random variable,\n% MU is the mean and COV is the covariance. The gradient is evaluated with\n% respect to the covariance matrix COV and returned in matrix form.\n%\n% d(LOG(N(Y|MU,COV))) / dCOV\n%\n% Usage:\n%\n% DX = GAUSSIAN_DLOGPDF_COV(INVCOV_Y, INVCOV_MU, INVCOV)\n%\n% where\n%\n% INVCOV_Y : INV(COV)*Y\n% INVCOV_MU : INV(COV)*MU\n% INVCOV : INV(COV)\n%\n% Letting the user to compute the terms allows greater efficiency and\n% flexibility.\n\n% Last modified 2010-11-19\n% Copyright (c) Jaakko Luttinen\n\nfunction dx = gaussian_dlogpdf_cov(invCov_y, invCov_mu, invCov)\n\n% $$$ if nargin == 3\n% $$$ y = varargin{1};\n% $$$ mu = varargin{2};\n% $$$ L = varargin{3};\n% $$$ invCov_y = linsolve_chol(L, y, 'lower');\n% $$$ invCov_mu = linsolve_chol(L, mu, 'lower');\n% $$$ invCov = linsolve_chol(L, eye(size(L)), 'lower');\n% $$$ end\n\ndx = - 0.5 * invCov ...\n + 0.5 * (invCov_y * invCov_y' - ...\n invCov_y * invCov_mu' - ...\n invCov_mu * invCov_y' + ...\n invCov_mu * invCov_mu');\n\n\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/distributions/gaussian_dlogpdf_cov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937033, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7427458544375495}} {"text": "function [ x, w ] = bashforth_set ( n )\n\n%*****************************************************************************80\n%\n%% BASHFORTH_SET sets abscissas and weights for Adams-Bashforth quadrature.\n%\n% Discussion:\n%\n% Adams-Bashforth quadrature formulas are normally used in solving\n% ordinary differential equations, and are not really suitable for\n% general quadrature computations. However, an Adams-Bashforth formula\n% is equivalent to approximating the integral of F(Y(X)) between X(M)\n% and X(M+1), using an explicit formula that relies only on known values\n% of F(Y(X)) at X(M-N+1) through X(M). For this reason, the formulas\n% have been included here.\n%\n% Suppose the unknown function is denoted by Y(X), with derivative\n% F(Y(X)), and that approximate values of the function are known at a\n% series of X values, which we write as X(1), X(2), ..., X(M). We write\n% the value Y(X(1)) as Y(1) and so on.\n%\n% Then the solution of the ODE Y'=F(X,Y) at the next point X(M+1) is\n% computed by:\n%\n% Y(M+1) = Y(M) + Integral ( X(M) < X < X(M+1) ) F(Y(X)) dX\n% = Y(M) + H * Sum ( 1 <= I <= N ) W(I) * F(Y(M+1-I)) approximately.\n%\n% In the documentation that follows, we replace F(Y(X)) by F(X).\n%\n% The integral:\n%\n% Integral ( 0 <= X <= 1 ) F(X) dX.\n%\n% The quadrature rule:\n%\n% Sum ( 1 <= I <= N ) W(I) * F ( 1 - I ),\n%\n% The Adams-Bashforth formulas require equally spaced data.\n%\n% Here is how the formula is applied in the case with non-unit spacing:\n%\n% Integral ( A <= X <= A+H ) F(X) dX =\n% H * Sum ( 1 <= I <= N ) W(I) * F ( A - (I-1)*H ),\n% approximately.\n%\n% The reference lists the second coefficient of the order 8 Adams-Bashforth\n% formula as\n% w(2) = -1162169.0 / 120960.0\n% but this should be\n% w(2) = -1152169.0 / 120960.0\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 April 2006\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%\n% Jean Lapidus, John Seinfeld,\n% Numerical Solution of Ordinary Differential Equations,\n% Academic Press, 1971.\n%\n% Daniel Zwillinger, editor,\n% Standard Mathematical Tables and Formulae,\n% 30th Edition,\n% CRC Press, 1996.\n%\n% Parameters:\n%\n% Input, integer N, the order. \n% N should be between 1 and 10, or 12, 14, 16, 18 or 20.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n% W(1) is the weight at X = 0, W(2) the weight at X = -1,\n% and so on. The weights are rational, and should sum to 1. Some\n% weights may be negative.\n%\n x = zeros ( n, 1 );\n w = zeros ( n, 1 );\n\n if ( n == 1 )\n\n w(1) = 1.0;\n\n elseif ( n == 2 )\n\n d = 2.0;\n\n w(1) = 3.0 / d;\n w(2) = - 1.0 / d;\n\n elseif ( n == 3 )\n\n d = 12.0;\n\n w(1) = 23.0 / d;\n w(2) = - 16.0 / d;\n w(3) = 5.0 / d;\n\n elseif ( n == 4 )\n\n d = 24.0;\n\n w(1) = 55.0 / d;\n w(2) = - 59.0 / d;\n w(3) = 37.0 / d;\n w(4) = - 9.0 / d;\n\n elseif ( n == 5 )\n\n d = 720.0;\n\n w(1) = 1901.0 / d;\n w(2) = - 2774.0 / d;\n w(3) = 2616.0 / d;\n w(4) = - 1274.0 / d;\n w(5) = 251.0 / d;\n\n elseif ( n == 6 )\n\n d = 1440.0;\n\n w(1) = 4277.0 / d;\n w(2) = - 7923.0 / d;\n w(3) = 9982.0 / d;\n w(4) = - 7298.0 / d;\n w(5) = 2877.0 / d;\n w(6) = - 475.0 / d;\n\n elseif ( n == 7 )\n\n d = 60480.0;\n\n w(1) = 198721.0 / d;\n w(2) = - 447288.0 / d;\n w(3) = 705549.0 / d;\n w(4) = - 688256.0 / d;\n w(5) = 407139.0 / d;\n w(6) = - 134472.0 / d;\n w(7) = 19087.0 / d;\n\n elseif ( n == 8 )\n\n d = 120960.0;\n\n w(1) = 434241.0 / d;\n w(2) = - 1152169.0 / d;\n w(3) = 2183877.0 / d;\n w(4) = - 2664477.0 / d;\n w(5) = 2102243.0 / d;\n w(6) = - 1041723.0 / d;\n w(7) = 295767.0 / d;\n w(8) = - 36799.0 / d;\n\n elseif ( n == 9 )\n \n d = 3628800.0;\n\n w(1) = 14097247.0 / d;\n w(2) = -43125206.0 / d;\n w(3) = 95476786.0 / d;\n w(4) = -139855262.0 / d;\n w(5) = 137968480.0 / d;\n w(6) = -91172642.0 / d;\n w(7) = 38833486.0 / d;\n w(8) = -9664106.0 / d;\n w(9) = 1070017.0 / d;\n \n elseif ( n == 10 )\n \n d = 7257600.0;\n\n w( 1) = 30277247.0 / d;\n w( 2) = -104995189.0 / d;\n w( 3) = 265932680.0 / d;\n w( 4) = -454661776.0 / d;\n w( 5) = 538363838.0 / d;\n w( 6) = -444772162.0 / d;\n w( 7) = 252618224.0 / d;\n w( 8) = -94307320.0 / d;\n w( 9) = 20884811.0 / d;\n w(10) = -2082753.0 / d;\n \n elseif ( n == 12 )\n \n d = 958003200.0;\n\n w( 1) = 4527766399.0 / d;\n w( 2) = -19433810163.0 / d;\n w( 3) = 61633227185.0 / d;\n w( 4) = -135579356757.0 / d;\n w( 5) = 214139355366.0 / d;\n w( 6) = -247741639374.0 / d;\n w( 7) = 211103573298.0 / d;\n w( 8) = -131365867290.0 / d;\n w( 9) = 58189107627.0 / d;\n w(10) = -17410248271.0 / d;\n w(11) = 3158642445.0 / d;\n w(12) = -262747265.0 / d;\n \n elseif ( n == 14 )\n \n d = 5230697472000.0;\n\n w( 1) = 27511554976875.0 / d;\n w( 2) = -140970750679621.0 / d;\n w( 3) = 537247052515662.0 / d;\n w( 4) = -1445313351681906.0 / d;\n w( 5) = 2854429571790805.0 / d;\n w( 6) = -4246767353305755.0 / d;\n w( 7) = 4825671323488452.0 / d;\n w( 8) = -4204551925534524.0 / d;\n w( 9) = 2793869602879077.0 / d;\n w(10) = -1393306307155755.0 / d;\n w(11) = 505586141196430.0 / d;\n w(12) = -126174972681906.0 / d;\n w(13) = 19382853593787.0 / d;\n w(14) = -1382741929621.0 / d;\n \n elseif ( n == 16 )\n \n d = 62768369664000.0;\n\n w( 1) = 362555126427073.0 / d;\n w( 2) = -2161567671248849.0 / d;\n w( 3) = 9622096909515337.0 / d;\n w( 4) = -30607373860520569.0 / d;\n w( 5) = 72558117072259733.0 / d;\n w( 6) = -131963191940828581.0 / d;\n w( 7) = 187463140112902893.0 / d;\n w( 8) = -210020588912321949.0 / d;\n w( 9) = 186087544263596643.0 / d;\n w(10) = -129930094104237331.0 / d;\n w(11) = 70724351582843483.0 / d;\n w(12) = -29417910911251819.0 / d;\n w(13) = 9038571752734087.0 / d;\n w(14) = -1934443196892599.0 / d;\n w(15) = 257650275915823.0 / d;\n w(16) = -16088129229375.0 / d;\n \n elseif ( n == 18 )\n \n d = 64023737057280000.0;\n\n w( 1) = 401972381695456831.0 / d;\n w( 2) = -2735437642844079789.0 / d;\n w( 3) = 13930159965811142228.0 / d;\n w( 4) = -51150187791975812900.0 / d;\n w( 5) = 141500575026572531760.0 / d;\n w( 6) = -304188128232928718008.0 / d;\n w( 7) = 518600355541383671092.0 / d;\n w( 8) = -710171024091234303204.0 / d;\n w( 9) = 786600875277595877750.0 / d;\n w(10) = -706174326992944287370.0 / d;\n w(11) = 512538584122114046748.0 / d;\n w(12) = -298477260353977522892.0 / d;\n w(13) = 137563142659866897224.0 / d;\n w(14) = -49070094880794267600.0 / d;\n w(15) = 13071639236569712860.0 / d;\n w(16) = -2448689255584545196.0 / d;\n w(17) = 287848942064256339.0 / d;\n w(18) = -15980174332775873.0 / d;\n \n elseif ( n == 20 )\n \n d = 102181884343418880000.0;\n\n w( 1) = 691668239157222107697.0 / d;\n w( 2) = -5292843584961252933125.0 / d;\n w( 3) = 30349492858024727686755.0 / d;\n w( 4) = -126346544855927856134295.0 / d;\n w( 5) = 399537307669842150996468.0 / d;\n w( 6) = -991168450545135070835076.0 / d;\n w( 7) = 1971629028083798845750380.0 / d;\n w( 8) = -3191065388846318679544380.0 / d;\n w( 9) = 4241614331208149947151790.0 / d;\n w(10) = -4654326468801478894406214.0 / d;\n w(11) = 4222756879776354065593786.0 / d;\n w(12) = -3161821089800186539248210.0 / d;\n w(13) = 1943018818982002395655620.0 / d;\n w(14) = -970350191086531368649620.0 / d;\n w(15) = 387739787034699092364924.0 / d;\n w(16) = -121059601023985433003532.0 / d;\n w(17) = 28462032496476316665705.0 / d;\n w(18) = -4740335757093710713245.0 / d;\n w(19) = 498669220956647866875.0 / d;\n w(20) = -24919383499187492303.0 / d;\n \n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BASHFORTH_SET - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of N = %d\\n', n );\n fprintf ( 1, ' Legal values are 1 through 10,\\n' );\n fprintf ( 1, ' or 12, 14, 16, 18 or 20.\\n' );\n error ( 'BASHFORTH_SET - Fatal error!' );\n\n end\n\n for i = 1 : n\n x(i) = 1 - 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/quadrule/bashforth_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7427299063067956}} {"text": "function r=rot4y(theta)\n % r = rot4y(theta)\n %\n % roty produces a 4x4 rotation matrix representing\n % a rotation by theta radians about the y axis.\n %\n %\tArgument definitions:\n %\n %\ttheta = rotation angle in radians\n c = cos(theta);\n s = sin(theta);\n r = [c 0 s 0;\n 0 1 0 0;\n -s 0 c 0;\n 0 0 0 1];\n", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/eztool/rot4y.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7426977929218824}} {"text": "function [ftAllNew,transMdl] = ftTrans_itl(ft,maSrc,target,maLabeled,param)\n%Wrapper of the Information-Theoretical Learning (ITL) algorithm\n% \n%\tA feaure-level transfer learning (domain adaptation) algorithm which\n% learns a domain-invariant subspace. Application scope:\n%\t+ two discrete domains (source and target)\n%\t+ labeled source domain\n%\t+ unlabeled target domain\n%\t+ label type: classification\n%\n% ftAll:\tAll samples in all domains. n-by-m matrix, n is the number of \n%\tsamples, m is the dimension of features.\n% maSrc:\tn-by-1 logical vector, maSrc(i)=true if i is from the source\n%\tdomain, 0 if target domain.\n% target:\tThe class labels of the source domain, nsrc-by-1 matrix, nsrc \n%\tis the number of source\tsamples. target(i)=j if the i'th sample is from\n%\tthe j'th class.\n% maLabeled:\tMask for the labeled samples. n-by-1 matrix, must be the\n% same with maSrc.\n% \n% param: Struct of hyper-parameters, please see the first cell of this\n%\tprogram (\"default parameters\") for details. You can set parameter p to \n%\tx by setting param.p = x. For parameters that are not set, default \n%\tvalues will be used.\n% \n% ftAllNew:\tAll samples in the learned subspace.\n% transMdl:\tA struct containing the model, transMdl.W is the projection\n%\tmatrix.\n% \n%\tThe ftProc_pca_tr function is a part of the PRTools toolbox.\n%\tNotice from the author of the paper: for practice use, you need to \n% properly preprocess the data and tune lambda and d.\n% \n% ref: Y. Shi and F. Sha, \"Information-theoretical learning of discriminative\n% clusters for unsupervised domain adaptation,\" in ICML, 2012.\n% \n% Copyright 2016 Ke YAN, Tsinghua Univ. http://yanke23.com , xjed09@gmail.com\n\naddpath infometric_0.1\n\n%% default parameters\npcaCoef = 0; % see ftProc_pca_tr\nlambda = 1; % regularization parameter\n\ndefParam\n\n%% sort samples\nif any(maSrc~=maLabeled)\n\terror('maLabeled must be the same with maSrc')\nend\n\nftSrc = ft(maSrc,:);\nftTar = ft(~maSrc,:);\n\n%% compute\n[~,pcaModelS] = ftProc_pca_tr(ftSrc,[],struct('pcaCoef',pcaCoef));\n[~,pcaModelT] = ftProc_pca_tr(ftTar,[],struct('pcaCoef',pcaCoef));\nd = min(size(pcaModelS.W_prj,2),size(pcaModelT.W_prj,2));\nW_prjT = pcaModelT.W_prj(:,1:d);\n\nL = infometric(W_prjT, ftSrc, target, ftTar, lambda);\n\n%% project the samples\nftAllNew = zeros(size(ft,1),d);\nftAllNew(maSrc,:) = ftSrc*L;\nftAllNew(~maSrc,:) = ftTar*L;\ntransMdl.L = L;\n\nend", "meta": {"author": "viggin", "repo": "domain-adaptation-toolbox", "sha": "2a991816a0ac39043b526c2b0cbe01bc844d8890", "save_path": "github-repos/MATLAB/viggin-domain-adaptation-toolbox", "path": "github-repos/MATLAB/viggin-domain-adaptation-toolbox/domain-adaptation-toolbox-2a991816a0ac39043b526c2b0cbe01bc844d8890/ftTrans_itl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.742697791331817}} {"text": "function v = lpp_value ( m, n, o, x )\n\n%*****************************************************************************80\n%\n%% LPP_VALUE evaluates a Legendre Product Polynomial at several points X.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 07 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, integer O(M,1), the degree of the polynomial factors.\n% 0 <= O(*).\n%\n% Input, real X(M,N), the evaluation points.\n%\n% Output, real VALUE(N,1), the value of the Legendre Product Polynomial\n% of degree O at the points X.\n%\n v = ones ( n, 1 );\n\n for i = 1 : m\n\n vi = lp_value ( n, o(i), x(i,1:n) );\n\n v(1:n) = v(1:n) .* vi(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/legendre_product_polynomial/lpp_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7426977911715027}} {"text": "function pdf = burr_pdf ( x, a, b, c, d )\n\n%*****************************************************************************80\n%\n%% BURR_PDF evaluates the Burr PDF.\n%\n% Discussion:\n%\n% PDF(X)(A,B,C,D) = ( C * D / B ) * ( ( X - A ) / B )**( - C - 1 )\n% * ( 1 + ( ( X - A ) / B )**( - C ) )**( - D - 1 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% M E Johnson,\n% Multivariate Statistical Simulation,\n% Wiley, New York, 1987.\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n% A <= X\n%\n% Input, real A, B, C, D, the parameters of the PDF.\n% 0 < B,\n% 0 < C.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( x <= a )\n pdf = 0.0;\n else\n\n y = ( x - a ) / b;\n\n pdf = ( c * d / b ) * y^( - c - 1.0 ) * ( 1.0 + y^( -c ) )^( - d - 1.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/prob/burr_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7426917729660486}} {"text": "function C1 = C1f(epsi)\n%C1F Evaluate C_{1,k}\n%\n% C1 = C1F(EPSI) evaluates C_{1,l} using Eq. (18). EPSI is a K x 1\n% array and C1 is a K x 6 array.\n\n nC1 = 6;\n C1 = zeros(length(epsi), nC1);\n eps2 = epsi.^2;\n d = epsi;\n C1(:,1) = d.*((6-eps2).*eps2-16)/32;\n d = d.*epsi;\n C1(:,2) = d.*((64-9*eps2).*eps2-128)/2048;\n d = d.*epsi;\n C1(:,3) = d.*(9*eps2-16)/768;\n d = d.*epsi;\n C1(:,4) = d.*(3*eps2-5)/512;\n d = d.*epsi;\n C1(:,5) = -7*d/1280;\n d = d.*epsi;\n C1(:,6) = -7*d/2048;\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/39108-geodesics-on-an-ellipsoid-of-revolution/geographiclib-matlab/private/C1f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983308, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7426819314733107}} {"text": "function w = cplxdual3D(x, J, Faf, af)\n\n% 3D Complex Dual-Tree Discrete Wavelet Transform\n%\n% USAGE:\n% w = cplxdual3D(x, J, Faf, af)\n% INPUT:\n% x - 3D array\n% J - number of stages\n% Faf - first stage filters\n% af - filters for remaining stages\n% OUPUT:\n% w{j}{m}{n}{p}{d} - wavelet coefficients\n% j = 1..J, m = 1..2, n = 1..2, p = 1..2, d = 1..7\n% w{J+1}{m}{n}{d} - lowpass coefficients\n% m = 1..2, n = 1..2, p = 1..2, d = 1..7\n% EXAMPLE:\n% x = rand(64,64,64);\n% J = 3;\n% [Faf, Fsf] = FSfarras;\n% [af, sf] = dualfilt1;\n% w = cplxdual3D(x, J, Faf, af);\n% y = icplxdual3D(w, J, Fsf, sf);\n% err = x - y;\n% max(max(max(abs(err))))\n%\n% WAVELET SOFTWARE AT POLYTECHNIC UNIVERSITY, BROOKLYN, NY\n% http://taco.poly.edu/WaveletSoftware/\n\n% normalization\nx = x/sqrt(8);\n\nfor m = 1:2\n for n = 1:2\n for p = 1:2\n [lo w{1}{m}{n}{p}] = afb3D(x, Faf{m}, Faf{n}, Faf{p});\n for j = 2:J\n [lo w{j}{m}{n}{p}] = afb3D(lo, af{m}, af{n}, af{p});\n end\n w{J+1}{m}{n}{p} = lo;\n end\n end\nend\n\nfor j = 1:J\n for m = 1:7\n [w{j}{1}{1}{1}{m} w{j}{2}{2}{1}{m} w{j}{2}{1}{2}{m} w{j}{1}{2}{2}{m}] = ...\n pm4(w{j}{1}{1}{1}{m}, w{j}{2}{2}{1}{m}, w{j}{2}{1}{2}{m}, w{j}{1}{2}{2}{m});\n [w{j}{2}{2}{2}{m} w{j}{1}{1}{2}{m} w{j}{1}{2}{1}{m} w{j}{2}{1}{1}{m}] = ...\n pm4(w{j}{2}{2}{2}{m}, w{j}{1}{1}{2}{m}, w{j}{1}{2}{1}{m}, w{j}{2}{1}{1}{m});\n end\nend\n\n\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/DTCWT/cplxdual3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7426794750841403}} {"text": "% SENSE_recon_demo.m\n% - demonstrates use of SENSE_recon.m, which implements the SENSE\n% reconstruction\n% - figure shows how Tikhonov regularization mitigates the increase in error\n% as noise variance increases \n% - applies complex AWGN to kspace\n% \n% 2012-06-08, Mai Le\n\n\n% number of coils\nnc = 4; \n% factor of undersampling\nnp = 2;\n% dimension to undersample\nreduced_dim = 1;\nregularizer1 = 'none';\nregularizer2 = 'tikhonov';\nfigs = 0;\n\nimage = double(imread('./data/mri/brainweb_t1.jpg','jpg'));\n\ndims = size(image);\n% introduce planar phase\n[xx,yy] = ndgrid(-dims(1)/2:dims(1)/2-1,-dims(2)/2:dims(2)/2-1);\nph_max = pi/5;\nph = ph_max*xx/(dims(1)/2)+ph_max*yy/(dims(2)/2);\nimage = image.*exp(1i*ph);\n\n% generate sensitivity maps\nsmap = mri_sensemap_sim('nx',dims(1),'ny',dims(2),'ncoil',nc);\n\nim_rep = repmat(image,[1 1 nc]);\n\n% apply sensitivity maps\nmapped_im = im_rep.*smap;\n\n% throw away k-space data\nim_fft = [];\nreduced_fft = [];\nfor ii = 1:nc\n im_fft(:,:,ii) = fft2(mapped_im(:,:,ii));\n if (reduced_dim == 1)\n reduced_fft(:,:,ii) = im_fft(1:np:end,:,ii);\n else\n reduced_fft(:,:,ii) = im_fft(:,1:np:end,ii);\n end\nend\n%% perform SENSE reconstruction for varying levels of noise\nsigmas = 0:25:150;\nfor ii = 1:length(sigmas)\n % introduce complex AWGN\n sigma = sigmas(ii);\n noisy_reduced_fft = reduced_fft + sigma*randn(size(reduced_fft)) + i*sigma*randn(size(reduced_fft));\n \n % SENSE reconstruction\n recon_im1(:,:,ii) = SENSE_recon(smap, noisy_reduced_fft, reduced_dim, np, regularizer1, figs);\n recon_im2(:,:,ii) = SENSE_recon(smap, noisy_reduced_fft, reduced_dim, np, regularizer2, figs);\n \n error1(ii) = sqrt((sum(sum((real(image)-real(recon_im1(:,:,ii))).^2))+sum(sum((imag(image)-imag(recon_im1(:,:,ii))).^2)))/prod(dims));\n error2(ii) = sqrt((sum(sum((real(image)-real(recon_im2(:,:,ii))).^2))+sum(sum((imag(image)-imag(recon_im2(:,:,ii))).^2)))/prod(dims)) ;\nend\n%% plot error as a function of noise variance\nfigure; plot(sigmas.^2, error1,'k');\nhold on; plot(sigmas.^2, error2, 'r'); legend('no regularization', 'tikhonov');\nxlabel('variance of complex AWGN in kspace');\nylabel('RMS error in reconstructed images');\ntitle('effect of Tikhonov regularization on noisy SENSE reconstruction')\n%% plot reconstructed image at sigma(ii)\nii = 4; % change as desired\nfigure; subplot(331); imshow(real(image),[]); colorbar; \ntitle('real of original image');\nsubplot(332); imshow(imag(image),[]); colorbar; \ntitle(['imag of original image, noise variance: ' num2str(sigmas(ii).^2)]);\nsubplot(334); imshow(real(recon_im1(:,:,ii)),[]); colorbar;\ntitle('real of recon image, no reg');\nsubplot(335); imshow(imag(recon_im1(:,:,ii)),[]); colorbar;\ntitle('imag of recon image, no reg');\nsubplot(336); imshow(abs(real(image)-real(recon_im1(:,:,ii)))+abs(imag(image)-imag(recon_im1(:,:,ii))),[]); colorbar;\ntitle('abs(differences), no reg');\nsubplot(337); imshow(real(recon_im2(:,:,ii)),[]); colorbar;\ntitle('real of recon image, Tikhonov');\nsubplot(338); imshow(imag(recon_im2(:,:,ii)),[]); colorbar;\ntitle('imag of recon image, Tikhonov');\nsubplot(339); imshow(abs(real(image)-real(recon_im2(:,:,ii)))+abs(imag(image)-imag(recon_im2(:,:,ii))),[]); colorbar;\ntitle('abs(differences), Tikhonov');", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/le-mai-sense/old/SENSE_recon_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7426786850093533}} {"text": "function [ table ] = integerparttable(nfinal )\n%Calculates a table of integer partions using numbers l.t. or e.t. k\n%(or equivilently using k nonnegative integers which can be zero)\n%Just calls with the largest value which has to recurrsively call all other\n%possible values. \n%\n%this table states with first row \"ways to partition 0\" and first column\n%\"using only numbers <=0\", this gives the one in the top left, these two\n%rows are essentially a definition limit to finish the reccurance relation.\n%Row k+1 column j+1 contains the ways to partition k \n% using integers <= j (or equivilently j integers >= 0)\n%\n%to obtain the partitions of nfinal using numbers g.e. 2 and l.e. k do\n% [1;table(2:nfinal,k+1)-table(1:nfinal-1,k+1)]\n%\n%use of 32 bit integers means this is only good up to 2^32-1= 4294967295, \n%for larger values change to 64 bit or dp\n% Scales as ~ exp(pi*sqrt(2*n/3))/(4*n*sqrt(3)) for n>>1 and k>n\n\n%Author: David Holdaway\n%Last update: 27/04/2012\n\nintpart(1,nfinal,1,1); %clears table\n\nfor n = 2:nfinal\n intpart(uint32(n),uint32(n));\nend\ntable = intpart(1,nfinal,2); %gets table\n\nfor n = 1:nfinal\n table(n+1,n+1:nfinal+1) = table(n+1,n+1); \nend\nend\n\nfunction p = intpart(k,n,gettable,cleartable) %#ok\npersistent table\nif nargin == 4\n table = uint32(zeros(n+1)); %clears\n% table(1,:) = uint32(ones(1,1+n)); %n=0\n% table(2,2:n+1) = uint32(ones(1,n)); %n=1 k>1\n% table(:,2) = uint32(ones(n+1,1)); %k=0\n table(1,:) = uint32(1); %n=0\n table(2,2:n+1) = uint32(1); %n=1 k>1\n table(:,2) = uint32(1); %k=0\n p = 0; return\nend\nif nargin == 3\n p = table; return\nend\nk = uint32(k);\nn = uint32(n);\nif n < 0\n p = uint32(0); return\nend\nif k < 0\n p = uint32(0); return\nend\nif table(n+1,k+1) ~= 0\n p = table(n+1,k+1); return\nend\n\nif n==0\n p = uint32(0); return\nend\n\n table(n+1,k+1) = intpart(k,n-k) + intpart(k-1,n);\n p = table(n+1,k+1);\n for lp = n+2:length(table)\n table(n+1,lp) = table(n+1,n+1);\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/36437-integer-partition-generator/integerparttable.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.8221891261650247, "lm_q1q2_score": 0.7426786787606757}} {"text": "function u = SB_ATV(g,mu)\n% Split Bregman Anisotropic Total Variation Denoising\n%\n% u = arg min_u 1/2||u-g||_2^2 + mu*ATV(u)\n% \n% g : noisy image\n% mu: regularisation parameter\n% u : denoised image\n%\n% Refs:\n% *Goldstein and Osher, The split Bregman method for L1 regularized problems\n% SIAM Journal on Imaging Sciences 2(2) 2009\n% *Micchelli et al, Proximity algorithms for image models: denoising\n% Inverse Problems 27(4) 2011\n%\n% Benjamin Trémoulhéac\n% University College London\n% b.tremoulheac@cs.ucl.ac.uk\n% April 2012\ng = g(:);\nn = length(g);\n[B Bt BtB] = DiffOper(sqrt(n));\nb = zeros(2*n,1);\nd = b;\nu = g;\nerr = 1;k = 1;\ntol = 1e-3;\nlambda = 1;\nwhile err > tol\n fprintf('it. %g ',k);\n up = u;\n [u,~] = cgs(speye(n)+BtB, g-lambda*Bt*(b-d),1e-5,100); \n Bub = B*u+b;\n d = max(abs(Bub)-mu/lambda,0).*sign(Bub);\n b = Bub-d;\n err = norm(up-u)/norm(u);\n fprintf('err=%g \\n',err);\n k = k+1;\nend\nfprintf('Stopped because norm(up-u)/norm(u) <= tol=%.1e\\n',tol);\nend\n\nfunction [B Bt BtB] = DiffOper(N)\nD = spdiags([-ones(N,1) ones(N,1)], [0 1], N,N+1);\nD(:,1) = [];\nD(1,1) = 0;\nB = [ kron(speye(N),D) ; kron(D,speye(N)) ];\nBt = B';\nBtB = Bt*B;\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/36278-split-bregman-method-for-total-variation-denoising/SplitBregmanTVdenoising/SB_ATV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.742678663950228}} {"text": "function bg = ball_grid ( n, r, c, ng )\n\n%*****************************************************************************80\n%\n%% BALL_GRID computes grid points inside a ball.\n%\n% Discussion:\n%\n% The grid is defined by specifying the radius and center of the ball,\n% and the number of subintervals N into which the horizontal radius\n% should be divided. Thus, a value of N = 2 will result in 5 points\n% along that horizontal line.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of subintervals.\n%\n% Input, real R, the radius of the ball.\n%\n% Input, real C(3), the coordinates of the center of the ball.\n%\n% Input, integer NG, the number of grid points, as determined by\n% BALL_GRID_COUNT.\n%\n% Output, real BG(3,NG), the grid points inside the ball.\n%\n bg = zeros ( 3, ng );\n\n p = 0;\n\n for i = 0 : n\n x = c(1) + r * 2 * i / ( 2 * n + 1 );\n \n for j = 0 : n\n y = c(2) + r * 2 * j / ( 2 * n + 1 );\n \n for k = 0 : n\n\n z = c(3) + r * 2 * k / ( 2 * n + 1 );\n\n if ( r * r < ( x - c(1) ).^2 ...\n + ( y - c(2) ).^2 ...\n + ( z - c(3) ).^2 )\n break\n end\n p = p + 1;\n bg(1:3,p) = [ x, y, z ]';\n if ( 0 < i )\n p = p + 1;\n bg(1:3,p) = [ 2 * c(1) - x, y, z ]';\n end\n if ( 0 < j )\n p = p + 1;\n bg(1:3,p) = [ x, 2 * c(2) - y, z ]';\n end\n if ( 0 < k )\n p = p + 1;\n bg(1:3,p) = [ x, y, 2 * c(3) - z ]';\n end\n if ( 0 < i && 0 < j )\n p = p + 1;\n bg(1:3,p) = [ 2 * c(1) - x, 2 * c(2) - y, z ]';\n end\n if ( 0 < i && 0 < k )\n p = p + 1;\n bg(1:3,p) = [ 2 * c(1) - x, y, 2 * c(3) - z ]';\n end\n if ( 0 < j && 0 < k )\n p = p + 1;\n bg(1:3,p) = [ x, 2 * c(2) - y, 2 * c(3) - z ]';\n end\n if ( 0 < i && 0 < j && 0 < k )\n p = p + 1;\n bg(1:3,p) = [ 2 * c(1) - x, 2 * c(2) - y, 2 * c(3) - z ]';\n end\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/ball_grid/ball_grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7426391431206817}} {"text": "function dif = r8mat_diff_frobenius ( m, n, a, b )\n\n%*****************************************************************************80\n%\n%% R8MAT_DIFF_FROBENIUS: Frobenius norm of the difference of two R8MAT's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 June 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows in A.\n%\n% Input, integer N, the number of columns in A.\n%\n% Input, real A(M,N), B(M,N), the matrices for which we\n% are to compute the Frobenius norm of the difference.\n%\n% Output, real DIF, the Frobenius norm of A-B.\n%\n dif = sqrt ( sum ( sum ( ( a(1:m,1:n) - b(1:m,1:n) ).^2 ) ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8mat_diff_frobenius.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7426391393048426}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% EUROPEAN OPTION PRICER (RUN SCRIPT)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Descritpion: Script to Price European options in Regime Switching Diffusion Models\n% using the PROJ method\n% Author: Justin Kirkby\n% References: (1) Efficient Option Pricing By Frame Duality with The Fast\n% Fourier Transform, SIAM J. Financial Math., 2015\n% (2) A unified approach to Bermudan and Barrier options under stochastic\n% volatility models with jumps. J. Economic Dynamics and Control, 2017\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[folder, name, ext] = fileparts(which( mfilename('fullpath')));\ncd(folder);\naddpath('../')\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Step 1) CHOOSE CONTRACT/GENERAL PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ncall = 1; %For call use 1 (else, its a put)\nS_0 = 100; %Initial price\nW = 100; %Strike %NOTE: no error handling in place for extreme values of W (increase grid if strike falls outside)\nr = .05; %Interest rate\nq = .00; %dividend yield\nT = 1; %Time (in years)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Step 2) CHOOSE MODEL PARAMETERS \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Transition Matrix (dictates how the regimes transition)\nQ = [-1 0.5 0.5;\n 0.5 -1 0.5; \n 0.5 0.5 -1]; \n\nsigma_vec = [0.15 0.25 0.35]; % Volatility in each state\n\ninitial_state = 1;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Step 3) CHOOSE PROJ PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\norder = 3; %Choose spline order from { 0,1,2,3} => {Haar, Linear, Quadratic, Cubic}, Haar is least accurate\nlogN = 8; %Uses N = 2^logN gridpoint \nL1 = 8; % determines grid witdth (usually set L1 = 8 to 15 for Levy)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% PRICE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nalpha = L1*sqrt(T)*max(sigma_vec); % Choose grid width based on the largest volatility\nN = 2^logN; % grid roughly centered on [- alph, alph]\n\ntic\nprice = PROJ_RegimeSwitching_European(order, N, alpha, r, q, T, S_0, W, call, Q, sigma_vec, initial_state);\ntoc\n\nfprintf('%.8f \\n', price)\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/REGIME_SWITCHING/European_Options/Script_EuropeanOptions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7426304511573592}} {"text": "function krn = spm_smoothkern(fwhm,x,t)\n% Generate a Gaussian smoothing kernel\n% FORMAT krn = smoothing_kernel(fwhm,x,t)\n% fwhm - full width at half maximum\n% x - position\n% t - either 0 (nearest neighbour) or 1 (linear).\n% if only two arguments are passed, then a value\n% of one is assumed.\n% krn - value of kernel at position x\n%\n% For smoothing images, one should really convolve a Gaussian\n% with a sinc function. For smoothing histograms, the\n% kernel should be a Gaussian convolved with the histogram\n% basis function used. This function returns a Gaussian\n% convolved with a triangular (1st degree B-spline) basis\n% function (by default). A Gaussian convolved with a hat\n% function (0th degree B-spline) can also be returned.\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id$\n\n\nif nargin<3, t = 1; end;\n\n% Variance from FWHM\ns = (fwhm/sqrt(8*log(2)))^2+eps;\n\n% The simple way to do it. Not good for small FWHM\n% krn = (1/sqrt(2*pi*s))*exp(-(x.^2)/(2*s));\n\nif t==0\n % Gaussian convolved with 0th degree B-spline\n % int(exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= -0.5..0.5)\n w1 = 1/sqrt(2*s);\n krn = 0.5*(erf(w1*(x+0.5))-erf(w1*(x-0.5)));\n krn(krn<0) = 0;\n\nelseif t==1\n % Gaussian convolved with 1st degree B-spline\n % int((1-t)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= 0..1)\n % +int((t+1)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t=-1..0)\n w1 = 0.5*sqrt(2/s);\n w2 = -0.5/s;\n w3 = sqrt(s/2/pi);\n krn = 0.5*(erf(w1*(x+1)).*(x+1) + erf(w1*(x-1)).*(x-1) - 2*erf(w1*x ).* x)...\n +w3*(exp(w2*(x+1).^2) + exp(w2*(x-1).^2) - 2*exp(w2*x.^2));\n krn(krn<0) = 0;\n\nelse\n error('Only defined for nearest neighbour and linear interpolation.');\n % If anyone knows a nice formula for a sinc function convolved with a\n % a Gaussian, then that could be quite useful.\nend;\nreturn;\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/spm8/spm_smoothkern.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850021922959, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.742573200375165}} {"text": "function [A,Q] = lti_disc(F,L,Q,dt)\n% LTI_DISC Equivalent discrete-time solution of an LTI SDE\n%\n% Syntax:\n% [A,Q] = lti_disc(F,L,Qc,dt)\n%\n% In:\n% F - NxN Feedback matrix\n% L - NxL Noise effect matrix (optional, default identity)\n% Qc - LxL Diagonal Spectral Density (optional, default zeros)\n% dt - Time step (optional, default 1)\n%\n% Out:\n% A - Transition matrix\n% Q - Discrete process covariance matrix\n%\n% Description:\n% Equivalent discrete-time solution of an LTI SDE of form\n%\n% dx/dt = F x + L w,\n%\n% where w(t) is a white-noise process with spectral density Qc.\n% Results in the following model:\n%\n% x[k] = A x[k-1] + q, q ~ N(0,Q).\n%\n% Can be used for integrating the model exactly over time steps, \n% which are multiples of dt.\n%\n% Copyright: \n% 2019 - 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 % Check number of arguments and defaults\n if nargin < 1\n error('Too few arguments');\n end\n if nargin < 2\n L = [];\n end\n if nargin < 3\n Q = [];\n end\n if nargin < 4\n dt = [];\n end\n if isempty(L)\n L = eye(size(F,1));\n end\n if isempty(Q)\n Q = zeros(size(F,1),size(F,1));\n end\n if isempty(dt)\n dt = 1;\n end\n\n % Closed-form integration of the transition matrix\n A = expm(F*dt);\n\n % Closed-form integration of the covariance matrix\n n = size(F,1);\n Phi = [F L*Q*L'; zeros(n,n) -F'];\n AB = expm(Phi*dt)*[zeros(n,n);eye(n)];\n Q = AB(1:n,:)*A'; % A' = inv(AB((n+1):(2*n),:));", "meta": {"author": "AaltoML", "repo": "SDE", "sha": "91111b0f1849ef0a0540c683bb2cf454ab4f2aff", "save_path": "github-repos/MATLAB/AaltoML-SDE", "path": "github-repos/MATLAB/AaltoML-SDE/SDE-91111b0f1849ef0a0540c683bb2cf454ab4f2aff/matlab/lti_disc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7425323852996317}} {"text": "%% Gauss Laguerre Quadrature\n% solution for class exercise:\n\nclear\nclc\nclose all\n\n%% Aproximate solution\n% Tau(m) is a function of m.\n\nm=5.5 % Exponent value of f(x).\nn=9; % number of points used to compute approximate solution.\n\n[x w]=GaussLaguerre(n,0); % built in function to generate weight and points\n\n% Initalizing row vectors:\nl=length(x);\nf=zeros(1,l);\nt=zeros(1,l);\n\nfor i=1:l\n f(i)=x(i)^(m-1);\n t(i)=w(i)*f(i);\nend\n\nGamma=sum(t)\n\n%% Exact Solution\n% Gamma=(m-1)! \n% Carefull! m can only be an integer number!\n\nGamma2=factorial(floor(m)-1) \n% I'm using a round to the floor in case m is a rational number.\n\n%% Exact solution of the Gamma function\n% this time using the Matlab's gamma function.\n\nGamma3=gamma(m)\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/NumericalMethods/GLaguerre_Prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7425323722542799}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Solve the following exercises:\n% A) Cart and pendulum.\n% Simulate a cart and pendulum system. Then, try to control it\n% using a P controller.\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 cart_and_pendulum_controlled()\nclose all;\n\n%uncomment to execute each of the exercises\nexerciseA()%\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Simulate a cart and pendulum\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction exerciseA()\nglobal L \nL = 0.8; % m length of the pendulum\nt0 = 0;\ntfinal = 10;\n[t, x] = runge_kutta(@fcart_and_pendulum, [0 0 0.01 0.01]', [t0 tfinal], 0.01);\nx = x(:, 1:length(t)); \n\n% animate the system\nclose all\nfigure\nfor i=1:length(t)\n %cart position\n posx_cart = x(1,i);\n posy_cart = 0;\n \n theta = x(3,i);\n %pendulum position \n posx_pend = L*sin(theta) + posx_cart;\n posy_pend = L*cos(theta);\n plot(posx_cart, posy_cart, 'rs', 'MarkerSize', 30), hold on\n plot(posx_pend, posy_pend, 'bo', 'MarkerSize', 12)\n xlim([-5 5])\n ylim([-0.9 0.9])\n line([posx_cart posx_pend], [posy_cart posy_pend])\n pause(0.05); \n hold off\nend\n% plot results\nfigure\nplot(t, x(1,:), 'r'), hold\nplot(t, x(2,:), 'g')\nplot(t, x(3,:), 'b') \nplot(t, x(4,:), 'k')\nlegend('Position x (m)', 'Speed xd (m/s)', '\\theta (rad)', '\\thetad (rad/s)')\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Helper function to solve a constant acceleration on x axis on a ramp.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction xd = fcart_and_pendulum(t, x)\n% We must return the solution of\n% [dx1/dt; dx2/dt]\nglobal L\nM = 5; % kg mass of the cart\nm = 5; % kg mass of the pendulum (centered at the tip)\ng = 9.81; %m/s^ 2\n\n% Computing a simple P controller\nref = 0; % theta reference\ntheta = x(3); \nerror = ref-theta;\nk = 1000;\n% the control action!\nF = k*error;\n% if F > 20\n% F=20;\n% elseif F<-20\n% F=-20\n% end\n\n% compute xdd and thetadd to simulate the system\nnum = F + m*sin(x(3))*(g*cos(x(3)) - L*x(4)^2);\nden = M + m*(1-cos(x(3))^2);\nxdd = num/den;\n\nnum = F + g*(M+m)*tan(x(3))-m*L*x(4)^2*sin(x(3));\nden = L*((M+m)/cos(x(3)) - m*cos(x(3)));\nthetadd = num/den;\n\nxd(1) = x(2);\nxd(2) = xdd;\nxd(3) = x(4);\nxd(4) = thetadd;\nxd = xd(:);\n\n\n\n\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/control/cart_and_pendulum_controlled.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7424875219411914}} {"text": "function [out, bestL] = Peubseparate(k, d, PeCh, e)\n%Excess-distortion probability for the transmission of a Gaussian source\n%over a Gaussian channel as achieved by a separated scheme - optimized with respect to the number of\n%messages allowable between the channel encoder and the channel decoder (2^L)\n\n%PeCh - array of channel error probabilities\n%k - source blocklength\n%d - target distortion\n%e - excess distortion probability\n\n%outputs: \n%out - the excess distortion probability\n%bestL - the optimal length of messages exchanged between the encoder and\n%the decoder\n\n%\n% Created in 2012 by Victoria Kostina (vkostina@caltech.edu)\n%\n\nKbig = 20;\ntol = 1e-3;\n\nout = Inf;\nbestL = NaN;\nfor L = find(PeCh <= e)\n cur = PeubSource(L, k, d) + PeCh(L);\n if out > cur\n out = cur;\n bestL = L;\n end\nend\n%fprintf('ASeparate: k = %i, Peub = %f\\n', k, out);\n\n function out = PeubSource(L, k, d)\n %achievability via sphere covering\n \n r0 = sqrt( max( 0, 1 - d) );\n a = r0 - sqrt(d);\n b = r0 + sqrt(d);\n \n out = chi2cdf((a^2 + tol)*k, k) + 1 - chi2cdf((b^2 - tol)*k, k)... %nontypical source realization\n + quad(@Pes, a^2 + tol, b^2- tol); %source error\n \n function out = logPdball(x)\n %x - distance squared from the origin (x*k central chi square k)\n cosa = (r0^2 + x - d)./(2*r0.*sqrt(x));\n sina = (1 - cosa.^2).^(1/2);\n out = loggamma(k/2+1, 'LB') - loggamma((k-1)/2 +1, 'UB')- .5*log(pi)-log(k) + (k-1)*log(sina);\n end\n \n function out = Pes(x)\n %source error conditioned on the distance squared from the origin (x*k central chi square k)\n if k < Kbig\n out = (1 - exp(logPdball(x))).^exp(L);\n else\n out = exp( - exp( logPdball(x) + L));\n end\n out = out.*chi2pdf(k*x, k).*k;\n end\n end\nend\n\n\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/jscc/GMS-AWGN/Peubseparate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7424875142754014}} {"text": "%==============================================================================\n% Copyright (C) 2005, Jan Modersitzki and Nils Papenberg, see copyright.m,\n% this file is part of the FLIRT Package, all rights reserved;\n% http://www.math.uni-luebeck.de/SAFIR/FLIRT-MATLAB.html\n%==============================================================================\n% function [B,Bstr] = getDiffusiveMatrix(Omega,m);\n% generates the elastic matrix B for the domain Omega with resolution m,\n% by default, mu = 1, lambda = 0;\n%==============================================================================\nfunction [B,Bstr] = getDiffusiveMatrixStg(Omega,m)\n\nBstr = 'diffusive-stg';\nh = Omega./m;\n\nd11 = spdiags(ones(m(1),1)*[-1,1],[0,1],m(1),m(1)+1)/h(1);\nd12 = spdiags(ones(m(2)-1,1)*[-1,1],[0,1],m(2)-1,m(2))/h(2);\nd21 = spdiags(ones(m(1)-1,1)*[-1,1],[0,1],m(1)-1,m(1))/h(1);\nd22 = spdiags(ones(m(2),1)*[-1,1],[0,1],m(2),m(2)+1)/h(2);\n\nD11 = sparse(kron(speye(m(2)),d11));\nD12 = sparse(kron(d12,speye(m(1)+1)));\nD21 = sparse(kron(speye(m(2)+1),d21));\nD22 = sparse(kron(d22,speye(m(1))));\n\n\n% build the diffusive operator \n%\n% | \\nabla 0 |\n% B = | |\n% | 0 \\nabla |\n% | |\n% B[U] = [\\partial_1 U1,\\partial_2 U1, \\partial_1 U2,\\partial_2 U2]\n\nn1 = (m(1)+1)*m(2);\nn2 = m(1)*(m(2)+1);\nj1 = size(D11,1);\nj2 = size(D12,1);\nj3 = size(D21,1);\nj4 = size(D22,1);\n\nB = [ D11,sparse(j1,n2);\n D12,sparse(j2,n2);\n sparse(j3,n1),D21;\n sparse(j4,n1),D22]; \nreturn;\n%==============================================================================\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/solvers/getDiffusiveMatrixStg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990283, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.742487513794335}} {"text": "function bubblesort_complexity ( )\n\n%*****************************************************************************80\n%\n%% BUBBLESORT_COMPLEXITY measures the complexity of the bubblesort algorithm.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 December 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BUBBLESORT_COMPLEXITY\\n' );\n fprintf ( 1, ' How does the time requirement increase with vector length\\n' );\n fprintf ( 1, ' for the bubblesort algorithm?\\n' );\n%\n% Get some data for N = 1 : 200.\n% Do the loop twice to avoid startup anomalies.\n%\n for i = 1 : 2\n\n data_size = zeros ( 200, 1 );\n data_time = zeros ( 200, 1 );\n\n for n = 1 : 200\n a = rand ( n, 1 );\n tic;\n a_heap = r8vec_sort_bubble_a ( n, a );\n data_size(n) = n;\n data_time(n) = toc;\n end\n\n end\n\n figure ( 1 )\n plot ( data_size, data_time, 'r-' )\n grid on\n xlabel ( 'Vector length N' );\n ylabel ( 'Elapsed time T' );\n title ( 'T(N), time to heap sort a vector of length N' );\n\n filename = 'bubblesort_1to200.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Plot saved as \"%s\".\\n', filename );\n%\n% Get some data for N = 1, 2, 4, ..., 2^12.\n% Do the loop twice to avoid startup anomalies.\n%\n for i = 1 : 2\n\n data_size = zeros ( 13, 1 );\n data_time = zeros ( 13, 1 );\n\n n = 1;\n\n for nlog = 0 : 12\n a = rand ( n, 1 );\n tic;\n a_heap = r8vec_sort_bubble_a ( n, a );\n data_size(nlog+1) = n;\n data_time(nlog+1) = toc;\n n = n * 2;\n end\n\n end\n\n figure ( 2 )\n loglog ( data_size, data_time, 'r-o' )\n grid on\n xlabel ( 'Vector length N' );\n ylabel ( 'Elapsed time T' );\n title ( 'T(N), time to heap sort a vector of length N' );\n\n filename = 'bubblesort_powersoftwo.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Plot saved as \"%s\".\\n', filename );\n!\n! Terminate.\n!\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BUBBLESORT_COMPLEXITY\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n return\nend\nfunction a = r8vec_sort_bubble_a ( n, a )\n\n%*****************************************************************************80\n%\n%% R8VEC_SORT_BUBBLE_A ascending sorts an R8VEC using bubble sort.\n%\n% Discussion:\n%\n% Bubble sort is simple to program, but inefficient. It should not\n% be used for large arrays.\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 N, the number of entries in the array.\n%\n% Input, real A(N), an unsorted array.\n%\n% Output, real A(N), the array has been sorted.\n%\n for i = 1 : n-1\n for j = i + 1 : n\n if ( a(j) < a(i) )\n t = a(i);\n a(i) = a(j);\n a(j) = t;\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/complexity/bubblesort_complexity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.9005297881200701, "lm_q1q2_score": 0.742452523872958}} {"text": "function [ x, seed ] = triangle01_sample ( n, seed )\n\n%*****************************************************************************80\n%\n%% TRIANGLE01_SAMPLE samples the interior of the unit triangle in 2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Reuven Rubinstein,\n% Monte Carlo Optimization, Simulation, and Sensitivity\n% of Queueing Networks,\n% Krieger, 1992,\n% ISBN: 0894647644,\n% LC: QA298.R79.\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n%\n% Input/output, integer SEED, a seed for the random\n% number generator.\n%\n% Output, real X(2,N), the points.\n%\n m = 2;\n\n for j = 1 : n\n\n [ e, seed ] = r8vec_uniform_01 ( m + 1, seed );\n\n e(1:m+1) = - log ( e(1:m+1) );\n\n x(1:m,j) = e(1:m) / sum ( e(1:m+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/triangle_monte_carlo/triangle01_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.8397339636614178, "lm_q1q2_score": 0.7423578100929894}} {"text": "function npartitions = npart_enum ( n, npart )\n\n%*****************************************************************************80\n%\n%% NPART_ENUM enumerates the number of partitions of N with NPART parts.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 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 integer to be partitioned.\n% Normally N must be positive, but for this routine any\n% N is allowed.\n%\n% Input, integer NPART, the number of parts of the partition.\n% Normally, 1 <= NPART <= N is required,\n% but for this routine any value of NPART is allowed.\n%\n% Output, integer NPARTITIONS is the number of partitions of N\n% with NPART parts.\n%\n if ( n <= 0 )\n\n npartitions = 0;\n\n elseif ( npart <= 0 || n < npart )\n\n npartitions = 0;\n\n else\n\n offset = 1;\n\n p = npart_table ( n, npart );\n\n npartitions = p(n+offset,npart+offset);\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/combo/npart_enum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7423577998309355}} {"text": "function [x_max y_max A]=crit_interp_g(y,x);\n%fits a gaussian to three points: y=[y(x(1)) y(x(2)) y(x(3))]. Returns the \n%position (x_max) and value (y_max) of the interpolated critical point \n%(peak or trough). Things go sideways (complex) if y is mixed sign and\n%rounding errors can cause spurious complex results if y is negative.\n%If x is omitted, it is assumed to be [-1 0 1].\n%y=A(1)*exp(-A(2)*(x-A(3)).^2)\n\n% Copyright Travis Wiens 2009 travis.mlfx@nutaksas.com\n\nif nargin<2\n x=[-1 0 1];\nend\n\nlny=log(y);\n\n%lny=1/denom*(a*x^2+b*x+c)\na =(x(3) * (lny(2) - lny(1)) + x(2) * (lny(1) - lny(3)) + x(1) * (lny(3) - lny(2)));\nb =(x(3)*x(3) * (lny(1) - lny(2)) + x(2)*x(2) * (lny(3) - lny(1)) + x(1)*x(1) * (lny(2) - lny(3)));\nc =(x(2) * x(3) * (x(2) - x(3)) * lny(1) + x(3) * x(1) * (x(3) - x(1)) * lny(2) + x(1) * x(2) * (x(1) - x(2)) * lny(3));\n\n%y=A*exp(-B*(x-C)^2);\nC=-b/(2*a);\nx_max=C;\n\nif nargout>1\n denom = (x(1) - x(2)) * (x(1) - x(3)) * (x(2) - x(3));\n A=exp(c/denom-b*b/(4*a*denom));\n y_max=A;\n if nargout>2\n B=-a/denom;\n A=[A B C];\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/24465-peak-interpolation/peak_interp_0_01/crit_interp_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7423275914457503}} {"text": "function M = specialeuclideanfactory(n, k)\n% Returns a manifold structure to optimize over the special Euclidean group\n% \n% function M = specialeuclideanfactory(n)\n% function M = specialeuclideanfactory(n, k)\n%\n% The special Euclidean group (the manifold of rigid transformations):\n% This is a product manifold of the rotations group SO(n) and the\n% translation group R^n, copied k times.\n%\n% Points on the manifold are represented as structures X with two fields.\n% X.R is a 3D array of size nxnxk such that each slice X.R(:, :, i)\n% corresponds to a rotation matrix (orthogonal with determinant 1).\n% X.t is a matrix of size nxk such that each column X.t(:, i) corresponds\n% to a translation vector.\n%\n% Tangent vectors are represented as structures with the same fields. Note\n% that rotational components of the tangent vectors are represented in the\n% Lie algebra, i.e., each slice Xdot.R(:, :, i) is a skew-symmetric matrix.\n% Use M.tangent2ambient(X, Xdot) to obtain a representation in the ambient\n% space.\n%\n% This is a description of SE(n)^k with the induced metric from the\n% embedding space (R^nxn)^k x (R^n)^k, i.e., this manifold is a Riemannian\n% submanifold of the embedding Euclidean space with the usual inner\n% product.\n%\n% By default, k = 1.\n%\n% This is a test geometry: it may not be the \"appropriate\" geometry to give\n% to SE(n).\n%\n% See rotationsfactory and euclideanfactory for details.\n%\n% See also: rotationsfactory euclideanfactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Sep. 23, 2014.\n% Contributors: \n% Change log:\n\n \n if ~exist('k', 'var') || isempty(k)\n k = 1;\n end\n \n elements = struct();\n elements.R = rotationsfactory(n, k);\n elements.t = euclideanfactory(n, k);\n \n M = productmanifold(elements);\n\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/manopt/manifolds/specialeuclidean/specialeuclideanfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248191350352, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.742327589509553}} {"text": "function y = convolve2(x, m, shape, tol)\n%CONVOLVE2 Two dimensional convolution.\n% Y = CONVOLVE2(X, M) performs the 2-D convolution of matrices X and\n% M. If [mx,nx] = size(X) and [mm,nm] = size(M), then size(Y) =\n% [mx+mm-1,nx+nm-1]. Values near the boundaries of the output array are\n% calculated as if X was surrounded by a border of zero values.\n%\n% Y = CONVOLVE2(X, M, SHAPE) where SHAPE is a string returns a\n% subsection of the 2-D convolution with size specified by SHAPE:\n%\n% 'full' - (default) returns the full 2-D convolution,\n% 'same' - returns the central part of the convolution\n% that is the same size as X (using zero padding),\n% 'valid' - returns only those parts of the convolution\n% that are computed without the zero-padded\n% edges, size(Y) = [mx-mm+1,nx-nm+1] when\n% size(X) > size(M),\n% 'wrap' - as for 'same' except that instead of using\n% zero-padding the input X is taken to wrap round as\n% on a toroid.\n% 'reflect' - as for 'same' except that instead of using\n% zero-padding the input X is taken to be reflected\n% at its boundaries.\n%\n% CONVOLVE2 is fastest when mx > mm and nx > nm - i.e. the first\n% argument is the input and the second is the mask.\n%\n% If the rank of the mask M is low, CONVOLVE2 will decompose it into a\n% sum of outer product masks, each of which is applied efficiently as\n% convolution with a row vector and a column vector, by calling CONV2.\n% The function will often be faster than CONV2 or FILTER2 (in some\n% cases much faster) and will produce the same results as CONV2 to\n% within a small tolerance.\n%\n% Y = CONVOLVE2(... , TOL) where TOL is a number in the range 0.0 to\n% 1.0 computes the convolution using a reduced-rank approximation to\n% M, provided this will speed up the computation. TOL limits the\n% relative sum-squared error in the effective mask; that is, if the\n% effective mask is E, the error is controlled such that\n%\n% sum(sum( (M-E) .* (M-E) ))\n% -------------------------- <= TOL\n% sum(sum( M .* M ))\n%\n% See also CONV2, FILTER2.\n\n% Copyright David Young, Feb 2002, revised Jan 2005, Jan 2009, Apr 2011\n\n% Deal with optional arguments\nerror(nargchk(2,4,nargin));\nif nargin < 3\n shape = 'full'; % shape default as for CONV2\n tol = 0;\nelseif nargin < 4\n if isnumeric(shape)\n tol = shape;\n shape = 'full';\n else\n tol = 0;\n end\nend;\n\n% Set up to do the wrap & reflect operations, not handled by conv2\nif ismember(shape, {'wrap' 'reflect'})\n x = extendarr(x, m, shape);\n shape = 'valid';\nend\n\n% do the convolution itself\ny = doconv(x, m, shape, tol);\nend\n\n%-----------------------------------------------------------------------\n\nfunction y = doconv(x, m, shape, tol)\n% Carry out convolution\n[mx, nx] = size(x);\n[mm, nm] = size(m);\n\n% If the mask is bigger than the input, or it is 1-D already,\n% just let CONV2 handle it.\nif mm > mx || nm > nx || mm == 1 || nm == 1\n y = conv2(x, m, shape);\nelse\n % Get svd of mask\n if mm < nm; m = m'; end % svd(..,0) wants m > n\n [u,s,v] = svd(m, 0);\n s = diag(s);\n rank = trank(m, s, tol);\n if rank*(mm+nm) < mm*nm % take advantage of low rank\n if mm < nm; t = u; u = v; v = t; end % reverse earlier transpose\n vp = v';\n % For some reason, CONV2(H,C,X) is very slow, so use the normal call\n y = conv2(conv2(x, u(:,1)*s(1), shape), vp(1,:), shape);\n for r = 2:rank\n y = y + conv2(conv2(x, u(:,r)*s(r), shape), vp(r,:), shape);\n end\n else\n if mm < nm; m = m'; end % reverse earlier transpose\n y = conv2(x, m, shape);\n end\nend\nend\n\n%-----------------------------------------------------------------------\n\nfunction r = trank(m, s, tol)\n% Approximate rank function - returns rank of matrix that fits given\n% matrix to within given relative rms error. Expects original matrix\n% and vector of singular values.\nif tol < 0 || tol > 1\n error('Tolerance must be in range 0 to 1');\nend\nif tol == 0 % return estimate of actual rank\n tol = length(m) * max(s) * eps;\n r = sum(s > tol);\nelse\n ss = s .* s;\n t = (1 - tol) * sum(ss);\n r = 0;\n sm = 0;\n while sm < t\n r = r + 1;\n sm = sm + ss(r);\n end\nend\nend\n\n%-----------------------------------------------------------------------\n\nfunction y = extendarr(x, m, shape)\n% Extend x so as to wrap around on both axes, sufficient to allow a\n% \"valid\" convolution with m to return the cyclical convolution.\n% We assume mask origin near centre of mask for compatibility with\n% \"same\" option.\n\n[mx, nx] = size(x);\n[mm, nm] = size(m);\n\nmo = floor((1+mm)/2); no = floor((1+nm)/2); % reflected mask origin\nml = mo-1; nl = no-1; % mask left/above origin\nmr = mm-mo; nr = nm-no; % mask right/below origin\n\nif strcmp(shape, 'wrap')\n y = exindex(x, 1-ml:mx+mr, 1-nl:nx+nr, 'circular');\nelse\n y = exindex(x, 1-ml:mx+mr, 1-nl:nx+nr, 'symmetric');\nend\n\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22619-fast-2-d-convolution/convolve2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.742248089372509}} {"text": "% This routine do:\n% 1. Discretize schrodinger equation over the specified set of points:\n% v(x)=2m*V(x)/hbar^2; ee=2m*E/hbar^2.\n% [ d^2 2m ] 2m*E\n% [ - ----- + ------ V(x) ] phi(x) = ------ phi(x)\n% [ d x^2 hbar^2 ] hbar^2\n%\n% 2. Find eigen values and eigen vectors.\n% 3. Plot the found eigen values and eigen vectors.\n%\n% Usage:\n% [ee,ev] = qm1d_fast(NPTS,NSTM,a,b,f_pot_handle)\n% NPTS - number of points for discretization of schrodinger equation\n% NSTM - number of eigen values and eigen vector to find\n% a - the start point of te interval for x\n% b - the end point of the interval for y\n% f_pot_handle - handle to function which defines the potential\n%\n% Examples:\n%\n% 1. Harmonic oscillator - symetric at x=L/2\n% NPTS=1000;\n% NSTM=5;\n% L=10d0;\n% f_pot = @(x) {4d0*(x-L/2).^2}; \n% qm1d_fast(NPTS,NSTM,0,L,f_pot);\n% \n% 2. Harmonic oscillator - symetric at x=0\n% NPTS=1000;\n% NSTM=5;\n% L=10d0;\n% f_pot = @(x) {4d0*x.^2}; \n% qm1d_fast(NPTS,NSTM,-L/2,L/2,f_pot);\n%\n% 3. Barrier - defined with heaviside function\n% NPTS=1000;\n% NSTM=5;\n% L=100d0;\n% bb=3d0;\n% aa=1d0;\n% f_pot = @(x) {heaviside(x-aa)-heaviside(x-bb)};\n% qm1d_fast(NPTS,NSTM,0,L,f_pot);\n%\n% If you don't have heaviside defined in your Matlab version define this function as:\n% function [y]=heaviside(x)\n% y=zeros(1,length(x))\n% ipos = find(x>0);\n% y(ipos)=1;\n%\n% 4.Barrier\n% NPTS=1000;\n% NSTM=5;\n% L=100d0;\n% bb=3d0;\n% aa=1d0;\n% pot_dat = [zeros(1,int16(aa/L*NPTS)), ones(1,int16((bb-aa)/L*NPTS)), zeros(1,int16((L-bb)/L*NPTS))];\n% f_pot = @(x) {pot_dat(int16(x/L*(NPTS-1)))};\n% qm1d_fast(NPTS,NSTM,0,L,f_pot);\n% \n% 5. Harmonic oscillator - with potential defined in file\n% Define the potential in file: \n% NPTS=1000;\n% L=10d0;\n% dx=L/(NPTS-1);\n% pot_dat=[[0:NPTS-1]*dx; 4d0*([0:NPTS-1]-((NPTS-1)/2)).^2*dx^2]';\n% save('pot.dat','-ascii','pot_dat');\n% clear\n%\n% pot_dat=load('pot.dat');\n% f_pot = @(x) {spline(pot_dat(:,1),pot_dat(:,2),x)};\n% %It is not obligatory the NPTS to be the same as the number of points for the potential\n% NPTS=10000; \n% NSTM=5;\n% L=10d0;\n% qm1d_fast(NPTS,NSTM,0,L,f_pot);\n%\n%\n% See also: http://iffwww.iff.kfa-juelich.de/~ekoch/DFT/qm1d.html\nfunction [ee,ev] = qm1d_fast(NPTS,NSTM,a,b,f_pot_handle)\n%pot_dat=load(pot_filename);\nj=1:NPTS; % indexes for main diagonal\nL=b-a;\nh=L/(NPTS-1); % space step\nx=j*h+a;\nV=cell2mat(f_pot_handle(x));\n\nmain_diag=2/h^2+V(j);\nsub_diag=-1/h^2*ones(1,NPTS-1);\n\n[ee,ev] = trideigs(main_diag,sub_diag,'I',1,NSTM);\n\n% average spacing of energy levels (for adjusting scale of ev)\nde0=(ee(NSTM)-ee(1))/(NSTM-1);\n\n% plot potential\nplot(x,V(j),'r'); hold on;\n\n% plot eign vectors\nde=0.15*sqrt(NPTS)*de0;\nfor n=1:NSTM\n plot(x,ee(n)+de*ev(:,n)); hold on;\n plot(x,ones(length(j),1)*ee(n)); hold on;\nend\n\n% set up plotting options\nxlim([0 NPTS]*h+a); ylim([min(V) ee(NSTM)+de0]);\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/42735-matlab-version-of-qm1d-1d-schr%C3%B6dinger-equation-solver/qm1d_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7421937705341307}} {"text": "%% CUBESTOKES Stokes equations on the unit cube\n%\n% SQUARESTOKE computes CR-P0 approximations of the Stokes equations in\n% the unit cube.\n%\n% Added by Shuhao Cao. Apr, 2020.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all; clear;\n\n%% Set up\nmaxIt = 4;\nN = zeros(maxIt,1); \nh = zeros(maxIt,1);\nerruH1 = zeros(maxIt,1);\nerruL2 = zeros(maxIt,1);\nerrp = zeros(maxIt,1);\n\n%% Generate initial mesh\n[node,elem] = cubemesh([-0.5,0.5,-0.5,0.5,-0.5,0.5],0.25);\nbdFlag = setboundary3(node,elem,'Dirichlet');\n\n%% PDE and options\npde.exactu = @(p)[(1-cos(2*pi*p(:,1))).*sin(2*pi*p(:,2)).*sin(pi*p(:,3)),... \n -(1-cos(2*pi*p(:,2))).*sin(2*pi*p(:,1)).*sin(pi*p(:,3)), 0*p(:,3)];\npde.f = @(p) [-pi^2*(9*cos(2*pi*p(:,1))-5).*sin(2*pi*p(:,2)).*sin(pi*p(:,3))+ p(:,1).^2,... \n pi^2*(9*cos(2*pi*p(:,2))-5).*sin(2*pi*p(:,1)).*sin(pi*p(:,3)), 0*p(:,3)];\npde.g = @(p) zeros(size(p,1),1);\npde.exactp = @(p) p(:,1).^3/3;\npde.g_D = @(p) pde.exactu(p);\n% solver\noption.solver = 'diag'; % diagonal preconditioner\n\n%% Finite Element Method \nfor k = 1:maxIt\n \n [soln,eqn] = Stokes3CRP0(node,elem,bdFlag,pde,option);\n uh = soln.u;\n uhvec = reshape(uh,size(uh,1)/3,3);\n ph = soln.p;\n N(k) = length(uh)+length(ph);\n h(k) = 1./((size(node,1)).^(1/3)-1);\n % compute error;\n uI = pde.exactu((node(eqn.face(:,1),:)+node(eqn.face(:,2),:)+node(eqn.face(:,3),:))/3);\n erruH1(k) = sqrt((uh-uI(:))'*eqn.A*(uh-uI(:)));\n erruL2(k) = getL2error3(node,elem,pde.exactu,uhvec);\n errp(k) = getL2error3(node,elem,pde.exactp,ph);\n fprintf('Number of Dof %d \\n', N(k));\n \n if k < maxIt\n [node,elem,bdFlag] = uniformrefine3(node,elem,bdFlag); \n end \nend\n\n%% Plot convergence rates and display error\nfigure(2);\nshowrateh3(h,erruH1,1,'-*','| u_I-u_h |_1',...\n h,erruL2,1,'-*','|| u-u_h ||',...\n h,errp,1,'-+','|| p-p_h||');\n\nfprintf('\\n');\ndisp('Table: Error')\ncolname = {'#Dof','h','|u_I-u_h|_1','||u-u_h||','||p-p_h||'};\ndisptable(colname,N,[],h,'%0.3e',erruH1,'%0.5e',erruL2,'%0.5e',errp,'%0.5e');\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/fem/Stokes/cubeStokes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7421352832041525}} {"text": "function [ p4, flag ] = line_exp_perp_2d ( p1, p2, p3 )\n\n%*****************************************************************************80\n%\n%% LINE_EXP_PERP_2D computes a line perpendicular to a line and through a point.\n%\n% Discussion:\n%\n% The explicit form of a line in 2D is:\n%\n% ( P1, P2 ) = ( (X1,Y1), (X2,Y2) ).\n%\n% The input point P3 should NOT lie on the line (P1,P2). If it\n% does, then the output value P4 will equal P3.\n%\n% P1-----P4-----------P2\n% |\n% |\n% P3\n%\n% P4 is also the nearest point on the line (P1,P2) to the point P3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 July 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P1(2,1), P2(2,1), two points on the line.\n%\n% Input, real P3(2,1), a point (presumably not on the\n% line (P1,P2)), through which the perpendicular must pass.\n%\n% Output, real P4(2,1), a point on the line (P1,P2),\n% such that the line (P3,P4) is perpendicular to the line (P1,P2).\n%\n% Output, logical FLAG, is TRUE if the value could not be computed.\n%\n dim_num = 2;\n\n bot = sum ( ( p2(1:dim_num,1) - p1(1:dim_num,1) ).^2 );\n\n if ( bot == 0.0 )\n p4(1:2,1) = Inf;\n flag = 1;\n end\n%\n% (P3-P1) dot (P2-P1) = Norm(P3-P1) * Norm(P2-P1) * Cos(Theta).\n%\n% (P3-P1) dot (P2-P1) / Norm(P3-P1)**2 = normalized coordinate T\n% of the projection of (P3-P1) onto (P2-P1).\n%\n t = sum ( ( p1(1:dim_num,1) - p3(1:dim_num,1) ) ...\n .* ( p1(1:dim_num,1) - p2(1:dim_num,1) ) ) / bot;\n\n p4(1:dim_num,1) = p1(1:dim_num,1) + t * ( p2(1:dim_num,1) - p1(1:dim_num,1) );\n flag = 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/geometry/line_exp_perp_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.7420535644381304}} {"text": "function a = maxij ( m, n )\n\n%*****************************************************************************80\n%\n%% MAXIJ returns the MAXIJ matrix.\n%\n% Discussion:\n%\n% This matrix is occasionally known as the \"Boothroyd MAX\" matrix.\n%\n% Formula:\n%\n% A(I,J) = max(I,J)\n%\n% Example:\n%\n% N = 5\n%\n% 1 2 3 4 5\n% 2 2 3 4 5\n% 3 3 3 4 5\n% 4 4 4 4 5\n% 5 5 5 5 5\n%\n% Properties:\n%\n% A is integral, therefore det ( A ) is integral, and \n% det ( A ) * inverse ( A ) is integral.\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% The inverse of A is tridiagonal.\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% 16 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Gregory, David Karney,\n% Example 3.13,\n% A Collection of Matrices for Testing Computational Algorithms,\n% Wiley, 1969, page 42,\n% LC: QA263.G68.\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns \n% of the matrix.\n%\n% Output, real A(M,N), the matrix.\n%\n for i = 1 : m\n for j = 1 : n\n a(i,j) = max ( i, j );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/maxij.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.742053558557144}} {"text": "function OUT = MovSum(DATA,window)\n% =======================================================================\n% Moving sum of the vector (or matrix) DATA (T obs x N variables). If \n% DATA is a matrix moving sum is computed down each column.\n% =======================================================================\n% OUT = MovAvg(DATA,window)\n% -----------------------------------------------------------------------\n% INPUT\n% DATA: T observations x N variables\n% window: window of the moving sum \n%------------------------------------------------------------------------\n% OUPUT\n% OUT: T observations x N variables matrix (the first windows-1 \n% obseravations are NaN)\n% =======================================================================\n% Ambrogio Cesa Bianchi, March 2015\n% ambrogio.cesabianchi@gmail.com\n\nif nargin<2, error('Not enough input.'), end\nif window<=0, error('window must be positive.'), end\nif (window~=floor(window)), error('window must be an integer.'), end\n\nif min(size(DATA))==1,\n DATA = DATA(:); % forces DATA to be a column vector\nend\n\n[nobs,nvar] = size(DATA);\nif window>nobs,\n error('window must not be greater than the length of DATA.')\nend\n\ntemp=[];\nfor row=1:(nobs-window+1),\n temp = [temp; sum(DATA(row:(row+window-1),:))];\nend\n\nOUT = temp;\nOUT = [nan(window-1,nvar); OUT]; % add nans to make conformable to original \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/Stats/MovSum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.8558511432905481, "lm_q1q2_score": 0.74205355806245}} {"text": "function p = predictOneVsAll(all_theta, X)\n%PREDICT Predict the label for a trained one-vs-all classifier. The labels \n%are in the range 1..K, where K = size(all_theta, 1). \n% p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions\n% for each example in the matrix X. Note that X contains the examples in\n% rows. all_theta is a matrix where the i-th row is a trained logistic\n% regression theta vector for the i-th class. You should set p to a vector\n% of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2\n% for 4 examples) \n\nm = size(X, 1);\nnum_labels = size(all_theta, 1);\n\n% You need to return the following variables correctly \np = zeros(size(X, 1), 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters (one-vs-all).\n% You should set p to a vector of predictions (from 1 to\n% num_labels).\n%\n% Hint: This code can be done all vectorized using the max function.\n% In particular, the max function can also return the index of the \n% max element, for more information see 'help max'. If your examples \n% are in rows, then, you can use max(A, [], 2) to obtain the max \n% for each row.\n% \n% temp = (X*all_theta');\n% p(:) = max(temp,[],2); \n\nh_theta = sigmoid(X * all_theta');\np = max(h_theta, [], 2);\n\n% temp is of dimension 5000x10\n\n% Dimention of X: 5000x401\n% Dimension of all_theta: 10x401\n% Dimension of X*all_theta': 5000x10 \n\n% =========================================================================\n\n\nend\n", "meta": {"author": "anirudhjayaraman", "repo": "Machine-Learning", "sha": "084e9c67ac3853f78461f9d0e46c7b41364da481", "save_path": "github-repos/MATLAB/anirudhjayaraman-Machine-Learning", "path": "github-repos/MATLAB/anirudhjayaraman-Machine-Learning/Machine-Learning-084e9c67ac3853f78461f9d0e46c7b41364da481/Andrew Ng Stanford Coursera/Week 04/ex3/predictOneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.855851143290548, "lm_q1q2_score": 0.7420535404194898}} {"text": "% This is small script that demonstrate the computation of extrinsic \n% parameters using 3D structures.\n% This test was build from data provided by Daniel Small (thank you Daniel!)\n\n\n%-- Image points (in pixels):\n\nx = [479.5200 236.0800\n 608.4100 415.3700\n 461.0000 40.0000\n 451.4800 308.7000\n 373.9900 314.8900\n 299.3200 319.1300\n 231.5500 321.3700\n 443.7300 282.9200\n 378.3600 288.3000\n 314.6900 292.7400\n 255.4700 296.2300]';\n\n\n% 3D world coordinates:\n\nX = [ 0 0 0\n 54.0000 0 0\n 0 0 40.5000\n 27.0000 -8.4685 -2.3750\n 27.0000 -18.4685 -2.3750\n 27.0000 -28.4685 -2.3750\n 27.0000 -38.4685 -2.3750\n 17.0000 -8.4685 -2.3750\n 17.0000 -18.4685 -2.3750\n 17.0000 -28.4685 -2.3750\n 17.0000 -38.4685 -2.3750]';\n\n\n%------------ Intrinsic parameters:\n%--- focal:\nfc = [ 395.0669 357.1178 ]';\n%--- Principal point:\ncc = [ 380.5387 230.5278 ]';\n%--- Distortion coefficients:\nkc = [-0.2601 0.0702 -0.0019 -0.0003 0]';\n%--- Skew coefficient:\nalpha_c = 0;\n\n%----- Computation of the pose of the object in space\n%----- (or the rigid motion between world reference frame and camera ref. frame)\n[om,T,R] = compute_extrinsic(x,X,fc,cc,kc,alpha_c);\n\n%--- Try to reproject the structure to see if the computed pose makes sense:\nx2 = project_points2(X_1,omckk,Tckk,fc,cc,kc,alpha_c);\n\n\n% Graphical output:\nfigure(2);\nplot(x(1,:),x(2,:),'r+');\nhold on;\nplot(x2(1,:),x2(2,:),'go');\nhold off;\naxis('equal');\naxis('image');\ntitle('red crosses: data, green circles: reprojected structure -- IT WORKS!!!');\nxlabel('x');\nylabel('y');\n\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/EKF_monoSLAM_1pRANSAC/matlab_code/matlabcalibration2ourcalibration/TOOLBOX_calib/small_test_script.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533069832974, "lm_q2_score": 0.7956581024858785, "lm_q1q2_score": 0.7419140288910129}} {"text": "function gauss_seidel_test01 ( )\n\n%*****************************************************************************80\n%\n%% GAUSS_SEIDEL_TEST01 tests GAUSS_SEIDEL1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 June 2011\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GAUSS_SEIDEL_TEST01:\\n' );\n\n it_num = 400;\n n = 20;\n\n x_exact = ( 1 : n )';\n a = dif2 ( n );\n b = a * x_exact;\n\n x = zeros ( n, 1 ); \n x_plot(1:n,1) = x;\n\n step = 1 : it_num + 1;\n e = nan ( it_num+1, 1 );\n xm = nan ( it_num+1, 1 );\n\n e(1,1) = ( norm ( a * x - b ) ).^2;\n\n for it = 1 : it_num\n\n x_new = gauss_seidel1 ( n, a, b, x );\n\n e(it+1,1) = ( norm ( a * x_new - b ) ).^2;\n x_plot(1:n,it+1) = x_new;\n%\n% Display the error.\n%\n figure ( 1 )\n plot ( step, log ( e ), 'm-*' )\n title ( 'Log (Error^2)' )\n xlabel ( 'Step' )\n ylabel ( 'Error' )\n grid\n%\n% Display the motion.\n%\n xm(it,1) = sum ( ( x_new(:) - x(:) ).^2 ) / n;\n\n figure ( 2 )\n plot ( step, log ( xm ), 'm-*' )\n title ( 'Log (Average generator motion)' )\n xlabel ( 'Step' )\n ylabel ( 'Energy' )\n grid\n%\n% Update the solution\n%\n x = x_new;\n\n end\n%\n% Plot the evolution of the locations of the generators.\n%\n figure ( 3 )\n\n y = ( 0 : it_num );\n for k = 1 : n\n plot ( x_plot(k,1:it_num+1), y )\n hold on;\n end\n grid on\n hold off;\n\n title ( 'Generator evolution.' );\n xlabel ( 'Generator positions' );\n ylabel ( 'Iterations' ); \n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/gauss_seidel/gauss_seidel_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7419040909222588}} {"text": "function value = r4_sin_deg ( x )\n\n%*****************************************************************************80\n%\n%% R4_SIN_DEG evaluates the sine of an R4 argument in degrees.\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 in degrees.\n%\n% Output, real VALUE, the sine of X.\n%\n raddeg = 0.017453292519943296;\n\n value = sin ( raddeg * x );\n\n if ( mod ( x, 90.0 ) == 0.0 )\n\n n = floor ( abs ( x ) / 90.0 + 0.5 );\n n = mod ( n, 2 );\n\n if ( n == 0 )\n value = 0.0;\n elseif ( value < 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/r4_sin_deg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7419040750151562}} {"text": "% FDLA and FMMC solutions for an 8-node, 13-edge graph\n% S. Boyd, et. al., \"Convex Optimization of Graph Laplacian Eigenvalues\"\n% ICM'06 talk examples (www.stanford.edu/~boyd/cvx_opt_graph_lapl_eigs.html)\n% Written for CVX by Almir Mutapcic 08/29/06\n% (figures are generated)\n%\n% In this example we consider a graph described by the incidence matrix A.\n% Each edge has a weight W_i, and we optimize various functions of the\n% edge weights as described in the referenced paper; in particular,\n%\n% - the fastest distributed linear averaging (FDLA) problem (fdla.m)\n% - the fastest mixing Markov chain (FMMC) problem (fmmc.m)\n%\n% Then we compare these solutions to the heuristics listed below:\n%\n% - maximum-degree heuristic (max_deg.m)\n% - constant weights that yield fastest averaging (best_const.m)\n% - Metropolis-Hastings heuristic (mh.m)\n\n% small example (incidence matrix A)\nA = [ 1 0 0 1 0 0 0 0 0 0 0 0 0;\n -1 1 0 0 1 1 0 0 0 0 0 0 1;\n 0 -1 1 0 0 0 0 0 -1 0 0 0 0;\n 0 0 -1 0 0 -1 0 0 0 -1 0 0 0;\n 0 0 0 -1 0 0 -1 1 0 0 0 0 0;\n 0 0 0 0 0 0 1 0 0 0 1 0 0;\n 0 0 0 0 0 0 0 -1 1 0 -1 1 -1;\n 0 0 0 0 -1 0 0 0 0 1 0 -1 0];\n\n% x and y locations of the graph nodes\nxy = [ 1 2 3 3 1 1 2 3 ; ...\n 3 2.5 3 2 2 1 1.5 1 ]';\n\n% Compute edge weights: some optimal, some based on heuristics\n[n,m] = size(A);\n\n[ w_fdla, rho_fdla ] = fdla(A);\n[ w_fmmc, rho_fmmc ] = fmmc(A);\n[ w_md, rho_md ] = max_deg(A);\n[ w_bc, rho_bc ] = best_const(A);\n[ w_mh, rho_mh ] = mh(A);\n\ntau_fdla = 1/log(1/rho_fdla);\ntau_fmmc = 1/log(1/rho_fmmc);\ntau_md = 1/log(1/rho_md);\ntau_bc = 1/log(1/rho_bc);\ntau_mh = 1/log(1/rho_mh);\n\nfprintf(1,'\\nResults:\\n');\nfprintf(1,'FDLA weights:\\t\\t rho = %5.4f \\t tau = %5.4f\\n',rho_fdla,tau_fdla);\nfprintf(1,'FMMC weights:\\t\\t rho = %5.4f \\t tau = %5.4f\\n',rho_fmmc,tau_fmmc);\nfprintf(1,'M-H weights:\\t\\t rho = %5.4f \\t tau = %5.4f\\n',rho_mh,tau_mh);\nfprintf(1,'MAX_DEG weights:\\t rho = %5.4f \\t tau = %5.4f\\n',rho_md,tau_md);\nfprintf(1,'BEST_CONST weights:\\t rho = %5.4f \\t tau = %5.4f\\n',rho_bc,tau_bc);\n\n% Plot results\nfigure(1), clf\nplotgraph(A,xy,w_fdla);\ntext(0.55,1.05,'FDLA optimal weights')\n\nfigure(2), clf\nplotgraph(A,xy,w_fmmc);\ntext(0.55,1.05,'FMMC optimal weights')\n\nfigure(3), clf\nplotgraph(A,xy,w_md);\ntext(0.5,1.05,'Max degree optimal weights')\n\nfigure(4), clf\nplotgraph(A,xy,w_bc);\ntext(0.5,1.05,'Best constant optimal weights')\n\nfigure(5), clf\nplotgraph(A,xy,w_mh);\ntext(0.46,1.05,'Metropolis-Hastings optimal weights')\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/graph_laplacian/small_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.741904075015156}} {"text": "function value = monomial_value ( dim_num, point_num, x, expon )\n\n%*****************************************************************************80\n%\n%% MONOMIAL_VALUE evaluates a monomial.\n%\n% Discussion:\n%\n% This routine evaluates a monomial of the form\n%\n% product ( 1 <= dim <= dim_num ) x(dim)^expon(dim)\n%\n% where the exponents are nonnegative integers. Note that\n% if the combination 0^0 is encountered, it should be treated\n% as 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 26 August 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer POINT_NUM, the number of points at which the\n% monomial is to be evaluated.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the point coordinates.\n%\n% Input, integer EXPON(DIM_NUM), the exponents.\n%\n% Output, real VALUE(POINT_NUM), the value of the monomial.\n%\n value(1,1:point_num) = 1.0;\n \n for dim = 1 : dim_num\n if ( 0 ~= expon(dim) )\n value(1,1:point_num) = value(1,1:point_num) .* ( x(dim,1:point_num).^expon(dim) );\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/sandia_sparse/monomial_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7419022791669262}} {"text": "function y = sqrt_cordic ( x, n )\n\n%*****************************************************************************80\n%\n%% SQRT_CORDIC returns the square root of a value using the CORDIC method.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 June 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the number whose square root is desired.\n%\n% Input, integer N, the number of iterations to take.\n% This is essentially the number of binary digits of accuracy.\n%\n% Output, real Y, the approximate square root of X.\n%\n if ( x < 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SQRT_CORDIC - Fatal error!\\n' );\n fprintf ( 1, ' X < 0.\\n' );\n error ( 'SQRT_CORDIC - Fatal error!' )\n end\n\n if ( x == 0.0 )\n y = 0.0;\n return\n end\n\n if ( x == 1.0 )\n y = 1.0;\n return\n end\n\n poweroftwo = 1.0;\n\n if ( x < 1.0 )\n\n while ( x <= poweroftwo * poweroftwo )\n poweroftwo = poweroftwo / 2.0;\n end\n\n y = poweroftwo;\n\n elseif ( 1.0 < x )\n\n while ( poweroftwo * poweroftwo <= x )\n poweroftwo = 2.0 * poweroftwo;\n end\n\n y = poweroftwo / 2.0;\n\n end\n\n for i = 1 : n\n poweroftwo = poweroftwo / 2.0;\n if ( ( y + poweroftwo ) * ( y + poweroftwo ) <= x )\n y = y + poweroftwo;\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/cordic/sqrt_cordic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.74190227013629}} {"text": "function h = compute_histogram_rbf(f, sigma, x, options)\n\n% compute_histogram_rbf - parzen windows density estimation\n%\n% h = compute_histogram_rbf(f, sigma, x);\n%\n% f is the signal, h is an estimate of the histogram, \n% where h(i) is the density of the estimation around value x(i).\n%\n% sigma is the bandwidth used to estimate the histogram (approx. size of\n% the bins).\n%\n% If f is (n,2) matrix, then a joint histogram is estimated.\n%\n% Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\n \n\nif size(f,1)nb_max\n h = zeros(n);\n niter = ceil(p/nb_max);\n for i=1:niter\n progressbar(i,niter);\n sel = (i-1)*nb_max+1:min(i*nb_max,p);\n h = h + compute_histogram_rbf_2d( f(sel,:) , sigma, x, options);\n end\n h = h/sum(h(:));\n return;\nend\n\n% hx is of size p x n x n\nhx = repmat( f(:,1), [1 n n]) - repmat( reshape(x(:,1),[1 n 1]),[p 1 n] );\nhy = repmat( f(:,2), [1 n n]) - repmat( reshape(x(:,2),[1 1 n]),[p n 1] );\nh = exp( -(hx.^2/(2*sigma(1)^2)+hy.^2/(2*sigma(2)^2)) );\nif renormalize\n d = repmat( sum(sum(h,2),3), [1 n n] );\n d(d= 1 - eps \n k = k - 1;\n log_sum_Pr = my_logsumexp([log_sum_Pr log_b{n+1}(k+1)+(n-k)*log(3)+log_Pr(k+1)]); \n end\n d = 1 - eps - (exp(log_sum_Pr) - exp(log_b{n+1}(k+1)+(n-k)*log(3)+log_Pr(k+1))); \n M1 = my_logsumexp(log_b{n+1}(k+2:n+1)+(n-(k+1:n))*log(3));\n M2 = log(d) - log_Pr(k+1);\n R(i) = 1/n*my_logsumexp([M1 M2]);\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_optimum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7418670401312024}} {"text": "% Get the freq. and amp. parameters of a spectral peak by quandratic fitting\n%\n% Octave compatible\n% \n% Inputs\n% S : The spectrum containing the peak to fit\n% fs : [Hz] The sampling frequency\n% index : The peak position where the parabola has to be fit\n% [zp] : the zero padding factor used for the DFT computation\n% (used for the Abe & Smith corrections)\n% [wintype]: The window type used for the DFT computation\n% wintype=2 => Hann\n%\n% Outputs\n% freq : [Hz] The frequency parameter\n% amp : The amplitude parameter (linear scale)\n%\n% Copyright (c) 2012 University of Crete - Computer Science Department\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 [freq amp p] = spec_fit_freq_amp(S, fs, index, zp, wintype)\n\n if index<=1\n freq = index;\n amp = log(abs(S(1)));\n return\n elseif index>=length(S)\n freq = index;\n amp = log(abs(S(end)));\n return\n end\n\n % fit a parabola in log amplitudes\n y1 = log(abs(S(index-1)));\n y2 = log(abs(S(index)));\n y3 = log(abs(S(index+1)));\n A = (y3-y2)/2 + (y1-y2)/2;\n B = -( y1 - y2 - A );\n C = y1 - A + B;\n p = [A B C];\n\n % max abscissa\n di = -p(2)/(2*p(1));\n\n % max amplitude\n logamp = p(1)*di*di + p(2)*di + p(3);\n\n if nargin>3 && ~isempty(zp)\n % Use Abe & Smith corrections\n if wintype==2;\n c0=0.247560; c1=0.084372; c2=-0.090608; c3=-0.055781; % Hann\n else\n error('Unknown correction terms for the given window for Abe&Smith corrections');\n end\n delta = di;\n\n % Frequency correction\n ksi = c0*zp^(-2) + c1*zp^(-4); % (3)\n di = delta + ksi*(delta-0.5)*(delta+0.5)*delta; % (1)\n\n % Amplitude correction\n ita = c2*zp^(-4) + c3*zp^(-6); % (4)\n logamp = logamp + ita*di^2; % (2)\n end\n\n freq = index + di;\n freq = (freq-1)*(fs/length(S));\n\n amp = exp(logamp);\nreturn\n\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/sinusoidal/private/spec_fit_freq_amp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037782, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7418670334382603}} {"text": "function determ = chow_determinant ( alpha, beta, n )\n\n%*****************************************************************************80\n%\n%% CHOW_DETERMINANT returns the determinant of the CHOW matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 October 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 DETERM, the determinant.\n%\n determ = 1.0;\n\n k = n - floor ( n / 2 );\n\n for i = 1 : k\n angle = i * pi / ( n + 2 );\n determ = determ * ( beta + 4.0 * alpha * ( cos ( angle ) )^2 );\n end\n\n determ = determ * beta^( n - 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/test_mat/chow_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7418226145352027}} {"text": "%% Simulating Pole Figure data\n%\n%%\n% Simulating pole figure data from a given ODF is useful to investigate\n% pole figure to ODF reconstruction routines. Let us start with a model ODF\n% given as the superposition of 6 components.\n\ncs = crystalSymmetry('orthorhombic');\nmod1 = orientation.byAxisAngle(xvector,45*degree,cs);\nmod2 = orientation.byAxisAngle(yvector,65*degree,cs);\nmodel_odf = 0.5*uniformODF(cs) + ...\n 0.05*fibreODF(Miller(1,0,0,cs),xvector,'halfwidth',10*degree) + ...\n 0.05*fibreODF(Miller(0,1,0,cs),yvector,'halfwidth',10*degree) + ...\n 0.05*fibreODF(Miller(0,0,1,cs),zvector,'halfwidth',10*degree) + ...\n 0.05*unimodalODF(mod1,'halfwidth',15*degree) + ...\n 0.3*unimodalODF(mod2,'halfwidth',25*degree);\n\n%%\n\nplot(model_odf,'sections',6,'silent','sigma')\n\n%%\n% In order to simulate pole figure data, the following parameters have to be\n% specified\n%\n% # an arbitrary \n% # a list of \n% # a grid of \n% # superposition coefficients (optional)\n% # the magnitude of error (optional)\n%\n%%\n% The list of \n\nh = [Miller(1,1,1,cs),Miller(1,1,0,cs),Miller(1,0,1,cs),Miller(0,1,1,cs),...\n Miller(1,0,0,cs),Miller(0,1,0,cs),Miller(0,0,1,cs)];\n\n%%\n% The of specimen directions\n\nr = regularS2Grid('resolution',5*degree);\n\n%%\n% Now the pole figures can be simulated using the command\n% . \n\npf = calcPoleFigure(model_odf,h,r)\n\n%%\n% Add some noise to the data. Here we assume that the mean intensity is 1000.\n\npf = noisepf(pf,1000);\n\n%%\n% Plot the simulated pole figures.\n\nplot(pf)\n\n\n%% ODF Estimation from Pole Figure Data\n%\n% From these simulated pole figures we can now estimate an ODF,\n\nodf = calcODF(pf)\n\n\n%%\n% which can be plotted,\n\nplot(odf,'sections',6,'silent','sigma')\n\n\n%%\n% and compared to the original model ODF.\n\ncalcError(odf,model_odf,'resolution',5*degree)\n\n\n%% Exploration of the relationship between estimation error and number of pole figures\n%\n% For a more systematic analysis of the estimation error, we vary the number\n% of pole figures used for ODF estimation from 1 to 7 and calculate for any\n% number of pole figures the approximation error. Furthermore, we also\n% apply ghost correction and compare the approximation error to the\n% previous reconstructions.\n\ne = [];\nfor i = 1:pf.numPF\n\n odf = calcODF(pf({1:i}),'silent','NoGhostCorrection');\n e(i,1) = calcError(odf,model_odf,'resolution',2.5*degree);\n odf = calcODF(pf({1:i}),'silent');\n e(i,2) = calcError(odf,model_odf,'resolution',2.5*degree);\n\nend\n\n%% \n% Plot the error in dependency of the number of single orientations.\n\nclose all;\nplot(1:pf.numPF,e,'LineWidth',2)\nylim([0.07 0.32])\nxlabel('Number of Pole Figures');\nylabel('Reconstruction Error');\nlegend({'Without Ghost Correction','With Ghost Correction'});\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/PoleFigureAnalysis/PoleFigureSimulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7418226102117874}} {"text": "%% Generate an Airy Pattern and add noise.\nN=65;\nxrange=[-1 1];\nx=linspace(xrange(1),xrange(2),N);\n[xx, yy]=meshgrid(x);\n[theta, rr]=cart2pol(xx,yy);\nAiryPattern=jinc(rr).^2;\nAiryPattern=uint16((2^10-1)*AiryPattern);\nNoisyPattern=imnoise(AiryPattern,'poisson');\n\n%% Filter and Interpolate.\nxs=x(2)-x(1);\nfcut=2; % The Fourier transform of the Airy Pattern (chinese hat) cuts-off at 2 in frequency domain.\n%gaussorder=500;\nAiryFiltI1=opticalLowpassInterpolation(AiryPattern,xs,fcut,1);\nAiryFiltI2=opticalLowpassInterpolation(AiryPattern,xs,fcut,2);\nAiryFiltI3=opticalLowpassInterpolation(AiryPattern,xs,fcut,3);\nNoisyFiltI1=opticalLowpassInterpolation(NoisyPattern,xs,fcut,1);\nNoisyFiltI2=opticalLowpassInterpolation(NoisyPattern,xs,fcut,2);\nNoisyFiltI3=opticalLowpassInterpolation(NoisyPattern,xs,fcut,3);\nfigure(1); clf; colormap jet;\nset(1,'defaultaxesfontsize',16);\nimagecat(x,x,AiryPattern,AiryFiltI1,AiryFiltI2,AiryFiltI3,NoisyPattern,NoisyFiltI1,NoisyFiltI2,NoisyFiltI3,'link','equal');\n\n%% Compare line profiles along X.\n\n% Function handles to extract the midprofile and generate xaxis.\nxprof=@(img) img(floor(0.5*size(img,1))+1,:);\nxaxis=@(img,xrange) linspace(xrange(1),xrange(2),size(img,2));\n\n% Profiles from airy pattern.\nAiryProfiles=cellfun(@(img) xprof(img),...\n {AiryPattern,AiryFiltI1,AiryFiltI2,AiryFiltI3},...\n 'UniformOutput',false);\nAiryAxis=cellfun(@(img) xaxis(img,xrange),...\n {AiryPattern,AiryFiltI1,AiryFiltI2,AiryFiltI3},...\n 'UniformOutput',false);\n\n% Profiles from noisy pattern.\nNoisyProfiles=cellfun(@(img) xprof(img),...\n {NoisyPattern,NoisyFiltI1,NoisyFiltI2,NoisyFiltI3},...\n 'UniformOutput',false);\nNoisyAxis=cellfun(@(img) xaxis(img,xrange),...\n {NoisyPattern,NoisyFiltI1,NoisyFiltI2,NoisyFiltI3},...\n 'UniformOutput',false);\n\n\nfigure(2); clf; set(2,'defaultaxesfontsize',16);\nplot(AiryAxis{1},AiryProfiles{1},AiryAxis{2},AiryProfiles{2},...\n AiryAxis{3},AiryProfiles{3},AiryAxis{4},AiryProfiles{4},...\n 'LineWidth',2);\nlegend('Airy','AiryFiltInterpolation1','AiryFiltInterpolation2','AiryFiltInterpolation3');\n\nsnapnow;\n\nfigure(3); clf; set(3,'defaultaxesfontsize',16);\nplot(NoisyAxis{1},NoisyProfiles{1},NoisyAxis{2},NoisyProfiles{2},...\n NoisyAxis{3},NoisyProfiles{3},NoisyAxis{4},NoisyProfiles{4},...\n 'LineWidth',2);\nlegend('Noisy','NoisyFiltInterpolation1','NoisyFiltInterpolation2','NoisyFiltInterpolation3');\nsnapnow;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/40207-filter-noise-and-interpolate-microscopy-images-in-frequency-domain/opticalLowPassInterpolation27Feb2013/ImageProcessing/TestBench_opticalLowpassInterpolation_Airy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7418178008255719}} {"text": "function result=mcdregres(x,y,varargin)\n\n%MCDREGRES is a robust multivariate regression method. It can handle multiple\n% response variables. The estimates are based on the robust MCD estimator of \n% location and scatter (see mcdcov.m). The explanatory variables should be \n% low-dimensional, otherwise robust principal component regression (rpcr.m) \n% or robust partial least squares (rsimpls.m) should be applied.\n%\n% The MCD regression method is described in \n% Rousseeuw, P.J., Van Aelst, S., Van Driessen, K, Agullo, J. (2004),\n% \"Robust multivariate regression\", Technometrics, 46, pp 293-305.\n%\n% Required input arguments:\n% x : Data matrix of the explanatory variables\n% (n observations in rows, p variables in columns)\n% y : Data matrix of the response variables\n% (n observations in rows, q variables in columns)\n%\n% Optional input arguments: \n% alpha : (1-alpha) measures the amount of contamination the algorithm should \n% resist. Any value between 0.5 and 1 may be specified. (default = 0.75)\n% h : The quantile of observations whose covariance determinant will \n% be minimized. Any value between n/2 and n may be specified.\n% The default value is 0.75*n.\n% ntrial : The number of random trial subsamples that are drawn for \n% large datasets. (default = 500)\n% plots : If equal to one, a menu is shown which allows to draw a regression\n% outlier map. (default)\n% If the input argument 'classic' is equal to one, the classical\n% plot is drawn as well.\n% If 'plots' is equal to zero, all plots are suppressed.\n% See also makeplot.m\n% classic : If equal to one, classical multivariate linear regression \n% is performed as well, see mlr.m. (default = 0)\n%\n% Input arguments for advanced users:\n% Hsets : Instead of random trial h-subsets (default, Hsets = []), Hsets makes it possible to give certain\n% h-subsets as input. Hsets is a matrix that contains the indices of the observations of one\n% h-subset as a row.\n%\n% I/O: result=mcdregres(x,y,'alpha',0.75,'ntrial',500,'plots',1,'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% Example: result=mcdregres(x,y,'plots',0,'alpha',0.70)\n%\n% The output is a structure which contains\n% result.slope : Robust slope (matrix)\n% result.int : Robust intercept (vector)\n% result.fitted : Robust prediction matrix\n% result.res : Robust residuals\n% result.cov : Estimated variance-covariance matrix of the residuals \n% result.rsquared : Robust R-squared value\n% result.h : The quantile h used throughout the algorithm\n% result.Hsubsets : A structure that contains Hopt and Hfreq:\n% Hopt : The subset of h points whose covariance matrix has minimal determinant, \n% ordered following increasing robust distances.\n% Hfreq : The subset of h points which are the most frequently selected during the whole\n% algorithm.\n% result.rd : Robust scores distances in x-space\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 and residual distances\n% result.weights : The observations with weight one are used in the reweighting, \n% the other observations have zero weight.\n% result.flag : The observations whose residual distance is larger than result.cutoff.resd\n% (bad leverage points/vertical outliers) can be considered as outliers and receive \n% a flag equal to zero.\n% The regular observations, including the good leverage points, \n% receive a flag 1.\n% result.class : 'MCDREG'\n% result.classic : If the input argument 'classic' is equal to one, this structure\n% contains results of classical multivariate regression (see also mlr.m). \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% Original S-PLUS code by Katrien Vandriessen, implemented in MATLAB by Sabine Verboven \n% Version date : 12/02/2004\n% Last update: 04/08/2006\n\n%%%%%%%%%%%%%%%%\n% INITIALIZATION\n%\nintercept=ones(length(x),1);\ngeg=[x,y];\n[n,m]=size(geg);\nalfa=0.75;\nhdefault=min(floor(2*floor((n+m+1)/2)-n+2*(n-floor((n+m+1)/2))*alfa),n);\n\nif nargin < 3\n options.alpha=alfa;\n options.h=hdefault;\n options.ntrial=500;\n options.plots=1;\n options.classic=0;\n options.Hsets=[];\nelse\n default=struct('alpha',alfa,'h',hdefault,'ntrial',500,'plots',1,'classic',0,'Hsets',[]);\n list=fieldnames(default);\n options=default;\n IN=length(list);\n i=1; \n counter=1;\n % \n if 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'));\n switch dummy\n case 0 %no input for alpha or h so take on the default values \n options.alpha=0.75;\n options.h=floor(options.alpha*n);\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');\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 if dummy==1\n options.alpha=options.h/n;\n elseif dummy==2\n options.h=floor(options.alpha*n);\n end\n Hsets = options.Hsets;\n end\nend\n%%%%%%%%\n% MAIN %\n[mcd_res, mcd_raw]=mcdcov(geg,'h',options.h,'plots',0,'Hsets',options.Hsets);\noptions.h = mcd_res.h;\n\n%in case of an exact fit, the calculations stop at this point.\nif ~isempty(mcd_res.plane)\n disp('Warning (mcdregres): The MCD covariance matrix is singular. See also mcdcov.m.')\n result=mcd_res;\n return\nend\n\nmcdreg.Hsubsets.Hopt = mcd_res.Hsubsets.Hopt;\nmcdreg.Hsubsets.Hfreq = mcd_res.Hsubsets.Hfreq;\n\nrewcovmcd=mcd_res.cov; %one-step reweighted covariance matrix\nrewcenmcd=mcd_res.center; %one-step reweighted location\nq=size(y,2);\np=size(x,2);\n\n%initializing reweighted location and reweighted scatter (paragraph 5.1 of paper)\nrewtmcdx=rewcenmcd(1:p)'; %column vectors!!!\nrewtmcdy=rewcenmcd((p+1):m)';\n\nrewsmcdx=rewcovmcd(1:p,1:p);\nrewsmcdxy=rewcovmcd(1:p,(p+1):m);\nrewsmcdyx=rewsmcdxy';\nrewsmcdy=rewcovmcd((p+1):m,(p+1):m);\n\ncovyy=rewsmcdy;\ncovxx = rewsmcdx;\ncovxy = rewsmcdxy;\ncovyx = rewsmcdyx;\nmcdreg.Sigma = [covxx, covxy ; covyx, covyy];\nmcdreg.Mu = [rewtmcdx;rewtmcdy];\n\n%reweighted beta and alpha (the columnvector [\\beta^L ; \\alpha^L])\nrewbetamcd=[inv(rewsmcdx)*rewsmcdxy; (rewtmcdy-(rewsmcdyx*inv(rewsmcdx)*rewtmcdx))'];\n\n%calculation of the reweighted weights based on \n%the residuals calculated with the reweighted beta-coefficients \nrewweights=zeros(n,1);\nweights=zeros(n,1);\nrewfitted=[x,intercept]*rewbetamcd(1:(p+1),:);\nrewresid=y-rewfitted; %(r_i^L)\nrewE=rewsmcdy-rewbetamcd(1:p,1:q)'*rewsmcdx*rewbetamcd(1:p,1:q); %reweighted scatter (\\Sigma_eps^L)\nfor j=1:n\n if (sqrt(rewresid(j,1:q)*inv(rewE)*rewresid(j,1:q)')) <= sqrt(chi2inv(0.99,q))\n rewweights(j)=1;\n end\nend\n\n%regression reweighting part based on the reweighted observations. (paragraph 5.3 of paper)\nrewclasscov=cov(geg(rewweights==1,:));\nrewclasscenter=mean(geg(rewweights==1,:));\n\nrewtmcdx=rewclasscenter(1:p)';\nrewtmcdy=rewclasscenter((p+1):m)';\n\nrewsmcdx=rewclasscov(1:p,1:p);\nrewsmcdxy=rewclasscov(1:p,(p+1):m);\nrewsmcdyx=rewsmcdxy';\nrewsmcdy=rewclasscov((p+1):m,(p+1):m);\n\n%regression reweighted coefficients beta and alpha ([\\beta^{RL} \\alpha^{RL}])\nrewbetamcdrew=[inv(rewsmcdx)*rewsmcdxy; (rewtmcdy-(rewsmcdyx*inv(rewsmcdx)*rewtmcdx))'];\n%regression reweighted scatter (\\Sigma_eps^{RL}])\nrewE2=rewsmcdy-rewbetamcdrew(1:p,1:q)'*rewsmcdx*rewbetamcdrew(1:p,1:q);\nrewfittedrew=[x,intercept]*rewbetamcdrew(1:(p+1),:);\nrewresidrew=y-rewfittedrew;\n\n%%%%%%%%%%%%%%%%%\n%OUTPUT STRUCTURE\n%\nmcdreg.covyy=rewsmcdy; %regression and location reweighted covariance matrix of responses\nmcdreg.covxx = rewsmcdx;\nmcdreg.covxy = rewsmcdxy;\nmcdreg.covyx = rewsmcdyx;\nmcdreg.Sigmarew = [mcdreg.covxx, mcdreg.covxy ; mcdreg.covyx, mcdreg.covyy];\nmcdreg.Murew = [rewtmcdx;rewtmcdy];\n\nmcdreg.x=x;\nmcdreg.y=y;\nmcdreg.coeffs=rewbetamcdrew; %regression and location reweighted coefficients\nmcdreg.cov=rewE2; %scatter matrix based on location and regression reweighting\nmcdreg.fitted=rewfittedrew; %estimated respons(es);\nmcdreg.res=rewresidrew; %regression and location reweighted residuals\n\nif(intercept)\n mcdreg.interc=1;\nelse\n mcdreg.interc=0;\nend\n\n% Robust distances in x-space = x-distances (rd) needed in diagnostic regression plot\nif (-log(det(mcd_res.cov))/m) > 50\n mcdreg.rd='singularity';\nelse\n mcdreg.rd=sqrt(libra_mahalanobis(mcdreg.x,rewcenmcd(1:p),'cov',rewcovmcd(1:p,1:p)))';\nend\n\n% Robust residual distances (resd) needed in diagnostic regression plot \nif q>1\n if (-log(det(mcd_res.cov))/m)>50\n mcdreg.resd='singularity';\n disp('Warning (mcdregres): A singularity ')\n else\n cen=zeros(q,1)';\n [nn,pp]=size(rewresidrew);\n mcdreg.resd=sqrt(libra_mahalanobis(rewresidrew,cen,'cov',mcdreg.cov))'; %robust distances of residuals\n end\nelse\n mcdreg.covarRes=sqrt(mcdreg.cov);\n mcdreg.resd=rewresidrew(:,1)/mcdreg.covarRes; %standardized residuals \nend\n\n% cutoff values \nmcdreg.cutoff.rd=sqrt(chi2inv(0.975,p)); \nmcdreg.cutoff.resd=sqrt(chi2inv(0.975,q));\nmcdreg.flag=(abs(mcdreg.resd)<=mcdreg.cutoff.resd);\n\n% robust multivariate Rsquared\nmcdreg.weights=rewweights;\nYw=y(mcdreg.weights==1,:);\ncYw=mcenter(Yw);\nres=rewresidrew(mcdreg.weights==1,:);\nmcdreg.rsquared=1-(det(res'*res)/det(cYw'*cYw));\nmcdreg.class='MCDREG';\n\n\nif options.classic\n mcdreg.classic=mlr(x,y,'plots',0);\nelse\n mcdreg.classic=0;\nend\n\nresult=struct('slope',{mcdreg.coeffs(1:p,:)}, 'int',{mcdreg.coeffs(p+1,:)}, ...\n 'fitted',{mcdreg.fitted},'res',{mcdreg.res},'cov',{mcdreg.cov},'rsquared',{mcdreg.rsquared},...\n 'h',{options.h},'Hsubsets',{mcdreg.Hsubsets},'rd', {mcdreg.rd},'resd',{mcdreg.resd},'cutoff',{mcdreg.cutoff},...\n 'weights',{mcdreg.weights},'flag',{mcdreg.flag'},'class',{mcdreg.class},'classic',{mcdreg.classic},...\n 'Mu',{mcdreg.Mu},'Sigma',{mcdreg.Sigma},'Murew',{mcdreg.Murew},'Sigmarew',{mcdreg.Sigmarew});\n\ntry\n if options.plots & options.classic\n makeplot(result,'classic',1)\n elseif options.plots\n makeplot(result) \n end\ncatch %output must be given even if plots are interrupted \n %> delete(gcf) to get rid of the menu \nend", "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/mcdregres.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7418177922314463}} {"text": "function [v s] = ricefit(mudat, vr)\n%RICEFIT Estimate parameters for Rice/Rician distribution from data.\n% Uses simple moment-matching approach, with numerical optimisation.\n% [v s] = ricefit(dat) estimates v and s from samples in dat\n% [v s] = ricefit(mu, vr) estimates v and s from given mean and variance\n%\n% R ~ Rice(v, s) if R = sqrt(X^2 + Y^2), where X ~ N(v*cos(a), s^2) and\n% Y ~ N(v*sin(a), s^2) are independent normal distributions (any real a).\n% Note that v and s are *not* the mean and standard deviation of R!\n%\n% Reference: http://en.wikipedia.org/wiki/Rice_distribution (!)\n%\n% Example:\n% % Sample data, fit model, compare expected, fitted & observed moments\n% V = 5; S = 4; N = 1000;\n% [MN VR] = ricestat(V, S) % expected mean and variance\n% r = ricernd(V*ones(1, N), S);\n% [v s] = ricefit(dat) % fitted Rician distribution parameters\n% [mn vr] = ricestat(v, s) % fitted mean and variance\n% mean(dat), var(dat) % observed mean and variance\n%\n% See also RICEPDF, RICERND, RICESTAT\n\n% Missing (?) 'See also's RICECDF, RICEINV, RICELIKE\n\n% Inspired by normfit from the MATLAB statistics toolbox\n% Copyright 2008 Ged Ridgway (Ged at cantab dot net)\n\nif nargin == 1\n dat = mudat;\n mu = mean(dat(:));\n vr = var(dat(:));\nelse\n mu = mudat;\nend\n\n% Optimise cost based on difference of mu and vr from ricestat(v, s) as a \n% function of v and s, using mu and sqrt(vr) as initial values for v and s\ncost = @(x) moment_cost(x(1), x(2), mu, vr);\nx = fminsearch(cost, [mu sqrt(vr)]);\nif nargout == 1\n v = x;\nelse\n v = x(1);\n s = x(2);\nend\n\nfunction cost = moment_cost(v, s, MU, VR)\n% Very naive approach...\n% Not clear how to wait relative errors in mean and variance...\n[mu vr] = ricestat(v, s);\ncost = norm([mu - MU; vr - VR;]);\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/rician/ricefit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122138417878, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7417953019264123}} {"text": "function euler = dcm2euler(DCMbn)\n% dcm2euler: converts from body-to-nav DCM to Euler angles.\n%\n% INPUT\n% DCMbn, 3x3 body-to-nav DCM.\n%\n% OUTPUT\n% euler, 3x1 Euler angles [roll pitch yaw] (rad, rad, rad).\n%\n% Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved.\n% \n% This file is part of NaveGo, an open-source MATLAB toolbox for\n% simulation of integrated navigation systems.\n%\n% NaveGo is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License (LGPL)\n% version 3 as published by the Free Software Foundation.\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 Lesser General Public License for more details.\n%\n% You should have received a copy of the GNU Lesser General Public\n% License along with this program. If not, see\n% .\n%\n% References:\n% \tTitterton, D.H. and Weston, J.L. (2004). Strapdown\n% Inertial Navigation Technology (2nd Ed.). Institution\n% of Engineering and Technology, USA. Eq. 11.4. Eq. 3.66, p. 46.\n%\n% R. Gonzalez, J. Giribet, and H.D. Patiño,. An approach to\n% benchmarking of loosely coupled low-cost navigation systems,\n% Mathematical and Computer Modelling of Dynamical Systems, vol. 21,\n% issue 2, pp. 272-287. Eq. 15.\n%\n% Version: 002\n% Date: 2016/11/26\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego\n\nphi = atan( DCMbn(3,2) ./ DCMbn(3,3) ); % roll\ntheta = -asin( DCMbn(3,1) ); % pitch\npsi = atan2( DCMbn(2,1), DCMbn(1,1) ); % yaw\n\neuler = [phi theta psi];\n\nend\n", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/conversions/dcm2euler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7417857636202659}} {"text": "function [bandwidth,density,X,Y]=kde2d(data,n,MIN_XY,MAX_XY)\n% fast and accurate state-of-the-art\n% bivariate kernel density estimator\n% with diagonal bandwidth matrix.\n% The kernel is assumed to be Gaussian.\n% The two bandwidth parameters are\n% chosen optimally without ever\n% using/assuming a parametric model for the data or any \"rules of thumb\".\n% Unlike many other procedures, this one\n% is immune to accuracy failures in the estimation of\n% multimodal densities with widely separated modes (see examples).\n% INPUTS: data - an N by 2 array with continuous data\n% n - size of the n by n grid over which the density is computed\n% n has to be a power of 2, otherwise n=2^ceil(log2(n));\n% the default value is 2^8;\n% MIN_XY,MAX_XY- limits of the bounding box over which the density is computed;\n% the format is:\n% MIN_XY=[lower_Xlim,lower_Ylim]\n% MAX_XY=[upper_Xlim,upper_Ylim].\n% The dafault limits are computed as:\n% MAX=max(data,[],1); MIN=min(data,[],1); Range=MAX-MIN;\n% MAX_XY=MAX+Range/4; MIN_XY=MIN-Range/4;\n% OUTPUT: bandwidth - a row vector with the two optimal\n% bandwidths for a bivaroate Gaussian kernel;\n% the format is:\n% bandwidth=[bandwidth_X, bandwidth_Y];\n% density - an n by n matrix containing the density values over the n by n grid;\n% density is not computed unless the function is asked for such an output;\n% X,Y - the meshgrid over which the variable \"density\" has been computed;\n% the intended usage is as follows:\n% surf(X,Y,density)\n% Example (simple Gaussian mixture)\n% clear all\n% % generate a Gaussian mixture with distant modes\n% data=[randn(500,2);\n% randn(500,1)+3.5, randn(500,1);];\n% % call the routine\n% [bandwidth,density,X,Y]=kde2d(data);\n% % plot the data and the density estimate\n% contour3(X,Y,density,50), hold on\n% plot(data(:,1),data(:,2),'r.','MarkerSize',5)\n%\n% Example (Gaussian mixture with distant modes):\n%\n% clear all\n% % generate a Gaussian mixture with distant modes\n% data=[randn(100,1), randn(100,1)/4;\n% randn(100,1)+18, randn(100,1);\n% randn(100,1)+15, randn(100,1)/2-18;];\n% % call the routine\n% [bandwidth,density,X,Y]=kde2d(data);\n% % plot the data and the density estimate\n% surf(X,Y,density,'LineStyle','none'), view([0,60])\n% colormap hot, hold on, alpha(.8)\n% set(gca, 'color', 'blue');\n% plot(data(:,1),data(:,2),'w.','MarkerSize',5)\n%\n% Example (Sinusoidal density):\n%\n% clear all\n% X=rand(1000,1); Y=sin(X*10*pi)+randn(size(X))/3; data=[X,Y];\n% % apply routine\n% [bandwidth,density,X,Y]=kde2d(data);\n% % plot the data and the density estimate\n% surf(X,Y,density,'LineStyle','none'), view([0,70])\n% colormap hot, hold on, alpha(.8)\n% set(gca, 'color', 'blue');\n% plot(data(:,1),data(:,2),'w.','MarkerSize',5)\n%\n% Reference:\n% Kernel density estimation via diffusion\n% Z. I. Botev, J. F. Grotowski, and D. P. Kroese (2010)\n% Annals of Statistics, Volume 38, Number 5, pages 2916-2957.\nglobal N A2 I\nif nargin<2\n n=2^8;\nend\nn=2^ceil(log2(n)); % round up n to the next power of 2;\nN=size(data,1);\nif nargin<3\n MAX=max(data,[],1); MIN=min(data,[],1); Range=MAX-MIN;\n MAX_XY=MAX+Range/2; MIN_XY=MIN-Range/2;\nend\nscaling=MAX_XY-MIN_XY;\nif N<=size(data,2)\n error('data has to be an N by 2 array where each row represents a two dimensional observation')\nend\ntransformed_data=(data-repmat(MIN_XY,N,1))./repmat(scaling,N,1);\n%bin the data uniformly using regular grid;\ninitial_data=ndhist(transformed_data,n);\n% discrete cosine transform of initial data\na= dct2d(initial_data);\n% now compute the optimal bandwidth^2\n I=(0:n-1).^2; A2=a.^2;\n t_star=root(@(t)(t-evolve(t)),N);\np_02=func([0,2],t_star);p_20=func([2,0],t_star); p_11=func([1,1],t_star);\nt_y=(p_02^(3/4)/(4*pi*N*p_20^(3/4)*(p_11+sqrt(p_20*p_02))))^(1/3);\nt_x=(p_20^(3/4)/(4*pi*N*p_02^(3/4)*(p_11+sqrt(p_20*p_02))))^(1/3);\n% smooth the discrete cosine transform of initial data using t_star\na_t=exp(-(0:n-1)'.^2*pi^2*t_x/2)*exp(-(0:n-1).^2*pi^2*t_y/2).*a; \n% now apply the inverse discrete cosine transform\nif nargout>1\n density=idct2d(a_t)*(numel(a_t)/prod(scaling));\n\tdensity(density<0)=eps; % remove any negative density values\n [X,Y]=meshgrid(MIN_XY(1):scaling(1)/(n-1):MAX_XY(1),MIN_XY(2):scaling(2)/(n-1):MAX_XY(2));\nend\nbandwidth=sqrt([t_x,t_y]).*scaling; \nend\n%#######################################\nfunction [out,time]=evolve(t)\nglobal N\nSum_func = func([0,2],t) + func([2,0],t) + 2*func([1,1],t);\ntime=(2*pi*N*Sum_func)^(-1/3);\nout=(t-time)/time;\nend\n%#######################################\nfunction out=func(s,t)\nglobal N\nif sum(s)<=4\n Sum_func=func([s(1)+1,s(2)],t)+func([s(1),s(2)+1],t); const=(1+1/2^(sum(s)+1))/3;\n time=(-2*const*K(s(1))*K(s(2))/N/Sum_func)^(1/(2+sum(s)));\n out=psi(s,time);\nelse\n out=psi(s,t);\nend\n\nend\n%#######################################\nfunction out=psi(s,Time)\nglobal I A2\n% s is a vector\nw=exp(-I*pi^2*Time).*[1,.5*ones(1,length(I)-1)];\nwx=w.*(I.^s(1));\nwy=w.*(I.^s(2));\nout=(-1)^sum(s)*(wy*A2*wx')*pi^(2*sum(s));\nend\n%#######################################\nfunction out=K(s)\nout=(-1)^s*prod((1:2:2*s-1))/sqrt(2*pi);\nend\n%#######################################\nfunction data=dct2d(data)\n% computes the 2 dimensional discrete cosine transform of data\n% data is an nd cube\n[nrows,ncols]= size(data);\nif nrows~=ncols\n error('data is not a square array!')\nend\n% Compute weights to multiply DFT coefficients\nw = [1;2*(exp(-i*(1:nrows-1)*pi/(2*nrows))).'];\nweight=w(:,ones(1,ncols));\ndata=dct1d(dct1d(data)')';\n function transform1d=dct1d(x)\n\n % Re-order the elements of the columns of x\n x = [ x(1:2:end,:); x(end:-2:2,:) ];\n\n % Multiply FFT by weights:\n transform1d = real(weight.* fft(x));\n end\nend\n%#######################################\nfunction data = idct2d(data)\n% computes the 2 dimensional inverse discrete cosine transform\n[nrows,ncols]=size(data);\n% Compute wieghts\nw = exp(i*(0:nrows-1)*pi/(2*nrows)).';\nweights=w(:,ones(1,ncols));\ndata=idct1d(idct1d(data)');\n function out=idct1d(x)\n y = real(ifft(weights.*x));\n out = zeros(nrows,ncols);\n out(1:2:nrows,:) = y(1:nrows/2,:);\n out(2:2:nrows,:) = y(nrows:-1:nrows/2+1,:);\n end\nend\n%#######################################\nfunction binned_data=ndhist(data,M)\n% this function computes the histogram\n% of an n-dimensional data set;\n% 'data' is nrows by n columns\n% M is the number of bins used in each dimension\n% so that 'binned_data' is a hypercube with\n% size length equal to M;\n[nrows,ncols]=size(data);\nbins=zeros(nrows,ncols);\nfor i=1:ncols\n [dum,bins(:,i)] = histc(data(:,i),[0:1/M:1],1);\n bins(:,i) = min(bins(:,i),M);\nend\n% Combine the vectors of 1D bin counts into a grid of nD bin\n% counts.\nbinned_data = accumarray(bins(all(bins>0,2),:),1/nrows,M(ones(1,ncols)));\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction t=root(f,N)\n% try to find smallest root whenever there is more than one\nN=50*(N<=50)+1050*(N>=1050)+N*((N<1050)&(N>50));\ntol=10^-12+0.01*(N-50)/1000;\nflag=0;\nwhile flag==0\n try\n t=fzero(f,[0,tol]);\n flag=1;\n catch\n tol=min(tol*2,.1); % double search interval\n end\n if tol==.1 % if all else fails\n t=fminbnd(@(x)abs(f(x)),0,.1); flag=1;\n end\nend\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "acerbilab", "repo": "vbmc", "sha": "54ba2cdd6c11d2595b9613557da14573abbb7b92", "save_path": "github-repos/MATLAB/acerbilab-vbmc", "path": "github-repos/MATLAB/acerbilab-vbmc/vbmc-54ba2cdd6c11d2595b9613557da14573abbb7b92/utils/kde2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7417857515689014}} {"text": "function [weight] = create_gc_weights(xDim, yDim, zDim, xVar, yVar, zVar)\n% NeuroSLAM System Copyright (C) 2018-2019 \n% NeuroSLAM: A Brain inspired SLAM System for 3D Environments\n%\n% Fangwen Yu (www.yufangwen.com), Jianga Shang, Youjian Hu, Michael Milford(www.michaelmilford.com) \n%\n% The NeuroSLAM V1.0 (MATLAB) was developed based on the OpenRatSLAM (David et al. 2013). \n% The RatSLAM V0.3 (MATLAB) developed by David Ball, Michael Milford and Gordon Wyeth in 2008.\n% \n% Reference:\n% Ball, David, Scott Heath, Janet Wiles, Gordon Wyeth, Peter Corke, and Michael Milford.\n% \"OpenRatSLAM: an open source brain-based SLAM system.\" Autonomous Robots 34, no. 3 (2013): 149-176.\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 % Creates a 3D normalised distributio of size dimension^3 with a variance of var.\n\n xDimCentre = floor(xDim / 2) + 1;\n yDimCentre = floor(yDim / 2) + 1;\n zDimCentre = floor(zDim / 2) + 1;\n\n weight = zeros(xDim, yDim, zDim);\n \n for z = 1 : zDim \n for x = 1 : xDim\n for y = 1 : yDim\n weight(x,y,z) = 1/(xVar*sqrt(2*pi))*exp((-(x - xDimCentre) ^ 2) / (2 * xVar ^ 2)) ...\n * 1/(yVar*sqrt(2*pi))*exp((-(y - yDimCentre) ^ 2) / (2 * yVar ^ 2)) ...\n * 1/(zVar*sqrt(2*pi))*exp((-(z - zDimCentre) ^ 2) / (2 * zVar ^ 2)); \n end\n end\n end\n\n % ensure that it is normalised\n total = sum(sum(sum(weight)));\n weight = weight./total; \n\nend", "meta": {"author": "cognav", "repo": "NeuroSLAM", "sha": "07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac", "save_path": "github-repos/MATLAB/cognav-NeuroSLAM", "path": "github-repos/MATLAB/cognav-NeuroSLAM/NeuroSLAM-07c0d895f6aa472f07aa03e19c9cc86ab2fea9ac/01_conjunctive_pose_cells_network/3d_grid_cells_network/create_gc_weights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7417857435008968}} {"text": "function [normal,normalf] = compute_normal(vertex,face)\n\n% compute_normal - compute the normal of a triangulation\n%\n% [normal,normalf] = compute_normal(vertex,face);\n%\n% normal(i,:) is the normal at vertex i.\n% normalf(j,:) is the normal at face j.\n%\n% Copyright (c) 2004 Gabriel Peyr�\n\n[vertex,face] = check_face_vertex(vertex,face);\n\nnface = size(face,2);\nnvert = size(vertex,2);\nnormal = zeros(3, nvert);\n\n% unit normals to the faces\nnormalf = crossp( vertex(:,face(2,:))-vertex(:,face(1,:)), ...\n vertex(:,face(3,:))-vertex(:,face(1,:)) );\nd = sqrt( sum(normalf.^2,1) ); d(d0)0)\n% w - Shape parameter (w>0)\n% F - PDF of Beta distribution with shape parameters [v,w] at points x\n%__________________________________________________________________________\n%\n% spm_Bpdf implements the Probability Density Function for Beta distributions.\n%\n% Definition:\n%--------------------------------------------------------------------------\n% The PDF of the Beta distribution shape parameters v & w, defined\n% for positive integer degrees of freedom v>0 & w>0, and for x in\n% [0,1] is given by: (See Evans et al., Ch5)\n%\n% x^(v-1) * (1-x)^(w-1)\n% f(x) = -----------------------\n% beta(v,w)\n%\n% Variate relationships:\n%--------------------------------------------------------------------------\n% Many: See Evans et al., Ch5\n%\n% Algorithm:\n%--------------------------------------------------------------------------\n% Direct computation using logs and MATLAB's implementation of the log\n% beta function (betaln).\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% Copyright (C) 1999-2011 Wellcome Trust Centre for Neuroimaging\n\n% Andrew Holmes\n% $Id: spm_Bpdf.m 4182 2011-02-01 12:29:09Z guillaume $\n\n\n%-Format arguments, note & check sizes\n%--------------------------------------------------------------------------\nif nargin<3, error('Insufficient arguments'), end\n\nad = [ndims(x);ndims(v);ndims(w)];\nrd = max(ad);\nas = [[size(x),ones(1,rd-ad(1))];...\n [size(v),ones(1,rd-ad(2))];...\n [size(w),ones(1,rd-ad(3))]];\nrs = max(as);\nxa = prod(as,2)>1;\nif sum(xa)>1 && any(any(diff(as(xa,:)),1))\n error('non-scalar args must match in size');\nend\n\n%-Computation\n%--------------------------------------------------------------------------\n%-Initialise result to zeros\nf = zeros(rs);\n\n%-Only defined for x in [0,1] & strictly positive v & w.\n% Return NaN if undefined.\nmd = ( x>=0 & x<=1 & v>0 & w>0 );\nif any(~md(:))\n f(~md) = NaN;\n warning('Returning NaN for out of range arguments');\nend\n\n%-Special cases: x=0 & x=1\nf(md & x==0 & v<1) = Inf;\nf(md & x==1 & w<1) = Inf;\n\n%-Non-zero where defined & x in (0,1)\nQ = find( md & x>0 & x<1 );\nif isempty(Q), return, end\nif xa(1), Qx=Q; else Qx=1; end\nif xa(2), Qv=Q; else Qv=1; end\nif xa(3), Qw=Q; else Qw=1; end\n\n%-Compute\nf(Q) = exp((v(Qv)-1).*log(x(Qx)) + (w(Qw)-1).*log(1-x(Qx)) -betaln(v(Qv),w(Qw)));\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_Bpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7417257048618469}} {"text": "function value = r8_shi ( x )\n\n%*****************************************************************************80\n%\n%% R8_SHI evaluates the hyperbolic sine integral Shi of an R8 argument.\n%\n% Discussion:\n%\n% Shi ( x ) = Integral ( 0 <= t <= x ) sinh ( t ) dt / t\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 hyperbolic sine integral\n% Shi evaluated at X.\n%\n persistent nshi\n persistent shics\n persistent xsml\n\n if ( isempty ( nshi ) )\n\n shics = [ ...\n 0.0078372685688900950695200984317332, ...\n 0.0039227664934234563972697574427225, ...\n 0.0000041346787887617266746747908275, ...\n 0.0000000024707480372882742135145302, ...\n 0.0000000000009379295590763630457157, ...\n 0.0000000000000002451817019520867353, ...\n 0.0000000000000000000467416155257592, ...\n 0.0000000000000000000000067803072389, ...\n 0.0000000000000000000000000007731289, ...\n 0.0000000000000000000000000000000711 ]';\n\n nshi = r8_inits ( shics, 10, 0.1 * r8_mach ( 3 ) );\n xsml = sqrt ( r8_mach ( 3 ) );\n\n end\n\n absx = abs ( x );\n\n if ( absx <= xsml )\n value = x;\n elseif ( absx <= 0.375 )\n value = x * ( 1.0 + r8_csevl ( 128.0 * x * x / 9.0 - 1.0, shics, nshi ) );\n else\n value = 0.5 * ( r8_ei ( x ) + r8_e1 ( 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/fn/r8_shi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7417169512658316}} {"text": "function [am,em]=v_lpcrr2am(rr);\n%V_LPCRR2AM Convert autocorrelation coefs to ar coef matrix [AM,EM]=(RR)\n%AM is a 3-dimensional matrix of size (p+1,p+1,nf) where p is the lpc order\n%and nf the number of frames.\n%The matrix AM(:,:,*) is upper triangular with 1's on the main diagonal\n%and contains the lpc coefficients for all orders from p down to 0.\n%\n%For lpc order p+1-r, AM(r,r:p+1,*), AM(p+1:-1:r,p+1,*) and EM(*,r) contain\n%the lpc coefficients, reflection coefficients and the residual energy respectively.\n%\n%If A=am(:,:,*), R=toeplitz(rr(*,:)) and E=diag(em(*,:)), then\n% A*R*A'=E; inv(R)=A'*(1/E)*A; A*R is lower triangular with the same diagonal as E\n%\n% This routine is equivalent to: c=chol(inv(toeplitz(rr))); d=diag(c).^-1; em=d.^2; am=diag(d)*c\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: v_lpcrr2am.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[nf,p1]=size(rr);\np=p1-1;\np2=p1+1;\nam=zeros(nf,p1,p1);\nem=zeros(nf,p1);\nam(:,p1,p1)=1;\nem(:,p1)=rr(:,1);\nar=ones(nf,p1);\nar(:,2) = -rr(:,2)./rr(:,1);\ne = rr(:,1).*(ar(:,2).^2-1);\nfor n = 2:p\n q=p2-n;\n em(:,q)=-e;\n am(:,q:p1,q)=ar(:,1:n);\n k = (rr(:,n+1)+sum(rr(:,n:-1:2).*ar(:,2:n),2)) ./ e;\n ar(:,2:n) = ar(:,2:n)+k(:,ones(1,n-1)).*ar(:,n:-1:2);\n ar(:,n+1) = k;\n e = e.*(1-k.^2);\nend\nem(:,1)=-e;\nam(:,:,1)=ar;\nam=permute(am,[3 2 1]);\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_lpcrr2am.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7417169368632185}} {"text": "function out = proj_hyperplane_box(x,a,b,l,u)\n%PROJ_HYPERPLANE_BOX computes the orthogonal projection onto the intersection of a hyperplane and a box {x:=b,l<=x<=u}\n%\n% Usage:\n% out = PROJ_HYPERPLANE_BOX(x,a,b,[l],[u])\n% ===========================================\n% Input:\n% x - point to be projected (vector/matrix)\n% a - vector/matrix\n% b - scalar\n% l - lower bound (vector/matrix/scalar) [default: -inf]\n% u - upper bound (vector/matrix/scalar) [default: inf]\n% ===========================================\n% Assumptions:\n% The intersection of the hyperplane and the box is nonempty\n% ===========================================\n% Output:\n% out - projection vector\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: proj_hyperplane_box(x,a,b,[l],[u])') ;\nend\n\nif (nargin < 5)\n %upper bound is not given, setting to defalut value :inf\n u = inf ;\nend\nif ((nargin < 4) || (isempty( l)))\n %lower bound is not given, setting to defalut value :-inf\n l = -inf;\nend\n\n%checking that sum (l) < b < sum (u)\n\n\nsumlb = trace(a'*((l .* (sign(a)>0)) + (u .* (sign(a)<0)))) ;\nsumub = trace(a'*((u .* (sign(a)>0)) + (l .* (sign(a)<0)))) ;\n\nif ((sumlb > b) || (any(any(l > u))) || (sumub < b))\n error('Set is infeasible') ;\nend\n\n%solve with equality\n%defining f on lambda - to be used by the bisetion\n\neps = 1e-10 ;\n\nf= @(lam) trace(a'*min(max(x-lam*a,l),u))-b;\nlambda_min = -1;\nwhile(f(lambda_min)<0)\n lambda_min = lambda_min *2 ;\nend\n\nlambda_max = 1;\nwhile(f(lambda_max)>0)\n lambda_max = lambda_max *2 ;\nend\n\nfinal_lam = bisection(f,lambda_min,lambda_max,eps) ;\nout= min(max(x-final_lam*a,l),u) ;\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/proj_hyperplane_box.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7417077928360446}} {"text": "function [ n_data, x, fx ] = bessel_j1_values ( n_data )\n\n%*****************************************************************************80\n%\n%% BESSEL_J1_VALUES returns some values of the J1 Bessel function.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% BesselJ[1,x]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 August 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 21;\n\n fx_vec = [ ...\n 0.3275791375914652E+00, ... \n 0.6604332802354914E-01, ... \n -0.3390589585259365E+00, ... \n -0.5767248077568734E+00, ... \n -0.4400505857449335E+00, ... \n 0.0000000000000000E+00, ... \n 0.4400505857449335E+00, ... \n 0.5767248077568734E+00, ... \n 0.3390589585259365E+00, ... \n -0.6604332802354914E-01, ... \n -0.3275791375914652E+00, ... \n -0.2766838581275656E+00, ... \n -0.4682823482345833E-02, ... \n 0.2346363468539146E+00, ... \n 0.2453117865733253E+00, ... \n 0.4347274616886144E-01, ... \n -0.1767852989567215E+00, ... \n -0.2234471044906276E+00, ... \n -0.7031805212177837E-01, ... \n 0.1333751546987933E+00, ... \n 0.2051040386135228E+00 ];\n\n x_vec = [ ...\n -5.0E+00, ...\n -4.0E+00, ...\n -3.0E+00, ...\n -2.0E+00, ...\n -1.0E+00, ...\n 0.0E+00, ...\n 1.0E+00, ...\n 2.0E+00, ...\n 3.0E+00, ...\n 4.0E+00, ...\n 5.0E+00, ...\n 6.0E+00, ...\n 7.0E+00, ...\n 8.0E+00, ...\n 9.0E+00, ...\n 10.0E+00, ...\n 11.0E+00, ...\n 12.0E+00, ...\n 13.0E+00, ...\n 14.0E+00, ...\n 15.0E+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 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/bessel_j1_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7417077724011332}} {"text": "function [sampleLabels, groupCodingLengths] = coding_seg(W, epsilon, affine )\n\n% coding_seg.m\n%\n% Implements an agglomerative segmentation algorithm which attempts to\n% minimize the number of bits needed to code the segmented vectors upto\n% distortion epsilon^2. This method is described in detail in Ma, et. al.,\n% Segmentation of Multivariate Mixed Data via Lossy Coding and Compression,\n% PAMI 2007.\n%\n% Run test_coding_seg.m, included in this package, for a demonstration. \n%\n% Inputs:\n% W - [ w1 | w2 | ... | wm ], the data matrix. \n% The columns are the input data vectors. \n%\n% epsilon - sqrt of the allowable distortion, \n% E[ \\| \\hat{w_i} - w_i \\|^2 ]\n%\n% affine - boolean, if true the algorithm uses the coding length for\n% nonzero-mean data, derived in Appendix II of the paper.\n%\n% Outputs:\n% sampleLabels - 1 x m list whose i-th entry is the group assignment of\n% the i-th data vector w_i. Groups are indexed\n% sequentially, starting from 1. \n%\n% Dependencies:\n% coding_length.m\n%\n% Feb '06, last revision Jan '07\n% Questions? John Wright -- jnwright@uiuc.edu\n\n% Copyright 2007, University of Illinois. All rights reserved. \n\n VERBOSE = 0;\n\n epsilon2 = epsilon^2;\n\n % n - dimension \n % m - number of samples\n [n,m] = size(W);\n\n % initially treat each sample as its own group\n sampleLabels = 1:m;\n curGroupCount = m;\n\n % compute the coding length of each of the initial groups\n squaredNormW = sum(W.^2,1);\n if affine\n groupCodingLengths = n * log2(1 + (squaredNormW/epsilon2))/ 2 + log2(m);\n else\n groupCodingLengths = (n + 1) * log2(1 + (n / epsilon2)*squaredNormW)/ 2 + log2(m);\n end\n\n if VERBOSE\n disp(' Computing initial table.');\n end\n\n % entropyChange is a matrix whose ij-th element is the entropy lost by\n % merging groups i and j into one group.\n delta_L_matrix = ones(m);\n\n for groupIndex1 = 1 : m-1\n for groupIndex2 = groupIndex1+1 : m\n L1 = groupCodingLengths(groupIndex1);\n L2 = groupCodingLengths(groupIndex2);\n L_union = coding_length(W(:, [groupIndex1 groupIndex2]),epsilon2,m,affine);\n delta_L_matrix(groupIndex1, groupIndex2) = L_union - L1 - L2;\n end;\n end;\n\n if VERBOSE\n disp(' Starting merging process');\n end\n\n while curGroupCount > 1 \n\n if mod( curGroupCount, 50 ) == 0 && VERBOSE\n disp([' Group count: ' num2str(curGroupCount)]);\n end\n\n % Find the best two groups to merge together\n [temp minIndex]=min(delta_L_matrix);\n [min_delta_L minIndex2]=min(temp);\n minIndex1=minIndex(minIndex2);\n\n % If this does not decrease the coding length, we are done\n if ( min_delta_L > 0 )\n break;\n end;\n\n % Merging groups with labels minIndex1 and minIndex2\n if (minIndex1 > minIndex2)\n temp = minIndex1;\n minIndex1 = minIndex2;\n minIndex2 = temp;\n end\n\n if (minIndex2 ~= curGroupCount)\n % First make the group to merge have the last label\n\n % Change the sample labels of the group minIndex2 to be the last\n % label.\n sampleLabels(sampleLabels == curGroupCount) = -1;\n sampleLabels(sampleLabels == minIndex2) = curGroupCount;\n sampleLabels(sampleLabels == -1) = minIndex2;\n\n % Swap the entropy of groups minIndex2 and the last group. \n [groupCodingLengths(minIndex2), groupCodingLengths(curGroupCount)] = ...\n swap(groupCodingLengths(minIndex2), groupCodingLengths(curGroupCount));\n\n delta_L_matrix = swap_matrix(delta_L_matrix, minIndex2, curGroupCount);\n\n end\n\n % Now we can assume the last group is the group to be merged \n sampleLabels(sampleLabels == curGroupCount) = minIndex1;\n groupCodingLengths(curGroupCount) = [];\n groupCodingLengths(minIndex1) = coding_length(W(:, sampleLabels == minIndex1),epsilon2,m,affine);\n delta_L_matrix = delta_L_matrix(1:end-1, 1:end-1);\n\n curGroupCount = curGroupCount - 1; \n\n for groupIndex2 = [1:minIndex1-1 minIndex1+1:curGroupCount],\n i = min(minIndex1, groupIndex2); j = max(minIndex1, groupIndex2); \n L1 = groupCodingLengths(i);\n L2 = groupCodingLengths(j);\n L_union = coding_length(W(:, (sampleLabels == i) | (sampleLabels == j)) ,epsilon2,m,affine);\n delta_L_matrix(i, j) = L_union - L1 - L2; \n end;\n end;\n\n %codingLength = sum(groupCodingLengths);\n\n if VERBOSE\n disp([' Final group count: ' num2str(curGroupCount)]);\n end\n\nend\n% If A is an upper triangular matrix where A(m,n) = f(x_m,x_n) for m < n\n% relabel so that the roles of x_i and x_j are swapped.\nfunction A = swap_matrix(A, i, j)\n[A(1:i-1, i), A(1:i-1, j)] = swap(A(1:i-1, i), A(1:i-1, j));\n[A(i, i+1:j-1), A(i+1:j-1, j)] = swap(A(i, i+1:j-1), A(i+1:j-1, j));\n[A(i, j+1:end), A(j, j+1:end)] = swap(A(i, j+1:end), A(j, j+1:end));\nend\n\n% swap the values of x and y\nfunction [y, x] = swap(x,y)\nend", "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/coding_seg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7416895382032597}} {"text": "% Convert a stroke [x,y,t] such that it is uniformly sampled\n% in time. This is done by linear interpolation in time\n%\n% Input\n% stk: [n x 2] for x and y\n% time: [n x 1] for time coordinate\n% tint: [scalar] time interval (in milliseconds)\n%\n% Output\n% unif_stk: [k x 2] new stroke x and y \n% unif_t: [k x 1] uniform time interval\n%\nfunction [unif_stk,unif_t] = uniform_time_lerp(stk,time,tint)\n\n mint = min(time);\n maxt = max(time);\n \n unif_t = mint:tint:maxt;\n % make sure we don't leave out the last point\n if unif_t(end) ~= maxt \n unif_t = [unif_t maxt]; \n end \n nt = length(unif_t);\n \n unif_stk = zeros(length(unif_t),2);\n for i=1:nt\n ti = unif_t(i);\n \n diff = time-ti;\n if any(diff==0)\n sel = stk(diff==0,:); \n unif_stk(i,:) = mean(sel,1);\n continue\n end\n \n % find the point before and after in time\n indx_gt = find(diff>0,1,'first');\n indx_lt = find(diff<0,1,'last');\n \n x_gt = stk(indx_gt,:);\n x_lt = stk(indx_lt,:);\n t_gt = time(indx_gt);\n t_lt = time(indx_lt); \n \n % Compute the linear interpolation\n frac = (ti - t_lt) ./ (t_gt - t_lt);\n assert(frac<=1);\n unif_stk(i,:) = (1-frac).*x_lt + frac.*x_gt;\n end\n\nend", "meta": {"author": "brendenlake", "repo": "BPL", "sha": "2c7f679bb0055f29cbade7ef099897c3342bcb79", "save_path": "github-repos/MATLAB/brendenlake-BPL", "path": "github-repos/MATLAB/brendenlake-BPL/BPL-2c7f679bb0055f29cbade7ef099897c3342bcb79/data/uniform_time_lerp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7416895305938702}} {"text": "%GRAD_AND_DIV\n% Generates pressure gradient matrices Pu, Pv and divergence matrix D\n% Vectorized matrix generation by evaluation of stencil coefficients\n% Output: Pu, Pv, Du, Dv\n\nJ= length(dx); K = length(dy);\n\n%.................Pressure gradient matrix Pu ....................\n\n% \t | 0 |\n% Stencil: [Pu] = |p1 p2 0 |\n% \t | 0 |\n\n% Indexing convention in staggered grid:\n% +--k+1--+ \n% | |\n% j jk j+1\n% | |\n% +---k---+ \ntic\np2 = 1./DXU(1,:)'; p1 = zeros(size(p2)); p1(1:J) = -p2(2:J+1); \nPuu = spdiags([p1 p2],[-1;0], J+1, J); Pu = kron(speye(K),Puu);\n\n%......................Boundary corrections....................................\nfor seg = 1:length(ybc(1,:))\n if (ybc(1,seg) == 1)|(ybc(1,seg) == 2) % No-slip or inflow at left boundary\n k = 1+kseg(seg):kseg(seg+1); Pu(1+(k-1)*(J+1),:) = 0;\n end\n if (ybc(2,seg) == 1)|(ybc(2,seg) == 2) % No-slip or inflow at right boundary\n k = 1+kseg(seg):kseg(seg+1); Pu(k*(J+1),:) = 0; \n end\nend\ntijd = toc; disp(['Breakdown of grad_and_div time'])\ndisp([' Pu time = ',num2str(tijd)])\n\n%.................Pressure gradient matrix Pv ....................\n\n% \t | 0 |\n% Stencil: [Pv] = |0 p2 0|\n% \t | p1 |\n\ntic\npp1 = zeros(size(XV)); pp2 = pp1; \t\t% Diagonals of Pv\npp1(2:K+1,:) = -1./DYV(2:K+1,:); \tpp2 = -pp1;\npp2(1,:) = 1./DYV(1,:); \t\tpp2(K+1,:) = 0;\n\n%......................Boundary corrections....................................\nfor seg = 1:length(xbc(1,:))\n if (xbc(1,seg) == 1)|(xbc(1,seg) == 2) % No-slip or inflow at lower boundary\n j = 1+jseg(seg):jseg(seg+1); \tpp1(1,j) = 0; pp2(1,j) = 0; \n end\n if (xbc(2,seg) == 1)|(xbc(2,seg) == 2) % No-slip or inflow at upper boundary\n j = 1+jseg(seg):jseg(seg+1);\tpp1(K+1,j) = 0; pp2(K+1,j) = 0; \n end\nend\nn = J*(K+1); p1 = reshape(pp1',n,1); p2 = reshape(pp2',n,1);\np1 = [p1(J+1:n); zeros(J,1)];\t\t% Shift to accomodate spdiags\nPv = spdiags([p1 p2],[-J;0], n,n-J);\ntijd = toc; disp([' Pv time = ',num2str(tijd)])\n\n%.................u divergence matrix Du ....................\n\n%\t\t | 0 |\n% Stencil: [Du] = |0 p1 p2| \n%\t\t | 0 |\n\ntic\nDuu = spdiags([-ones(J,1) ones(J,1)], [0;1], J,J+1);\nDu = kron(spdiags(dy',0,K,K),Duu);\ntijd = toc; disp([' Du time = ',num2str(tijd)])\n\n%.................v divergence matrix Dv ....................\n\n%\t\t | p2 |\n% Stencil: [Dv] = |0 p1 0| \n%\t\t | 0 |\n\ntic\nDvv = spdiags([-ones(K,1) ones(K,1)], [0;1], K,K+1);\nDv = kron(Dvv,spdiags(dx',0,J,J));\ntijd = toc; disp([' Dv time = ',num2str(tijd)])\n\nclear pp1 pp2 p1 p2 Puu Duu Dvv \t\t\t% Save storage\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/chap6.5/grad_and_div.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7416839856738313}} {"text": "N = 15; % Set N as an odd number;\nw0 = 0.4*pi;\nn0 = floor(N/2);\nhn = zeros(1,N);\nfor i = 1:length(hn)\n if i == n0\n hn(i) = w0/pi;\n else\n hn(i) = sin(w0*(i-n0))/(pi*(i-n0));\n end;\nend;\nsubplot(3,1,1);stem(hn);title('h[n]');\n \nNp = 1000;\nhn = [hn,zeros(1, Np-length(hn))];%zero padding\n[w,y] = calculateDiscreteFourierTransform(hn);\n \nsubplot(3,1,2);plot(w,abs(y)),title('幅度谱');\nsubplot(3,1,3);plot(w,angle(y)),title('相位谱');\n", "meta": {"author": "VipaiLab", "repo": "Signals-and-Systems-course", "sha": "a48269b0247359ab746cb42bb55c984ed850e437", "save_path": "github-repos/MATLAB/VipaiLab-Signals-and-Systems-course", "path": "github-repos/MATLAB/VipaiLab-Signals-and-Systems-course/Signals-and-Systems-course-a48269b0247359ab746cb42bb55c984ed850e437/信号与系统MATLAB程序示例/8. FIR数字滤波器设计程序/showhn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.741615473222414}} {"text": "function geometry_test2062 ( )\n\n%*****************************************************************************80\n%\n%% TEST2062 tests TRIANGLE_AREA_HERON;\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 dim_num = 3;\n\n t = [ ...\n 1.0, 0.0, 0.0; ...\n 0.0, 1.0, 0.0; ...\n 0.0, 0.0, 1.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST2062\\n' );\n fprintf ( 1, ' For a triangle in any dimension,\\n' );\n fprintf ( 1, ' TRIANGLE_AREA_HERON computes the area;\\n' );\n\n r8mat_transpose_print ( dim_num, 3, t, ' Triangle vertices:' );\n\n for j = 1 : 3\n\n s(j) = 0.0;\n\n jp1 = mod ( j, 3 ) + 1;\n\n for i = 1 : dim_num\n s(j) = s(j) + ( t(i,j) - t(i,jp1) ).^2;\n end\n\n s(j) = sqrt ( s(j) );\n\n end\n\n r8vec_print ( 3, s, ' Side lengths:' );\n\n area = triangle_area_heron ( s );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The area is %f\\n', area );\n\n return\nend\n", "meta": {"author": "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_test2062.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.8221891348788759, "lm_q1q2_score": 0.741549372095022}} {"text": "function x = Adj_USFFT(n,y,omega,D,L,center)\n% USFFT_simple -- 1d adjoint unequispaced Fourier transform\n% Usage:\n% x = USFFT(n,y,omega,D,L,center)\n% Inputs:\n% n length of output x\n% y\t vector of length m, \n% omega vector of sampled frequencies (length m)\n% center 0 for unbiased FT, 1 otherwise\n% Outputs:\n% x vector of length n\n% Description:\n% Evaluates the adjoint of the FT\n% \n% If center = 0, \n%\n% x(t) = sum_{k} exp(i omega_k t) y(k), -n/2 <= t < n/2\n%\n% If center = 1, \n%\n% x(t) = sum_{k} exp(i omega_k t) y(k), 0 <= t < n\n% \n% See Also\n% USFFT, USFT_simple, Evaluate_FT\n% Notes:\n% To work properly, D*n must be even\n%\n% By Emmanuel candes, 2003-2004\n\n if nargin < 6,\n center = 0;\n end\n \n if nargin < 5,\n L = 4;\n end\n \n if nargin < 4,\n D = 16;\n end\n \n n2 = n/2;\n N = D*n; N2 = N/2;\n m = length(omega);\n \n if rem(L,2) == 1,\n L = L + 1;\n end\n \n % Nearest point calculations\n \n near_index = round(N *omega/(2*pi));\n row = near_index + N/2 + 1;\n \n delta = omega - 2*pi*near_index/N; \n \n % Make matrix y(k) * delta(k)^l, l = 0, 1, ..., L-1\n \n FA = repmat(y(:),1,L); \n for l = 2:L;\n FA(:,l) = FA(:,l-1) .* delta/(l-1);\n end\n \n % Sum entries corresponding to the same index \n \n F = zeros(N,L);\n for k = 1:m,\n F(row(k),:) = F(row(k),:) + FA(k,:);\n end\n \n % Take IFFT along columns\n X = ifft_mid0(F) * N; \n X = X((N2-n2+1):(N2+n2),:);\n \n t = -n2:(n2-1);\n tp = ones(n,L); \n \n for k = 2:L;\n tp(:,k) = tp(:,k-1) .* (i*t.');\n end\t\n \n x = sum(X.*tp,2);\n \n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/CurveLab-2.1.3/fdct_usfft_matlab/USFFT/Adj_USFFT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.74150793318587}} {"text": "function [Xt xfm] = perspective_xfm(X,Y)\n% perspective_xfm - 2D perspective transformation\n%\n% Xt = perspective_xfm(X,Y)\n%\n% X,Y : input matrix (nx2) giving the each points (n) coordinates\n% Xt : X transformed to match Y\n% xfm : tranformation matrices (3x3 and 1x3)\n%\n% 2008/03 SOD: after A Plane Measuring Device by A. Criminisi, I. Reid, and\n% A. Zisserman\n\n% input check\nif ~exist('X','var') || isempty(X), error('Need X'); end\nif ~exist('Y','var') || isempty(Y), error('Need Y'); end\nif ~all(size(X) == size(Y)), error('X and Y need to be the same size'); end\n\n% some variables needed\nn = size(Y,1);\nmy1 = ones(n,1);\nmy0 = zeros(n,3);\n\n% compute xfm\nB = [ X my1 my0 -X(:,1).*Y(:,1) -X(:,2).*Y(:,1) ...\n my0 X my1 -X(:,1).*Y(:,2) -X(:,2).*Y(:,2)];\nB = reshape (B', 8 , n*2)';\n\nD = reshape (Y', n*2 , 1 );\nl = inv(B' * B) * B' * D;\nA = reshape([l(1:6)' 0 0 1 ],3,3)';\nC = [l(7:8)' 1];\n\n\n% now transform\nX = [X my1]';\nXt = ((A*X) ./ (ones(3,1)*(C*X)))';\nXt = Xt(:,1:2);\n\n% xfm matrices\nxfm = [A;C];\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/mrBOLD/Analysis/retinotopyModel/EyeTrack/perspective_xfm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7415079212619031}} {"text": "function [C_tri]=transitivity_bu(A)\n%TRANSITIVITY_BU Transitivity\n%\n% T = transitivity_bu(A);\n%\n% Transitivity is the ratio of 'triangles to triplets' in the network.\n% (A classical version of the clustering coefficient).\n%\n% Input: A binary undirected connection matrix\n%\n% Output: T transitivity scalar\n%\n% Reference: e.g. Humphries et al. (2008) Plos ONE 3: e0002051\n%\n%\n% Alexandros Goulas, Maastricht University, 2010\n\n C_tri = trace(A^3) / (sum(sum(A^2)) - trace(A^2));\n\nreturn;", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/transitivity_bu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7414795936832227}} {"text": "function [lambda_vec, error_train, error_val] = ...\n validationCurve(X, y, Xval, yval)\n%VALIDATIONCURVE Generate the train and validation errors needed to\n%plot a validation curve that we can use to select lambda\n% [lambda_vec, error_train, error_val] = ...\n% VALIDATIONCURVE(X, y, Xval, yval) returns the train\n% and validation errors (in error_train, error_val)\n% for different values of lambda. You are given the training set (X,\n% y) and validation set (Xval, yval).\n%\n\n% Selected values of lambda (you should not change this)\nlambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';\n\n% You need to return these variables correctly.\nerror_train = zeros(length(lambda_vec), 1);\nerror_val = zeros(length(lambda_vec), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return training errors in \n% error_train and the validation errors in error_val. The \n% vector lambda_vec contains the different lambda parameters \n% to use for each calculation of the errors, i.e, \n% error_train(i), and error_val(i) should give \n% you the errors obtained after training with \n% lambda = lambda_vec(i)\n%\n% Note: You can loop over lambda_vec with the following:\n%\n% for i = 1:length(lambda_vec)\n% lambda = lambda_vec(i);\n% % Compute train / val errors when training linear \n% % regression with regularization parameter lambda\n% % You should store the result in error_train(i)\n% % and error_val(i)\n% ....\n% \n% end\n%\n%\n\n\nfor i=1:length(lambda_vec)\n [theta] = trainLinearReg(X,y,lambda_vec(i));\n [error_train(i),~] = linearRegCostFunction(X,y,theta,0);\n [error_val(i),~] = linearRegCostFunction(Xval,yval,theta,0);\nend;\n\n\n\n\n\n\n\n% =========================================================================\n\nend\n", "meta": {"author": "1094401996", "repo": "machine-learning-coursera", "sha": "e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb", "save_path": "github-repos/MATLAB/1094401996-machine-learning-coursera", "path": "github-repos/MATLAB/1094401996-machine-learning-coursera/machine-learning-coursera-e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb/problem_sets/ex5/validationCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.8807970748488297, "lm_q1q2_score": 0.7414775536507121}} {"text": "function [A, C, Z] = ldsPca(X, k, m)\n% Subspace method for learning linear dynamic system.\n% Input:\n% X: d x n data matrix\n% k: dimension of hidden variable\n% m: stacking order for the Hankel matrix\n% Output:\n% A: k x k transition matrix\n% C: k x d emission matrix\n% Z: k x n latent variable\n% Y: d x n reconstructed data\n% reference: Bayesian Reasoning and Machine Learning (BRML) chapter 24.5.3 p.507\n% Written by Mo Chen (sth4nth@gmail.com).\n[d,n] = size(X);\nH = reshape(X(:,hankel(1:m,m:n)),d*m,[]);\n[U,S,V] = svd(H,'econ');\nC = U(1:d,1:k);\nZ = S(1:k,1:k)*V(:,1:k)';\nA = Z(:,2:end)/Z(:,1:end-1); % estimated transition\n% Y = C*Z; % reconstructions", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter13/LDS/ldsPca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7414701961638309}} {"text": "function varargout = slogfrac(varargin)\n%logfrac\n%\n% y = SLOGFRAC(x)\n%\n% Computes/declares log(1 + x(1)/x(2))\n\nswitch class(varargin{1})\n case 'double'\n x = varargin{1}; \n % Safe version with defined negative values (helps fmincon when\n % outside feasible region) \n if all(x==0)\n varargout{1} = log(2);% ?definition...\n elseif x(1)==0\n varargout{1} = log(1);\n else\n aux = 1 + (x(1)./(x(2)+sqrt(eps)));\n if aux <= 0\n varargout{1} = -15;\n else\n varargout{1} = log(1 + (x(1)./(x(2)+sqrt(eps))));\n end\n \n end\n \n case 'sdpvar'\n if min(size(varargin{1}))>1\n error('SLOGFRAC only defined for vector arguments');\n else\n varargout{1} = yalmip('define',mfilename,varargin{1});\n end\n\n case 'char' \n \n operator = CreateBasicOperator('callback');\n operator.range = [-inf inf];\n operator.domain = [-inf inf];\n operator.bounds = @bounds; \n operator.derivative = @(x) ([1./(x(1)+x(2)+sqrt(eps));1./(x(1)+x(2)+sqrt(eps))-(x(2)+sqrt(eps)).^-1]);\n \n varargout{1} = [];\n varargout{2} = operator;\n varargout{3} = varargin{3};\n\n otherwise\n error(['SDPVAR/' upper(mfilename) ' called with weird argument']);\nend\n\nfunction [L,U] = bounds(xL,xU)\n\n% Derive bounds on x1/x2\nz = [xL(1)./xL(2) xU(1)./xL(2) xL(1)./xU(2) xU(1)./xU(2)];\nfL = min(z);\nfU = max(z);\n\nif fL <= -1\n L = -inf;\nelse\n L = log(1 + fL);\nend\nif fU <= -1\n U = -inf;\nelse\n U = log(1 + fU);\nend\n\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/operators/slogfrac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552536, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7413608727069397}} {"text": "function [kf] = ext_kalman_filter(F, G, H, u, Q, R, time, last_measure, kf, P)\n\n%EXT_KALMAN_FILTER - This is the extended Kalman filter.\n%\n% Synthax: \n%\n% Inputs:\n% uu - state variables, delta, wind\n% kf.x_prev - previous a posteriori state estimate\n% kf.P_prev - previous a posteriori estimate covariance\n% last_measure- (time, sensor measure)\n% P - parameters\n% \n% Outputs:\n% kf.x - a priori/a posteriori state estimate\n% kf.P - a priori/a posteriori estimate covariance\n% kf.z_res - post-fit residual\n\n% A -> F\n% B -> G\n% C -> H\n\n% Q - covariance of the zero-mean Gaussian noise on x_dot\n% R - covariance of the zero-mean Gaussian noise on y\n\ntime_m = last_measure(:,1);\nz_m = last_measure(:,2);\n\n% prediction (a priori)\nkf.x = F * kf.x_prev + G * u; % a priori state estimate\nkf.P = F * kf.P_prev * (F') + Q; % a priori estimate covariance\n\n% update (a posteriori)\nif time - time_m < P.dt\n kf.z_tilde = z_m - H*kf.x; % innovation (a priori residual)\n S = R + H*kf.P*(H'); % innovation covariance\n K = kf.P*(H')/S; % optimal kalman gain\n kf.x = kf.x + K*kf.z_tilde; % a posteriori state estimate\n kf.P = kf.P - K*S*(K'); % a posteriori estimate covariance\nend\n\nkf.z_res = z_m - H*kf.x; % a posteriori residual\n\nend\n\n", "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/estimation/ext_kalman_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109713976399, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7413138051531791}} {"text": "function ellipsoid_monte_carlo_test01 ( )\n\n%*****************************************************************************80\n%\n%% ELLIPSOID_MONTE_CARLO_TEST01 uses ELLIPSOID_SAMPLE on a 2D ellipse centered at (0,0).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 August 2014\n%\n% Author:\n%\n% John Burkardt\n%\n m = 2;\n\n a = [ ...\n 9.0, 1.0;\n 1.0, 4.0 ]';\n e_test = [ ...\n 0, 0;\n 1, 0;\n 0, 1;\n 2, 0;\n 1, 1;\n 0, 2;\n 3, 0 ]';\n r = 2.0;\n v = [ 0.0, 0.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ELLIPSOID_MONTE_CARLO_TEST01\\n' );\n fprintf ( 1, ' Use ELLIPSOID_SAMPLE to estimate integrals\\n' );\n fprintf ( 1, ' in a 2D ellipse x'' * A * x <= r^2.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Ellipsoid radius R = %g\\n', r );\n r8vec_print ( m, v, ' Ellipsoid center V:' );\n r8mat_print ( m, m, a, ' Ellipsoid matrix A:' );\n\n volume = ellipsoid_volume ( m, a, v, r );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Ellipsoid volume = %g\\n', volume );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N 1 X Y ' );\n fprintf ( 1, ' X^2 XY Y^2 X^3\\n' );\n fprintf ( 1, '\\n' );\n\n n = 1;\n\n while ( n <= 65536 )\n\n [ x, seed ] = ellipsoid_sample ( m, n, a, v, r, seed );\n\n fprintf ( 1, ' %8d', n );\n\n for j = 1 : 7\n\n e(1:m) = e_test(1:m,j);\n\n value = monomial_value ( m, n, e, x );\n\n result = volume * sum ( value(1:n) ) / n;\n\n fprintf ( 1, ' %14.6g', result );\n\n end\n\n fprintf ( 1, '\\n' );\n\n n = 2 * 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/ellipsoid_monte_carlo/ellipsoid_monte_carlo_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7412913452685836}} {"text": "%% Author: epokh\n%% Website: www.epokh.org/drupy\n%% This software is under GPL\n\nfunction [Mdh]=DHmatrix(theta,d,a,alpha)\n%%output: DH matrix\n%%input: DH parameters:\n%%theta: rotation along x(n) axis\n%%d: traslation along z(n) axis\n%%a: translation along x(n+1) axis\n%%alpha: rotation along x(n+1) axis\n%%all angles expressed in degrees\n\nMdh=[cosd(theta) -sind(theta)*cosd(alpha) sind(theta)*sind(alpha) a*cosd(theta);\n sind(theta) cosd(theta)*cosd(alpha) -cosd(theta)*sind(alpha) a*sind(theta);\n 0,sind(alpha),cosd(alpha),d;\n 0,0,0,1];\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/14886-robotic-toolbox/DHmatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7412775896395075}} {"text": "function disk_monte_carlo_test01 ( )\n\n%*****************************************************************************80\n%\n%% DISK_MONTE_CARLO_TEST01 uses DISK01_SAMPLE with an increasing number of points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n e_test = [ ...\n 0, 0; ...\n 2, 0; ...\n 0, 2; ...\n 4, 0; ...\n 2, 2; ...\n 0, 4; ...\n 6, 0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DISK_MONTE_CARLO_TEST01\\n' );\n fprintf ( 1, ' Use DISK01_SAMPLE to estimate integrals in the unit disk.\\n' );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N 1 X^2 Y^2 ' );\n fprintf ( 1, ' X^4 X^2Y^2 Y^4 X^6\\n' );\n fprintf ( 1, '\\n' );\n\n n = 1;\n\n while ( n <= 65536 )\n\n [ x, seed ] = disk01_sample ( n, seed );\n\n fprintf ( 1, ' %8d', n );\n for j = 1 : 7\n\n e(1:2) = e_test(1:2,j);\n\n value = monomial_value ( 2, n, e, x );\n\n result(j) = disk01_area ( ) * sum ( value(1:n) ) / n;\n fprintf ( 1, ' %14.6g', result(j) );\n end\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:2) = e_test(1:2,j);\n\n result(j) = disk01_monomial_integral ( e );\n fprintf ( 1, ' %14.6g', result(j) );\n end\n\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/disk_monte_carlo/disk_monte_carlo_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7412448314185947}} {"text": "function [yi, ypi] = hermint(x, y, yp, xi, c)\n\n% HERMINT 1-D piecewise hermite interpolation\n% HERMINT(X,Y,YP,XI,C) interpolates to find YI, the values of\n% the underlying function Y at the points in the array XI,\n% using piecewise hermite interpolation. X and Y must be\n% vectors of length N.\n%\n% C specifies the number of data points to use in the\n% interpolation. The default is to use all points.\n%\n% [YI,YPI] = HERMINT() also returns the interpolated derivative\n% of the underlying function Y at points XI.\n\n% Joe Henning - Fall 2011\n\nif (nargin < 5)\n c = 0;\nend\n\nn = length(x);\n\nif (n < c)\n fprintf('??? Bad c input to hermint ==> c <= length(x)\\n');\n yi = [];\n ypi = [];\n return\nend\n\nfor i = 1:length(xi)\n % Find the right place in the table by means of a bisection.\n klo = 1;\n khi = n;\n while (khi-klo > 1)\n k = fix((khi+klo)/2.0);\n if (x(k) > xi(i))\n khi = k;\n else\n klo = k;\n end\n end\n \n h = x(khi) - x(klo);\n if (h == 0.0)\n fprintf('??? Bad x input to hermint ==> x values must be distinct\\n');\n yi(i) = NaN;\n ypi(i) = NaN;\n continue;\n end\n \n isiny = 0;\n for k = 1:n\n if (xi(i) == x(k))\n yi(i) = y(k);\n ypi(i) = yp(k);\n isiny = 1;\n break\n end\n end\n \n if (isiny)\n continue\n end\n\n % Evaluate hermite polynomial\n yi(i) = 0;\n ypi(i) = 0;\n if (c == 0)\n for k = 1:n\n f = 0;\n g = 0;\n h = 1;\n \n for m = 1:n\n if (k ~= m)\n f = f + 1/(x(k)-x(m));\n h = h*(xi(i)-x(m))/(x(k)-x(m));\n end\n end\n \n for m = 1:n\n if (k ~= m)\n g = g + h/(xi(i)-x(m));\n end\n end\n \n a = h*h;\n b = 2*h*g;\n u = xi(i) - x(k);\n \n b1 = a*u;\n b2 = b*u + a;\n a1 = a - 2*f*b1;\n a2 = b - 2*f*b2;\n \n yi(i) = yi(i) + a1*y(k) + b1*yp(k);\n ypi(i) = ypi(i) + a2*y(k) + b2*yp(k);\n end\n else\n if (mod(c,2) == 0) % even\n c2 = c/2;\n if (klo < c2)\n klo = c2;\n end\n if (klo > n-c2)\n klo = n-c2;\n end\n khi = klo + 1;\n for k = klo-(c2-1):klo+c2\n f = 0;\n g = 0;\n h = 1;\n \n for m = klo-(c2-1):klo+c2\n if (k ~= m)\n f = f + 1/(x(k)-x(m));\n h = h*(xi(i)-x(m))/(x(k)-x(m));\n end\n end\n \n for m = klo-(c2-1):klo+c2\n if (k ~= m)\n g = g + h/(xi(i)-x(m));\n end\n end\n \n a = h*h;\n b = 2*h*g;\n u = xi(i) - x(k);\n \n b1 = a*u;\n b2 = b*u + a;\n a1 = a - 2*f*b1;\n a2 = b - 2*f*b2;\n \n yi(i) = yi(i) + a1*y(k) + b1*yp(k);\n ypi(i) = ypi(i) + a2*y(k) + b2*yp(k);\n end\n else % odd\n c2 = floor(c/2);\n if (klo < c2+1)\n klo = c2+1;\n end\n if (klo > n-c2)\n klo = n-c2;\n end\n khi = klo + 1;\n for k = klo-c2:klo+c2\n f = 0;\n g = 0;\n h = 1;\n \n for m = klo-c2:klo+c2\n if (k ~= m)\n f = f + 1/(x(k)-x(m));\n h = h*(xi(i)-x(m))/(x(k)-x(m));\n end\n end\n \n for m = klo-c2:klo+c2\n if (k ~= m)\n g = g + h/(xi(i)-x(m));\n end\n end\n \n a = h*h;\n b = 2*h*g;\n u = xi(i) - x(k);\n \n b1 = a*u;\n b2 = b*u + a;\n a1 = a - 2*f*b1;\n a2 = b - 2*f*b2;\n \n yi(i) = yi(i) + a1*y(k) + b1*yp(k);\n ypi(i) = ypi(i) + a2*y(k) + b2*yp(k);\n end\n end\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/36800-interpolation-utilities/hermint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7412422049953412}} {"text": "function [evects,evals] = pca(X)\n% [evects,evals] = pca(X)\n%\n% finds principal components of \n%\n% input: \n% X dxn matrix (each column is a dx1 input vector)\n% \n% output: \n% evects columns are principal components (leading from left->right)\n% evals corresponding eigenvalues\n%\n% See also applypca\n%\n% copyright by Kilian Q. Weinberger, 2006\n\n[d,N] = size(X);\n\nmm = mean(X,2);\nX = X - mm*ones(1,N); % remove mean from data\n\ncc = cov(X',1); % compute covariance \n[cvv,cdd] = eig(cc); % compute eignvectors\n[zz,ii] = sort(diag(-cdd)); % sort according to eigenvalues\nevects = cvv(:,ii); % pick leading eigenvectors\ncdd = diag(cdd); % extract eigenvalues\nevals = cdd(ii); % sort eigenvalues\n\n\n", "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/LMNN/pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.7412421886218389}} {"text": "function b = r8blt_vxm ( n, ml, a, x )\n\n%*****************************************************************************80\n%\n%% R8BLT_VXM multiplies a vector by a R8BLT matrix.\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% 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% 23 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, integer ML, the lower bandwidth.\n%\n% Input, real A(ML+1,N), the R8BLT matrix.\n%\n% Input, real X(N), the vector to be multiplied by A.\n%\n% Output, real B(N), the product X*A.\n%\n b(1:n) = 0.0;\n\n for i = 1 : n\n jlo = max ( 1, i - ml );\n jhi = i;\n for j = jlo : jhi\n b(j) = b(j) + x(i) * a(i-j+1,j);\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/r8blt_vxm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7412225560141066}} {"text": "function [ o, x, w ] = en_r2_03_2 ( n )\n\n%*****************************************************************************80\n%\n%% EN_R2_03_2 implements the Stroud rule 3.2 for region EN_R2.\n%\n% Discussion:\n%\n% The rule has order O = 2^N.\n%\n% The rule has precision P = 3.\n%\n% EN_R2 is the entire N-dimensional space with weight function\n%\n% w(x) = exp ( - x1^2 - x2^2 ... - xn^2 ) \n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Arthur Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971,\n% ISBN: 0130438936,\n% LC: QA311.S85.\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n%\n% Output, 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 volume = sqrt ( pi^n );\n\n a = volume / o;\n r = sqrt ( 1 / 2 );\n\n x = zeros ( n, o );\n w = zeros ( o, 1 );\n\n k = 0;\n%\n% 2^N points.\n%\n k = k + 1;\n x(1:n,k) = - r;\n w(k) = a;\n more = 1;\n\n while ( more )\n more = 0;\n for i = n : -1 : 1\n if ( x(i,k) < 0.0 )\n k = k + 1;\n x(1:n,k) = x(1:n,k-1);\n x(i,k) = + r;\n x(i+1:n,k) = - r;\n w(k) = a;\n more = 1;\n break;\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/en_r2_03_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7412225496036998}} {"text": "function [sMin,sMax,s0]=projEllipseOntoLine(z,A,gammaVal,x0,v)\n%%PROJELLIPSEONTOLINE Determine the orthogonal projection of an ellipse or\n% ellipsoid onto a line.\n%\n%INPUTS: z The numDimX1 center of the ellipsoid.\n% A A numDimXnumDim symmetric, positive definite matrix that\n% specifies the size and shape of the ellipse or ellipsoid, where\n% a point zp is on the ellipse/ellipsoid if\n% (zp-z)'*A*(zp-z)=gammaVal.\n% gammaVal The threshold for declaring a point to be in the ellipsoid. If\n% an empty matrix is passed, the default value of 1 is used.\n% x0,v Two numDimX1 vectors that specify the line. A point y is on the\n% line if y=x0+s*v, where s is a scalar quantity.\n%\n%OUTPUTS: sMin,sMax The range of values of s on the line y=x0+s*v onto\n% which the ellipsoid is orthogonally projected. These\n% are scalar quantities.\n%\n%The mathematics for projecting an ellipsoid onto a line are described in\n%Section 12 of [1].\n%\n%EXAMPLE:\n% A=[1,0;\n% 0,10];\n% M=[0.413074198133900, 0.910697373904216;\n% -0.910697373904216, 0.413074198133900];%A rotation matrix\n% A=M*A*M';\n% z=[5;6];\n% x0=[0;0];\n% v=[1;2];\n% [sMin,sMax,s0]=projEllipseOntoLine(z,A,[],x0,v);\n% figure(1)\n% clf\n% hold on\n% axis([-0.5, 7.5, 2, 10])%Same size in x and y\n% axis square\n% drawEllipse(z,A,1,'b','linewidth',2)\n% %Draw a segment of the line.\n% xStart=x0+v;\n% xEnd=x0+5*v;\n% plot([xStart(1);xEnd(1)],[xStart(2);xEnd(2)],'-k','linewidth',4)\n% %Draw the segment of the orthogonal projection onto the line.\n% xStart=x0+sMin*v;\n% xEnd=x0+sMax*v;\n% plot([xStart(1);xEnd(1)],[xStart(2);xEnd(2)],'-r','linewidth',2)\n% %Draw the line from the center of the ellipse to the place on the line onto\n% %which it is orthogonally projected.\n% xS0=x0+s0*v;\n% plot([z(1);xS0(1)],[z(2);xS0(2)],'--c')\n%\n%REFERENCES:\n%[1] S. B. Pope, \"Algorithms for ellipsoids,\" Cornell University, Tech.\n% Rep. FDA-08-01, Feb. 2008. [Online].\n% Available: https://tcg.mae.cornell.edu/pubs/Pope_FDA_08.pdf\n%\n%May 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(isempty(gammaVal))\n gammaVal=1; \nend\n\nA=A/gammaVal;\n\nL=chol(A,'lower');\n\ns0=v'*(z-x0)/(v'*v);\nw=norm(L\\v/(v'*v));\n\nsMin=s0+w;\nsMax=s0-w;\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/projEllipseOntoLine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7412225469793365}} {"text": "function [MBox] = MBoxtest(X,alpha)\n% Multivariate Statistical Testing for the Homogeneity of Covariance Matrices by the Box's M. \n%\n% Syntax: function [MBox] = MBoxtest(X,alpha) \n% \n% Inputs:\n% X - data matrix (Size of matrix must be n-by-(1+p); sample=column 1, variables=column 2:p). \n% alpha - significance level (default = 0.05). \n% Output:\n% MBox - the Box's M statistic.\n% Chi-sqr. or F - the approximation statistic test.\n% df's - degrees' of freedom of the approximation statistic test.\n% P - observed significance level.\n% \n% If the groups sample-size is at least 20 (sufficiently large), Box's M test\n% takes a Chi-square approximation; otherwise it takes an F approximation.\n%\n% Example: For a two groups (g = 2) with three independent variables (p = 3), we \n% are interested to test the homogeneity of covariances matrices with a \n% significance level = 0.05. The two groups have the same sample-size\n% n1 = n2 = 5.\n% Group\n% --------------------------------------- \n% 1 2\n% ---------------------------------------\n% x1 x2 x3 x1 x2 x3\n% ---------------------------------------\n% 23 45 15 277 230 63\n% 40 85 18 153 80 29\n% 215 307 60 306 440 105\n% 110 110 50 252 350 175\n% 65 105 24 143 205 42\n% ---------------------------------------\n%\n% Total data matrix must be:\n% X=[1 23 45 15;1 40 85 18;1 215 307 60;1 110 110 50;1 65 105 24;\n% 2 277 230 63;2 153 80 29;2 306 440 105;2 252 350 175;2 143 205 42];\n%\n% Calling on Matlab the function: \n% MBoxtest(X,0.05)\n%\n% Answer is:\n%\n% ------------------------------------------------------------\n% MBox F df1 df2 P\n% ------------------------------------------------------------\n% 27.1622 2.6293 6 463 0.0162\n% ------------------------------------------------------------\n% Covariance matrices are significantly different.\n%\n\n% Created by A. Trujillo-Ortiz and R. Hernandez-Walls\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 2002:2\n% Multivariate Statistics Course: Karel Castro-Morales, Alejandro Espinoza-Tenorio,\n% Andrea Guia-Ramirez, Raquel Muniz-Salazar, Jose Luis Sanchez-Osorio and\n% Roberto Carmona-Pina.\n% November 2002.\n%\n% To cite this file, this would be an appropriate format:\n% Trujillo-Ortiz, A., R. Hernandez-Walls, K. Castro-Morales, A. Espinoza-Tenorio, A. Guia-Ramirez\n% and R. Carmona-Pina. (2002). MBoxtest: Multivariate Statistical Testing for the Homogeneity of \n% Covariance Matrices by the Box's M. A MATLAB file. [WWW document]. URL http://www.mathworks.com/\n% matlabcentral/fileexchange/loadFile.do?objectId=2733&objectType=FILE\n%\n% References:\n% \n% Stevens, J. (1992), Applied Multivariate Statistics for Social Sciences. 2nd. ed.\n% New-Jersey:Lawrance Erlbaum Associates Publishers. pp. 260-269.\n \nif nargin < 1, \n error('Requires at least one input arguments.'); \nend;\n\nif nargin < 2, \n alpha = 0.05; %(default)\nend; \n\nif (alpha <= 0 | alpha >= 1)\n fprintf('Warning: significance level must be between 0 and 1\\n');\n return;\nend;\n\ng = max(X(:,1)); %Number of groups.\n\nn = []; %Vector of groups-size.\nindice = X(:,1);\nfor i = 1:g\n Xe = find(indice==i);\n eval(['X' num2str(i) '= X(Xe,2);']);\n eval(['n' num2str(i) '= length(X' num2str(i) ') ;'])\n eval(['xn= n' num2str(i) ';'])\n n = [n,xn];\nend;\n\n[f,c] = size(X);\nX = X(:,2:c);\n\n[N,p]=size(X);\nr=1; \nr1=n(1);\nbandera=2;\nfor k=1:g\n if n(k)>=20;\n bandera=1;\n end\nend\n%Partition of the group covariance matrices.\nfor k=1:g\n eval(['S' num2str(k) '=cov(X(r:r1,:));';]);\n if k= alpha\n disp('Covariance matrices are not significantly different.');\n else\n disp('Covariance matrices are significantly different.');\n end\nelse\n%To obtain the F approximation we first define Co, which combined to the before C value\n%are used to estimate the denominator degrees of freedom (v2); resulting two possible cases. \nCo=(((p-1)*(p+2))/(6*(g-1)))*(suma2-(1/(deno^2)));\n if Co-(C^2)>= 0;\n\tv1=(p*(p+1)*(g-1))/2; %Numerator degrees of freedom.\n v21=fix((v1+2)/(Co-(C^2))); %Denominator degrees of freedom.\n F1=MB*((1-C-(v1/v21))/v1); %F approximation.\n P1=1-fcdf(F1,v1,v21); %Significance value associated to the observed F statistic.\ndisp(' ')\n ;\nfprintf('------------------------------------------------------------\\n');\ndisp(' MBox F df1 df2 P')\nfprintf('------------------------------------------------------------\\n');\nfprintf('%10.4f%11.4f%11.i%14.i%13.4f\\n',MB,F1,v1,v21,P1);\nfprintf('------------------------------------------------------------\\n'); \n if P1 >= alpha\n disp('Covariance matrices are not significantly different.');\n else\n disp('Covariance matrices are significantly different.');\n end\n \n else \n v1=(p*(p+1)*(g-1))/2; %Numerator degrees of freedom.\n v22=fix((v1+2)/((C^2)-Co)); %Denominator degrees of freedom.\n b=v22/(1-C-(2/v22));\n F2=(v22*MB)/(v1*(b-MB)); %F approximation.\n P2=1-fcdf(F2,v1,v22); %Significance value associated to the observed F statistic.\ndisp(' ') \n ;\nfprintf('------------------------------------------------------------\\n');\ndisp(' MBox F df1 df2 P')\nfprintf('------------------------------------------------------------\\n');\nfprintf('%10.4f%11.4f%11.i%14.i%13.4f\\n',MB,F2,v1,v22,P2);\nfprintf('------------------------------------------------------------\\n');\n \n if P2 >= alpha\n disp('Covariance matrices are not significantly different.');\n else\n disp('Covariance matrices are significantly different.');\n end\n end\nend\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/external/MBoxtest/MBoxtest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7412225432492606}} {"text": "%................................................................\n\n% MATLAB codes for Finite Element Analysis\n% problem16vibrations.m\n% Timoshenko beam in free vibrations\n% AJM Ferreira 2008\n% modified by Manuel Diaz, 2013.07.25\n\n% clear memory\nclear all\n\n% E; modulus of elasticity\n% G; shear modulus\n% I: second moments of area\n% L: length of beam\n% thickness: thickness of beam\n<<<<<<< HEAD\nE=30e6; poisson = 0.30;L = 1;thickness=0.01;\n=======\nE=10e7; poisson = 0.30;L = 3;thickness=0.001;\n>>>>>>> 47f4967135b009f9128c106a6744c97a2ffd18ce\nI=thickness^3/12;\nEI=E*I;\nkapa=5/6;\nrho=1;\nA=1*thickness;\n% \n\nP = 0; % uniform pressure\n%P = -1; % uniform pressure\n% constitutive matrix\nG=E/2/(1+poisson);\nC=[ EI 0; 0 kapa*A*G];\n\n% mesh\n<<<<<<< HEAD\nnumberElements = 50; \n=======\nnumberElements = 40; \n>>>>>>> 47f4967135b009f9128c106a6744c97a2ffd18ce\nnodeCoordinates=linspace(0,L,numberElements+1);\nxx=nodeCoordinates';x=xx';\nfor i=1:size(nodeCoordinates,2)-1\n elementNodes(i,1)=i; \n elementNodes(i,2)=i+1\nend\n% generation of coordinates and connectivities\nnumberNodes=size(xx,1);\n\n% GDof: global number of degrees of freedom\nGDof=2*numberNodes; \n\n% computation of the system stiffness, force, mass\n[stiffness,force,mass]=...\n formStiffnessMassTimoshenkoBeam(GDof,numberElements,...\n elementNodes,numberNodes,xx,C,P,rho,I,thickness);\n\n% boundary conditions (simply-supported at both bords)\n%fixedNodeW =[1 ; numberNodes];\n%fixedNodeTX=[]; \n% boundary conditions (clamped at both bords)\n%fixedNodeW =[1 ; numberNodes];\n%fixedNodeTX=[1 ; numberNodes];\n% boundary conditions (cantilever)\n%fixedNodeW =[1];\n%fixedNodeTX=[1];\n<<<<<<< HEAD\n% Free-free\n%fixedNodeW =[];\n%fixedNodeTX=[];\n=======\n% Free-Free conditions\nfixedNodeW =[];\nfixedNodeTX=[];\n>>>>>>> 47f4967135b009f9128c106a6744c97a2ffd18ce\nprescribedDof=[fixedNodeW; fixedNodeTX+numberNodes];\n\n% solution (optional*)\ndisplacements=solution(GDof,prescribedDof,stiffness,force);\n\n% output displacements/reactions (optional*)\noutputDisplacementsReactions(displacements,stiffness,...\n GDof,prescribedDof)\n\n% free vibration problem\nactiveDof=setdiff([1:GDof]',[prescribedDof]);\nmodeNumber=4;\n\n[V,D]=eig(stiffness(activeDof,activeDof),...\n mass(activeDof,activeDof));\nD = diag(sqrt(D)*L*L*sqrt(rho*A/E/I));\n[D,ii] = sort(D); \n\nV1=zeros(GDof,1);\nV1(activeDof,1:modeNumber)=V(:,1:modeNumber);\n!\n% drawing eigenmodes\ndrawEigenmodes1D(modeNumber,numberNodes,V1,xx,x)\n\n\n \n\n \n\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/FEM/Timoshenko_beam/Timoshenko.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7411256780056512}} {"text": "% Figure 4.16 Feedback Control of Dynamic Systems, 6e\n% Franklin, Powell, Emami\n%% script to generate Figure 4.16(a), 4.16 (b)\n% case I, P control by reaction curve data.\n% First, input the plant model and compute the reaction curve.\nsysp=tf(1,[600 70 1])\nset(sysp,'td', 5)\n\n% From the curve, kp = 6.92 for proportional control\nsysdP = tf(6.92,1)\n% To get the closed loop response, we must use a pade approximation to the\n% delay\nsyspade=pade(sysp,3);\nsysforward=syspade*sysdP;\nsysback=tf(1,1)\nsyscl=feedback(sysforward,sysback)\nfigure(1)\nclf\nstep(syscl)\ntitle('Figure 4.16a Closed loop response using Reaction Curve data')\ngtext('P')\nhold on\n%case II, PI control\n%kp = 6.22, TI=43.3\nsysdPI=6.22*tf([43.3 1],[43.3 0])\nsysforward=syspade*sysdPI;\nsyscl=feedback(sysforward,sysback)\nstep(syscl)\ngtext('PI')\nnicegrid\n%\nsysdP = tf(6.92/3,1)\n% To get the closed loop response, we must use a pade approximation to the\n% delay\nsyspade=pade(sysp,3);\nsysforward=syspade*sysdP;\nsysback=tf(1,1)\nsyscl=feedback(sysforward,sysback)\nfigure(2)\nclf\nstep(syscl)\ntitle('Figure 4.16b Closed loop response using Reaction Curve data')\ngtext('P')\nhold on\n%case II, PI control\n%kp = 6.22, TI=43.3\nsysdPI=(6.22/3)*tf([43.3 1],[43.3 0])\nsysforward=syspade*sysdPI;\nsyscl=feedback(sysforward,sysback)\nstep(syscl)\ngtext('PI')\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/fig4_16.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7410743718587415}} {"text": "function [logml log10ml ml]=mmlikdata(X,y,n,T,q,sigma,beta0,omega0,betabar)\n\n\n% function [logml log10ml ml]=bear.mmlik(X,y,n,T,q,sigma,omega0,beta0,betabar)\n% computes the marginal likelihood for a Minesota prior, by implementing algorithm XXX\n% inputs: - matrix 'X': matrix of regressors for the VAR model (defined in 1.1.8)\n% - vector 'y': vectorised regressands for the VAR model (defined in 1.1.12)\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% - matrix 'sigma': 'true' variance-covariance matrix of VAR residuals, for the original Minnesota prior\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% - vector 'betabar': posterior mean vector (defined in 1.3.18)\n% outputs: - scalar 'logml': base e log of the marginal likelihood (defined in 1.2.9)\n% - scalar 'log10ml': base 10 log of the marginal likelihood (defined in 1.2.9)\n% - scalar 'ml': marginal likelihood (defined in 1.2.9)\n\n\n\n% compute the constant part of the marginal likelihood\ntemp1=(-n*T/2)*log(2*pi)+(-T/2)*log(det(sigma));\n\n% compute the log determinant part\n% create the square root matrix of omega0\n% because omega0 is diagonal, this is simply the square root of the diagonal terms of omega0\nFomega=spdiags(diag(omega0).^0.5,0,q,q);\n% compute the inverse of sigma\nC=chol(bear.nspd(sigma));\ninvC=C\\speye(n);\ninvsigma=invC*invC';\n% compute the product\nproduct=Fomega'*kron(invsigma,X'*X)*Fomega;\n% compute the eigenvalues of the product\nif n == 1\n eigenvalues=eig(full(product));\nelse\n eigenvalues=eig(product);\nend\n% now compute the full determinant term\ntemp2=(-1/2)*log(prod(diag(eye(q)+diag(eigenvalues))));\n\n% compute the final term\n% first compute the inverse of omega0, which is a diagonal matrix (hence simply invert element wise the diagonal terms)\ninvomega0=spdiags(1./diag(omega0),0,q,q);\n% compute the inverse of omegabar\ninvomegabar=invomega0+kron(invsigma,X'*X);\n% now compute the whole matrix sum\nsumm=beta0'*invomega0*beta0-betabar'*invomegabar*betabar+y'*kron(invsigma,speye(T))*y;\n% finally, compute the whole exponential term\ntemp3=-0.5*summ;\n\n% compute the marginal likelihood\nlogml=real(temp1+temp2+temp3);\nlog10ml=logml/log(10);\nml=exp(logml);\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/mmlikdata.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140232, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7410743627199264}} {"text": "function [ Ix, Iy, Iz, It ] = imageDerivatives3D( image1, image2 )\n%This fucntion computes 3D derivatives between two 3D images. \n%\n% Description :\n%\n% There are four derivatives here; three along X, Y, Z axes and one along\n% timeline axis.\n%\n% -image1, image2 : two subsequent images or frames\n% -dx, dy, dz : vectors along X, Y and Z axes respectively\n% -dt : vectors along timeline axis\n% -Ix, Iy, Iz : derivatives along X, Y and Z axes respectively\n% -It : derivatives along timeline axis\n%\n% Author : Mohammad Mustafa\n% By courtesy of The University of Nottingham and \n% Mirada Medical Limited, Oxford, UK\n%\n% Published under a Creative Commons Attribution-Non-Commercial-Share Alike\n% 3.0 Unported Licence http://creativecommons.org/licenses/by-nc-sa/3.0/\n% \n% June 2012\n\n\ndx=zeros(2,2,2);\ndx(:,:,1)=[-1 1; -1 1 ]; dx(:,:,2)=[-1 1; -1 1 ];\ndx=0.25*dx;\n\ndy=zeros(2,2,2);\ndy(:,:,1)=[-1 -1; 1 1 ]; dy(:,:,2)=[-1 -1; 1 1 ];\ndy=0.25*dy;\n\ndz=zeros(2,2,2);\ndz(:,:,1)=[-1 -1; -1 -1 ]; dz(:,:,2)=[1 1; 1 1 ];\ndz=0.25*dz;\n\ndt=ones(2,2,2);\ndt=0.25*dt;\n\n% Computing derivatives\nIx = 0.5 * (convn(image1,dx) + convn(image2,dx) );\nIy = 0.5 * (convn(image1,dy) + convn(image2,dy) );\nIz = 0.5 * (convn(image1,dz) + convn(image2,dz) );\nIt = 0.5 * (convn(image1,dt) - convn(image2,dt) );\n\n% Adjusting sizes\nIx=Ix(1:size(Ix,1)-1, 1:size(Ix,2)-1, 1:size(Ix,3)-1);\nIy=Iy(1:size(Iy,1)-1, 1:size(Iy,2)-1, 1:size(Iy,3)-1);\nIz=Iz(1:size(Iz,1)-1, 1:size(Iz,2)-1, 1:size(Iz,3)-1);\nIt=It(1:size(It,1)-1, 1:size(It,2)-1, 1:size(It,3)-1);\n\n\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/37170-lucas-kanade-optical-flow-method-for-3-d-images/LK3D/imageDerivatives3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.798186787341014, "lm_q1q2_score": 0.7410436410166346}} {"text": "function gray = rgb_to_gray ( rgb, equal )\n\n%*****************************************************************************80\n%\n%% RGB_TO_GRAY returns a grayscale version of an RGB image.\n%\n% Discussion:\n%\n% An RGB image is an (M,N,3) array.\n%\n% A grayscale image is an (M,N) array.\n%\n% A grayscale version of an RGB image can be made by averaging\n% the RGB components of each pixel.\n%\n% A more sophisticated approach uses the luminance function:\n%\n% GRAY = 0.2126 * R + 0.7152 * G + 0.0722 * B\n%\n% which attempts to better model the contributions to brightness\n% of the different colors.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 February 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, uint8 RGB(M,N,3), the original data.\n%\n% Input, logical EQUAL, is TRUE (1) if the R, G and B channels\n% are to be assigned equal weight. EQUAL is FALSE by default.\n%\n% Output, uint8 GRAY(M,N), the grayscale version of the data.\n%\n if ( nargin < 1 )\n error ( 'RGB_TO_GRAY - Fatal error! Missing RGB input argument.' )\n end\n\n if ( nargin < 2 )\n equal = 0;\n end\n\n if ( equal )\n v = [ 1, 1, 1 ]' / 3;\n else\n v = [ 0.2126, 0.7152, 0.0722 ]';\n end\n%\n% This is really a matrix multiply, but the obvious equation\n% gray = rgb * v\n% is illegal according to MATLAB.\n%\n gray = uint8 ( double ( rgb(:,:,1) ) * v(1) ...\n + double ( rgb(:,:,2) ) * v(2) ...\n + double ( rgb(:,:,3) ) * v(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/image_rgb_to_gray/rgb_to_gray.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7410046448663166}} {"text": "function yp = p15_fun ( neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P15_FUN evaluates the function for problem P15.\n%\n% Discussion:\n%\n% 30 equations.\n%\n% This system models the motion of the five outer planets of the\n% solar system.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Wayne Enright, John Pryce,\n% Algorithm 648,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 1, pages 28-34.\n%\n% Parameters:\n%\n% Input, integer NEQN, the number of equations.\n%\n% Input, real T, Y(NEQN), the arguments of the derivative\n% function.\n%\n% Output, real YP(NEQN), the value of the derivative function.\n%\n yp = zeros ( neqn, 1 );\n\n m = zeros ( 5, 1 );\n k2 = p15_param ( 'GET', 'K2', [] );\n m0 = p15_param ( 'GET', 'M0', [] );\n m(1) = p15_param ( 'GET', 'M1', [] );\n m(2) = p15_param ( 'GET', 'M2', [] );\n m(3) = p15_param ( 'GET', 'M3', [] );\n m(4) = p15_param ( 'GET', 'M4', [] );\n m(5) = p15_param ( 'GET', 'M5', [] );\n i = 0;\n for l = 3 : 3 : 15\n i = i + 1;\n p = y(l-2).^2 + y(l-1).^2 + y(l).^2;\n r(i) = 1.0 / ( p * sqrt ( p ) );\n j = 0;\n for ll = 3 : 3 : 15\n j = j + 1;\n if ( ll ~= l )\n p = ( y(l-2) - y(ll-2) ).^2 + ( y(l-1) - y(ll-1) ).^2 ...\n + ( y(l) - y(ll) ).^2;\n q(i,j) = 1.0 / ( p * sqrt ( p ) );\n q(j,i) = q(i,j);\n end\n end\n end\n i3 = 0;\n for i = 1 : 5\n i3 = i3 + 3;\n for ll = i3-2 : i3\n mm = ll - i3;\n yp(ll) = y(ll+15);\n p = 0.0;\n for j = 1 : 5\n mm = mm + 3;\n if ( j ~= i )\n p = p + m(j) ...\n * ( y(mm) * ( q(i,j) - r(j) ) - y(ll) * q(i,j) );\n end\n end\n yp(ll+15) = k2 * ( - ( m0 + m(i) ) * y(ll) * r(i) + p );\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_ode/p15_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.740941579866203}} {"text": "function [x, w, v] = radaupts(n, alp, bet)\n%RADAUPTS Gauss-Jacobi-Radau quadrature nodes and weights.\n% RADAUPTS(N) returns N Legendre-Radau points X in [-1,1).\n%\n% [X, W] = RADAUPTS(N) returns also a row vector W of weights for\n% Gauss-Legendre-Lobatto quadrature.\n%\n% [X, W, V] = RADAUPTS(N) returns additionally a column vector V of weights in\n% the barycentric formula corresponding to the points X. The weights are scaled\n% so that max(abs(V)) = 1.\n%\n% [...] = RADUAPTS(N, ALP, BET) is similar, but for the Gauss-Jacobi-Radau\n% nodes and weights. Here ALP and BET should be scalars > -1.\n%\n% In each case, N should be a positive integer.\n%\n% See also CHEBPTS, LEGPTS, JACPTS, LEGPOLY, JACPOLY, LOBPTS.\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% Developer note:\n% The approach used here is to observe that the Gauss-Radau points are\n% precisely the roots of (1+x)P^(0,1)_{n-2}(x), which can be obtained from\n% JACPTS. A similar identity [NIST, (18.9.5) and (18.9.17)] is used for the\n% computation of the quadrature weights from those of JACPTS, and the missing\n% barycentric weights are determined by enforcing the interpolation of f(x) =\n% x at x = 0.\n%\n% x_j = roots of (1+x)P^(0,1)_{n-2}(x)\n% w_j = { 2/n^2 : x_j = -1\n% { 1/(1-x_j) * 1/[d/dx P_{n-1}(x_j)]^2 : otherwise\n%\n% (Note that the weights for n-1 point Gauss-Jacobi with a = 0, b = 1 satisfy \n% u_j = C/(1-x_j^2)/[d/dx P^(0,1)_{n-1}(x_j)]^2)\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% TODO: Scaled domains?\n\nif ( nargin < 3 )\n % Default to Gauss-Legendre-Lobatto:\n alp = 0; bet = 0;\nend\n\n%% Trivial cases:\nif ( n == 1 )\n x = -1;\n w = 2^(1+alp+bet)*beta(1+alp,1+bet);\n v = 1;\n return\nend\n\n%% Call JACPTS():\n[xi, w, v] = jacpts(n-1, alp, bet+1);\n\n%% Nodes:\nx = [-1 ; xi];\n\n%% Quadrature weights:\nwi = w./(1 + xi.');\nif ( alp == 0 && bet == 0 )\n w = [2/n^2, wi];\nelse\n % See Walter Gautschi, \"Gauss–Radau formulae for Jacobi and Laguerre\n % weight functions\", Mathematics and Computers in Simulation, (2000).\n w = [2^(alp+bet+1)*beta(bet+1,n)*beta(alp+n,bet+1)*(bet+1), wi];\nend\n\n%% Barycentric weights:\nv = v./(1 + xi);\nv = v/max(abs(v));\nv1 = -sum(v);\nv = [v1 ; v];\n\nend\n\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/radaupts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.7409415764173894}} {"text": "function [a1, b1, c1, a2, b2, c2] = aaad(A, B, C)\n%AAAD gives both solutions to the angle-angle-angle problem, in degrees.\n%\n% AAAD(A, B, C) will result in NaNs if the existence condition \n% |pi - |A|-|B|| <= |C| <= pi - ||A| - |B||\n% is not met. \n%\n% See also AAAD.\n\n% Rody P.S. Oldenhuis\n% Delft University of Technology\n% oldenhuis@gmail.com\n%\n% Crated : 23/Feb/2009\n% Last edited: 30/Nov/2012\n \n % find both solutions by calling aaa directly\n r2d = 180/pi; \n d2r = 1/r2d; \n [a1, b1, c1, a2, b2, c2] = aaa(A*d2r, B*d2r, C*d2r);\n [a1, b1, c1, a2, b2, c2] = deal(a1*r2d, b1*r2d, c1*r2d, a2*r2d, b2*r2d, c2*r2d);\n \nend", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SphericalTrigToolbox/aaad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7408936261327475}} {"text": "function [xr,Yr]=noisergeo(x,dim,tau,r,q,p,theta)\n%Syntax: [xr,Yr]=noisergeo(x,dim,tau,r,q,p,theta)\n%________________________________________________\n%\n% Noise reduction by Local Geometric Projection.\n%\n% xr is the vector/matrix with the cleaned time series.\n% Yr is the phase space of the last cleaned xr.\n% x is the time series.\n% dim is the embedding dimension.\n% tau is the time delay.\n% r can be either\n% real defining the neighborhood range.\n% integer defining the number of nearest neighbors.\n% q can take one of the following values\n% 'wAV' for the weighted average.\n% [an integer from 0 to dim-1] for the local geometric projection.\n% 'mod' for the adaptive selection of the local neighborhood dimensions.\n% p defines the norm.\n% theta is the correction paprameter [0,1]\n% 1: full correction.\n% 0: no correction.\n%\n%\n% References:\n%\n% Kantz H, Schreiber T, Hoffmann I, Buzug T, Pfister G, Flepp L G, Simonet\n% J, Badii R, Brun E (1993): Nonlinear noise reduction: A case study on\n% experimental data. Physical Review E 48: 1529-1538\n%\n% Leontitsis A., Bountis T., Pange J. (2004): An adaptive way for improving\n% noise reduction using local geometric projection. CHAOS 14(6): 106-110\n%\n%\n% Alexandros Leontitsis\n% Department of Education\n% University of Ioannina\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% 14 Jul 2001\n\nif nargin<1 | isempty(x)==1\n error('You should provide a time series.');\nelse\n % x must be a vector\n if min(size(x))>1\n error('Invalid time series.');\n end\n x=x(:);\n % n is the time series length\n n=length(x);\nend\n\nif nargin<2 | isempty(dim)==1\n dim=2;\nelse\n % dim must be either a scalar or a vector\n if min(size(dim))>1\n error('dim must be a scalar or a vector.');\n end\n % dim must be an integer\n if round(dim)-dim~=0\n error('dim must be an integer.');\n end\n % dim values must be above 1\n if any(dim<1)==1\n error('dim values must be above 1');\n end\nend\n\nif nargin<3 | isempty(tau)==1\n tau=1;\nelse\n % tau must be either a scalar or a vector\n if min(size(tau))>1\n error('tau must be a scalar or a vector.');\n end\n % tau must be an integer\n if round(tau)-tau~=0\n error('tau must be an integer.');\n end\n % tau values must be above 1\n if any(tau<1)==1\n error('tau values must be above 1');\n end\nend\n\nif nargin<4 | isempty(r)==1\n r=dim+1;\nelse\n % r must be either a scalar or a vector\n if min(size(r))>1\n error('r must be a scalar or a vector.');\n end\n % r values must be above 0\n if any(r<=0)==1\n error('r values must be greater than 0');\n end\nend\n\nif nargin<5 | isempty(q)==1\n q=1;\nend\n\nif nargin<6 | isempty(p)==1\n p=2;\nelse\n % p must be either a scalar or a vector\n if min(size(p))>1\n error('p must be a scalar or a vector.');\n end\nend\n\nif nargin<7 | isempty(theta)==1\n theta=1;\nelse\n % theta must be either a scalar or a vector\n if min(size(theta))>1\n error('theta must be a scalar or a vector.');\n end\n % theta must be above 0 and bellow 1\n if theta<0 | theta>1\n error('theta must be above 0 and bellow 1.')\n end\nend\n\n% Only one of dim, tau, r, p or theta should be vector\nl=[length(dim),length(tau),length(r),length(p),length(theta)];\nif length(find(l>1))>1\n error('Only one of dim, tau, r, p, or theta should be vector.');\nend\n\n% Make the phase-space\n[Y,T]=phasespace(x,dim,tau);\n\n\nm=max(l);\ndim=ones(1,m).*dim;\ntau=ones(1,m).*tau;\nr=ones(1,m).*r;\np=ones(1,m).*p;\ntheta=ones(1,m).*theta;\n\nfor i=1:m\n \n % Initialize Yr\n Yr=zeros(T,dim(i));\n \n % For every phase-space point\n for j=1:T\n \n % Locate the j-th point\n y=Y(j,:);\n \n % Check neighborhood or neighbors\n if mod(r(i),floor(r(i)))==0\n lock=Knearest(y,Y,r(end)+1,p(i));\n else\n lock=radnearest(y,Y,T,r(i),p(i));\n lock(find(j==lock))=[];\n end\n \n if isempty(lock)==1\n Yr(j,:)=y;\n elseif q=='wAV'\n % The calculations for the weighted average\n Ynearest=Y(lock,:);\n w=[];\n for k=1:length(lock)\n w(k)=norm(y-Ynearest(k,:))/2/r(i);\n w(k)=exp(-w(k)^2);\n Ynearest(k,:)=Ynearest(k,:)*w(k);\n end\n Yr(j,:)=sum(Ynearest)/sum(w);\n else\n % All the neighboring points have equal weight\n if length(lock)=0 elementwise.\n%\n% Reference:\n% Jingu Kim and Haesun Park. Fast Nonnegative Matrix Factorization: An Activeset-like Method and Comparisons,\n% SIAM Journal on Scientific Computing, 33(6), pp. 3261-3281, 2011.\n%\n% Written by Jingu Kim (jingu.kim@gmail.com)\n% School of Computational Science and Engineering,\n% Georgia Institute of Technology\n%\n% Note that this algorithm assumes that the input matrix A has full column rank.\n% This code comes with no guarantee or warranty of any kind. \n% Please send bug reports, comments, or questions to Jingu Kim.\n%\n% Modified Feb-20-2009\n% Modified Mar-13-2011: numChol and numEq\n%\n% \n% A : input matrix (m x n) (by default), or A'*A (n x n) if isInputProd==1\n% B : input matrix (m x k) (by default), or A'*B (n x k) if isInputProd==1\n% isInputProd : (optional, default:0) if turned on, use (A'*A,A'*B) as input instead of (A,B)\n% init : (optional) initial value for X\n% \n% X : the solution (n x k)\n% Y : A'*A*X - A'*B where X is the solution (n x k)\n% success : 0 for success, 1 for failure.\n% Failure could only happen on a numericall very ill-conditioned problem.\n% numChol : number of unique cholesky decompositions done\n% numEqs : number of systems of linear equations solved\n\nfunction [ X,Y,success,numChol,numEq ] = nnlsm_blockpivot( A, B, isInputProd, init )\n if nargin<3, isInputProd=0;, end\n if isInputProd\n AtA = A;, AtB = B;\n else\n AtA = A'*A;, AtB = A'*B;\n end\n\n if size(AtA,1)==1\n X = AtB/AtA; X(X<0) = 0;\n Y = AtA*X - AtB;\n numChol = 1; numEq = size(AtB,2); success = 1;\n return\n end\n \n [n,k]=size(AtB);\n MAX_BIG_ITER = n*5;\n % set initial feasible solution\n X = zeros(n,k);\n if nargin<4\n Y = - AtB;\n PassiveSet = false(n,k);\n numChol = 0;\n numEq = 0;\n else\n PassiveSet = (init > 0);\n [ X,numChol,numEq] = normalEqComb(AtA,AtB,PassiveSet);\n Y = AtA * X - AtB;\n end\n % parameters\n pbar = 3;\n P = zeros(1,k);, P(:) = pbar;\n Ninf = zeros(1,k);, Ninf(:) = n+1;\n\n NonOptSet = (Y < 0) & ~PassiveSet;\n InfeaSet = (X < 0) & PassiveSet;\n NotGood = sum(NonOptSet)+sum(InfeaSet);\n NotOptCols = NotGood > 0;\n\n bigIter = 0;, success=0;\n while(~isempty(find(NotOptCols)))\n bigIter = bigIter+1;\n if ((MAX_BIG_ITER >0) && (bigIter > MAX_BIG_ITER)) % set max_iter for ill-conditioned (numerically unstable) case\n success = 1;, break\n end\n\n Cols1 = NotOptCols & (NotGood < Ninf);\n Cols2 = NotOptCols & (NotGood >= Ninf) & (P >= 1);\n Cols3Ix = find(NotOptCols & ~Cols1 & ~Cols2);\n if ~isempty(find(Cols1))\n P(Cols1) = pbar;,Ninf(Cols1) = NotGood(Cols1);\n PassiveSet(NonOptSet & repmat(Cols1,n,1)) = true;\n PassiveSet(InfeaSet & repmat(Cols1,n,1)) = false;\n end\n if ~isempty(find(Cols2))\n P(Cols2) = P(Cols2)-1;\n PassiveSet(NonOptSet & repmat(Cols2,n,1)) = true;\n PassiveSet(InfeaSet & repmat(Cols2,n,1)) = false;\n end\n if ~isempty(Cols3Ix)\n for i=1:length(Cols3Ix)\n Ix = Cols3Ix(i);\n toChange = max(find( NonOptSet(:,Ix)|InfeaSet(:,Ix) ));\n if PassiveSet(toChange,Ix)\n PassiveSet(toChange,Ix)=false;\n else\n PassiveSet(toChange,Ix)=true;\n end\n end\n end\n [ X(:,NotOptCols),tempChol,tempEq ] = normalEqComb(AtA,AtB(:,NotOptCols),PassiveSet(:,NotOptCols));\n numChol = numChol + tempChol;\n numEq = numEq + tempEq;\n X(abs(X)<1e-12) = 0; % One can uncomment this line for numerical stability.\n Y(:,NotOptCols) = AtA * X(:,NotOptCols) - AtB(:,NotOptCols);\n Y(abs(Y)<1e-12) = 0; % One can uncomment this line for numerical stability.\n \n % check optimality\n NotOptMask = repmat(NotOptCols,n,1);\n NonOptSet = NotOptMask & (Y < 0) & ~PassiveSet;\n InfeaSet = NotOptMask & (X < 0) & PassiveSet;\n NotGood = sum(NonOptSet)+sum(InfeaSet);\n NotOptCols = NotGood > 0;\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/nnlsm_blockpivot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7408935502135945}} {"text": "function cvt_test14 ( )\n\n%*****************************************************************************80\n%\n%% CVT_TEST14 generates a 10 point CVT on [0,1].\n%\n% Discussion:\n%\n% Generate 10 CVT points on the interval [0,1].\n% We expect them to be at 1/20, 3/20, 5/20, ..., 19/20.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST14\\n' );\n fprintf ( 1, ' Generate a CVT in the interval [0,1] using 10 points.\\n' );\n fprintf ( 1, ' Exact answer: { 0.05, 0.15, 0.25, ..., 0.85, 0.95 }\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' It turns out that, for a fixed number of points N,\\n' );\n fprintf ( 1, ' a 1D problem will converge much more slowly than for\\n' );\n fprintf ( 1, ' cases where the dimension is higher.\\n' );\n\n dim_num = 1;\n n = 10;\n batch = 10000;\n init = 1;\n init_string = 'uniform';\n it_max = 50;\n it_fixed = 1;\n sample = 1;\n sample_num = 100000;\n sample_string = 'uniform';\n seed = 123456789;\n r = [];\n\n seed_init = seed;\n\n [ r, seed, it_num, it_diff, energy ] = cvt ( dim_num, n, batch, init, ...\n sample, sample_num, it_max, it_fixed, seed, r );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Dimension DIM_NUM = %12d\\n', dim_num );\n fprintf ( 1, ' Number of points N = %12d\\n', n );\n fprintf ( 1, ' Initial SEED = %12d\\n', seed_init );\n fprintf ( 1, ' Current SEED = %12d\\n', seed );\n fprintf ( 1, ' INIT = \"%s\".\\n', init_string );\n fprintf ( 1, ' Max iterations IT_MAX = %12d\\n', it_max );\n fprintf ( 1, ' IT_FIXED (fixed samples) = %12d\\n', it_fixed );\n fprintf ( 1, ' Iterations IT_NUM = %12d\\n', it_num );\n fprintf ( 1, ' Difference IT_DIFF = %14f\\n', it_diff );\n fprintf ( 1, ' CVT ENERGY = %14f\\n', energy );\n fprintf ( 1, ' SAMPLE = \"%s\".\\n', sample_string );\n fprintf ( 1, ' Samples SAMPLE_NUM = %12d\\n', sample_num );\n fprintf ( 1, ' Sampling BATCH size = %12d\\n', batch );\n fprintf ( 1, ' EPSILON (unit roundoff) = %12e\\n', eps );\n \n r = sort ( r );\n\n r8mat_transpose_print ( dim_num, n, r, ' Generators (rows):' );\n\n return\nend\n", "meta": {"author": "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/cvt_test14.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7408653915472464}} {"text": "%% Spherical Functions\n%\n%%\n% By a variable of type @S2Fun it is possible to represent an entire\n% function on the two dimensional sphere. A typical example of such a\n% function is the pole density function of a given ODF with respect to a\n% fixed crystal direction.\n\n% the famouse Santa Fe orientation distribution function\nodf = SantaFe;\n\n% the (100) pole density function\npdf = odf.calcPDF(Miller(1,0,0,odf.CS))\n\n%%\n% Since, the variable |pdf| stores all information about this function we\n% may evaluate it for any direction |r|\n\n% take a random direction\nr = vector3d.rand;\n\n% and evaluate the pdf at this direction\npdf.eval(r)\n\n%%\n% We may also plot the function in any spherical projection\n\nplot(pdf)\n\n%%\n% or find its local maxima\n\n[~,localMax] = max(pdf,'numLocal',12)\n\nannotate(localMax)\n\n%%\n% A complete list of operations that can be performed with spherical\n% functions can be found in section .\n%\n\n\n%% Representation of Spherical Functions\n%\n% In MTEX there exist different ways for representing spherical functions\n% internally. \n%\n% || harmonic expansion || @S2FunHarmonic ||\n% || finite elements || @S2FunTri ||\n% || function handle || @S2FunHandle ||\n% || Bingham distribution || @BinghamS2 ||\n%\n% All representations allow for the same operations which are specified for\n% the abstact class @S2Fun. In particular it is possible\n% to calculate with spherical functions as with ordinary numbers, i.e., you\n% can add, multiply arbitrary functions, take the mean, integrate them or\n% compute gradients.\n%\n%% Generalizations of Spherical Functions\n%\n% || spherical vector fields || @S2VectorField ||\n% || spherical axis fields || @S2AxisField ||\n% || radial spherical functions || @S2Kernel ||\n% || symmetric spherical functions || @S2FunHarmonicSym ||\n%\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/SphericalFunctions/S2FunConcept.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7408653764097791}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Function (ldiv) : calculate inverse Z-transform by long division \n% Author : Tamer mohamed samy abdelazim Mellik\n% Contact information : \n%Department of Electrical & Computer Engineering,\n%University of Calgary,\n%2500 University Drive N.W. ,\n%Calgary, AB T2N 1N4 ,\n%Canada .\n% email :abdelasi@enel.ucalgary.ca \n% email : tabdelaz@ucalgary.ca\n% Webpage : http://www.enel.ucalgary.ca/~abdelasi/\n% Date : 2-5-2002\n% Version : 1.0.0\n%Example\n% This function like deconv but it help if the numerator less or equal degree of denominator\n% if you have this function (It must arranged in terms of minus power of Z):\n% 1\n% G(z)= ----------------- \n% -1 -2\n% ( 5 - Z - 3 Z )\n% and you want to calculate long division or inverse Z transform :\n% The numerator is a=[1] and the denominator is b= [5 -1 -3 ]\n% call the function ldiv(a,b) to get the funresult 20 items (default)\n% another example :\n% -2 -3 \n% ( 5 - 3 Z + 4 Z )\n% G(z)----------------- \n% -1 -2\n% (5 - Z - 3 Z )\n% a=[5 0 -3 4] , b= [5 -1 -3 ] and you want the funresult 100 terms !\n% ldiv(a,b,100) \n% Note : The author doesn't have any responsibility for any harm caused by the use of this file\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction funresult=ldiv(a,b,N)\n%a numerator\n%b denominator\n%default order of the filter == 20\nfunresult=[];\nif nargin < 3\n if nargin > 1\n N=20;\n else\n disp('Usage: M = ldiv(a,b,N)')\n disp('a:numerator , b denominator and N is the order of the resultant filter')\n return\n end \nend\n\nif size(a) < 1\n disp('Error: numerator must at least have one element not empty')\n return\nend\nif size(b) < 1\n disp('Error: denominator must at least have one element not empty')\n return\nend\n\nif b(1)==0\n disp('Error: The first element of denominator must have nonzero value')\n return\nend\nif size(b) < 2\n funresult=a./b;\n for i =length(funresult)+1:N\n funresult(i)=0;\n end\n return\nend\n\n\nfor i = length(a)+1:N\n a(i)=0;\nend\nfor i = 1 : N\n funresult(i)=a(1)/b(1);\n if length(a)>1\n for k= 2:length(b)\n if k > length(a)\n a(k)=0;\n end\n a(k)=a(k)-funresult(length(funresult))*b(k);\n end\n\n for i = 1:length(a)-1\n a(i)=a(i+1);\n end\n a=a(1:length(a)-1);\n end\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/1752-calculates-inverse-z-transform-by-long-division/ldiv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7408653662052334}} {"text": "function a = frank_inverse ( n )\n\n%*****************************************************************************80\n%\n%% FRANK_INVERSE returns the inverse of the FRANK matrix.\n%\n% Formula:\n%\n% if ( I = J-1 )\n% A(I,J) = -1\n% elseif ( I = J )\n% if ( I = 1 )\n% A(I,J) = 1\n% else\n% A(I,J) = N + 2 - I\n% elseif ( J < I )\n% A(I,J) = - (N+1-I) * A(I-1,J)\n% else\n% A(I,J) = 0\n%\n% Example:\n%\n% N = 5\n%\n% 1 -1 0 0 0\n% -4 5 -1 0 0\n% 12 -15 4 -1 0\n% -24 30 -8 3 -1\n% 24 -30 8 -3 2\n%\n% Properties:\n%\n% A is generally not symmetric: A' /= A.\n%\n% A is lower Hessenberg.\n%\n% det ( A ) = 1.\n%\n% A is unimodular.\n%\n% A is integral: int ( A ) = A.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n\n if ( i == j-1 )\n a(i,j) = - 1.0;\n elseif ( i == j )\n if ( i == 1 )\n a(i,j) = 1.0;\n else\n a(i,j) = ( n + 2 - i );\n end\n elseif ( j < i )\n a(i,j) = - ( n + 1 - i ) * a(i-1,j);\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/frank_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7408653645044755}} {"text": "function [detJ,J] = dtiJacobian(inData)\n%\n% [detJ,J] = dtiJacobian(inData)\n%\n% Computes the Jacobian (J) and the determinant of the Jacobian (detJ)\n% given an XxYxZx3 or Nx3 input array. The array is assumed to represent a\n% vector field. The Jacobian is a useful metric for interpreting\n% deformations. E.g., abs(detJ) represents the local volume change for a\n% deformation field.\n%\n% HISTORY:\n% 2008.06.25 RFD wrote it.\n\nsz = size(inData);\n\nif((numel(sz)~=4 && numel(sz)~=2) || sz(end)~=3)\n error('inData must be XxYxZx3 or Nx3.');\nend\n\n% Approximate the Jacobian of the input array using grad.\n\nif(numel(sz)==2)\n inData = reshape(inData,[1 1 1 sz(1) sz(2)]);\nend\n\ndim = size(inData);\nJ = zeros(dim(1),dim(2),dim(3),3,3);\n\nfor(ii=1:3)\n [gradX,gradY,gradZ] = gradient(inData(:,:,:,ii),1); \n J(:,:,:,ii,1) = gradX; \n J(:,:,:,ii,2) = gradY; % Or Y,X,Z?\n J(:,:,:,ii,3) = gradZ;\nend\n% Compute the determinant of J\n% det(J) for a 3x3 [a b c; d e f; g h i] is: (aei+bfg+cdh)-(gec+hfa+idb)\n% a=1,1; b=1,2; c=1,3; d=2,1; e=2,2; f=2,3; g=3,1; h=3,2; i=3,3;\ndetJ = J(:,:,:,1,1).*J(:,:,:,2,2).*J(:,:,:,3,3) ...\n + J(:,:,:,1,2).*J(:,:,:,2,3).*J(:,:,:,3,1) ...\n + J(:,:,:,1,3).*J(:,:,:,2,1).*J(:,:,:,3,2) ...\n - J(:,:,:,3,1).*J(:,:,:,2,2).*J(:,:,:,1,3) ...\n - J(:,:,:,3,2).*J(:,:,:,2,3).*J(:,:,:,1,1) ...\n - J(:,:,:,3,3).*J(:,:,:,2,1).*J(:,:,:,1,2);\n \nif(numel(sz)==2)\n J = squeeze(J);\n detJ = squeeze(detJ);\nend\nreturn;", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/tensor/dtiJacobian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.740824240496317}} {"text": "function chi = RoadInclination_Arkussinus(z_I_Ground_m,l_WheelbaseFB_m,w_TrackFB_m,phiz_IK_rad)\n%% Computation of Road Angles from Street Profile in Inertial Frame\n% Input parameters:\n% phiz_IK_rad [rad] Euler-Angle around z-Axis from Inertial Reference Frame I to Vehicle Fixed Reference Frame K [Psi]\n% w_TrackFB_m [m] Track width at Front and Rear Axle [w_TrackF_m w_TrackR_m]\n% l_WheelbaseFB_m [m] Wheelbase from Cog to Front and Rear Axle [l_WheelbaseF_m l_WheelbaseR_m]\n% z_I_Ground_m [m] Input Vector with z-Profile of Street in Inertial Coordinate System at the Axle Locations [x1 x2 x3 x4] [3x4]\n% Output parameters:\n% Y [rad] Approximated Cardan Angles from Inertial Reference Frame to Road Fixed Reference Frame [chi_x chi_y Psi] [3x1]\n\n%% Computation of Road Angles\n% Inclination Angle in x-direction for negative z-road-profile\nchi_y = -asin( 0.5*((z_I_Ground_m(1)+z_I_Ground_m(2))-(z_I_Ground_m(3)+z_I_Ground_m(4)))/sum(abs(l_WheelbaseFB_m)) );\n% Inclination Angle in y-direction for negative z-road-profile\nchi_x = -asin( 0.5*((z_I_Ground_m(1)+z_I_Ground_m(3))-(z_I_Ground_m(2)+z_I_Ground_m(4)))/mean(abs(w_TrackFB_m)) );\n\n%% Output Parameters\nchi = [chi_x;chi_y;phiz_IK_rad];\n\n", "meta": {"author": "TUMFTM", "repo": "sim_vehicle_dynamics", "sha": "df2ae95dbeb6f8e4591f31ee378acac8e812f358", "save_path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics", "path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics/sim_vehicle_dynamics-df2ae95dbeb6f8e4591f31ee378acac8e812f358/vehicle_model/vehicledynamics/src/RoadInclination_Arkussinus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305349799242, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7408015783924359}} {"text": "%%***************************************************************\n%% logcheby: logarithmic Chebyshev approximation problem. \n%% SDP formulation. \n%% minimize t \n%% x,t\n%% such that 1/t <= (x'*B(i,:))/f(i) <= t, i = 1:p.\n%% \n%% B = pxm matrix, f = p-vector, p > m.\n%%\n%% Ref: Vanderberghe & Boyd. \n%%--------------------------------------------------------------\n%% [blk,Avec,C,b,X0,y0,Z0,obj,x] = logcheby(B,f,feas,solve);\n%%\n%% B = pxm matrix (p > m).\n%% f = px1 vector, [B(:,j)./f must be positive for each j] \n%% feas = 1 if want feasible starting point\n%% = 0 if otherwise.\n%% solve = 0 if just want initialization. \n%% = 1 if want to solve the problem. \n%%\n%% SDPT3: version 3.0 \n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last modified: 2 Feb 01\n%%***************************************************************\n\n function [blk,Avec,C,b,X0,y0,Z0,objval,x] = logcheby(B,f,feas,solve);\n \n if (nargin < 4); solve = 0; end; \n if (nargin < 3); feas = 1; end; \n\n if ~isreal(B); error('B must be real'); end;\n\n [p,m] = size(B); \n blk{1,1} = 's'; blk{1,2} = 2*ones(1,p); \n blk{2,1} = 'l'; blk{2,2} = p; \n\n E = zeros(p,m); \n for j = [1:m]; E(:,j) = B(:,j)./f; end;\n if any(E < 1e-10);\n error(' B(:,j)./f must have all entry positive'); \n end;\n for i = [1:p]; beta(i) = sum(E(i,:)); end; \n%%\n temp = zeros(2*p+1,1);\n temp(2:2:2*p) = ones(p,1); \n C{1,1} = spdiags(temp,1,2*p,2*p); C{1,1} = C{1,1} + C{1,1}'; \n C{2,1} = zeros(p,1); \n b = [zeros(m,1); 1];\n\n A = cell(2,m+1); \n temp = zeros(2*p,1);\n for k = 1:m\n temp(1:2:2*p-1) = -E(:,k);\n A{1,k} = spdiags(temp,0,2*p,2*p); \n A{2,k} = E(:,k);\n end;\n temp = zeros(2*p,1);\n temp(2:2:2*p) = ones(p,1); \n A{1,m+1} = spdiags(temp,0,2*p,2*p); \n A{2,m+1} = ones(p,1);\n%%\n Avec = svec(blk,A,ones(size(blk,1),1)); \n if (feas == 1); \n X0{1,1} = speye(2*p)/(2*p);\n X0{2,1} = ones(p,1)/(2*p); \n y0 = [ones(m,1); -1.1*max(beta)]/min(beta);\n Z0 = ops(C,'-',Atyfun(blk,Avec,[],[],y0));\n elseif (feas == 0);\n [X0,y0,Z0] = infeaspt(blk,Avec,C,b);\n end; \n if (solve)\n [obj,X,y,Z] = sqlp(blk,Avec,C,b,[],X0,y0,Z0);\n objval = -mean(obj);\n x = y(1:m);\n else\n objval = []; x = [];\n end \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/sdpt3/Examples/logcheby.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7407348360161655}} {"text": "%% Machine Learning Online Class\n% Exercise 1: Linear regression with multiple variables\n%\n% Instructions\n% ------------\n%\n% This file contains code that helps you get started on the\n% linear regression exercise.\n%\n% You will need to complete the following functions in this\n% exericse:\n%\n% warmUpExercise.m\n% plotData.m\n% gradientDescent.m\n% computeCost.m\n% gradientDescentMulti.m\n% computeCostMulti.m\n% featureNormalize.m\n% normalEqn.m\n%\n% For this part of the exercise, you will need to change some\n% parts of the code below for various experiments (e.g., changing\n% learning rates).\n%\n\n%% Initialization\n\n%% ================ Part 1: Feature Normalization ================\n\n%% Clear and Close Figures\nclear ; close all; clc\n\nfprintf('Loading data ...\\n');\n\n%% Load Data\ndata = load('ex1data2.txt');\nX = data(:, 1:2);\ny = data(:, 3);\nm = length(y);\n\n% Print out some data points\nfprintf('First 10 examples from the dataset: \\n');\nfprintf(' x = [%.0f %.0f], y = %.0f \\n', [X(1:10,:) y(1:10,:)]');\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n% Scale features and set them to zero mean\nfprintf('Normalizing Features ...\\n');\n\n[X mu sigma] = featureNormalize(X);\n\n% Add intercept term to X\nX = [ones(m, 1) X];\n\n\n%% ================ Part 2: Gradient Descent ================\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: We have provided you with the following starter\n% code that runs gradient descent with a particular\n% learning rate (alpha).\n%\n% Your task is to first make sure that your functions -\n% computeCost and gradientDescent already work with\n% this starter code and support multiple variables.\n%\n% After that, try running gradient descent with\n% different values of alpha and see which one gives\n% you the best result.\n%\n% Finally, you should complete the code at the end\n% to predict the price of a 1650 sq-ft, 3 br house.\n%\n% Hint: By using the 'hold on' command, you can plot multiple\n% graphs on the same figure.\n%\n% Hint: At prediction, make sure you do the same feature normalization.\n%\n\nfprintf('Running gradient descent ...\\n');\n\n% Choose some alpha value\nalpha = 0.01;\nnum_iters = 400;\n\n% Init Theta and Run Gradient Descent\ntheta = zeros(3, 1);\n[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters);\n\n% Plot the convergence graph\nfigure;\nplot(1:numel(J_history), J_history, '-b', 'LineWidth', 2);\nxlabel('Number of iterations');\nylabel('Cost J');\n\n% Display gradient descent's result\nfprintf('Theta computed from gradient descent: \\n');\nfprintf(' %f \\n', theta);\nfprintf('\\n');\n\n% Estimate the price of a 1650 sq-ft, 3 br house\n% ====================== YOUR CODE HERE ======================\n% Recall that the first column of X is all-ones. Thus, it does\n% not need to be normalized.\n\nx = [1 1650 3]';\nprice = theta' * x;\n\n% ============================================================\n\nfprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...\n '(using gradient descent):\\n $%f\\n'], price);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% ================ Part 3: Normal Equations ================\n\nfprintf('Solving with normal equations...\\n');\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: The following code computes the closed form\n% solution for linear regression using the normal\n% equations. You should complete the code in\n% normalEqn.m\n%\n% After doing so, you should complete this code\n% to predict the price of a 1650 sq-ft, 3 br house.\n%\n\n%% Load Data\ndata = csvread('ex1data2.txt');\nX = data(:, 1:2);\ny = data(:, 3);\nm = length(y);\n\n% Add intercept term to X\nX = [ones(m, 1) X];\n\n% Calculate the parameters from the normal equation\ntheta = normalEqn(X, y);\n\n% Display normal equation's result\nfprintf('Theta computed from the normal equations: \\n');\nfprintf(' %f \\n', theta);\nfprintf('\\n');\n\n\n% Estimate the price of a 1650 sq-ft, 3 br house\n% ====================== YOUR CODE HERE ======================\n\nx = [1 1650 3]';\nprice = theta' * x;\n\n% ============================================================\n\nfprintf(['Predicted price of a 1650 sq-ft, 3 br house ' ...\n '(using normal equations):\\n $%f\\n'], price);\n\n", "meta": {"author": "zsiciarz", "repo": "ml-coursera", "sha": "54208ee72b88f1dc3c9235e644a47f618b80441c", "save_path": "github-repos/MATLAB/zsiciarz-ml-coursera", "path": "github-repos/MATLAB/zsiciarz-ml-coursera/ml-coursera-54208ee72b88f1dc3c9235e644a47f618b80441c/octave/ex1/ex1_multi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936435, "lm_q2_score": 0.9059898241909247, "lm_q1q2_score": 0.7407141559496664}} {"text": "function [ xout, yout ] = quaerotate ( xin, yin )\n\n%*****************************************************************************80\n%\n%% QUAEROTATE applies a rotation.\n%\n% Licensing:\n%\n% This code is distributed under the GNU GPL license.\n%\n% Modified:\n%\n% 26 June 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This 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, real XIN, YIN, the coordinates of the point.\n%\n% Output, real XOUT, YOUT, the coordinates of the point\n% after rotation.\n%\n\n%\n% Initialize the matrix of rotation.\n%\n theta = 2.0 * pi / 3.0;\n a11 = cos ( theta );\n a22 = cos ( theta );\n a12 = - sin ( theta );\n a21 = -a12;\n%\n% Apply the rotation matrix to the input vector.\n%\n xout = a11 * xin + a12 * yin;\n yout = a21 * xin + a22 * yin;\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/triangle_symq_rule/quaerotate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7407141384950886}} {"text": "function jac = p18_jac ( neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P18_JAC evaluates the jacobian for problem p18.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NEQN, the number of equations.\n%\n% Input, real T, Y(NEQN), the arguments of the jacobian.\n%\n% Output, real JAC(NEQN,NEQN), the jacobian matrix.\n%\n jac = zeros ( neqn, neqn );\n\n d = ( sqrt ( ( y(1).^2 + y(2).^2 ) ) ).^5;\n\n jac(1,3) = 1.0;\n jac(2,4) = 1.0;\n jac(3,1) = ( 2.0 * y(1).^2 - y(2).^2 ) / d;\n jac(3,2) = 3.0 * y(1) * y(2) / d;\n jac(4,1) = 3.0 * y(1) * y(2) / d;\n jac(4,2) = ( - y(1).^2 + 2.0 * y(2).^2 ) / 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/test_ode/p18_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7406682091154387}} {"text": "function [W,fun,iter] = wLassomtl(X,y,XtX,Xty,lambda,W0,tol,maxiter,L,Lflag)\n% Lasso Multi-Task Learning\n% min_W ||XW - Y||_F^2 + \\sum_i lambda_ij*|W^ij|\n% By Nesterov's method\n% ------------------------------- Input ---------------------------------------------\n% X: block diagonal data matrix whose i-th block (n_i*d) is the data matrix of the i-th task\n% y: \\sum_i{n_i}*1 vector; response vector which is stacked by the reponses of all tasks\n% XtX: X'*X\n% Xty: X'*y\n% lambda: regularized parameter (vector)\n% W0: d*m matrix; starting point of W \n% tol: stopping tolerance\n% maxiter: maximum iterative steps\n% Lflag: estimate the upper bound of Lipschitz constant if nonzero, zero otherwise \n%\n% ------------------------------- Output -------------------------------------------\n%\n% W: output weight\n% fun: function values\n% iter: iterative steps \n%\n% -----------------------------------------------------------------------------------\n\nW = W0;\n[d,m] = size(W); % d: dimension, m: the number of tasks\n\nWn = W;\nt_new = 1; \nfun = zeros(maxiter+1,1);\n\n% Initial function value\nfun(1) = norm(X*W(:) - y)^2 + wL1norm(W,lambda);\ncount = 0;\nfor iter = 1:maxiter\n W_old = W;\n t_old = t_new;\n gradvec = 2*(XtX*Wn(:) - Xty);\n gradmat = reshape(gradvec,d,m);\n % If we estimate the upper bound of Lipschitz constant, no line search\n % is needed.\n if Lflag\n W = proximalwL1norm(Wn - gradmat/L, lambda/L);\n else\n % line search \n for inneriter = 1:20\n W = proximalwL1norm(Wn - gradmat/L, lambda/L);\n dW = W - Wn;\n if 2*(dW(:)'*XtX*dW(:)) <= L*sum(sum((dW.*dW)))\n break;\n else\n L = L*2;\n end\n end\n end\n fun(iter+1) = norm(X*W(:) - y)^2 + wL1norm(W,lambda);\n % stopping condition\n if abs(fun(iter) - fun(iter+1))/fun(iter+1) < tol\n count = count + 1;\n else\n count = 0;\n end\n if count >= 1\n break;\n end\n\n % Update the coefficient\n t_new = (1+sqrt(1+4*t_old^2))/2;\n Wn = W + (t_old-1)/t_new*(W - W_old);\n \nend\n\n\n", "meta": {"author": "jiayuzhou", "repo": "MALSAR", "sha": "fb9751594983df020ddc4f7e4a40520ee7c37989", "save_path": "github-repos/MATLAB/jiayuzhou-MALSAR", "path": "github-repos/MATLAB/jiayuzhou-MALSAR/MALSAR-fb9751594983df020ddc4f7e4a40520ee7c37989/MALSAR/functions/msmtfl/wLassomtl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7406681950770453}} {"text": "function I=getNextCombo(I,n,startVal)\n%%GETNEXTCOMBO Return the next combination in lexicographic order given the\n% current combination. If the final combination in the\n% sequence has been reached, then an empty matrix is returned.\n% The first element in the combination is the least\n% significant element for defining the lexicographic order.\n%\n%INPUTS: I The rX1 or 1Xr current combination of r elements. The next\n% combination in lexicographic order is desired. The first element\n% is the least significant and one begins with I=[0;1;2;...;r-1]\n% is startVal=0 and I=[1;2;3;...;r] if startVal=1.\n% n The number of items from which r items are chosen for\n% combinations. The elements of I can range from 0 to n-1. if\n% startVal=0 or they range from 1 to n if startVal=1.\n% startVal This is zero or 1, indicating which value the value at which the\n% elements in I can start. The default if omitted or an empty\n% matrix is passed is 0.\n%\n%OUTPUTS: I The next combination in the lexicographic sequence, or an empty\n% matrix if the final combination in the lexicographic ordering\n% is provided.\n%\n%This function can be useful for generating combinations when used in a\n%loop. It is more computationally efficient than sequentially unranking the\n%combinations. If the final combination is put in, an empty matrix will be\n%returned.\n%\n%The algorithm is from [1], with an option to start at 0 instead of 1.\n%\n%REFERENCES:\n%[1] C. J. Mifsud, \"Algorithm 154: Combination in lexicographical order,\" \n% Communications of the ACM, vol. 6, no. 3 pp. 103, Mar. 1963.\n% modified to start from zero instead of one.\n%\n%September 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(startVal))\n startVal=0; \nend\n\nif(startVal==0)\n r=length(I);\n if(I(r) 1\n initial_solution = true;\n ydata = no_dims;\n no_dims = size(ydata, 2);\n else\n initial_solution = false;\n end\n \n % Compute joint probabilities\n D = D / max(D(:)); % normalize distances\n P = d2p(D .^ 2, perplexity, 1e-5); % compute affinities using fixed perplexity\n \n % Run t-SNE\n if initial_solution\n ydata = tsne_p(P, labels, ydata);\n else\n ydata = tsne_p(P, labels, no_dims);\n end\n ", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/tsne_d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8198933381139646, "lm_q1q2_score": 0.7406048981645169}} {"text": "function [oHDev] = calculateHDEV(tau,sPeriod,readings)\n%Overlapping Hadamard (ADEV) function that uses phase error or time error values\n%input argument is readings already grouped as tau values. tau is the\n%desired gate or tau time needed for calculating overlap. \n%sPeriod is used to determine the overlap\n\nN = numel(readings); %get the reading count\nn = tau / sPeriod; %calculate averaging factor\nn = floor(n); %make sure this is an integer\nconst = 1/(6*(N - (3*n))*tau^2); %calculate the const mult 1/(2*(N - (2*n))*tau^2)\n%sum from i=1 to N-(3*n) (Xi+3m - 3Xi+2m + 3Xi+m - Xi)^2\nsum = 0; %variable to store summation calculation\n\n\n%loop for performing summation\nfor i = 1:(N-(3*n))\n sum = sum + (readings(i+(3*n)) - (3*readings(i+(2*n))) + (3*readings(i+n)) - readings(i))^2; \nend\n\noHDev = sqrt(const*sum); %square root for Allan Dev", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31319-stability-analyzer-53230a/Stability Analyzer 2.0/calculateHDEV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7405870495291125}} {"text": "function J2=numDiff2(x,f,fDim,N,epsilon)\n%%NUMDIFF2 Numerically compute the second derivatives using central\n% difference formulae based on Lagrange interpolating polynomials.\n% The algorithm is made to alert (and not crash) in the event that\n% f fails. Specifically, if f returns an empty matrix or it any of\n% the components of f are NaNs, then the numDiff function will\n% terminate early, returning an empty matrix to indicate failure.\n% The function only computes second derivatives, not considering\n% cross terms (it does not find a Hessian matrix). Use numDiffHess\n% to get a Hessian matrix with cross terms.\n%\n%INPUTS: x The xDimX1 vector or scalar point at which the second derivative\n% of the (possibly vector) function is desired.\n% f The scalar or vector function that is to be differentiated. The\n% function f must take x as its parameter and its output should be\n% a scalar or a column vector.\n% fDim The dimensionality of the output of f.\n% N A number >=1 specifying the order of the second derivative\n% approximation. Values for n=1 through 3 are explicitly coded in.\n% For values 3 and above, the coefficients of the second\n% derivative of the Lagrange interpolating polynomial are\n% explicitly solved. If omitted, a value of N=1 is used.\n% epsilon A scalar or xDimX1 vector quantity specifying the finite step\n% size used for numerical differentiation. If a scalar value is\n% given, that value is used for differentiating with respect to\n% elements of xDim. If an xDimX1 value is given, then the\n% corresponding element of epsilon is used to differentiate each\n% element of x. If epsilon is omitted, then\n% epsilon=max(1e-5*x,1e-7); is used.\n%\n%OUTPUTS: J2 A fDimXxDim matrix of second derivatives. Each column is the\n% derivative vector of f with respect to the corresponding\n% element of x. If at any point the function f returned a NaN or\n% an empty matrix, J2 will be an empty matrix.\n%\n%The function is similar to the numDiff function. Central-difference\n%numerical differentiation is discussed in terms of Lagrange interpolating\n%polynomials in Chapter 4.1 of [1]. The Lagrange interpolating polynomials\n%themselves are discussed in Chapter 3 of [1]. In general, the coefficients\n%of the interpolating polynomial for first derivative central difference\n%numerical differentiation come from Equation 4.2, which expresses them in\n%terms of the first derivative of a Lagrange interpolating polynomial. This\n%function just extends the concept by using the second-derivative\n%coefficients.\n%\n%REFERENCES:\n%[1] R. L. Burden and J. D. Faires, Numerical Analysis, 9th ed. Boston, MA:\n% Brooks/ Cole, 2011.\n%\n%April 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<4)\n N=1; \nend\n\nswitch(N)\n case 1\n a=[1; -2; 1];\n case 2\n a=[-1/12; 4/3; -5/2; 4/3; -1/12];\n case 3\n a=[1/90; -3/20; 3/2; -49/18; 3/2; -3/20; 1/90];\n otherwise\n [~,~,d2Li]=LagrangeInterpPoly(-N:1:N);\n a=d2Li(end,:);\nend\n\nxDim=size(x,1);\n\nif(nargin<5)\n %If epsilon is not specified, then use some ad-hoc default value\n epsilon=max(1e-5*x,1e-7);\nend\n\nif(isscalar(epsilon))\n epsilon=repmat(epsilon,[xDim,1]); \nend\n\nJ2=zeros(fDim,xDim);\nfor curEl=1:xDim\n epsCur=epsilon(curEl);\n \n curIdx=1;\n for curP=-N:1:N\n xP=x;\n xP(curEl)=xP(curEl)+curP*epsCur;\n fxP=f(xP);\n if(isempty(fxP)||any(isnan(fxP)))\n J2=[];\n return;\n end\n J2(:,curEl)=J2(:,curEl)+a(curIdx)*fxP;\n curIdx=curIdx+1;\n end\n J2(:,curEl)=J2(:,curEl)/(epsCur^2);\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/numDiff2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.740503030233312}} {"text": "function fn = facenormals( V,F )\n%FACENORMALS Compute face normals of triangular mesh\n% V - nverts by 3 matrix containing vertex positions\n% F - ntri by 3 matrix containing triangle vertex indices\n\n% Get the triangle vertices\nv1 = F(:, 1);\nv2 = F(:, 2);\nv3 = F(:, 3);\n\n% Compute the edge vectors\ne1s = V(v2, :) - V(v1, :);\ne2s = V(v3, :) - V(v1, :);\n\n% Compute cross products between edge vectors\nfn = cross(e1s, e2s, 2);\n\n% Normalise face normals to unit length\nnorms = sqrt(fn(:,1).^2+fn(:,2).^2+fn(:,3).^2);\nfn=fn./repmat(norms,[1 3]);\n\nend\n\n", "meta": {"author": "waps101", "repo": "3DMM_edges", "sha": "848e9775c0581ae97469eacad60dfe3943c30707", "save_path": "github-repos/MATLAB/waps101-3DMM_edges", "path": "github-repos/MATLAB/waps101-3DMM_edges/3DMM_edges-848e9775c0581ae97469eacad60dfe3943c30707/utils/facenormals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8289388104343893, "lm_q1q2_score": 0.7404988364045428}} {"text": "function [ output_maps ] = max_pooling( input_maps)\n%POOLING Summary of this function goes here\n% Detailed explanation goes here\n \n orig_rows = size(input_maps,1);\n orig_cols = size(input_maps,2);\n \n pooled_rows = ceil(orig_rows / 2);\n pooled_cols = ceil(orig_cols / 2);\n\n up_to_rows_out = floor(orig_rows / 2);\n up_to_cols_out = floor(orig_cols / 2);\n\n if(mod(orig_cols,2) == 0)\n up_to_cols = orig_cols;\n else\n up_to_cols = orig_cols - 1;\n end\n \n if(mod(orig_rows,2) == 0)\n up_to_rows = orig_rows;\n else\n up_to_rows = orig_rows - 1;\n end\n \n output_maps = zeros(pooled_rows, pooled_cols, size(input_maps,3));\n for i=1:size(input_maps,3)\n temp = im2col(input_maps(1:up_to_rows,1:up_to_cols,i), [2,2], 'distinct');\n max_val = max(temp);\n output_maps(1:up_to_rows_out,1:up_to_cols_out,i) = reshape(max_val, up_to_rows_out, up_to_cols_out); \n end\n \n % A bit of a hack for non-even number of rows or columns\n if(mod(orig_cols,2) ~= 0)\n for i=1:size(input_maps,3)\n temp = im2col(input_maps(1:up_to_rows,end,i), [2,1], 'distinct');\n max_val = max(temp);\n output_maps(1:up_to_rows_out,end,i) = max_val; \n end \n end\n\n if(mod(orig_rows,2) ~= 0)\n for i=1:size(input_maps,3)\n temp = im2col(input_maps(end, 1:up_to_cols,i), [1,2], 'distinct');\n max_val = max(temp);\n output_maps(end, 1:up_to_cols_out,i) = max_val; \n end \n end\n \n if(mod(orig_cols,2) ~= 0 && mod(orig_rows,2) ~= 0)\n output_maps(end,end,:) = input_maps(end,end,:);\n end\n \n\n \nend\n\n", "meta": {"author": "TadasBaltrusaitis", "repo": "OpenFace", "sha": "3d4b5cf8d96138be42bed229447f36cbb09a5a29", "save_path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace", "path": "github-repos/MATLAB/TadasBaltrusaitis-OpenFace/OpenFace-3d4b5cf8d96138be42bed229447f36cbb09a5a29/matlab_version/face_detection/mtcnn/max_pooling.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7404988269668464}} {"text": "function [C,numberOfOverlapPixels] = normxcorr2_general(varargin)\n%NORMXCORR2_GENERAL Normalized two-dimensional cross-correlation.\n% [C,numberOfOverlapPixels] = NORMXCORR2_GENERAL(TEMPLATE,A) computes the\n% normalized cross-correlation of matrices TEMPLATE and A. The resulting\n% matrix C contains correlation coefficients and its values may range\n% from -1.0 to 1.0.\n%\n% [C,numberOfOverlapPixels] =\n% NORMXCORR2_GENERAL(TEMPLATE,A,requiredNumberOfOverlapPixels) sets to 0\n% all locations in C computed from positions where A and T overlap less\n% than requiredNumberOfOverlapPixels.\n% Larger values of requiredNumberOfOverlapPixels zero-out pixels on a\n% larger border around C. \n% Thus, larger values remove less stable computations but also limit the\n% capture range. \n% If the template is smaller than the image and it is desired that the\n% computation only be carried out when the template is fully overlapping\n% the image, requiredNumberOfOverlapPixels should be set to\n% numel(template).\n% The default is set to 0, meaning no modifications to C.\n%\n% Limitations of normxcorr2:\n% The documentation of normxcorr2 states that, \"The matrix A must be\n% larger than the matrix TEMPLATE for the normalization to be\n% meaningful.\" It is implemented following the details of the paper \"Fast\n% Normalized Cross-Correlation\", by J. P. Lewis, Industrial Light &\n% Magic. This approach assumes the template is small relative to the\n% image and proceeds to calculate the normalization across the entire\n% template. This leads to correct computations wherever the template is\n% wholly overlapping with the image, but the computation is incorrect in\n% the borders of the output (the border size is proportional to the\n% template size). This problem is therefore worse for larger templates\n% to the point that, when the template is the same size as the image, the\n% only correct value is at the center pixel (where the images are fully\n% overlapping). Thus, if normxcorr2 is used for such things as\n% registering images of the same size, the result will be incorrect.\n% \n% The new normxcorr2_general:\n% normxcorr2_general is more general than normxcorr2 in that it gives\n% correct results everywhere regardless of the relative size of A and\n% TEMPLATE. It accomplishes this by computing the normalized correlation\n% only in the overlap regions between the two matrices. Thus, the result\n% is correct for all locations of correlation. The result is the same as\n% if the NCC were carried out in the spatial domain (which would take a\n% long time to compute for large matrices).\n% \n% Class Support\n% -------------\n% The input matrices can be numeric. The output matrix C is double.\n%\n% Example\n% -------\n% This example correlates an input with itself using normxcorr2 (the\n% built-in Matlab version) and normxcorr2_general (the general version).\n% Because the template is not small compared with the input image (they\n% are the same size in this case), the output of normxcorr2.m is\n% incorrect for most pixels. On the other hand, the general version is\n% correct at all locations, which can be easily verified analytically or\n% visually.\n% \n% Note that the image processing toolbox (IPT) is needed to run this\n% example since normxcorr2 is part of that toolbox. However,\n% normxcorr2_general does not require the IPT.\n% \n% input = repmat([1:6 5:-1:1],11,1);\n% normxcorr2_output = normxcorr2(input,input);\n% normxcorr2_general_output = normxcorr2_general(input,input);\n% figure;\n% subplot(2,2,1), imagesc(input); title('Input pattern');\n% subplot(2,2,3), imagesc(normxcorr2_output); title('Output of Matlab built-in normxcorr2');\n% subplot(2,2,4), imagesc(normxcorr2_general_output); title('Output of normxcorr2\\_general');\n%\n% See also NORMXCORR2.\n%\n% References: Dirk Padfield. \"Masked FFT registration\". In Proc. Computer\n% Vision and Pattern Recognition, 2010.\n%\n% Author: Dirk Padfield, GE Global Research, padfield@research.ge.com\n%\n\n% Input-output specs\n% ------------------\n% T: 2-D, real, full matrix\n% logical, uint8, uint16, or double\n% no NaNs, no Infs\n% prod(size(T)) >= 2\n%\n% A: 2-D, real, full matrix\n% logical, uint8, uint16, or double\n% no NaNs, no Infs\n% prod(size(A)) >= 2\n%\n% C: double\n\n[T, A, requiredNumberOfOverlapPixels] = ParseInputs(varargin{:});\n\nsizeA = size(A);\nsizeT = size(T);\n\n% Find the number of pixels used for the calculation as the two images are\n% correlated. The size of this image will be the same as the correlation\n% image. \nnumberOfOverlapPixels = local_sum(ones(sizeA),sizeT(1),sizeT(2));\n\nlocal_sum_A = local_sum(A,sizeT(1),sizeT(2));\nlocal_sum_A2 = local_sum(A.*A,sizeT(1),sizeT(2));\n\n% Note: diff_local_sums should be nonnegative, but it may have negative\n% values due to round off errors. Below, we use max to ensure the radicand\n% is nonnegative.\ndiff_local_sums_A = ( local_sum_A2 - (local_sum_A.^2)./ numberOfOverlapPixels );\nclear local_sum_A2;\ndenom_A = max(diff_local_sums_A,0); \nclear diff_local_sums_A;\n\n% Flip T in both dimensions so that its correlation can be more easily\n% handled.\nrotatedT = rot90(T,2);\nlocal_sum_T = local_sum(rotatedT,sizeA(1),sizeA(2));\nlocal_sum_T2 = local_sum(rotatedT.*rotatedT,sizeA(1),sizeA(2));\nclear rotatedT;\n\ndiff_local_sums_T = ( local_sum_T2 - (local_sum_T.^2)./ numberOfOverlapPixels );\nclear local_sum_T2;\ndenom_T = max(diff_local_sums_T,0); \nclear diff_local_sums_T;\n\ndenom = sqrt(denom_T .* denom_A);\nclear denom_T denom_A;\n\nxcorr_TA = xcorr2_fast(T,A);\nclear A T;\nnumerator = xcorr_TA - local_sum_A .* local_sum_T ./ numberOfOverlapPixels;\nclear xcorr_TA local_sum_A local_sum_T;\n\n% denom is the sqrt of the product of positive numbers so it must be\n% positive or zero. Therefore, the only danger in dividing the numerator\n% by the denominator is when dividing by zero. We know denom_T~=0 from\n% input parsing; so denom is only zero where denom_A is zero, and in these\n% locations, C is also zero.\nC = zeros(size(numerator));\ntol = 1000*eps( max(abs(denom(:))) );\ni_nonzero = find(denom > tol);\nC(i_nonzero) = numerator(i_nonzero) ./ denom(i_nonzero);\nclear numerator denom;\n\n% Remove the border values since they result from calculations using very\n% few pixels and are thus statistically unstable.\n% By default, requiredNumberOfOverlapPixels = 0, so C is not modified.\nif( requiredNumberOfOverlapPixels > max(numberOfOverlapPixels(:)) )\n error(['ERROR: requiredNumberOfOverlapPixels ' num2str(requiredNumberOfOverlapPixels) ...\n ' must not be greater than the maximum number of overlap pixels ' ...\n num2str(max(numberOfOverlapPixels(:))) '.']);\nend\nC(numberOfOverlapPixels < requiredNumberOfOverlapPixels) = 0;\n\n\n%-------------------------------\n% Function local_sum\n%\nfunction local_sum_A = local_sum(A,m,n)\n\n% This algorithm depends on precomputing running sums.\n\n% If m,n are equal to the size of A, a faster method can be used for\n% calculating the local sum. Otherwise, the slower but more general method\n% can be used. The faster method is more than twice as fast and is also\n% less memory intensive. \nif( m == size(A,1) && n == size(A,2) )\n s = cumsum(A,1);\n c = [s; repmat(s(end,:),m-1,1) - s(1:end-1,:)];\n s = cumsum(c,2);\n clear c;\n local_sum_A = [s, repmat(s(:,end),1,n-1) - s(:,1:end-1)];\nelse\n % Break the padding into parts to save on memory.\n B = zeros(size(A,1)+2*m,size(A,2));\n B(m+1:m+size(A,1),:) = A;\n s = cumsum(B,1);\n c = s(1+m:end-1,:)-s(1:end-m-1,:);\n d = zeros(size(c,1),size(c,2)+2*n);\n d(:,n+1:n+size(c,2)) = c;\n s = cumsum(d,2);\n local_sum_A = s(:,1+n:end-1)-s(:,1:end-n-1);\nend\n\n\n%-------------------------------\n% Function xcorr2_fast\n%\nfunction cross_corr = xcorr2_fast(T,A)\n\nT_size = size(T);\nA_size = size(A);\noutsize = A_size + T_size - 1;\n\n% Figure out when to use spatial domain vs. freq domain\nconv_time = time_conv2(T_size,A_size); % 1 conv2\nfft_time = 3*time_fft2(outsize); % 2 fft2 + 1 ifft2\n\nif (conv_time < fft_time)\n cross_corr = conv2(rot90(T,2),A);\nelse\n cross_corr = freqxcorr(T,A,outsize);\nend\n\n\n%-------------------------------\n% Function freqxcorr\n%\nfunction xcorr_ab = freqxcorr(a,b,outsize)\n \n% Find the next largest size that is a multiple of a combination of 2, 3,\n% and/or 5. This makes the FFT calculation much faster.\noptimalSize(1) = FindClosestValidDimension(outsize(1));\noptimalSize(2) = FindClosestValidDimension(outsize(2));\n\n% Calculate correlation in frequency domain\nFa = fft2(rot90(a,2),optimalSize(1),optimalSize(2));\nFb = fft2(b,optimalSize(1),optimalSize(2));\nxcorr_ab = real(ifft2(Fa .* Fb));\n\nxcorr_ab = xcorr_ab(1:outsize(1),1:outsize(2));\n\n\n%-------------------------------\n% Function time_conv2\n%\nfunction time = time_conv2(obssize,refsize)\n\n% time a spatial domain convolution for 10-by-10 x 20-by-20 matrices\n\n% a = ones(10);\n% b = ones(20);\n% mintime = 0.1;\n\n% t1 = cputime;\n% t2 = t1;\n% k = 0;\n% while (t2-t1) 3 )\n error('ERROR: The number of arguments must be either 2 or 3. Please see the documentation for details.');\nend\n\nT = varargin{1};\nA = varargin{2};\n\nif( nargin == 3 )\n requiredNumberOfOverlapPixels = varargin{3};\nelse\n requiredNumberOfOverlapPixels = 0;\nend\n\n% The following requires the image processing toolbox, so it is commented\n% out here for generality.\n%iptcheckinput(T,{'logical','numeric'},{'real','nonsparse','2d','finite'},mfilename,'T',1)\n%iptcheckinput(A,{'logical','numeric'},{'real','nonsparse','2d','finite'},mfilename,'A',2)\n\ncheckSizesTandA(T,A)\n\n% See geck 342320. If either A or T has a minimum value which is negative, we\n% need to shift the array so all values are positive to ensure numerically\n% robust results for the normalized cross-correlation.\nA = shiftData(A);\nT = shiftData(T);\n\ncheckIfFlat(T);\n\n%-----------------------------------------------------------------------------\nfunction B = shiftData(A)\n\nB = double(A);\n\nis_unsigned = isa(A,'uint8') || isa(A,'uint16') || isa(A,'uint32');\nif ~is_unsigned\n \n min_B = min(B(:)); \n \n if min_B < 0\n B = B - min_B;\n end\n \nend\n\n%-----------------------------------------------------------------------------\nfunction checkSizesTandA(T,A)\n\nif numel(T) < 2\n eid = sprintf('Images:%s:invalidTemplate',mfilename);\n msg = 'TEMPLATE must contain at least 2 elements.';\n error(eid,'%s',msg);\nend\n\n%-----------------------------------------------------------------------------\nfunction checkIfFlat(T)\n\nif std(T(:)) == 0\n eid = sprintf('Images:%s:sameElementsInTemplate',mfilename);\n msg = 'The values of TEMPLATE cannot all be the same.';\n error(eid,'%s',msg);\nend\n\n%-----------------------------------------------------------------------------\nfunction [newNumber] = FindClosestValidDimension(n)\n\n% Find the closest valid dimension above the desired dimension. This\n% will be a combination of 2s, 3s, and 5s.\n\n% Incrementally add 1 to the size until\n% we reach a size that can be properly factored.\nnewNumber = n;\nresult = 0;\nnewNumber = newNumber - 1;\nwhile( result ~= 1 )\n newNumber = newNumber + 1;\n result = FactorizeNumber(newNumber);\nend\n\n%-----------------------------------------------------------------------------\nfunction [n] = FactorizeNumber(n)\n\nfor ifac = [2 3 5]\n while( rem(n,ifac) == 0 )\n n = n/ifac;\n end\nend", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Analysis/+SpatialTuning_BNT/normxcorr2_general.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777552, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7404983574122944}} {"text": "function [shortestPaths, totalCosts] = kShortestPath(netCostMatrix, source, destination, k_paths)\n% Function kShortestPath(netCostMatrix, source, destination, k_paths) \n% returns the K first shortest paths (k_paths) from node source to node destination\n% in the a network of N nodes represented by the NxN matrix netCostMatrix.\n% In netCostMatrix, cost of 'inf' represents the 'absence' of a link \n% It returns \n% [shortestPaths]: the list of K shortest paths (in cell array 1 x K) and \n% [totalCosts] : costs of the K shortest paths (in array 1 x K)\n%==============================================================\n% Meral Shirazipour\n% This function is based on Yen's k-Shortest Path algorithm (1971)\n% This function calls a slightly modified function dijkstra() \n% by Xiaodong Wang 2004.\n% * netCostMatrix must have positive weights/costs\n%==============================================================\n% DATE : December 9 decembre 2009 \n% Last Updated: August 2 2010; January 6 2011; August 2 2011\n% ----Changes April 2 2010:----\n% 1-previous version(9/12/2009)did not handle some exceptions which should\n% have returned empty matrices for the return values (added lines 20 and 29)\n% 2-includes the changes proposed by Darren Rowland\n% ----Changes January 6 2011:----\n% 1-fixed a bug reported by Babak Zafari that prevented from finding ALL\n% the shortest paths in large networks\n%==============================================================\nif source > size(netCostMatrix,1) || destination > size(netCostMatrix,1)\n warning('The source or destination node are not part of netCostMatrix');\n shortestPaths=[];\n totalCosts=[];\nelse\n %---------------------INITIALIZATION---------------------\n k=1;\n [path cost] = dijkstra(netCostMatrix, source, destination);\n %P is a cell array that holds all the paths found so far:\n if isempty(path)\n shortestPaths=[];\n totalCosts=[];\n else\n path_number = 1; \n P{path_number,1} = path; P{path_number,2} = cost; \n current_P = path_number;\n %X is a cell array of a subset of P (used by Yen's algorithm below):\n size_X=1; \n X{size_X} = {path_number; path; cost};\n\n %S path_number x 1\n S(path_number) = path(1); %deviation vertex is the first node initially\n\n %***********************\n % K = 1 is the shortest path returned by dijkstra():\n shortestPaths{k} = path ;\n totalCosts(k) = cost;\n %***********************\n\n %--------------------------------------------------------\n while (k < k_paths && size_X ~= 0 )\n %remove P from X\n for i=1:length(X)\n if X{i}{1} == current_P\n size_X = size_X - 1;\n X(i) = [];%delete cell\n break;\n end\n end\n\n %---------------------------------------\n P_ = P{current_P,1}; %P_ is current P, just to make is easier for the notations\n\n %Find w in (P_,w) in set S, w was the dev vertex used to found P_\n w = S(current_P);\n for i = 1: length(P_)\n if w == P_(i)\n w_index_in_path = i;\n end\n end\n\n\n for index_dev_vertex= w_index_in_path: length(P_) - 1 %index_dev_vertex is index in P_ of deviation vertex\n temp_netCostMatrix = netCostMatrix;\n %------\n %Remove vertices in P before index_dev_vertex and there incident edges\n for i = 1: index_dev_vertex-1\n v = P_(i);\n temp_netCostMatrix(v,:)=inf;\n temp_netCostMatrix(:,v)=inf;\n end\n %------\n %remove incident edge of v if v is in shortestPaths (K) U P_ with similar sub_path to P_....\n SP_sameSubPath=[];\n index =1;\n SP_sameSubPath{index}=P_;\n for i = 1: length(shortestPaths)\n if length(shortestPaths{i}) >= index_dev_vertex\n if P_(1:index_dev_vertex) == shortestPaths{i}(1:index_dev_vertex)\n index = index+1;\n SP_sameSubPath{index}=shortestPaths{i};\n end\n end \n end \n v_ = P_(index_dev_vertex);\n for j = 1: length(SP_sameSubPath)\n next = SP_sameSubPath{j}(index_dev_vertex+1);\n temp_netCostMatrix(v_,next)=inf; \n end\n %------\n\n %get the cost of the sub path before deviation vertex v\n sub_P = P_(1:index_dev_vertex);\n cost_sub_P=0;\n for i = 1: length(sub_P)-1\n cost_sub_P = cost_sub_P + netCostMatrix(sub_P(i),sub_P(i+1));\n end\n\n %call dijkstra between deviation vertex to destination node \n [dev_p c] = dijkstra(temp_netCostMatrix, P_(index_dev_vertex), destination);\n if ~isempty(dev_p)\n path_number = path_number + 1;\n P{path_number,1} = [sub_P(1:end-1) dev_p] ; %concatenate sub path- to -vertex -to- destination\n P{path_number,2} = cost_sub_P + c ;\n\n S(path_number) = P_(index_dev_vertex);\n\n size_X = size_X + 1; \n X{size_X} = {path_number; P{path_number,1} ;P{path_number,2} };\n else\n %warning('k=%d, isempty(p)==true!\\n',k);\n end \n end\n %---------------------------------------\n %Step necessary otherwise if k is bigger than number of possible paths\n %the last results will get repeated !\n if size_X > 0\n shortestXCost= X{1}{3}; %cost of path\n shortestX= X{1}{1}; %ref number of path\n for i = 2 : size_X\n if X{i}{3} < shortestXCost\n shortestX= X{i}{1};\n shortestXCost= X{i}{3};\n end\n end\n current_P = shortestX;\n %******\n k = k+1;\n shortestPaths{k} = P{current_P,1};\n totalCosts(k) = P{current_P,2};\n %******\n else\n %k = k+1;\n end\n end\n end\nend\n%--------------------------------------------------------\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/32513-k-shortest-path-yens-algorithm/MATLAB_kShortestPath_Yen's algorithm/kShortestPath.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7404889576711341}} {"text": "function cc_grids_animate ( )\n\n%*****************************************************************************80\n%\n%% CC_GRIDS_ANIMATE displays a sequence of merged 2D Clenshaw-Curtis grids.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 November 2006\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CC_GRIDS_ANIMATE:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Display a sequence of merged 2D Clenshaw-Curtis grids.\\n' );\n\n dim_num = 2;\n \n while ( 1 )\n \n fprintf ( 1, '\\n' );\n order_max_1d = input ( 'Enter the maximum orders [A,B] or RETURN to exit;' );\n \n if ( isempty ( order_max_1d ) )\n break\n end\n\n points_old = [];\n points_old_num = 0;\n\n points = [];\n order_nd = 0;\n \n for order = 1 : max ( order_max_1d(1:2) )\n\n if ( 0 < order_nd )\n points_old(1:2,points_old_num+1:points_old_num+order_nd) = points(1:2,1:order_nd);\n points_old_num = points_old_num + order_nd;\n end\n\n clf\n%\n% We have to name the axes in order to control the grid.\n%\n axes_handle = axes;\n%\n% Compute the new points and plot them in red.\n%\n order_1d(1:2) = min ( order, order_max_1d(1:2) );\n order_nd = prod ( order_1d(1:2) );\n \n points = cc_grid ( dim_num, order_1d, order_nd );\n\n handle_new = scatter ( points(1,:), points(2,:), 'r', 'filled' );\n%\n% Plot the old points in blue.\n%\n hold on\n\n if ( 0 < points_old_num )\n handle_old = scatter ( points_old(1,:), points_old(2,:), 'b', 'filled' );\n end\n%\n% Force the plotting region to be square, not rectangular.\n%\n axis square\n%\n% Request grid lines.\n%\n grid on\n%\n% Specify the location of the grid lines, and suppress labeling.\n%\n set ( axes_handle, 'xtick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );\n set ( axes_handle, 'xticklabel', [] );\n set ( axes_handle, 'ytick', [ -1, -.75, -.5, -.25, 0, .25, .50, .75, 1] );\n set ( axes_handle, 'yticklabel', [] );\n%\n% Make the plotting region slightly bigger than the data.\n%\n axis ( [ -1.1, 1.1, -1.1, 1.1 ] )\n%\n% Title\n%\n s = sprintf ( '%dx%d Clenshaw-Curtis Grid', order_1d(1), order_1d(2) );\n title ( s );\n\n fprintf ( 1, '+%dx%d Clenshaw-Curtis Grid, Press return\\n', ...\n order_1d(1), order_1d(2) );\n\n pause\n\n hold off\n \n end\n\n fprintf ( 1, 'Press return to CLEAR the grid!\\n' );\n pause\n clf\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CC_GRIDS_ANIMATE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\n", "meta": {"author": "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_animate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7404889474349148}} {"text": "function [ ptab, b, c, d, eps, ierror ] = least_set_old ( ...\n ntab, xtab, ytab, ndeg )\n\n%*****************************************************************************80\n%\n%% LEAST_SET_OLD constructs the least squares polynomial approximation to data.\n%\n% Discussion:\n%\n% The least squares polynomial is not returned directly as a simple\n% polynomial. Instead, it is represented in terms of a set of\n% orthogonal polynomials appopriate for the given data. This makes\n% the computation more accurate, but means that the user can not\n% easily evaluate the computed polynomial. Instead, the routine \n% LEAST_EVAL should be used to evaluate the least squares polynomial\n% at any point. (However, the value of the least squares polynomial\n% at each of the data points is returned as part of this computation.)\n%\n%\n% A discrete unweighted inner product is used, so that\n%\n% ( F(X), G(X) ) = sum ( 1 <= I <= NTAB ) F(XTAB(I)) * G(XTAB(I)).\n%\n% The least squares polynomial is determined using a set of\n% orthogonal polynomials PHI. These polynomials can be defined\n% recursively by:\n%\n% PHI(0)(X) = 1\n% PHI(1)(X) = X - B(1)\n% PHI(I)(X) = ( X - B(I) ) * PHI(I-1)(X) - D(I) * PHI(I-2)(X)\n%\n% The array B(1:NDEG) contains the values\n%\n% B(I) = ( X*PHI(I-1), PHI(I-1) ) / ( PHI(I-1), PHI(I-1) )\n%\n% The array D(2:NDEG) contains the values\n%\n% D(I) = ( PHI(I-1), PHI(I-1) ) / ( PHI(I-2), PHI(I-2) )\n%\n% Using this basis, the least squares polynomial can be represented as\n%\n% P(X)(I) = sum ( 0 <= I <= NDEG ) C(I) * PHI(I)(X)\n%\n% The array C(0:NDEG) contains the values\n%\n% C(I) = ( YTAB(I), PHI(I) ) / ( PHI(I), PHI(I) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 May 2004\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Gisela Engeln-Muellges and Frank Uhlig,\n% Numerical Algorithms with C, pages 191-193.\n% Springer, 1996.\n%\n% Parameters:\n%\n% Input, integer NTAB, the number of data points.\n%\n% Input, real XTAB(NTAB), the X data. The values in XTAB\n% should be distinct, and in increasing order.\n%\n% Input, real YTAB(NTAB), the Y data values corresponding\n% to the X data in XTAB.\n%\n% Input, integer NDEG, the degree of the polynomial which the\n% program is to use. NDEG must be at least 1, and less than or \n% equal to NTAB-1.\n%\n% Output, real PTAB(NTAB), the value of the least squares polynomial \n% at the points XTAB(1:NTAB).\n%\n% Output, real B(1:NDEG), C(1:NDEG+1), D(1:NDEG-1), arrays containing \n% data about the polynomial.\n%\n% Output, real EPS, the root-mean-square discrepancy of the\n% polynomial fit.\n%\n% Output, integer IERROR, error flag.\n% zero, no error occurred;\n% nonzero, an error occurred, and the polynomial could not be computed.\n%\n ierror = 0;\n C_OFFSET = 1;\n D_OFFSET = -1;\n%\n% Check NDEG.\n%\n if ( ndeg < 1 )\n ierror = 1;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEAST_SET_OLD - Fatal error!\\n' );\n fprintf ( 1, ' NDEG < 1.\\n' );\n error ( 'LEAST_SET_OLD - Fatal error!' );\n end\n\n if ( ntab <= ndeg )\n ierror = 1;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEAST_SET_OLD - Fatal error!\\n' );\n fprintf ( 1, ' NTAB <= NDEG.\\n' );\n error ( 'LEAST_SET_OLD - Fatal error!' );\n end\n%\n% Check that the abscissas are strictly increasing.\n%\n for i = 1 : ntab-1\n if ( xtab(i+1) <= xtab(i) )\n ierror = 1;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LEAST_SET_OLD - Fatal error!\\n' );\n fprintf ( 1, ' XTAB must be strictly increasing, but\\n' );\n fprintf ( 1, ' XTAB(%d) = %f\\n', i, xtab(i) );\n fprintf ( 1, ' XTAB(%d) = %f\\n', i+1, xtab(i+1) );\n error ( 'LEAST_SET_OLD - Fatal error!' );\n end\n end\n\n i0l1 = 0;\n i1l1 = ntab;\n%\n% The polynomial is of degree at least 0.\n%\n y_sum = sum ( ytab(1:ntab) );\n rn0 = ntab;\n c(0+C_OFFSET) = y_sum / ntab;\n\n ptab(1:ntab) = y_sum / ntab;\n\n if ( ndeg == 0 )\n eps = sum ( ( ptab(1:ntab) - ytab(1:ntab) ).^2 );\n eps = sqrt ( eps / ntab );\n b = [];\n d = [];\n return;\n end\n%\n% The polynomial is of degree at least 1.\n%\n b(1) = sum ( xtab(1:ntab) ) / ntab;\n\n s = 0.0E+00;\n sum2 = 0.0E+00;\n for i = 1 : ntab\n ztab(i1l1+i) = xtab(i) - b(1);\n s = s + ztab(i1l1+i)^2;\n sum2 = sum2 + ztab(i1l1+i) * ( ytab(i) - ptab(i) );\n end\n\n rn1 = s;\n c(1+C_OFFSET) = sum2 / s;\n\n for i = 1 : ntab\n ptab(i) = ptab(i) + c(1+C_OFFSET) * ztab(i1l1+i);\n end\n\n if ( ndeg == 1 )\n eps = sum ( ( ptab(1:ntab) - ytab(1:ntab) ).^2 );\n eps = sqrt ( eps / ntab );\n d = [];\n return;\n end\n\n ztable(1:ntab) = 1.0;\n\n mdeg = 2;\n k = 2;\n\n while ( 1 )\n\n d(k+D_OFFSET) = rn1 / rn0;\n\n sum2 = 0.0;\n for i = 1 : ntab\n sum2 = sum2 + xtab(i) * ztab(i1l1+i) * ztab(i1l1+i);\n end\n\n b(k) = sum2 / rn1;\n\n s = 0.0;\n sum2 = 0.0;\n for i = 1 : ntab\n ztab(i0l1+i) = ( xtab(i) - b(k) ) * ztab(i1l1+i) ...\n - d(k+D_OFFSET) * ztab(i0l1+i);\n s = s + ztab(i0l1+i) * ztab(i0l1+i);\n sum2 = sum2 + ztab(i0l1+i) * ( ytab(i) - ptab(i) );\n end\n\n rn0 = rn1;\n rn1 = s;\n \n c(k+C_OFFSET) = sum2 / rn1;\n\n it = i0l1;\n i0l1 = i1l1;\n i1l1 = it;\n\n for i = 1 : ntab\n ptab(i) = ptab(i) + c(k+C_OFFSET) * ztab(i1l1+i);\n end\n \n if ( ndeg <= mdeg )\n break;\n end\n\n mdeg = mdeg + 1;\n k = k + 1;\n\n end\n%\n% Compute the RMS error.\n%\n eps = sum ( ( ptab(1:ntab) - ytab(1:ntab) ).^2 );\n eps = sqrt ( eps / ntab );\n\n return\nend\n", "meta": {"author": "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/least_set_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7404058035860386}} {"text": "function julian = jed_to_yearcount_julian ( jed )\n\n%*****************************************************************************80\n%\n%% JED_TO_YEARCOUNT_JULIAN converts a JED to a Julian year count.\n%\n% Discussion:\n%\n% An average year in the Julian calendar is exactly 365.25 days long.\n% This calculation counts the number of average Julian years from\n% the beginning of the year 2000.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 June 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real JED, the Julian Ephemeris Date.\n%\n% Output, real JULIAN, the Julian year.\n%\n year_length = 365.25;\n\n jed_epoch = epoch_to_jed_y2k ( );\n\n julian = 2000.0 + ( jed - jed_epoch ) / year_length;\n\n return\nend\n", "meta": {"author": "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/jed_to_yearcount_julian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7404057994293767}} {"text": "function face_normal = stla_face_normal_compute ( node_num, face_num, ...\n node_xyz, face_node )\n\n%*****************************************************************************80\n%\n%% STLA_FACE_NORMAL_COMPUTE computes normal vectors for an ASCII StereoLithography file.\n%\n% Discussion:\n%\n% This routine computes the normal vector to each triangular face\n% in the STLA solid. If the nodes of each triangular face are\n% listed in counterclockwise order (as seen from outside the solid),\n% then the normal vectors will be properly outward facing.\n%\n% The normal vectors will have unit Euclidean norm.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 September 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% 3D Systems, Inc,\n% Stereolithography Interface Specification,\n% October 1989.\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, integer FACE_NUM, the number of faces.\n%\n% Input, real NODE_XYZ(3,NODE_NUM), the node coordinates.\n%\n% Input, integer FACE_NODE(3,FACE_NUM), the nodes making faces.\n%\n% Input, integer FACE_MAX, the maximum number of faces.\n%\n% Output, real FACE_NORMAL(3,FACE_NUM), the normal vector at each face.\n%\n for face = 1 : face_num\n\n n1 = face_node(1,face);\n n2 = face_node(2,face);\n n3 = face_node(3,face);\n\n v1(1:3) = node_xyz(1:3,n2) - node_xyz(1:3,n1);\n v2(1:3) = node_xyz(1:3,n3) - node_xyz(1:3,n1);\n\n face_normal(1:3,face) = r8vec_cross_3d ( v1, v2 );\n\n norm = sqrt ( sum ( ( face_normal(1:3,face) ).^2 ) );\n\n if ( norm ~= 0.0 )\n face_normal(1:3,face) = face_normal(1:3,face) / norm;\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/stla_io/stla_face_normal_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7404057979338472}} {"text": "function a_inverse = r8ut_inverse ( n, a )\n\n%*****************************************************************************80\n%\n%% R8UT_INVERSE computes the inverse of a R8UT matrix.\n%\n% Discussion:\n%\n% The R8UT storage format is used for an M by N upper triangular \n% matrix. The format stores all M*N entries, even those which are zero.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% A Nijenhuis and H Wilf,\n% Combinatorial Algorithms,\n% Academic Press, 1978, second edition,\n% ISBN 0-12-519260-6\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real A(N,N), the R8UT matrix to be inverted.\n%\n% Output, real A_INVERSE(N,N), the inverse of the upper triangular matrix.\n%\n\n%\n% Check.\n%\n for i = 1 : n\n if ( a(i,i) == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8UT_INVERSE - Fatal error!\\n' );\n fprintf ( 1, ' Zero diagonal element.\\n' );\n error ( 'R8UT_INVERSE - Fatal error!' );\n end\n end\n\n a_inverse(1:n,1:n) = a(1:n,1:n);\n\n for j = n : -1 : 1\n\n for i = n : -1 : 1\n\n if ( j < i )\n\n a_inverse(i,j) = 0.0;\n\n elseif ( i == j )\n\n a_inverse(i,j) = 1.0 / a_inverse(i,j);\n\n elseif ( i < j )\n\n a_inverse(i,j) = - ( a_inverse(i,i+1:j) * a_inverse(i+1:j,j) ) ...\n / a_inverse(i,i);\n\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/wishart/r8ut_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7404057871925116}} {"text": "function gqn_sparse_test ( )\n\n%*****************************************************************************80\n%\n%% GQN_SPARSE_TEST uses the GQN function to build a sparse grid.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 May 2014\n%\n% Author:\n%\n% Original MATLAB version by Florian Heiss, Viktor Winschel.\n% This MATLAB version by John Burkardt.\n%\n% Local parameters:\n%\n% Local, integer D, the spatial dimension.\n%\n d = 5;\n trueval = hermite_integral ( d );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GQN_SPARSE_TEST:\\n' );\n fprintf ( 1, ' GQN sparse grid:\\n' );\n fprintf ( 1, ' Gauss quadrature, Hermite weight over (-oo,+oo).\\n' );\n fprintf ( 1, ' Exact integral is %g\\n', trueval );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' D Level Nodes SG estimate MC estimate\\n' );\n fprintf ( 1, ' SG error MC error\\n' );\n fprintf ( 1, '\\n' );\n\n for k = 1 : 8\n%\n% Compute sparse grid estimate.\n%\n [ x, w ] = nwspgr ( 'gqn', d, k );\n [ n, ~ ] = size ( x );\n fx = hermite_integrand ( d, n, x );\n sgappr = w' * fx;\n sgerror = sqrt ( ( sgappr - trueval ) .^ 2 ) / trueval;\n%\n% Average 1000 Monte Carlo estimates.\n%\n sim = zeros(1000,1);\n for r = 1 : 1000\n x = randn ( n, d );\n fx = hermite_integrand ( d, n, x );\n sim(r) = mean ( fx );\n end\n simappr = mean ( sim );\n simerror = sqrt ( mean ( ( sim - trueval ) .^ 2 ) ) / trueval;\n\n fprintf ( ' %2d %2d %6d %10.5g %10.5g\\n', ...\n d, k, n, sgappr, simappr );\n fprintf ( ' %10.5g %10.5g\\n', ...\n sgerror, simerror );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_hw/gqn_sparse_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7403728899159676}} {"text": "% Elmore delay sizing for a straight wire (GP)\n% Boyd, \"Problems in VLSI design\" (Lecture)\n% Written for CVX by Almir Mutapcic 02/08/06\n%\n% We consider the problem of finding optimal width profile\n% for a straight wire segmented into N parts. We want to\n% minimize the Elmore delay, subject to limits on wire width\n% and the total area. We use a pi-model for each wire segment.\n% Problem can be formulated as GP:\n%\n% minimize D\n% s.t. w_min <= w <= w_max\n% area <= Amax\n%\n% where variables are widths w (and arrival times T that are used\n% to formulate the overall delay D expression).\n%\n% Important: We label root node as 1, and all the other nodes as\n% node_label_in_the_paper + 1 (due to Matlab's convention).\n% Also label nodes with increasing numbers downstream.\n\n%********************************************************************\n% user supplied data (problem constants and tree topology)\n%********************************************************************\nN = 10+1; % number of segments (including the root node which is labeled as 1)\n\n% parent node array for the straight wire\n% specifies which node is a unique parent for node i (always have a tree)\nparent = [0:N-1];\n\n% problem constants\nRsource = 0.1;\nl = 1*ones(N-1,1);\nalpha = 1*ones(N-1,1);\nbeta = 1*ones(N-1,1);\ngamma = 1*ones(N-1,1);\n\n% load capacitance at each node\nCload = [0; ones(N-1,1)];\n\n% minimum and maximum width and area specification\nWmin = 1;\nWmax = 10;\nAmax = 50;\n\n%********************************************************************\n% derived data (computed from user's data)\n%********************************************************************\n% compute children cell array (evaluate who are children for each node)\nchildren = cell(N,1);\nleafs = [];\nfor node = [1:N]\n children{node} = find(parent == node);\n if isempty(children{node})\n leafs(end+1) = node; % leafs have no children\n end\nend\n\n%********************************************************************\n% optimization\n%********************************************************************\n\ndisp('Generating the tradeoff curve...')\nDarray = []; widths = [];\nfor Amax = [10.05 10.5 11 12:2:20 22.5 25:5:60]\n fprintf( 'Amax = %5.2f: ', Amax );\n cvx_begin gp quiet\n % optimization variables\n variable w(N-1) % wire width\n variable T(N) % arrival time (Elmore delay to node i)\n\n % objective is the critical Elmore delay\n minimize( max( T(leafs) ) )\n subject to\n\n % wire segment resistance is inversely proportional to widths\n R = alpha.*l./w;\n R = [Rsource; R];\n\n % wire segment capacitance is an affine function of widths\n C_bar = beta.*l.*w + gamma.*l;\n C_bar = [0; C_bar];\n\n % compute common capacitances for each node (C_tilde in GP tutorial)\n C_tilde = cvx( zeros(N,1) );\n for node = [1:N]\n C_tilde(node,1) = Cload(node);\n for k = parent(node)\n if k > 0; C_tilde(node,1) = C_tilde(node,1) + C_bar(k); end;\n end\n for k = children{node}\n C_tilde(node,1) = C_tilde(node,1) + C_bar(k);\n end\n end\n\n % now compute total downstream capacitances\n C_total = C_tilde;\n for node = N:-1:1\n for k = children{node}\n C_total(node,1) = C_total(node,1) + C_total(k,1);\n end\n end\n\n % generate Elmore delay constraints\n R(1)*C_total(1) <= T(1,1);\n for node = 2:N\n R(node)*C_total(node) + T(parent(node),1) <= T(node,1);\n end\n\n % collect all the constraints\n sum(w.*l) <= Amax;\n Wmin <= w <= Wmax;\n cvx_end\n % display and store computed values\n fprintf('delay = %3.2f\\n',cvx_optval);\n Darray = [Darray cvx_optval];\n widths = [widths w];\nend\n\n% indices of four taper designs on the tradeoff curve\nAmax = [10.05 10.5 11 12:2:20 22.5 25:5:60];\nA11ind = find(Amax == 11);\nA20ind = find(Amax == 20);\nA35ind = find(Amax == 35);\nA50ind = find(Amax == 50);\n\n% plot the tradeoff curve\nfigure, clf\nplot(Darray,Amax, ...\n Darray(A11ind),Amax(A11ind),'ro',...\n Darray(A20ind),Amax(A20ind),'ro',...\n Darray(A35ind),Amax(A35ind),'ro',...\n Darray(A50ind),Amax(A50ind),'ro');\nxlabel('Elmore delay D'); ylabel('Amax');\ndisp('Optimal tradeoff curve plotted.')\n\n% plot four taper designs\nfigure, clf\nw1 = widths(:,A50ind);\nw2 = widths(:,A35ind);\nw3 = widths(:,A20ind);\nw4 = widths(:,A11ind);\nplot_four_tapers(w1,w2,w3,w4);\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/circuit_design/elmore_straight_wire.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7403266584003815}} {"text": "function [lImFea] = extr_lIm_fea( lIm )\n\n[nrow, ncol] = size(lIm);\n\nlImFea = zeros([nrow, ncol, 4]);\n\n% first order gradient filters\nhf1 = [-1,0,1];\nvf1 = [-1,0,1]';\n \nlImFea(:, :, 1) = conv2(lIm, hf1, 'same');\nlImFea(:, :, 2) = conv2(lIm, vf1, 'same');\n\n% second order gradient filters\nhf2 = [1,0,-2,0,1];\nvf2 = [1,0,-2,0,1]';\n \nlImFea(:, :, 3) = conv2(lIm,hf2,'same');\nlImFea(:, :, 4) = conv2(lIm,vf2,'same');\n\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/SRAlgorithms/ScSR/extr_lIm_fea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.7956581024858785, "lm_q1q2_score": 0.7403266484744825}} {"text": "function Lms = gallager_ach(Ns, delta, epsil)\n% computes gallager's achievability bound for BSC \n%\n% We use it in the form \n%\n% P_e \\le M^s ( Sum_y [ Sum_x Q(x) W(y|x)^{1/1+s} ]^(1+s) )^n\n%\n% Note: we then conclude that from (M, P_e) code with AVG P_e \n% we can get (M/2, 2 P_e) code with MAXIMAL. Thus we must take P_e = epsil/2 and then \n% subtract 1 bit from gallager's result\n% \n\nLms = [];\n\nfor n = Ns;\n\n\tf = @(x) -( log2(epsil/2) ./ x + n - n .* (1+x) ./ x .* log2( delta.^(1./(1+x)) + (1-delta).^(1./(1+x))));\n\n\t[lambda f] = fminbnd(f, 0, 1);\n\n\t% Cut half of the codewords\n\n\tlogm = -f-1;\n\n\tdisp(sprintf('--- Gallager: n=%d, best_lambda = %g, log M >= %g', n, lambda, logm));\n\n\tif ( lambda <= 0 ) || (lambda >= 1)\n\t\tdisp(sprintf('------- WARNING: lambda on the boundary! params: n=%d, delta=%g, epsil=%g', n, delta, epsil));\n\tend\n\tLms = [Lms logm];\nend\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/bsc/gallager_ach.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7403095395618569}} {"text": "% GET ROTATION MATRIX FROM QUATERNION\nfunction [R] = R_q(q)\n% This function defines the equivalent rotation matrix from the\n% provided quaternion. (Associated block \"Quaternion to DCM\")\n% INPUT:\n% q - The quaternion rotation\n% OUTPUT:\n% R_AB - The rotation matrix through A to B\n% R_BA - The reverse rotation matrix from B to A\n\nassert(numel(q) == 4,'Input quaternion has wrong dimensions');\n\nR = zeros(3,3);\n% Normalise the quaternion\nq = unit(q); \n\n% SAME AS THE ROBOTICS TOOL BOX....\nR(1,1) = q(1)^2 + q(2)^2 - q(3)^2 - q(4)^2; \nR(1,2) = 2*(q(2)*q(3) - q(1)*q(4));\nR(1,3) = 2*(q(1)*q(3) + q(2)*q(4));\nR(2,1) = 2*(q(2)*q(3) + q(1)*q(4));\nR(2,2) = q(1)^2 - q(2)^2 + q(3)^2 - q(4)^2;\nR(2,3) = 2*(q(3)*q(4) - q(1)*q(2));\nR(3,1) = 2*(q(2)*q(4) - q(1)*q(3));\nR(3,2) = 2*(q(1)*q(2) + q(3)*q(4));\nR(3,3) = q(1)^2 - q(2)^2 - q(3)^2 + q(4)^2;\nend", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/environment/common/R_q.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221032, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7403095185242206}} {"text": "%\n% This code calculates the interevent distances and the correlation integral\n% of a subset selected with the sampling sphere. The code is called from circlefd.m.\n% Francesco Pacchiani 1/2000\n%\n% Calculation of the 3D distances between all possible pairs\n% (combination of n epicenters taken 2 at a time) of earthquakes of\n% the given dataset.\n%\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);\nk = 0;\n%E.Latitude= (max(Da(:,2))+min(Da(:,2)))/2;\n\n\nHo_Wb = waitbar(0,'Calculating the fractal dimension D');\nHf_Cfig = gcf;\nHf_child = get(groot,'children');\nset(Hf_child,'pointer','watch','papertype','A4');\n%\n%\n% Calculation of the interevent distances in 2D plus the depths differences.\n%\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\n lon2 = E((i+1):end, 1);\n lat2 = E((i+1):end, 2);\n\n pairdist(k+1:k + size(lon1, 1)) = distance(lat1,lon1,lat2,lon2);\n\n k = k + size(lon1,1);\n\n waitbar((0.75/(N-1))*i, Ho_Wb);\n\nend\n\nclear i j k;\n%\n%\n% Conversion of the interevent distances from degrees to kilometers and calculates\n% the interevent distances in three dimensions.\n%\n%\nif dtokm == 1\n pairdist = pairdist.*111;\nend\n%\n%\n% Calculation of the correlation integral using as input the\n% pair distances computed above.\n%\n%\n% Variables\n%\nd = 2;\t\t\t\t\t\t%d = the dimension of the embedding volume.\nrmax = max(pairdist);\nrmin = min(pairdist);\n\nif rmin == 0\n rmin = 0.01;\nend\n\nlrmin = log10(rmin);\nlrmax = log10(max(pairdist));\n\n%u = (log10(rmin):0.15:log10(rmax))';\n%\n% Defining the distance vector r in order that on the\n% log-log graph all the points plot at equal distances from one another.\n%\nr = (logspace(lrmin, lrmax, 50))';\n%r = zeros(size(u,1),1);\n%r = 10.^u;\n%\n%\ncorint = [];\t\t\t\t\t\t% corint= Vector of ?cumulative? correlation integral values for increasing interevent radius\ncorint = zeros(size(r,1),1);\nk = 1;\n\nfor i = 1:size(r,1)\n\n j = [];\n j = pairdist < r(i);\n corint (k,1) = (2/(N*(N-1)))*sum(j);\n k = k + 1;\n waitbar(0.75 + (0.25/size(r,1))*i,Ho_Wb);\n\nend\n\nclear i j k;\nclose(Ho_Wb);\nHf_child = get(groot,'children');\nset(Hf_child,'pointer','arrow');\n%\n%\ndofd = 'fd';\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/pdc2circle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7402091322313185}} {"text": "function [x, c, funVal, ValueL]=sgLogisticR(A, y, z, opts)\n%\n%%\n% Function sgLogisticR\n% Logistic Loss with the \n% sparse group Lasso Regularization\n%\n%% Problem\n%\n% min f(x,c) = - sum_i weight_i * log (p_i) \n% + z_1 \\|x\\|_1 + z_2 * sum_j w_j ||x_{G_j}||\n%\n% a_i denotes a training sample,\n% and a_i' corresponds to the i-th row of the data matrix A\n%\n% y_i (either 1 or -1) is the response\n% \n% p_i= 1/ (1+ exp(-y_i (x' * a_i + c) ) ) denotes the probability\n%\n% G_j's are nodes with tree structure\n%\n% For this special case, \n% we have L1 for each element\n% and the L2 for the non-overlapping group \n%\n% The tree overlapping group information is contained in\n% opts.ind, which is a 3 x nodes matrix, where nodes denotes the number of\n% nodes of the tree.\n% opts.ind(1,:) contains the starting index\n% opts.ind(2,:) contains the ending index\n% opts.ind(3,:) contains the corresponding weight (w_j)\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 - Regularization parameter (z >=0)\n% opts- Optional inputs (default value: opts=[])\n% !!We require that opts.ind is specified.!!\n%\n%% Output parameters:\n% x- The obtained weight of size n x 1\n% c- The obtained intercept (scalar)\n% funVal- Function value during iterations\n%\n%% Copyright (C) 2009-2010 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 February 19, 2010.\n%\n%% Related papers\n%\n% [1] Jun Liu and Jieping Ye, Moreau-Yosida Regularization for \n% Grouped Tree Structure Learning, NIPS 2010\n%\n%% Related functions:\n%\n% sll_opts\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 the function 'sll_opts'\n% 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 ind \nif (~isfield(opts,'ind'))\n error('\\n In sgLogisticR, the field .ind should be specified');\nelse\n ind=opts.ind;\n \n if (size(ind,1)~=3)\n error('\\n Check opts.ind');\n end\nend\n\n% The parameter 'weight' contains the weight for each training sample.\n% See the definition of the problem above.\n% The summation of the weights for all the samples equals to 1.\nif (isfield(opts,'sWeight'))\n sWeight=opts.sWeight;\n \n if ( length(sWeight)~=2 || sWeight(1) <=0 || sWeight(2) <= 0)\n error('\\n Check opts.sWeight, which contains two positive values');\n end\n \n % we process the weight, so that the summation of the weights for all\n % the samples is 1.\n \n p_flag=(y==1); % the indices of the postive samples\n m1=sum(p_flag) * sWeight(1); % the total weight for the positive samples\n m2=sum(~p_flag) * sWeight(2); % the total weight for the positive samples\n \n weight(p_flag,1)=sWeight(1)/(m1+m2);\n weight(~p_flag,1)=sWeight(2)/(m1+m2);\nelse\n weight=ones(m,1)/m; % if not specified, we apply equal weight\nend\n\n\n%% Starting point initialization\n\np_flag=(y==1); % the indices of the postive samples\nm1=sum(weight(p_flag)); % the total weight for the positive samples\nm2=1-m1; % the total weight for the positive samples\n\n% process the regularization parameter\nif (opts.rFlag==0)\n lambda=z;\nelse % 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 % we compute ATb for computing lambda_max, when the input z is a ratio\n \n b(p_flag,1)=m2; b(~p_flag,1)=-m1;\n b=b.*weight;\n \n % compute AT b\n if (opts.nFlag==0)\n ATb =A'*b;\n elseif (opts.nFlag==1)\n ATb= A'*b - sum(b) * mu'; ATb=ATb./nu;\n else\n invNu=b./nu; ATb=A'*invNu-sum(invNu)*mu';\n end\n \n % compute lambda1_max\n temp=abs(ATb);\n lambda1_max=max(temp);\n \n lambda1=lambda1*lambda1_max;\n \n % compute lambda2_max(lambda_1)\n temp=max(temp-lambda1,0);\n \n if ( min(ind(3,:))<=0 )\n error('\\n In this case, lambda2_max = inf!');\n end\n lambda2_max=computeLambda2Max(temp,n,ind,size(ind,2));\n \n lambda2=lambda2*lambda2_max; \nend\n\n% initialize a starting point\nif opts.init==2\n x=zeros(n,1); c=log(m1/m2);\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=zeros(n,1);\n end\n \n if isfield(opts,'c0')\n c=opts.c0;\n else\n c=log(m1/m2);\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\n%% The main program\n\nif (opts.mFlag==0 && opts.lFlag==0)\n \n bFlag=0; % this flag tests whether the gradient step only changes a little\n \n L=1/m; % the intial guess of the Lipschitz continuous gradient\n \n weighty=weight.*y;\n % the product between weight and y\n \n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,1);\n cp=c; ccp=0; \n \n %% The Armijo Goldstein line search schemes + accelearted gradient descent\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; sc=c + beta* ccp;\n \n % --------------------------- step 2 ---------------------------\n % line search for L and compute the new approximate solution x\n \n % compute As=A*s\n As=Ax + beta* (Ax-Axp);\n \n % aa= - diag(y) * (A * s + sc)\n aa=- y.*(As+ sc);\n \n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_s= weight' * ( log( exp(-bb) + exp(aa-bb) ) + bb );\n \n % compute prob=[p_1;p_2;...;p_m]\n prob=1./( 1+ exp(aa) );\n \n % b= - diag(y.* weight) * (1 - prob)\n b= -weighty.*(1-prob);\n \n gc=sum(b); % the gradient of c\n \n % compute g= AT b, the gradient of x\n if (opts.nFlag==0)\n g=A'*b;\n elseif (opts.nFlag==1)\n g=A'*b - sum(b) * mu'; g=g./nu;\n else\n invNu=b./nu; g=A'*invNu-sum(invNu)*mu';\n end\n \n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n cp=c; \n \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; c= sc- gc/L;\n \n % tree overlapping group Lasso projection\n ind_work(1:2,:)=[ [-1, -1]', ind(1:2,:) ];\n ind_work(3,:)=[ lambda1/L, ind(3,:) * (lambda2 / L) ];\n \n x=altra(v, n, ind_work, size(ind_work,2));\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 % aa= - diag(y) * (A * x + c)\n aa=- y.*(Ax+ c);\n \n % fun_x is the logistic loss at the new approximate solution\n bb=max(aa,0);\n fun_x= weight'* ( log( exp(-bb) + exp(aa-bb) ) + bb );\n \n r_sum= (v'*v + (c-sc)^2) / 2;\n l_sum=fun_x - fun_s - v'* g - (c-sc)* gc;\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 fun_x <= fun_s + v'* g + c * gc\n % + L/2 * (v'*v + (c-sc)^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=%e, r_sum=%e',L, r_sum);\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 ValueL(iterStep)=L;\n % store values for L\n \n xxp=x-xp; ccp=c-cp;\n funVal(iterStep)=fun_x;\n \n % compute the regularization part\n ind_work(1:2,:)=[ [-1, -1]', ind(1:2,:) ];\n ind_work(3,:)=[ lambda1, ind(3,:) * lambda2 ];\n tree_norm=treeNorm(x, n, ind_work, size(ind_work,2));\n \n % function value = loss + regularizatioin\n funVal(iterStep)=fun_x + tree_norm; \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\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_SLEP/SLEP/functions/sgLasso/sgLogisticR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7402091284029616}} {"text": "% Minimum-phase spectrum of a given spectrum using the complex cepstrum\n%\n% Description\n% Compute the minimum-phase spectrum of a given spectrum X by dropping the\n% negative quefrencies of X.\n%\n% Input\n% X : The spectrum to convert (full DFT length)\n%\n% Output\n% M : The corresponding minimum-phase spectrum\n% lM : The log minimum-phase spectrum\n%\n% References\n% [1] Alan V. Oppenheim and Ronald W. Schafer, \"Digital Signal Processing\",\n% Prentice-Hall, 2nd edition, 1978.\n% Note that this 2nd edition contains a chapter about complex cepstrum which\n% has been removed in the 3rd edition (and possibly came back in the 4th ed.)\n%\n% Copyright (c) 2011 University of Crete - Computer Science Department (UOC-CSD)\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 [M lM] = spec2minphasespec(X)\n\n X = X(:).';\n\n rcc = ifft(log(abs(X))); % Compute the real cepstrum\n\n if mod(length(X),2)==0\n % For even DFT length\n lM = fft([rcc(1),2*rcc(2:end/2),rcc(end/2+1)], length(X));% [1]\n else\n % For odd DFT length\n lM = fft([rcc(1),2*rcc(2:(end-1)/2+1)], length(X)); % [1]\n end\n\n M = exp(lM);\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/misc/spec2minphasespec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.8244619328462579, "lm_q1q2_score": 0.7401156024074642}} {"text": "function pers=ordinal_persistence(S)\n% ORDINAL_PERSISTENCE computes the persistence of an ordered multilayer partition\n%\n% Version: 2.2.0\n% Date: Thu 11 Jul 2019 12:25:42 CEST\n%\n% pers = ORDINAL_PERSISTENCE(S) with a single multilayer partition or a\n% cell of multilayer partitions S (with S{i} the ith multilayer partition\n% of cell S) computes the \"persistence\" of ordered multilayer partitions. The\n% output pers is a vector such that pers(i) is the persistence of multilayer\n% partition S{i} (stored as an N*T matrix where N is the number of nodes in\n% each layer and T is the number of layers). For a multilayer partition with\n% ordered layers, the value of persistence is the number of nodes that do\n% not change community assignments between consecutive layers (see Bazzi\n% et al. 2016 for more detail). Ordinal persistence varies between 0 and 1.\n% Ordinal persistence is related to the multilayer quality function\n% developed in Mucha et al. 2010 when one uses ordinal interlayer coupling.\n%\n% References:\n%\n% Mucha, Peter J., Thomas Richardson, Kevin Macon, Mason A. Porter, and\n% Jukka-Pekka Onnela. \"Community Structure in Time-Dependent,\n% Multiscale, and Multiplex Networks,\" Science 328, 876-878 (2010).\n%\n% Bazzi, Marya, Mason A. Porter, Stacy Williams, Mark McDonald, Daniel\n% J. Fenn, and Sam D. Howison. \"Community Detection in Temporal Multilayer\n% Networks, with an Application to Correlation Networks\", MMS: A SIAM\n% Interdisciplinary Journal 14, 1-41 (2016).\n\n\nif ~iscell(S)\n S={S};\nend\n\n[N,T]=size(S{1});\npers=zeros(length(S),1);\nfor i=1:length(S)\n pers(i)=sum(sum(S{i}(:,1:end-1)==S{i}(:,2:end)))/(N*(T-1));\nend\n\nend\n", "meta": {"author": "GenLouvain", "repo": "GenLouvain", "sha": "5688f219baa726988a2faa19cf00d63159fa4ff9", "save_path": "github-repos/MATLAB/GenLouvain-GenLouvain", "path": "github-repos/MATLAB/GenLouvain-GenLouvain/GenLouvain-5688f219baa726988a2faa19cf00d63159fa4ff9/HelperFunctions/ordinal_persistence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7401155927277842}} {"text": "%%***********************************************************\n%% lmiexamp2: generate SDP data for the following LMI problem\n%%\n%% max -Tr(P)\n%% s.t. A1*P + P*A1' + B*diag(d)*B' <= 0\n%% A2*P + P*A2' + B*diag(d)*B' <= 0\n%% -d <= 0 \n%% sum(d) = 1\n%%***********************************************************\n%% Here is an example on how to use this function to \n%% find an optimal P. \n%%\n%% A1 = [-1 0 0; 0 -2 0; 1 1 -1];\n%% A2 = A1 + 0.1*A1'; \n%% B = [1 2; 3 4; 5 6]; \n%%\n%% [blk,Avec,C,b] = lmiexamp2(A1,A2,B);\n%% [obj,X,y,Z] = sqlp(blk,Avec,C,b);\n%% n = size(A1,2); N = n*(n+1)/2; dlen = size(B,2); \n%% P = smat(blk(1,:),y(1:N)); \n%% d = y(N+[1:dlen]); \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,Avec,C,b] = lmiexamp2(A1,A2,B); \n\n%%\n n1 = size(A1,2); n2 = size(A2,2); \n if (n1 ~= n2); error('lmiexamp2: A1, A2 not compatible'); end; \n%% \n n = n1; \n I = speye(n); \n blk{1,1} = 's'; blk{1,2} = n;\n Avec{1,1} = lmifun(A1,I,B);\n C{1,1} = sparse(n,n); \n%%\n blk{2,1} = 's'; blk{2,2} = n;\n Avec{2,1} = lmifun(A2,I,B);\n C{2,1} = sparse(n,n); \n%%\n%% and constraints: -d <= 0\n%%\n N = n*(n+1)/2; dlen = size(B,2); \n blk{3,1} = 'l'; blk{3,2} = dlen;\n Avec{3,1} = [sparse(dlen,N) -speye(dlen,dlen)]; \n C{3,1} = zeros(dlen,1); \n%%\n%% add in the constraint: sum(d) = 1\n%%\n blk{4,1} = 'u'; blk{4,2} = 1;\n Avec{4,1} = sparse([zeros(1,N) ones(1,dlen)]); \n C{4,1} = 1; \n%%\n blktmp{1,1} = 's'; blktmp{1,2} = n; \n b = [-svec(blktmp,I); zeros(dlen,1)]; \n%%**********************************************************\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/lmiexamp2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443461, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7401155920865532}} {"text": "function lambdamax = tvdiplmax(y)\n% Calculate the value of lambda so that if lambda >= lambdamax, the TVD\n% functional solved by TVDIP is minimized by the trivial constant\n% solution x = mean(y). This can then be used to determine a useful range\n% of values of lambda, for example.\n%\n% Usage:\n% lambdamax = tvdiplmax(y)\n%\n% Input arguments:\n% - y Original signal to denoise, size N x 1.\n%\n% Output arguments:\n% - lambdamax Value of at which x = mean(y) is the output of the TVDIP\n% function.\n%\n% (c) Max Little, 2010. Based around code originally written by \n% S.J. Kim, K. Koh, S. Boyd and D. Gorinevsky. If you use this code for\n% your research, please cite:\n% M.A. Little, Nick S. Jones (2010)\n% \"Sparse Bayesian Step-Filtering for High-Throughput Analysis of Molecular\n% Machine Dynamics\", in 2010 IEEE International Conference on Acoustics,\n% Speech and Signal Processing, 2010, ICASSP 2010 Proceedings.\n%\n% This code is released under the terms of GNU General Public License as\n% published by the Free Software Foundation; version 2 or later.\n\nerror(nargchk(1,1,nargin));\ny = y(:);\nN = length(y);\nM = N - 1;\n\n% Construct sparse operator matrices\nI1 = speye(M,M);\nO1 = spalloc(M,1,M);\nD = [I1 O1]-[O1 I1];\n\nDDT = D*D';\nDy = D*y;\n\nlambdamax = max(abs(DDT\\Dy));\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/TVDIP/tvdiplmax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7401155917659376}} {"text": "function [ x, w ] = legendre_ek_compute ( n )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_EK_COMPUTE: Legendre quadrature rule by the Elhay-Kautsky method.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 April 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer N, the order.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n%\n\n%\n% Define the zero-th moment.\n%\n zemu = 2.0;\n%\n% Define the Jacobi matrix.\n%\n bj = zeros ( n, 1 );\n\n for i = 1 : n\n bj(i) = ( i * i ) / ( 4 * i * i - 1 );\n end\n bj(1:n) = sqrt ( bj(1:n) );\n\n x = zeros ( n, 1 );\n\n w = zeros ( n, 1 );\n w(1) = sqrt ( zemu );\n%\n% Diagonalize the Jacobi matrix.\n%\n [ x, w ] = imtqlx ( n, x, bj, w );\n\n w(1:n) = w(1:n).^2;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule/legendre_ek_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7401155769319224}} {"text": "function b = r8ge_ml ( n, a_lu, pivot, x, job )\n\n%*****************************************************************************80\n%\n%% R8GE_ML computes A * x or A' * x, using R8GE_FA factors.\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% It is assumed that R8GE_FA has overwritten the original matrix\n% information by LU factors. R8GE_ML is able to reconstruct the\n% original matrix from the LU factor data.\n%\n% R8GE_ML allows the user to check that the solution of a linear\n% system is correct, without having to save an unfactored copy\n% of the matrix.\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 R8GE_FA.\n%\n% Input, integer PIVOT(N), the pivot vector computed by R8GE_FA.\n%\n% Input, real X(N), the vector to be multiplied.\n%\n% Input, integer JOB, specifies the operation to be done:\n% JOB = 0, compute A * x.\n% JOB nonzero, compute A' * X.\n%\n% Output, real B(N), the result of the multiplication.\n%\n b(1:n) = x(1:n);\n\n if ( job == 0 )\n%\n% Y = U * X.\n%\n for j = 1 : n\n b(1:j-1) = b(1:j-1) + a_lu(1:j-1,j)' * b(j);\n b(j) = a_lu(j,j) * b(j);\n end\n%\n% B = PL * Y = PL * U * X = A * x.\n%\n for j = n-1 : -1 : 1\n\n b(j+1:n) = b(j+1:n) - a_lu(j+1:n,j)' * b(j);\n k = pivot(j);\n\n if ( k ~= j )\n t = b(k);\n b(k) = b(j);\n b(j) = t;\n end\n\n end\n\n else\n%\n% Y = (PL)' * X:\n%\n for j = 1 : n-1\n\n k = pivot(j);\n\n if ( k ~= j )\n t = b(k);\n b(k) = b(j);\n b(j) = t;\n end\n\n b(j) = b(j) - sum ( b(j+1:n) * a_lu(j+1:n,j) );\n\n end\n%\n% B = U' * Y = ( PL * U )' * X = A' * X.\n%\n for i = n : -1 : 1\n b(i+1:n) = b(i+1:n) + b(i) * a_lu(i,i+1:n);\n b(i) = b(i) * a_lu(i,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/linplus/r8ge_ml.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7400883054077447}} {"text": "function [z,e]=exactPairMult(xIn,yIn)\n%%EXACTPAIRMULT Calculate the product of the floating point double values\n% x and y such that the result z+e (if added with infinite\n% precision) is exactly the product x*y, where z is the\n% floating point product and e is the part of the result that\n% cannot be expressed exactly. This is implemented for x and\n% y being floating point doubles.\n%\n%INPUTS xIn, yIn Two real arrays of sizes that can be added.\n%\n%OUTPUTS: z The real product x.*y as limited by floating point precision.\n% e The real error such that if done with inifite precision\n% (z+e)==x*y. This does not necessarily hold when numbers become\n% denormalized.\n%\n%This function implements Dekker's algorithm, which is given as Mul12 in\n%[1]. Note that additional scaling is performed for the instance where\n%Dekker's algorithm might result in an overflow. That is when x or y is\n%above 2^(1023 (maximum exponent) -53 (mantissa length))=2^970.\n%\n%The output pair (z,e) can be considered to be a \"doublelength\" floating\n%point number, as defined in [1]. This means that\n%abs(e)<=abs(z+e)*2^(-t)/(1+2^(-t)) (considering exact arithmetic), where t\n%is the number of bits in the mantissa of the floating point number. Here,\n%that is 53.\n%\n%Note that this assumes that the processor rounding mode has been set to\n%round to \"nearest,\" which is the default in Matlab, but which can be\n%changed using the function setProcRoundingMode.\n%\n%EXAMPLE:\n%Consider the product\n% [z,e]=exactPairMult(1+2^50,1+2^(-15))\n%One will get z=1.125934266580993e+15 and e=3.051757812500000e-05.\n%The exact value of the product can be found to be\n%1125934266580993.000030517578125\n%If one adds z and e exactly, one gets precisely that result.\n%\n%REFERENCES:\n%[1] T. J. Dekker, \"A Floating Point Technique for Extending the Available\n% Precision,\" Numerische Mathematik, vol. 18, no. 3, Jun. 1971, pp.\n% 224-242.\n%\n%November 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(~isa(xIn,'double')||~isa(yIn,'double'))\n error('This function is only implemented for x and y being double floating point values.')\nend\n\nif(isempty(xIn)||isempty(yIn))\n %Returning empty matrices if one input is an empty matrix is consistent\n %with what Matlab does when trying to multiply an empty matrix with\n %something.\n z=[];\n e=[];\n return\nend\n\n%This is 2^(1023 (maximum exponent) -53)=2^970\nmaxUnscaled=9.9792015476735990582818635651842e291;\ntwo53=9007199254740992;%2^53;\ntwom53=1.1102230246251565404236316680908e-16;%2^(-53)\n\nisScalX=isscalar(xIn);\nisScalY=isscalar(yIn);\n\nif(xor(isScalX,isScalY))\n %If one is scalar and the other is not.\n if(isScalX)\n dims=size(yIn);\n xIn=repmat(xIn,dims);\n else\n dims=size(xIn);\n yIn=repmat(yIn,dims);\n end\nelse\n %If neither is scalar or both are scalar, assume that they are the same\n %size.\n dims=size(xIn);\nend\n\nz=zeros(dims);\ne=zeros(dims);\nnumEl=numel(z);\n\nfor curEl=1:numEl\n x=xIn(curEl);\n y=yIn(curEl);\n if(x>maxUnscaled)\n x=x*twom53;\n invScalFactX=two53;\n else\n invScalFactX=1;\n end\n\n if(y>maxUnscaled)\n y=y*twom53;\n invScalFactY=two53;\n else\n invScalFactY=1;\n end\n invScalFact=invScalFactX*invScalFactY;\n\n [zCur,eCur]=exactPairMultPrescaled(x,y);\n\n z(curEl)=zCur*invScalFact;\n e(curEl)=eCur*invScalFact;\nend\nend\n\nfunction [z,e]=exactPairMultPrescaled(x,y)\n %The double mantissa is 53 bits (including the implicit one).\n const=134217729;%This is 2^ceil(53/2)+1=2^27+1\n \n p=x*const;\n hx=(x-p)+p;\n tx=x-hx;\n p=y*const;\n hy=(y-p)+p;\n ty=y-hy;\n p=hx*hy;\n q=(hx*ty)+(tx*hy);\n z=p+q;\n e=p-z+q+tx*ty;\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/Accurate_Arithmetic/exactPairMult.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7399825780458392}} {"text": "function value = problem4 ( x, h, epsilon, o )\n\n%*****************************************************************************80\n%\n%% PROBLEM4 evaluates problem data for problem 4.\n%\n% Discussion:\n%\n% case # 4: u_anl = x-1/4.......................................x<0.5\n% x-1/2.......................................x>0.5 \n% \n% w_anl = 0...................................x<0.5-epsilon\n% -2/epsilon^2(-1/4(log(epsilon)-\n% log(1/2-v)))....................0.5-epsilon0.5+epsilon\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 February 2012\n%\n% Parameters:\n%\n% Input, real X(:), the evaluation points.\n%\n% Input, real H, the discretization parameter.\n%\n% Input, real EPSILON, the nonlocalization parameter.\n%\n% Input, string O, the option:\n% 'U', evaluate the exact solution.\n% 'D', evaluate the derivative of the exact solution.\n% 'F', evaluate the right hand side.\n% 'L', evaluate the lifting function.\n%\n if ( o == 'u' )\n value = (x-1/4).*(x<0.5) + (x-1/2).*(x>=0.5);\n elseif ( o == 'd' )\n value = zeros ( size ( x ) );\n elseif ( o == 'f' )\n epsilon2 = epsilon * epsilon;\n value = (x<0.5-epsilon).*0 + ...\n (x>=0.5-epsilon & x<0.5).*(-2)/epsilon2.*(-1/4* (log(epsilon)-log(1/2-x))) + ...\n (x>0.5 & x<0.5+epsilon).*2/epsilon2.*(1/4*(log(x-1/2)-log(epsilon))) + ...\n (x>=0.5+epsilon).*0;\n elseif ( o == 'l' )\n value = (x<=0).*(x-1/4) + ...\n (x>0 & x<=h).* (1/4).*(x./h-1)+ ...\n (x>h & x< 1-h).* 0 * epsilon + ...\n (x>=1-h & x<=1).* (1/2).*(1. + (x-1)./h) + ...\n (x>1).*(x-1/2);\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PROBLEM4 - Fatal error!\\n' );\n fprintf ( 1, ' Unrecognized option O = \"%s\"\\n', o );\n error ( 'PROBLEM4 - Fatal 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/peridynamics_1d_steady/problem4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7399618640371883}} {"text": "function spline_test17 ( )\n\n%*****************************************************************************80\n%\n%% TEST17 tests SPLINE_CUBIC_SET, SPLINE_CUBIC_VAL.\n%\n% Discussion:\n%\n% For boundary condition 0, the spline should come very close within\n% the interpolation interval.\n%\n% For conditions 1 and 2, the spline should be essentially exactly equal\n% to the data, inside and outside the interpolation interval.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 February 2009\n%\n% Author\n%\n% John Burkardt\n%\n n = 11;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST17\\n' );\n fprintf ( 1, ' SPLINE_CUBIC_SET sets up a cubic spline;\\n' );\n fprintf ( 1, ' SPLINE_CUBIC_VAL evaluates it.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Cubic data, unevenly spaced knots.\\n' );\n\n for i = 1 : n\n t(i) = ( ( i - 1 ) / ( n - 1 ) )^2;\n end\n\n for i = 1 : n\n y(i) = fcube ( t(i) );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The data to be interpolated:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of data values = %d\\n', n );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' T Y\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n fprintf ( 1, '%14f %14f\\n', t(i), y(i) );\n end\n%\n% Try boundary condition types 0, 1 and 2.\n%\n for k = 0 : 2\n\n if ( k == 0 )\n\n ibcbeg = 0;\n ybcbeg = 0.0E+00;\n\n ibcend = 0;\n ybcend = 0.0E+00;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Boundary condition 0 at both ends:\\n' );\n fprintf ( 1, ' Spline is quadratic in boundary intervals.\\n' );\n\n elseif ( k == 1 )\n\n ibcbeg = 1;\n ybcbeg = fpcube ( t(1) );\n\n ibcend = 1;\n ybcend = fpcube ( t(n) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Boundary condition 1 at both ends:\\n' );\n fprintf ( 1, ' Y''(left) = %f\\n', ybcbeg );\n fprintf ( 1, ' Y''(right) = %f\\n', ybcend );\n\n elseif ( k == 2 )\n\n ibcbeg = 2;\n ybcbeg = fppcube ( t(1) );\n\n ibcend = 2;\n ybcend = fppcube ( t(n) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Boundary condition 2 at both ends:\\n' );\n fprintf ( 1, ' YP\"(left) = %f\\n', ybcbeg );\n fprintf ( 1, ' YP\"(right) = %f\\n', ybcend );\n\n end\n\n ypp = spline_cubic_set ( n, t, y, ibcbeg, ybcbeg, ibcend, ybcend );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' SPLINE\"(T), F\"(T):\\n' );\n fprintf ( 1, '\\n' );\n for i = 1: n\n fprintf ( 1, '%14f %14f\\n', ypp(i), fppcube(t(i)) );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' T, SPLINE(T), F(T)\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : n\n\n if ( i == 0 )\n jhi = 1;\n elseif ( i < n )\n jhi = 2;\n else\n jhi = 2;\n end\n\n for j = 1 : jhi\n\n if ( i == 0 )\n tval = t(1) - 1.0E+00;\n elseif ( i < n )\n tval = ( ( jhi - j + 1 ) * t(i) ...\n + ( j - 1 ) * t(i+1) ) ...\n / ( jhi );\n else\n if ( j == 1 )\n tval = t(n);\n else\n tval = t(n) + 1.0E+00;\n end\n end\n\n [ yval, ypval, yppval ] = spline_cubic_val ( n, t, y, ypp, tval );\n\n fprintf ( 1, '%14f %14f %14f\\n', tval, yval, fcube ( tval ) );\n\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/spline/spline_test17.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7399618619857453}} {"text": "function [ num1, num2 ] = myconvert( str )\n% Function to convert the vector string to numbers\n% By Kyriakos Tsourapas\n% You may contact me through the Mathworks site\n% University of Essex 2002\n\n\n% CREATE THE NUMBERS FROM THE STRING\nsign1 = str(1);\nintpart1 = sprintf('%d%d', str(2:3));\ndecpart1 = sprintf('%d%d%d%d%d%d%d%d%d%d', str(4:13));\nsign2 = str(14);\nintpart2 = sprintf('%d%d', str(15:16));\ndecpart2 = sprintf('%d%d%d%d%d%d%d%d%d%d', str(17:26));\n\n% CONVERT THEM TO DECIMAL FROM BINARY\nnum1 = bin2dec(intpart1) + bin2dec(decpart1)/1000;\nnum2 = bin2dec(intpart2) + bin2dec(decpart2)/1000;\n\nif sign1 == 1\n num1 = - num1;\nend\n\nif sign2 == 1\n num2 = - num2;\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/1339-simple-hill-climbing/myconvert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7399618558427181}} {"text": "function fd1d_advection_diffusion_steady ( )\n\n%*****************************************************************************80\n%\n%% FD1D_ADVECTION_DIFFUSION_STEADY solves steady advection diffusion equation.\n%\n% Discussion:\n%\n% The steady advection diffusion equation has the form:\n%\n% v ux - k * uxx = 0\n%\n% where V (the advection velocity) and K (the diffusivity) are positive \n% constants, posed in the region\n%\n% a = 0 < x < 1 = b\n%\n% with boundary conditions\n%\n% u(0) = 0, u(1) = 1.\n%\n% The discrete solution is unreliable when dx > 2 * k / v / ( b - a ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Charles Hall, Thomas Porsching,\n% Numerical Analysis of Partial Differential Equations,\n% Prentice-Hall, 1990,\n% ISBN: 013626557X,\n% LC: QA374.H29.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD1D_ADVECTION_DIFFUSION_STEADY:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solve the 1D steady advection diffusion equation:\\n' );\n fprintf ( 1, ' v du/dx - k d2u/dx2 = 0\\n' );\n fprintf ( 1, ' with constant, positive velocity V and diffusivity K,\\n' );\n fprintf ( 1, ' over the interval:\\n' );\n fprintf ( 1, ' 0.0 <= x <= 1.0\\n' );\n fprintf ( 1, ' with boundary conditions:\\n' );\n fprintf ( 1, ' u(0) = 0, u(1) = 1.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Use finite differences:\\n' );\n fprintf ( 1, ' d u/dx = (u(x+dx)-u(x-dx))/2/dx\\n' );\n fprintf ( 1, ' d2u/dx2 = (u(x+dx)-2u(x)+u(x-dx))/dx^2\\n' );\n%\n% Physical constants.\n%\n v = 1.0;\n k = 0.05;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Diffusivity K = %g\\n', k );\n fprintf ( 1, ' Constant velocity V = %g\\n', v );\n%\n% Spatial discretization.\n%\n nx = 41;\n a = 0.0;\n b = 1.0;\n dx = ( b - a ) / ( nx - 1 );\n x = ( linspace ( a, b, nx ) )';\n\n fprintf ( 1, ' Number of nodes NX = %d\\n', nx );\n fprintf ( 1, ' DX = %g\\n', dx );\n fprintf ( 1, ' Maximum safe DX is %g\\n', 2 * k / v / ( b - a ) );\n%\n% Set up linear system corresponding to boundary conditions and\n% advection-diffusion equation.\n%\n A = sparse ( nx, nx );\n f = zeros ( nx, 1 );\n\n A(1,1) = 1.0;\n f(1) = 0.0;\n\n for i = 2 : nx - 1\n A(i,i-1) = - v / dx / 2.0 - k / dx / dx;\n A(i,i) = + 2.0 * k / dx / dx;\n A(i,i+1) = + v / dx / 2.0 - k / dx / dx;\n f(i) = 0.0;\n end\n\n A(nx,nx) = 1.0;\n f(nx) = 1.0;\n%\n% Solve linear system for U.\n%\n u = A \\ f;\n%\n% The exact solution to the differential equation is known.\n%\n r = v * ( b - a ) / k;\n w = ( 1.0 - exp ( r * x ) ) / ( 1.0 - exp ( r ) );\n%\n% Plot discrete solution U (dots) and exact solution W (line).\n%\n hold on\n plot ( x, w, 'b-', 'LineWidth', 2 );\n plot ( x, u, 'r.', 'LineWidth', 2, 'Markersize', 20 );\n\n grid on\n xlabel ( '<--X-->', 'Fontsize', 16 );\n ylabel ( '<--U(X)-->', 'Fontsize', 16 );\n title ( 'Solution of Steady Advection-Diffusion Equation', 'Fontsize', 24);\n hold off\n\n filename = 'fd1d_advection_diffusion_steady.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_DIFFUSION_STEADY\\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_diffusion_steady/fd1d_advection_diffusion_steady.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7399618541704293}} {"text": "function D=distMat(P1, P2)\n%\n% Euclidian distances between vectors\n% each vector is one row\n \nif nargin == 2\n P1 = double(P1);\n P2 = double(P2);\n \n X1=repmat(sum(P1.^2,2),[1 size(P2,1)]);\n X2=repmat(sum(P2.^2,2),[1 size(P1,1)]);\n R=P1*P2';\n D=real(sqrt(X1+X2'-2*R));\nelse\n P1 = double(P1);\n\n % each vector is one row\n X1=repmat(sum(P1.^2,2),[1 size(P1,1)]);\n R=P1*P1';\n D=X1+X1'-2*R;\n D = real(sqrt(D));\nend\n\n\n", "meta": {"author": "willard-yuan", "repo": "hashing-baseline-for-image-retrieval", "sha": "822837884bdb5d44e297015d05ad081cea695a56", "save_path": "github-repos/MATLAB/willard-yuan-hashing-baseline-for-image-retrieval", "path": "github-repos/MATLAB/willard-yuan-hashing-baseline-for-image-retrieval/hashing-baseline-for-image-retrieval-822837884bdb5d44e297015d05ad081cea695a56/utils/distMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7399529696026883}} {"text": "function [y,L] = mdwt(x,h,L);\n% [y,L] = mdwt(x,h,L);\n%\n% Function computes the discrete wavelet transform y for a 1D or 2D input\n% signal x using the scaling filter h.\n%\n% Input:\n%\tx : finite length 1D or 2D signal (implicitly periodized)\n% h : scaling filter\n% L : number of levels. In the case of a 1D signal, length(x) must be\n% divisible by 2^L; in the case of a 2D signal, the row and the\n% column dimension must be divisible by 2^L. If no argument is\n% specified, a full DWT is returned for maximal possible L.\n%\n% Output:\n% y : the wavelet transform of the signal \n% (see example to understand the coefficients)\n% L : number of decomposition levels\n%\n% 1D Example:\n% x = makesig('LinChirp',8);\n% h = daubcqf(4,'min');\n% L = 2;\n% [y,L] = mdwt(x,h,L)\n%\n% 1D Example's output and explanation:\n%\n% y = [1.1097 0.8767 0.8204 -0.5201 -0.0339 0.1001 0.2201 -0.1401]\n% L = 2\n%\n% The coefficients in output y are arranged as follows\n%\n% y(1) and y(2) : Scaling coefficients (lowest frequency)\n% y(3) and y(4) : Band pass wavelet coefficients\n% y(5) to y(8) : Finest scale wavelet coefficients (highest frequency)\n%\n% 2D Example:\n%\n% load test_image \n% h = daubcqf(4,'min');\n% L = 1;\n% [y,L] = mdwt(test_image,h,L);\n%\n% 2D Example's output and explanation:\n%\n% The coefficients in y are arranged as follows.\n%\n% .------------------.\n% | | |\n% | 4 | 2 |\n% | | |\n% | L,L | H,L |\n% | | |\n% --------------------\n% | | |\n% | 3 | 1 |\n% | | |\n% | L,H | H,H |\n% | | |\n% `------------------'\n% \n% where \n% 1 : High pass vertically and high pass horizontally\n% 2 : Low pass vertically and high pass horizontally\n% 3 : High pass vertically and low pass horizontally\n% 4 : Low pass vertically and Low pass horizontally \n% (scaling coefficients)\n%\n%\n%\n%\n% See also: midwt, mrdwt, mirdwt\n%\n\n%File Name: mdwt.m\n%Last Modification Date: 08/07/95\t15:13:25\n%Current Version: mdwt.m\t2.4\n%File Creation Date: Wed Oct 19 10:51:58 1994\n%Author: Markus Lang \n%\n%Copyright (c) 2000 RICE UNIVERSITY. All rights reserved.\n%Created by Markus Lang, Department of ECE, Rice University. \n%\n%This software is distributed and licensed to you on a non-exclusive \n%basis, free-of-charge. Redistribution and use in source and binary forms, \n%with or without modification, are permitted provided that the following \n%conditions are met:\n%\n%1. Redistribution of source code must retain the above copyright notice, \n% this list of conditions and the following disclaimer.\n%2. Redistribution in binary form must reproduce the above copyright notice, \n% this list of conditions and the following disclaimer in the \n% documentation and/or other materials provided with the distribution.\n%3. All advertising materials mentioning features or use of this software \n% must display the following acknowledgment: This product includes \n% software developed by Rice University, Houston, Texas and its contributors.\n%4. Neither the name of the University 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%\n%THIS SOFTWARE IS PROVIDED BY WILLIAM MARSH RICE UNIVERSITY, HOUSTON, TEXAS, \n%AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, \n%BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS \n%FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RICE UNIVERSITY \n%OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, \n%EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n%PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; \n%OR BUSINESS INTERRUPTIONS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \n%WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n%OTHERWISE), PRODUCT LIABILITY, OR OTHERWISE ARISING IN ANY WAY OUT OF THE \n%USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n%\n%For information on commercial licenses, contact Rice University's Office of \n%Technology Transfer at techtran@rice.edu or (713) 348-6173\n%\n%Change History:\n% \n%Modification #1\n%Mon Aug 7 11:42:11 CDT 1995\n%Rebecca Hindman \n%Added L to function line so that it can be displayed as an output\n%\n%Change History:\n% \n%Modification #1\n%Thu Mar 2 13:07:11 CDT 2000\n%Ramesh Neelamani\n%Revamped the help file\n%\n\n\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_WaveletRice/mdwt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895028, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7399529689793455}} {"text": "function h = histc2( A, edges, wtMask )\n% Multidimensional histogram count with weighted values.\n%\n% Creates a histogram h of the values in A [n x nd], with edges as\n% specified. If nd==1, that is when A is a vector, the resulting histogram\n% h is a vector of length nBins, where nBins=length(edges)-1. h(q) contains\n% the weighted count of values v in A such that edges(q) <= v < edges(q+1).\n% h(nBins) additionally contains the weighted count of values in A such\n% that v==edges(nBins+1) -- which is different then how histc treates the\n% boundary condition. Finally, h is normalized so that sum(h(:))==1.\n%\n% It usually makes sense to specify edges explicitly, especially if\n% different histograms are going to be compared. In general, edges must\n% have monotonically non-decreasing values. Also, if the exact bounds are\n% unknown then it is convenient to set the first element in edges to -inf\n% and the last to inf. If h = histc2( A, nBins, ...), edges are\n% automatically generated and have bins equally spaced between min(A) and\n% max(A). That is the edges vector is generated by:\n% edges = linspace( min(A)-eps, max(A)+eps, nBins+1 );\n%\n% If nd>1, that is when A is a 2d matrix instead of a vector, the created\n% histogram is multi-dimensional with dimensions nBins^nd, where each bin\n% h(q1,...,qnd) contains the the weighted count of vectors v in A such that\n% edges{k}(qk) <= v(k) < edges{k}(qk+1), for k=1,...,nd. Note that if nd>1\n% edges may be a cell vector where each element is a vector of edges or a\n% scalar nBins as before.\n%\n% Each value in A may optionally have an associated weight given by wtMask,\n% which should have the same number of elements as A. If not specified, the\n% default is wtMask=ones(n,1).\n%\n% USAGE\n% h = histc2( A, edges, [wtMask] )\n%\n% INPUTS\n% A - [n x nd] 2D numeric array\n% edges - quantization bounds, see above\n% wtMask - [] length [n] vector of weights\n%\n% OUTPUTS\n% h - nd histogram [nBins^nd]\n%\n% EXAMPLE - 1D histograms\n% A=filterGauss([1000 1000],[],[],0); A=A(:); n=length(A);\n% h1 = histc2( A, 25 ); figure(1); bar(h1);\n% h2 = histc2( A, 25, ones(n,1) ); figure(2); bar(h2);\n% h3 = histc2( A, 25, A ); figure(3); bar(h3);\n%\n% EXAMPLE - 2D histograms\n% A=filterGauss([1000 1000],[],[],0); A=A(:); n=length(A);\n% h=histc2( [A A], 25 ); figure(1); im(h); % decreasing along diag\n% h=histc2( [A A], 25, A ); figure(2); im(h); % constant along diag\n%\n% See also HISTC, ASSIGNTOBINS, BAR\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\nif( nargin<3 ); wtMask=[]; end;\nif( ~isa(A,'double') ); A=double(A); end;\nif( ~ismatrix(A) ); error('A must be a 2 dim array'); end;\n[n,nd] = size(A);\nif( ~isempty(wtMask) && n~=numel(wtMask) )\n error( 'wtMask must have n elements (A is nxnd)' ); end\n\nif( nd==1 )\n % if nBins given instead of edges calculate edges\n if(length(edges)==1)\n edges = linspace(min(A)-eps,max(A)+eps,edges+1);\n end\n\n % create 1d histogram\n if(isempty(wtMask))\n h = histc( A, edges );\n h(end-1) = h(end-1)+h(end);\n h = h(1:end-1); h = h / sum(h);\n else\n h = histc2c( A, wtMask, edges );\n h = h / sum(h);\n end\n\nelse\n % if nBins given instead of edges calculate edges per dimension\n if( ~iscell(edges ) )\n edges=repmat({edges},[1 nd]);\n elseif( length(edges)~=nd )\n error( 'Illegal dimensions for edges' );\n end\n for i=1:length( edges );\n if(length(edges{i})==1)\n edges{i}=linspace(min(A(:,i))-eps,max(A(:,i))+eps,edges{i}+1);\n end\n end\n\n % create multidimensional histogram\n if( isempty(wtMask) ); wtMask=ones(1,n); end;\n h = histc2c( A, wtMask, edges{:} );\n h = h / sum(h(:));\nend\n\n", "meta": {"author": "pdollar", "repo": "toolbox", "sha": "e87332637bbe8e8b92dd487c87567d9628404523", "save_path": "github-repos/MATLAB/pdollar-toolbox", "path": "github-repos/MATLAB/pdollar-toolbox/toolbox-e87332637bbe8e8b92dd487c87567d9628404523/images/histc2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7399305217575377}} {"text": "function [E,v] = km_kpca(X,m,ktype,kpar)\n% KM_KPCA performs kernel principal component analysis (KPCA) on a data set\n% X.\n% Input:\t- X: data matrix in column format (each data point is a row)\n%\t\t\t- m: the number of principal components to return. If m is \n%\t\t\tsmaller than 1, it is interpreted as the fraction of the signal\n%\t\t\tenergy that is to be contained within the returned principal\n%\t\t\tcomponents.\n%\t\t\t- ktype: string representing kernel type.\n%\t\t\t- kpar: vector containing the kernel parameters.\n% Output:\t- E: matrix containing the principal components.\n%\t\t\t- v: array containing the eigenvalues.\n%\t\t\t- Xep: projections of Xe on principal directions\n% USAGE: [E,v] = km_kpca(X,m,ktype,kpar)\n%\n% Author: Steven Van Vaerenbergh (steven *at* gtas.dicom.unican.es), 2010.\n%\n% This file is part of the Kernel Methods Toolbox for MATLAB.\n% https://github.com/steven2358/kmbox\n\nn = size(X,1);\n\nK = km_kernel(X,X,ktype,kpar);\n[E,V] = eig(K);\nv = diag(V);\t% eigenvalues\n[v,ind] = sort(v,'descend');\nv = v(1:m);\nE = E(:,ind(1:m));\t% principal components\nfor i=1:m\n\tE(:,i) = E(:,i)/sqrt(n*v(i));\t% normalization\nend\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/toolboxes/kmbox/lib/km_kpca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094437, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.7398869524537068}} {"text": "function dz = dynamics_3_link(~,z,P) \n%DZ = DYNAMICS_3_LINK(T,Z,P)\n% \n%FUNCTION: This function computes the dynamics of a 3\n% link pendulum, and is designed to be called from ode45.\n% The model allows for arbitrary mass and inertia for each\n% link, but no friction or actuation\n% \n%INPUTS: \n% t = time. Dummy input for ode45. Not used.\n% z = [6 X nTime] matrix of states\n% P = struct of parameters\n%OUTPUTS: \n% dz = [6 X nTime] matrix of state derivatives\n% \n%NOTES:\n% This file was automatically generated by writeDynamics.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\nl1 = P.l(1); % Link 1 length\nl2 = P.l(2); % Link 2 length\nl3 = P.l(3); % Link 3 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\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\n\nnTime = size(z,2);\ndz = zeros(size(z)); \nM = zeros(3,3,nTime);\nf = zeros(3,nTime);\n\nth1 = z(1,:); \nth2 = z(2,:); \nth3 = z(3,:); \n\ndth1 = z(4,:); \ndth2 = z(5,:); \ndth3 = z(6,:); \n\ndz(1,:) = dth1; \ndz(2,:) = dth2; \ndz(3,:) = dth3; \n\nM(1,1,:) = - I1 - d1.^2.*m1 - l1.^2.*m2 - l1.^2.*m3;\nM(1,2,:) = - d2.*l1.*m2.*cos(th1 - th2) - l1.*l2.*m3.*cos(th1 - th2);\nM(1,3,:) = -d3.*l1.*m3.*cos(th1 - th3);\nM(2,1,:) = - d2.*l1.*m2.*cos(th1 - th2) - l1.*l2.*m3.*cos(th1 - th2);\nM(2,2,:) = - I2 - d2.^2.*m2 - l2.^2.*m3;\nM(2,3,:) = -d3.*l2.*m3.*cos(th2 - th3);\nM(3,1,:) = -d3.*l1.*m3.*cos(th1 - th3);\nM(3,2,:) = -d3.*l2.*m3.*cos(th2 - th3);\nM(3,3,:) = - I3 - d3.^2.*m3;\n\nf(1,:) = - d1.*g.*m1.*cos(th1) - g.*l1.*m2.*cos(th1) - g.*l1.*m3.*cos(th1) - d2.*dth2.^2.*l1.*m2.*sin(th1 - th2) - d3.*dth3.^2.*l1.*m3.*sin(th1 - th3) - dth2.^2.*l1.*l2.*m3.*sin(th1 - th2);\nf(2,:) = d2.*dth1.^2.*l1.*m2.*sin(th1 - th2) - g.*l2.*m3.*cos(th2) - d2.*g.*m2.*cos(th2) - d3.*dth3.^2.*l2.*m3.*sin(th2 - th3) + dth1.^2.*l1.*l2.*m3.*sin(th1 - th2);\nf(3,:) = d3.*dth1.^2.*l1.*m3.*sin(th1 - th3) - d3.*g.*m3.*cos(th3) + d3.*dth2.^2.*l2.*m3.*sin(th2 - th3);\n\nfor i=1:nTime \n MM = M(:,:,i); ff = f(:,i); \n dz(4:6,i) = -MM \\ ff;\nend \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/dynamics_3_link.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158416, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7398869444458489}} {"text": "function beampattern(N,d,w,steer_angle)\n% beampattern(N,d,w,steer_angle)\n% where:\n% N = NO. OF ELEMENTS\n% d = INTER-ELEMENT SPACINGS B/W ELEMENTS\n% w = WEIGHTINGS\n% steer_angle = STEERING ANGLE FOR BEAM PATTERN\n% By: Muhammad Fahad\n% 2005-MS-E-EE-38\nif nargin < 4, steer_angle = 0; end % for no steering direction\nif nargin < 3, w = 1/N*ones(1,N); end % for uniform linear arrays\nif nargin < 2, d = 1/2; end % for standard linear array\n\nn = (-(N-1)/2:(N-1)/2).'; \ntheta = pi*(-1:0.001:1);\nu = cos(theta);\nvv = exp(j*2*pi*d*n*u);\ntheta_T = steer_angle/180*pi;\nut=cos(theta_T);\nW = w.*exp(j*n*pi*cos(theta_T))';\nB = W*vv;\nB = 10*log10(abs(B).^2);\nfigure\npolardb(theta,B,-40)\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/13864-digital-beamforming/m files/beampattern.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248225478306, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7398869418160865}} {"text": "% This function returns the oblique shock wave angle (beta) for a given\n% deflection angle (theta) in degrees and ratio of specific heats (gamma).\n% and Mach number M. Specify 0 for the weak oblique shock \n% or 1 for the strong shock.\n%\n% Syntax:\n% beta(M,theta,gamma,n) where n specifies weak or strong shock returned\n%\n% NOTE: Angles supplied and returned from this function are in DEGREES.\n%\n% Based on an analytical solution to the theta-beta-Mach relation given in\n% the following reference: Rudd, L., and Lewis, M. J., \"Comparison of\n% Shock Calculation Methods\", AIAA Journal of Aircraft, Vol. 35, No. 4,\n% July-August, 1998, pp. 647-649.\n%\n% By Chris Plumley, undergraduate, University of Maryland.\n\nfunction Beta=beta(M,theta,gamma,n)\n\ntheta=theta*pi/180; % convert to radians\nmu=asin(1/M); % Mach wave angle\nc=tan(mu)^2;\na=((gamma-1)/2+(gamma+1)*c/2)*tan(theta);\nb=((gamma+1)/2+(gamma+3)*c/2)*tan(theta);\nd=sqrt(4*(1-3*a*b)^3/((27*a^2*c+9*a*b-2)^2)-1);\nBeta=atan((b+9*a*c)/(2*(1-3*a*b))-(d*(27*a^2*c+9*a*b-2))/(6*a*(1-3*a*b))*tan(n*pi/3+1/3*atan(1/d)))*180/pi;\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/32777-theta-beta-mach-analytic-relation/beta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377272885903, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7398411072105237}} {"text": "function y = wshift(type,x,p)\n%WSHIFT Shift Vector or Matrix.\n% Y = WSHIFT(TYPE,X,P) with TYPE = {1,'1','1d' or '1D'}\n% performs a P-circular shift of vector X.\n% The shift P must be an integer, positive for right to left\n% shift and negative for left to right shift.\n%\n% Y = WSHIFT(TYPE,X,P) with TYPE = {2,'2','2d' or '2D'}\n% performs a P-circular shift of matrix X.\n% The shifts P must be integers. P(1) is the shift for rows\n% and P(2) is the shift for columns.\n%\n% WSHIFT('1D',X) is equivalent to WSHIFT('1D',X,1)\n% WSHIFT('2D',X) is equivalent to WSHIFT('2D',X,[1 1])\n%\n% Example 1D:\n% x = [1 2 3 4 5]\n% wshift('1D',x,1) = [2 3 4 5 1]\n% wshift('1D',x,-1) = [5 1 2 3 4]\n%\n% Example 2D:\n% x = [1 2 3;5 6 7]\n% wshift('2D',x,[1 1]) = [6 7 5;2 3 1]\n% wshift('2D',x,[-1,0]) = [5 6 7;1 2 3]\n\n% M. Misiti, Y. Misiti, G. Oppenheim, J.M. Poggi 01-Dec-97.\n% Last Revision: 01-May-1998.\n% Copyright (c) 1995-98 by The MathWorks, Inc.\n% $Revision: 1.2 $ $Date: 1998/07/16 14:33:59 $\n\nif isempty(x) | all(p==0) , y = x; return; end\nswitch type\n case {1,'1','1d','1D'}\n if nargin<3 , p = 1; end\n L = length(x);\n p = rem(p,L);\n if p<0 , p = L+p; end\n y = x([p+1:L,1:p]);\n\n case {2,'2','2d','2D'}\n if nargin<3 , p = [1 1]; end\n S = size(x);\n p = rem(p,S);\n k = (p<0);\n p(k) = S(k)+p(k);\n y = x([p(1)+1:S(1),1:p(1)],[p(2)+1:S(2),1:p(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/25514-tp-tool/tptool/array/wshift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.8723473630627234, "lm_q1q2_score": 0.739722451389579}} {"text": "function g = std(f, varargin)\n%STD Standard deviation of a CHEBFUN3 along one variable.\n% G = STD(F) returns the standard deviation of F in the x-variable \n% (default). If F is defined on the cuboid [a, b] x [c, d] x [e, g] then\n%\n% b \n% /\n% G.^2 = 1/(b-a) | (F(x,y,z) - mean(F, 1))^2 dx\n% /\n% a\n%\n% The output G is a CHEBFUN2 object over the rectangle [c, d] x [e, g]. \n%\n% G = STD(F, FLAG, DIM) takes the standard deviation along the x, y, or\n% z directions if DIM = 1, 2, or 3, respectively. FLAG is ignored and\n% kept in this function so the syntax agrees with the Matlab STD command.\n%\n% See also CHEBFUN/STD, CHEBFUN2/STD, CHEBFUN2/STD2, CHEBFUN3/STD2 and \n% CHEBFUN3/STD3.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Empty check: \nif ( isempty(f) )\n g = chebfun2();\n return\nend\n\ndom = f.domain; \nif ( nargin < 3 )\n dim = 1; % default to std over the x-variable.\nelseif ( nargin == 3 )\n dim = varargin{ 2 }; \nelse \n error( 'CHEBFUN:CHEBFUN3:std:nargin', 'Too many input arguments.' ); \nend\n\n% std(X) = sqrt( mean( (X - mean(X) )^2 ) ).\nif ( dim == 1 ) % x-variable.\n mx = chebfun3(@(x,y,z) feval(mean(f, 1), y, z), dom);\n g = sqrt(1/(diff(dom(1:2))) * sum((f - mx).^2, 1)) ;\n \nelseif ( dim == 2 ) % y-variable.\n my = chebfun3(@(x,y,z) feval(mean(f, 2), x, z), dom);\n g = sqrt(1/(diff(dom(3:4))) * sum((f - my).^2, 2));\n \nelseif ( dim == 3 ) % z-variable.\n mz = chebfun3(@(x,y,z) feval(mean(f, 3), x, y), dom);\n g = sqrt(1/(diff(dom(5:6))) * sum((f - mz).^2, 3));\n \nelse\n error('CHEBFUN:CHEBFUN3:std:dim', ...\n 'Third argument should have value 1, 2 or 3.');\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/@chebfun3/std.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122138417881, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7396704008192084}} {"text": "function M = multinomialdoublystochasticfactory(n)\n% Manifold of n-by-n doubly-stochastic matrices with positive entries.\n%\n% function M = multinomialdoublystochasticfactory(n)\n%\n% M is a Manopt manifold structure to optimize over the set of n-by-n\n% matrices with (strictly) positive entries and such that the entries of\n% each column and each row sum to one.\n%\n% Points on the manifold and tangent vectors are represented naturally as\n% matrices of size n. The Riemannian metric imposed on the manifold is the\n% Fisher metric, that is, if X is a point on the manifold and U, V are two\n% tangent vectors:\n%\n% M.inner(X, U, V) = _X = sum(sum(U.*V./X)).\n%\n% The retraction here provided is only first order. Consequently, the\n% slope test in the checkhessian tool is only valid at points X where the\n% gradient is zero. Furthermore, if some entries of X are very close to\n% zero, this may cause numerical difficulties that can also lead to a\n% failed slope test. More generally, it is important that the solution of\n% the optimization problem should have positive entries, sufficiently far\n% away from zero to avoid numerical issues.\n%\n% The file is based on developments in the research paper\n% A. Douik and B. Hassibi, \"Manifold Optimization Over the Set\n% of Doubly Stochastic Matrices: A Second-Order Geometry\"\n% ArXiv:1802.02628, 2018.\n%\n% Link to the paper: https://arxiv.org/abs/1802.02628.\n%\n% Please cite the Manopt paper as well as the research paper:\n% @Techreport{Douik2018Manifold,\n% Title = {Manifold Optimization Over the Set of Doubly Stochastic\n% Matrices: {A} Second-Order Geometry},\n% Author = {Douik, A. and Hassibi, B.},\n% Journal = {Arxiv preprint ArXiv:1802.02628},\n% Year = {2018}\n% }\n%\n% See also: multinomialsymmetricfactory multinomialfactory\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Ahmed Douik, March 6, 2018.\n% Contributors: Nicolas Boumal\n% Change log:\n%\n% Apr. 24, 2018 (AD):\n% Changed pinv() to a particular solution to the equation.\n%\n% July 24, 2018 (AD):\n% A bugfix related to the pinv() change, with effects in many places.\n%\n% Sep. 6, 2018 (NB):\n% Removed M.exp() as it was not implemented.\n%\n% Aug. 19, 2019 (AD, BM, NB):\n% Fixed typos in comments; replaced some linear solves with pcg\n% for efficiency when n is large. By default, pcg is used:\n% comments in the code indicate other possibilities and how they \n% differ. Added maxDSiters to doubly_stochastic argument.\n% The main change has been to factor out these linear solves.\n\n e = ones(n, 1);\n\n maxDSiters = 100 + 2*n;\n \n function [alpha, beta] = mylinearsolve(X, b)\n % zeta = sparse(A)\\b; % sparse might not be better perf.-wise.\n % where A = [eye(n) X ; X' eye(n)];\n %\n % For large n use the pcg solver instead of \\.\n % [zeta, ~, ~, iter] = pcg(sparse(A), b, 1e-6, 100);\n %\n % Even faster is to create a function handle\n % computing A*x (x is a given vector). \n % Make sure that A is not created, and X is only \n % passed with mylinearsolve and not A.\n [zeta, ~, ~, iter] = pcg(@mycompute, b, 1e-6, 100);\n \n function Ax = mycompute(x)\n xtop = x(1:n,1);\n xbottom = x(n+1:end,1);\n Axtop = xtop + X*xbottom;\n Axbottom = X'*xtop + xbottom;\n Ax = [Axtop; Axbottom];\n end\n \n alpha = zeta(1:n, 1);\n beta = zeta(n+1:end, 1);\n end\n\n M.name = @() sprintf('%dx%d doubly-stochastic matrices with positive entries', n, n);\n\n M.dim = @() (n-1)^2;\n\n % 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('multinomialdoublystochasticfactory.dist not implemented yet.');\n\n % The manifold is not compact as a result of the choice of the metric,\n % thus any choice here is arbitrary. This is notably used to pick\n % default values of initial and maximal trust-region radius in the\n % trustregions solver.\n M.typicaldist = @() n;\n\n % Pick a random point on the manifold\n M.rand = @random;\n function X = random()\n Z = abs(randn(n, n)); % Random point in the ambient space\n X = doubly_stochastic(Z, maxDSiters); % Projection on the Manifold\n end\n\n % Pick a random vector in the tangent space at X.\n M.randvec = @randomvec;\n function eta = randomvec(X) % A random vector in the tangent space\n % A random vector in the ambient space\n Z = randn(n, n);\n % Projection of the vector onto the tangent space\n b = [sum(Z, 2) ; sum(Z, 1)'];\n [alpha, beta] = mylinearsolve(X, b);\n eta = Z - (alpha*e' + e*beta').*X;\n % Normalizing the vector\n nrm = M.norm(X, eta);\n eta = eta / nrm;\n end\n\n % Projection of vector eta in the ambient space to the tangent space.\n M.proj = @projection; \n function etaproj = projection(X, eta) % Projection of the vector eta in the ambeint space onto the tangent space\n b = [sum(eta, 2) ; sum(eta, 1)'];\n [alpha, beta] = mylinearsolve(X, b);\n etaproj = eta - (alpha*e' + e*beta').*X;\n end\n\n M.tangent = M.proj;\n M.tangent2ambient = @(X, eta) eta;\n\n % Conversion of Euclidean to Riemannian gradient\n M.egrad2rgrad = @egrad2rgrad;\n function rgrad = egrad2rgrad(X, egrad) % projection of the euclidean gradient\n mu = (X.*egrad); \n b = [sum(mu, 2) ; sum(mu, 1)'];\n [alpha, beta] = mylinearsolve(X, b);\n rgrad = mu - (alpha*e' + e*beta').*X;\n end\n\n % First-order retraction\n M.retr = @retraction;\n function Y = retraction(X, eta, t)\n if nargin < 3\n t = 1.0;\n end\n Y = X.*exp(t*(eta./X));\n Y = doubly_stochastic(Y, maxDSiters);\n Y = max(Y, eps);\n end\n\n % Conversion of Euclidean to Riemannian Hessian\n M.ehess2rhess = @ehess2rhess;\n function rhess = ehess2rhess(X, egrad, ehess, eta)\n\n % computing the directional derivative of the Riemannian\n % gradient\n gamma = egrad.*X;\n gammadot = ehess.*X + egrad.*eta;\n \n b = [sum(gamma, 2) ; sum(gamma, 1)'];\n bdot = [sum(gammadot, 2) ; sum(gammadot, 1)'];\n [alpha, beta] = mylinearsolve(X, b);\n [alphadot, betadot] = mylinearsolve(X, bdot- [eta*beta; eta'*alpha]);\n \n S = (alpha*e' + e*beta');\n deltadot = gammadot - (alphadot*e' + e*betadot').*X- S.*eta;\n\n % projecting gamma\n delta = gamma - S.*X;\n\n % computing and projecting nabla\n nabla = deltadot - 0.5*(delta.*eta)./X;\n rhess = projection(X, nabla);\n end\n\n\n % Miscellaneous manifold functions\n M.hash = @(X) ['z' hashmd5(X(:))];\n M.lincomb = @matrixlincomb;\n M.zerovec = @(X) zeros(n, n);\n M.transp = @(X1, X2, d) projection(X2, d);\n M.vec = @(X, U) U(:);\n M.mat = @(X, u) reshape(u, n, n);\n M.vecmatareisometries = @() false;\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/multinomial/multinomialdoublystochasticfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7396703967596167}} {"text": "function [data clustPoints idx centers slopes lengths] = generateData( ...\n slope, ...\n slopeStd, ...\n numClusts, ...\n xClustAvgSep, ...\n yClustAvgSep, ...\n lengthAvg, ...\n lengthStd, ...\n lateralStd, ...\n totalPoints ...\n )\n% generateData Generates 2D data for clustering; data is created along \n% straight lines, which can be more or less parallel depending\n% on slopeStd argument.\n%\n% Inputs:\n% slope - Base direction of the lines on which clusters are based.\n% slopeStd - Standard deviation of the slope; used to obtain a random\n% slope variation from the normal distribution, which is\n% added to the base slope in order to obtain the final slope\n% of each cluster.\n% numClusts - Number of clusters (and therefore of lines) to generate.\n% xClustAvgSep - Average separation of line centers along the X axis.\n% yClustAvgSep - Average separation of line centers along the Y axis.\n% line centers along each dimension.\n% lengthAvg - The base length of lines on which clusters are based.\n% lengthStd - Standard deviation of line length; used to obtain a random\n% length variation from the normal distribution, which is\n% added to the base length in order to obtain the final\n% length of each line.\n% lateralStd - \"Cluster fatness\", i.e., the standard deviation of the \n% distance from each point to the respective line, in both x \n% and y directions; this distance is obtained from the \n% normal distribution.\n% totalPoints - Total points in generated data (will be \n% randomly divided among clusters).\n%\n% Output:\n% data - Matrix (totalPoints x 2) with the generated data\n% clustPoints - Vector (numClusts x 1) containing number of points in each \n% cluster\n% idx - Vector (totalPoints x 1) containing the cluster indices of \n% each point\n% centers - Matrix (numClusts x 2) containing centers from where\n% clusters were generated\n% slopes - Vector (numClusts x 1) containing the effective slopes \n% used to generate clusters\n% lengths - Vector (numClusts x 1) containing the effective lengths \n% used to generate clusters\n%\n% ----------------------------------------------------------\n% Usage example:\n%\n% [data cp idx] = generateData(1, 0.5, 5, 15, 15, 5, 1, 2, 200);\n%\n% This creates 5 clusters with a total of 200 points, with a base slope \n% of 1 (std=0.5), separated in average by 15 units in both x and y \n% directions, with average length of 5 units (std=1) and a \"fatness\" or\n% spread of 2 units.\n%\n% To take a quick look at the clusters just do:\n%\n% scatter(data(:,1), data(:,2), 8, idx);\n% ----------------------------------------------------------\n%\n% N. Fachada\n% Instituto Superior Técnico\n% Aug 10, 2010\n% Updated: Aug 2, 2012\n\n% Make sure totalPoints >= numClusts\nif totalPoints < numClusts\n error('Number of points must be equal or larger than the number of clusters.');\nend;\n\n% Determine number of points in each cluster\nclustPoints = abs(randn(numClusts, 1));\nclustPoints = clustPoints / sum(clustPoints);\nclustPoints = round(clustPoints * totalPoints);\n\n% Make sure totalPoints is respected\nwhile sum(clustPoints) < totalPoints\n % If one point is missing add it to the smaller cluster\n [C,I] = min(clustPoints);\n clustPoints(I(1)) = C + 1;\nend;\nwhile sum(clustPoints) > totalPoints\n % If there is one extra point, remove it from larger cluster\n [C,I] = max(clustPoints);\n clustPoints(I(1)) = C - 1;\nend;\n\n% Make sure there are no empty clusters\nemptyClusts = find(clustPoints == 0);\nif ~isempty(emptyClusts)\n % If there are empty clusters...\n numEmptyClusts = size(emptyClusts, 1);\n for i=1:numEmptyClusts\n % ...get a point from the largest cluster and assign it to the\n % empty cluster\n [C,I] = max(clustPoints);\n clustPoints(I(1)) = C - 1;\n clustPoints(emptyClusts(i)) = 1;\n end;\nend;\n\n% Initialize data matrix\ndata = zeros(sum(clustPoints), 2);\n\n% Initialize idx (vector containing the cluster indices of each point)\nidx = zeros(totalPoints, 1);\n\n% Initialize lengths vector\nlengths = zeros(numClusts, 1);\n\n% Determine cluster centers\nxCenters = xClustAvgSep * numClusts * (rand(numClusts, 1) - 0.5);\nyCenters = yClustAvgSep * numClusts * (rand(numClusts, 1) - 0.5);\ncenters = [xCenters yCenters];\n\n% Determine cluster slopes\nslopes = slope + slopeStd * randn(numClusts, 1);\n\n% Create clusters\nfor i=1:numClusts\n % Determine length of line where this cluster will be based\n lengths(i) = abs(lengthAvg + lengthStd*randn);\n % Determine how many points have been assigned to previous clusters\n sumClustPoints = 0;\n if i > 1\n sumClustPoints = sum(clustPoints(1:(i - 1)));\n end;\n % Create points for this cluster\n for j=1:clustPoints(i)\n % Determine where in the line the next point will be projected\n position = lengths(i) * rand - lengths(i) / 2;\n % Determine x coordinate of point projection\n delta_x = cos(atan(slopes(i))) * position;\n % Determine y coordinate of point projection\n delta_y = delta_x * slopes(i);\n % Get point distance from line in x coordinate\n delta_x = delta_x + lateralStd * randn;\n % Get point distance from line in y coordinate\n delta_y = delta_y + lateralStd * randn;\n % Determine the actual point\n data(sumClustPoints + j, :) = [(xCenters(i) + delta_x) (yCenters(i) + delta_y)];\n end;\n % Update idx\n idx(sumClustPoints + 1 : sumClustPoints + clustPoints(i)) = i;\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/37435-generate-data-for-clustering/generateData.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7396703947030129}} {"text": "function v = rowNorm(A)\n%ROWNORM norm of each row\n% V = ROWNORM(A) returns the Euclidean norm of each row of A. When A is \n% an M*N matrix, the output, V, will be a M*1 vector.\n%\n% Babak taati May 4, 2005\n% revised May 19, 2009\n\nif nargin ~= 1\n error('Requires one input arguments.')\nend\n\nv = sqrt(sum(A.*A, 2));\n", "meta": {"author": "covartech", "repo": "PRT", "sha": "4305e612af048e7dbf3d9392efc7436db125b1fc", "save_path": "github-repos/MATLAB/covartech-PRT", "path": "github-repos/MATLAB/covartech-PRT/PRT-4305e612af048e7dbf3d9392efc7436db125b1fc/+prtExternal/+clickA3DPoint/rowNorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7396352197493382}} {"text": "function bti_test02 ( )\n\n%*****************************************************************************80\n%\n%% BTI_TEST02 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_TEST02\\n' );\n fprintf ( 1, ' Test BURGERS_TIME_INVISCID\\n' );\n\n method = 2;\n nx = 81;\n nt = 200;\n t_max = 2.0;\n bc = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Method: 2, Upwind conservative.\\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 ( 2 )\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, upwind conservative' )\n\n filename = 'bti_test02.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_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.739635216128746}} {"text": "%% ODF Estimation from EBSD data\n%\n%%\n% In order to discuss ODF estimation from individual orientation data we\n% start by loading an EBSD data set\n\nmtexdata copper\n\nplot(ebsd,ebsd.orientations)\n\n%%\n% of copper. The orientation distribution function can now be computed by\n\nodf = calcDensity(ebsd('copper').orientations)\n\nplotSection(odf,'contourf')\nmtexColorMap LaboTeX\nmtexColorbar\n\n%%\n% The function implements the ODF\n% estimation from EBSD data in MTEX. The underlying statistical method is\n% called kernel density estimation, which can be seen as a generalized\n% histogram. To be more precise, let's $\\psi : SO(3) \\to R$ be a radially\n% symmetric, unimodal model ODF. Then the kernel density estimator for the\n% individual orientation data $o_1,o_2,\\ldots,o_M$ is defined as\n%\n% $$f(o) = \\frac{1}{M} \\sum_{i=1}^{M} \\psi(o o_i^{-1})$$\n%\n% The choice of the model ODF $\\psi$ and in particular its halfwidth has a\n% great impact in the resulting ODF. If no halfwidth is specified the\n% default halfwidth of 10 degrees is selected.\n%\n%% Automatic halfwidth selection\n%\n% MTEX includes an automatic halfwidth selection algorithm which is called\n% by the command . To work\n% properly, this algorithm needs spatially independent EBSD data as in the\n% case of this dataset of very rough EBSD measurements (only one\n% measurement per grain).\n\n% try to compute an optimal kernel\npsi = calcKernel(ebsd.orientations)\n\n%%\n% In the above example, the EBSD measurements are spatial dependent and the\n% resulting halfwidth is too small. To avoid this problem we have to perform\n% grain reconstruction first and then estimate the halfwidth from the\n% grains.\n\n% grains reconstruction\ngrains = calcGrains(ebsd);\n\n% correct for to small grains\ngrains = grains(grains.grainSize>5);\n\n% compute optimal halfwidth from the meanorientations of grains\npsi = calcKernel(grains('co').meanOrientation)\n\n% compute the ODF with the kernel psi\nodf = calcDensity(ebsd('co').orientations,'kernel',psi)\n\n\n%%\n% Once an ODF is estimated all the functionality MTEX offers for\n% and is available.\n\nh = [Miller(1,0,0,odf.CS),Miller(1,1,0,odf.CS),Miller(1,1,1,odf.CS)];\nplotPDF(odf,h,'antipodal','silent')\n\n\n%% Effect of halfwidth selection\n%\n% As mentioned above a proper halfwidth selection is crucial for ODF\n% estimation. The following simple numerical experiment illustrates the\n% dependency between the kernel halfwidth and the estimated error.\n%\n% Let's start with a model ODF and simulate some individual orientation data.\n\nmodelODF = fibreODF(Miller(1,1,1,crystalSymmetry('cubic')),xvector);\nori = discreteSample(modelODF,10000)\n\n%%\n% Next we define a list of kernel halfwidth ,\n\nhw = [1*degree, 2*degree, 4*degree, 8*degree, 16*degree, 32*degree];\n\n%%\n% estimate for each halfwidth an ODF and compare it to the original ODF.\n\ne = zeros(size(hw));\nfor i = 1:length(hw)\n \n odf = calcDensity(ori,'halfwidth',hw(i),'silent');\n e(i) = calcError(modelODF, odf);\n \nend\n\n%%\n% After visualizing the estimation error we observe that its value is large \n% either if we choose a very small or a very large halfwidth.\n% In this specific example, the optimal halfwidth seems to be about 4\n% degrees.\n\nclose all\nplot(hw/degree,e)\nxlabel('halfwidth in degree')\nylabel('esimation error')\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/EBSDAnalysis/EBSD2ODF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7396352127278344}} {"text": "% Figure 5.45 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n\n\nclf\nnumG=[1 0];\ndenG=[1 1 4];\nK1=0:.1:8; % K = 2 at breakin point\nK2=100;\nK=[K1 K2];\naxis('square')\nr=rlocus(numG,denG,K); % roots vs. K\nplot(r,'-'),nicegrid;\naxis([-6 2 -4 4])\nhold on\np=roots(denG); % find and plot OL poles\nz=roots(numG); % find and plot OL zeros\nplot(z(1),0,'o')\nplot(real(p(1)),imag(p(1)),'x',real(p(2)),imag(p(2)),'x')\ntitle('Fig. 5.45 Root Locus vs. K_T')\nxlabel('Re(s)')\nylabel('Im(s)')\nhold off\naxis('normal')\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/fig5_45.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8128673223709252, "lm_q1q2_score": 0.7396336676328894}} {"text": "function [s,lon,lat] = m_geodesic(lon1,lat1,lon2,lat2,Npoints,varargin)\n% M_GEODESIC - Compute points along geodesics of an ellipsoidal earth.\n%\n% [S,LON,LAT] = m_geodesic(lon1,lat1,lon2,lat2,Npoints,spheroid)\n%\n% lat1 = GEODETIC latitude of first point (degrees)\n% lon1 = longitude of first point (degrees)\n% lat2, lon2 = second point (degrees)\n% Npoints = number of points along geodesic\n% spheroid = (Optional) spheroid, defaults to 'wgs84'\n% S = distance in meters \n% LON,LAT = points on geodesics.\n%\n% Note that inputs can be the same size, or a mixture of scalars and matrices.\n% However, output curves will be on columns of a matrix (i.e. form of\n% inputs will not be preserved).\n%\n% See M_FDIST, M_IDIST, M_LLDIST\n\n% R. pawlowicz (rich@ocgy.ubc.ca) 10/Jan/2005\n%\n%\n% This software is provided \"as is\" without warranty of any kind. But\n% it's mine, so you can't sell it.\n\n\n\n% Do the equivalent of meshgrid-type calls to make all\n% matrix sizes match. To do this we can have no more than\n% two different numbers in any particular dimension, and one\n% of these has to be a '1'.\nallsize=[size(lon1);size(lat1);size(lon2);size(lat2)];\ni1=ones(1,size(allsize,2));\nfor k=1:size(allsize,2)\n rs=unique(allsize(:,k));\n if length(rs)==2 && rs(1)==1\n j1=i1;j1(k)=rs(2);\n if allsize(1,k)==1,lon1=repmat(lon1,j1); end\n if allsize(2,k)==1,lat1=repmat(lat1,j1); end\n if allsize(3,k)==1,lon2=repmat(lon2,j1); end\n if allsize(4,k)==1,lat2=repmat(lat2,j1); end\n elseif length(rs)>2\n error('incompatible array sizes!'); \n end\nend\n\n% Get the distances and bearings\n\n[S,A12,A21]=m_idist(lon1,lat1,lon2,lat2,varargin{:});\n\ns=[0:Npoints-1]'/(Npoints-1)*S(:)';\n\n[lon,lat]=m_fdist(lon1(:)',lat1(:)',A12(:)',s,varargin{:});\n\n\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/thirdParty/m_map/m_geodesic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7396336573205682}} {"text": "function geometry_test0415 ( )\n\n%*****************************************************************************80\n%\n%% TEST0415 tests LINES_IMP_INT_2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n dim_num = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST0415\\n' );\n fprintf ( 1, ' LINES_IMP_INT_2D finds the intersection of\\n' );\n fprintf ( 1, ' two lines written in implicit form.\\n' );\n fprintf ( 1, '\\n' );\n%\n% x + 2y - 4 = 0\n%\n a1 = 1.0;\n b1 = 2.0;\n c1 = -4.0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Line 1 coefficients: %8f %8f %8f\\n', a1, b1, c1 );\n%\n% x - y - 1 = 0\n%\n a2 = 1.0;\n b2 = -1.0;\n c2 = -1.0;\n fprintf ( 1, ' Line 2 coefficients: %8f %8f %8f\\n', a2, b2, c2 );\n\n [ ival, p ] = lines_imp_int_2d ( a1, b1, c1, a2, b2, c2 );\n\n if ( ival == 1 )\n fprintf ( 1, ' Intersection at %8f %8f\\n', p(1:dim_num) )\n elseif ( ival == 0 )\n fprintf ( 1, ' Lines are parallel, no intersection.\\n' );\n elseif ( ival == 2 )\n fprintf ( 1, ' Lines are coincident.\\n' );\n else\n fprintf ( 1, ' Unknown return value of ival = %d\\n', ival );\n end\n%\n% 2x + 4y - 1 = 0\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Line 1 coefficients: %8f %8f %8f\\n', a1, b1, c1 );\n\n a2 = 2.0;\n b2 = +4.0;\n c2 = -1.0;\n fprintf ( 1, ' Line 2 coefficients: %8f %8f %8f\\n', a2, b2, c2 );\n\n [ ival, p ] = lines_imp_int_2d (a1, b1, c1, a2, b2, c2 );\n\n if ( ival == 1 )\n fprintf ( 1, ' Intersection at %8f %8f\\n', p(1:dim_num) );\n elseif ( ival == 0 )\n fprintf ( 1, ' Lines are parallel, no intersection.\\n' );\n elseif ( ival == 2 )\n fprintf ( 1, ' Lines are coincident.\\n' );\n else\n fprintf ( 1, ' Unknown return value of ival = %d\\n', ival );\n end\n%\n% -3x - 6y +12 = 0\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Line 1 coefficients: %8f %8f %8f\\n', a1, b1, c1 );\n\n a2 = -3.0;\n b2 = -6.0;\n c2 = +12.0;\n fprintf ( 1, ' Line 2 coefficients: %8f %8f %8f\\n', a2, b2, c2 );\n \n [ ival, p ] = lines_imp_int_2d ( a1, b1, c1, a2, b2, c2 );\n\n if ( ival == 1 )\n fprintf ( 1, ' Intersection at %8f %8f\\n', p(1:dim_num) );\n elseif ( ival == 0 )\n fprintf ( 1, ' Lines are parallel, no intersection.\\n' );\n elseif ( ival == 2 )\n fprintf ( 1, ' Lines are coincident.\\n' );\n else\n fprintf ( 1, ' Unknown return value of ival = %d\\n', ival );\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_test0415.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7396191914856836}} {"text": "% Plot steady state objects\ngSS = reshape(ggSS,I,2);\ng_a = (lla(2) / (lla(1) + lla(2))) * gSS(:,1) ...\n + (lla(1) / (lla(1) + lla(2))) * gSS(:,2);\n\nfigure\nhold on\nf = bar(a / (wSS * (1 - ttau) * zAvg),g_a,'histc');\nsh=findall(gcf,'marker','*'); delete(sh);\nset(f,'FaceColor',[.03,.24,.8],'EdgeColor',[.8,.24,.03]);\nxlim([min(a / (wSS * (1 - ttau) * zAvg)) .8*max(a / (wSS * (1 - ttau) * zAvg))])\nxlabel('Net worth to average income','interpreter','latex')\nylabel('Mass of households','interpreter','latex')\ntitle('Steady State Distribution of Assets','interpreter','latex','fontsize',14)\ngrid on\nalpha(0.9)\nset(gcf,'color','w')\nhold off\n\n% Plot steady state MPCs\ntau_MPC = 1;\nJ = 2;\nN_MPC = 21;\ndt_MPC = tau_MPC / (N_MPC - 1);\n\nC_stacked = zeros(I*J,N_MPC );\nctilde = zeros(I*J,1);\nC_stacked(:,N_MPC) = 0;\n\nB = (1/dt_MPC) * speye(I*J) - A;\nc_stacked = reshape(cSS,I*J,1);\n\nfor n=N_MPC-1:-1:1\n vec = c_stacked + C_stacked(:,n+1)/dt_MPC;\n C_stacked(:,n) = B\\vec;\nend\n\nC = reshape(C_stacked(:,1),I,J);\nMPC = (C(2:I,:) - C(1:I-1,:)) ./ (aa(2:I,:) - aa(1:I-1,:));\n\nfigure\nhold on\nplot(a(2:I) / (wSS * (1 - ttau) * zAvg),MPC(:,1),'linewidth',1.5,'linestyle','-','color',[.03,.24,.8])\nplot(a(2:I) / (wSS * (1 - ttau) * zAvg),MPC(:,2),'linewidth',1.5,'linestyle','-','color',[.8,.24,.03])\nplot(a(2:I) / (wSS * (1 - ttau) * zAvg),ones(I-1,1)*MPC(.8*I-1,2),'linewidth',1.5,'linestyle','--','color','k')\nxlim([min(a(2:I) / (wSS * (1 - ttau) * zAvg)) .8*max(a / (wSS * (1 - ttau) * zAvg))])\nxlabel('Net worth to average income','interpreter','latex')\nylabel('MPC','interpreter','latex')\ntext(3,.05,'$\\leftarrow z=0 $','Fontsize',20,'interpreter','latex','Color',[.8,.24,.03]);\ntext(1,0.25,'$\\leftarrow z=1 $','Fontsize',20,'interpreter','latex','Color',[.03,.24,.8]);\nset(gcf,'color','w')\ntitle('MPCs in steady state','interpreter','latex','fontsize',14)\nalpha(0.7)\ngrid on\nhold off\ndrawnow", "meta": {"author": "gregkaplan", "repo": "phact", "sha": "4cd7ff0c013b082db9c2ca070225feaff1056123", "save_path": "github-repos/MATLAB/gregkaplan-phact", "path": "github-repos/MATLAB/gregkaplan-phact/phact-4cd7ff0c013b082db9c2ca070225feaff1056123/examples/KrusellSmith/plot_steady_state.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7396191855452299}} {"text": "function [res] = lmc(x)\n\n%LMC calculates the left medcouple, a robust measure of\n%left tail weight\n%\n% The left medcouple is described in:\n% Brys, G., Hubert, M. and Struyf, A. (2006),\n% \"Robust Measures of Tail Weight\",\n% Computational Statistics and Data Analysis,\n% 50 (No 3), 733-759. \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 (rows=observations, columns=variables)\n%\n% I/O:\n% result=lmc(x);\n% \n% Example:\n% result = lmc([chi2rnd(5,1000,1) trnd(3,1000,1)]);\n%\n% The output of LMC is a vector containing the left medcouple\n% for each column of the data matrix x\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 Guy Brys\n% Last Update: 17/03/2006\n\nif (nargin<1)\n error('No input arguments')\nend\nif (size(x,1)==1)\n x = x';\nend\nfor (i=1:size(x,2))\n res(i) = -mc(x(x(:,i)<=prctile(x(:,i),50),i));\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/lmc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.739554149207219}} {"text": "\n\nfunction call_price=european_call_div(S, K, r, sigma, time_to_maturity, dividend_times, dividend_amounts)\n\n\n%--------------------------------------------------------------------------\n%\n% DESCRIPTION:\n%\n% European option price with an underlying stock paying a discrete-time\n% dividend \n%\n%\n% Reference:\n%\n% John Hull, \"Options, Futures and other Derivative Securities\",\n% Prentice-Hall, second edition, 1993.\n% \n%--------------------------------------------------------------------------\n%\n% INPUTS:\n%\n% S: spot price\n% K: exercice price\n% r: interest rate\n% y: continous payout\n% sigma: volatility\n% time_to_maturity: time to maturity\n% dividend_times: periods of dividend payment\n% dividend_amounts: amounts of dividend payment \n%\n%--------------------------------------------------------------------------\n%\n% OUTPUT:\n%\n% call_price: price of a call option\n%\n%--------------------------------------------------------------------------\n%\n% Author: Paolo Z., February 2012\n%\n%--------------------------------------------------------------------------\n\n\n\nadjusted_S = S;\n\nfor ( i=1:max(size(dividend_times)) ) \n if (dividend_times(i)<=time_to_maturity)\n adjusted_S = adjusted_S-dividend_amounts(i)*exp(-r*dividend_times(i));\n end\nend\n\ncall_price = bs_european_call(adjusted_S,K,r,sigma,time_to_maturity);\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/35351-option-pricing-package/european_call_div.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8031738057795402, "lm_q1q2_score": 0.7395541448162047}} {"text": "function dcor = distcorr(x,y)\n\n% This function calculates the distance correlation between x and y.\n% Reference: http://en.wikipedia.org/wiki/Distance_correlation \n% Date: 18 Jan, 2013\n% Author: Shen Liu (shen.liu@hotmail.com.au)\n\n% Check if the sizes of the inputs match\nif size(x,1) ~= size(y,1);\n error('Inputs must have the same number of rows')\nend\n\n% Delete rows containing unobserved values\nN = any([isnan(x) isnan(y)],2);\nx(N,:) = [];\ny(N,:) = [];\n\n% Calculate doubly centered distance matrices for x and y\na = pdist2(x,x);\nmcol = mean(a);\nmrow = mean(a,2);\najbar = ones(size(mrow))*mcol;\nakbar = mrow*ones(size(mcol));\nabar = mean(mean(a))*ones(size(a));\nA = a - ajbar - akbar + abar;\n\nb = pdist2(y,y);\nmcol = mean(b);\nmrow = mean(b,2);\nbjbar = ones(size(mrow))*mcol;\nbkbar = mrow*ones(size(mcol));\nbbar = mean(mean(b))*ones(size(b));\nB = b - bjbar - bkbar + bbar;\n\n% Calculate squared sample distance covariance and variances\ndcov = sum(sum(A.*B))/(size(mrow,1)^2);\n\ndvarx = sum(sum(A.*A))/(size(mrow,1)^2);\ndvary = sum(sum(B.*B))/(size(mrow,1)^2);\n\n% Calculate the distance correlation\ndcor = sqrt(dcov/sqrt(dvarx*dvary));", "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/distcorr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7395541366160534}} {"text": "% This program illustrates various examples presented in\n% 'Advanced Mathematics and Mechanics Applications Using MATLAB'\n% 3rd Ed., CRC Press, 2003, by Howard Wilson, Louis Turcotte and\n% David Halpern. The program is executed by typing rundynam.\n% Then select the individually numbered examples. The separate\n% program modules are listed below.\n% \n% rundynam main program which calls the other modules\n% beamwave vibrating beam with initial deflection\n% beszeros zeros of integer order Bessel functions\n% circwave circular membrane with an oscillating force\n% elipmodes elliptic membrane modes by Moler's method\n% forcmove moving force on a semi-infinite string\n% rectwave rectangular membrane with an oscillating force \n% runchain falling elastic chain with one end fixed\n% runpenl pendulum with large amplitude oscillations\n% runtop spinning and nutating top motion \n% smdplot spring-mass-damper with harmonic applied force\n% stringmo vibrating string shaken at one end\n% strngwave vibrating string with initial deflection\n% trusvibs natural frequencies of a pin-connected truss", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6558-dynamics-of-some-classical-system-models/dynamics/contents.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760996, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7395167882330271}} {"text": "function r = revaltrig(zz, zj, fj, wj, form)\n%REVALTRIG Evaluate rational function in trigonometric barycentric form.\n% R = REVALTRIG(ZZ, ZJ, FJ, WJ, FORM) returns R (vector of floats), the\n% values of the trigonometric barycentric rational function of form FORM\n% with support points ZJ, function values FJ, and barycentric weights WJ\n% evaluated at the points ZZ.\n%\n% See also AAATRIG, PRZTRIG, REVAL.\n\n% Copyright 2018 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\nm = numel(zj);\nzv = zz(:); % vectorize zz if necessary\n\n% Define basis functions\nif strcmp(form,'even')\n cst = @(x) cot(x);\nelseif strcmp(form,'odd')\n cst = @(x) csc(x);\nend\n\nCC = cst(bsxfun(@minus, zv, zj.')/2); % Cauchy matrix\nr = (CC*(wj.*fj))./(CC*wj); % vector of values\n\nif strcmp(form,'odd') \nr(isinf(real(zv/1i)) & real(zv/1i)>0) = sum(wj.*fj.*exp(-1i*zj/2))./sum(wj.*exp(-1i*zj/2));\nr(isinf(real(zv/1i)) & real(zv/1i)<0) = sum(wj.*fj.*exp(+1i*zj/2))./sum(wj.*exp(+1i*zj/2));\nelseif strcmp(form,'even')\nr(isinf(real(zv/1i))) = sum(wj.*fj)./sum(wj);\nend\n\n% Deal with NaN:\nii = find(isnan(r));\nfor jj = 1:length(ii)\n if ( isnan(zv(ii(jj))) || ~any(zv(ii(jj)) == zj) )\n % r(NaN) = NaN is fine.\n % The second case may happen if r(zv(ii)) = 0/0 at some point.\n else\n % Clean up values NaN = inf/inf at support points.\n % Find the corresponding node and set entry to correct value:\n r(ii(jj)) = fj(zv(ii(jj)) == zj);\n end\nend\n\n% Reshape to input format:\nr = reshape(r, size(zz));\n\nend % End of REVALTRIG().\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/revaltrig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7395102735410598}} {"text": "function K = Abrarov2010CPC(x,y,tau,N)\n% This is an approximation of the Voigt function within the Humlicek\n% regions 3 and 4. The approximation is one given by S.M. Abrarov et. al.\n% \"High-accurace approximation of the complex probability function by\n% Fourier expansion of exponential multiplier\" (2010).\n% x = sqrt(ln(2))*(nu - nu0)/alphaD\n% y = sqrt(ln(2))*alphaL/alphaD\n% where 'ln' denotes the natural log, nu the wavenumber, nu0 the wavenumber\n% at center, alphaD and alphaL the Doppler and Lorentzian half-width at\n% half-maximum.\n% Suggested values for N & tau are 23 and 12 respectively.\n\nif nargin == 2\n tau = 12;\n N = 23;\nend\n\nK = zeros(size(x));\na = zeros(1,N);\nfor c = 1:length(x)\n summation = 0;\n for n = 0:N\n a(n+1) = 2*sqrt(pi)/tau*exp(-(n*pi/tau)^2);\n first = ((1i*n*pi*tau+tau^2*y)*(1-exp(-(1i*n*pi+tau*y))*cos(tau*x(c))) + exp(-(1i*n*pi+tau*y))*tau^2*x(c)*sin(tau*x(c)))/(tau^2*x(c)^2 - (n*pi - 1i*tau*y)^2);\n second = ((1i*n*pi*tau-tau^2*y)*(1-exp(1i*n*pi-tau*y)*cos(tau*x(c))) - exp(1i*n*pi-tau*y)*tau^2*x(c)*sin(tau*x(c)))/(tau^2*x(c)^2 - (n*pi + 1i*tau*y)^2);\n summation = summation + a(n+1)*(first - second);\n end\n third = (y-exp(-(tau*y))*(y*cos(tau*x(c))-x(c)*sin(tau*x(c))))/(2*sqrt(pi)*(x(c)^2+y^2));\n K(c) = summation/(2*sqrt(pi)) - a(1)*third;\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/29617-voigt-funtcion-approximation-humlicek-region-1/Abrarov2010CPC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338068793908, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7394966583246724}} {"text": "function [xk,niter,residuals,outputData,opts] =NESTA(A,At,b,muf,delta,opts)\n% [xk,niter,residuals,outputData] =NESTA(A,At,b,muf,delta,opts)\n%\n% Solves a L1 minimization problem under a quadratic constraint using the\n% Nesterov algorithm, with continuation:\n%\n% min_x || U x ||_1 s.t. ||y - Ax||_2 <= delta\n% \n% Continuation is performed by sequentially applying Nesterov's algorithm\n% with a decreasing sequence of values of mu0 >= mu >= muf\n%\n% The primal prox-function is also adapted by accounting for a first guess\n% xplug that also tends towards x_muf \n%\n% The observation matrix A is a projector\n%\n% Inputs: A and At - measurement matrix and adjoint (either a matrix, in which\n% case At is unused, or function handles). m x n dimensions.\n% b - Observed data, a m x 1 array\n% muf - The desired value of mu at the last continuation step.\n% A smaller mu leads to higher accuracy.\n% delta - l2 error bound. This enforces how close the variable\n% must fit the observations b, i.e. || y - Ax ||_2 <= delta\n% If delta = 0, enforces y = Ax\n% Common heuristic: delta = sqrt(m + 2*sqrt(2*m))*sigma;\n% where sigma=std(noise).\n% opts -\n% This is a structure that contains additional options,\n% some of which are optional.\n% The fieldnames are case insensitive. Below\n% are the possible fieldnames:\n% \n% opts.xplug - the first guess for the primal prox-function, and\n% also the initial point for xk. By default, xplug = At(b)\n% opts.U and opts.Ut - Analysis/Synthesis operators\n% (either matrices of function handles).\n% opts.normU - if opts.U is provided, this should be norm(U)\n% otherwise it will have to be calculated (potentially\n% expensive)\n% opts.MaxIntIter - number of continuation steps.\n% default is 5\n% opts.maxiter - max number of iterations in an inner loop.\n% default is 10,000\n% opts.TolVar - tolerance for the stopping criteria\n% opts.stopTest - which stopping criteria to apply\n% opts.stopTest == 1 : stop when the relative\n% change in the objective function is less than\n% TolVar\n% opts.stopTest == 2 : stop with the l_infinity norm\n% of difference in the xk variable is less\n% than TolVar\n% opts.TypeMin - if this is 'L1' (default), then\n% minimizes a smoothed version of the l_1 norm.\n% If this is 'tv', then minimizes a smoothed\n% version of the total-variation norm.\n% The string is case insensitive.\n% opts.Verbose - if this is 0 or false, then very\n% little output is displayed. If this is 1 or true,\n% then output every iteration is displayed.\n% If this is a number p greater than 1, then\n% output is displayed every pth iteration.\n% opts.fid - if this is 1 (default), the display is\n% the usual Matlab screen. If this is the file-id\n% of a file opened with fopen, then the display\n% will be redirected to this file.\n% opts.errFcn - if this is a function handle,\n% then the program will evaluate opts.errFcn(xk)\n% at every iteration and display the result.\n% ex. opts.errFcn = @(x) norm( x - x_true )\n% opts.outFcn - if this is a function handle, \n% then then program will evaluate opts.outFcn(xk)\n% at every iteration and save the results in outputData.\n% If the result is a vector (as opposed to a scalar),\n% it should be a row vector and not a column vector.\n% ex. opts.outFcn = @(x) [norm( x - xtrue, 'inf' ),...\n% norm( x - xtrue) / norm(xtrue)]\n% opts.AAtinv - this is an experimental new option. AAtinv\n% is the inverse of AA^*. This allows the use of a \n% matrix A which is not a projection, but only\n% for the noiseless (i.e. delta = 0) case.\n% opts.USV - another experimental option. This supercedes\n% the AAtinv option, so it is recommended that you\n% do not define AAtinv. This allows the use of a matrix\n% A which is not a projection, and works for the\n% noisy ( i.e. delta > 0 ) case.\n% opts.USV should contain three fields: \n% opts.USV.U is the U from [U,S,V] = svd(A)\n% likewise, opts.USV.S and opts.USV.V are S and V\n% from svd(A). S may be a matrix or a vector.\n%\n% Outputs:\n% xk - estimate of the solution x\n% niter - number of iterations\n% residuals - first column is the residual at every step,\n% second column is the value of f_mu at every step\n% outputData - a matrix, where each row r is the output\n% from opts.outFcn, if supplied.\n% opts - the structure containing the options that were used \n%\n% Written by: Jerome Bobin, Caltech\n% Email: bobin@acm.caltech.edu\n% Created: February 2009\n% Modified (version 1.0): May 2009, Jerome Bobin and Stephen Becker, Caltech\n% Modified (version 1.1): Nov 2009, Stephen Becker, Caltech\n%\n% NESTA Version 1.1\n% See also Core_Nesterov\n\n\nif nargin < 6, opts = []; end\nif isempty(opts) && isnumeric(opts), opts = struct; end\n\n%---- Set defaults\nfid = setOpts('fid',1);\nVerbose = setOpts('Verbose',true);\nfunction printf(varargin), fprintf(fid,varargin{:}); end\nMaxIntIter = setOpts('MaxIntIter',5,1);\nTypeMin = setOpts('TypeMin','L1');\nTolVar = setOpts('tolvar',1e-5);\n[U,U_userSet] = setOpts('U', @(x) x );\nif ~isa(U,'function_handle')\n Ut = setOpts('Ut',[]);\nelse\n Ut = setOpts('Ut', @(x) x );\nend\nxplug = setOpts('xplug',[]);\nnormU = setOpts('normU',[]); % so we can tell if it's been set\n\nresiduals = []; outputData = [];\nAAtinv = setOpts('AAtinv',[]);\nUSV = setOpts('USV',[]);\nif ~isempty(USV)\n if isstruct(USV)\n Q = USV.U; % we can't use \"U\" as the variable name\n % since \"U\" already refers to the analysis operator\n S = USV.S;\n if isvector(S), s = S; %S = diag(s);\n else s = diag(S); end\n %V = USV.V;\n else\n error('opts.USV must be a structure');\n end\nend\n\n% -- We can handle non-projections IF a (fast) routine for computing\n% the psuedo-inverse is available.\n% We can handle a nonzero delta, but we need the full SVD\nif isempty(AAtinv) && isempty(USV)\n % Check if A is a partial isometry, i.e. if AA' = I\n z = randn(size(b));\n if isa(A,'function_handle'), AAtz = A(At(z));\n else AAtz = A*(A'*z); end\n if norm( AAtz - z )/norm(z) > 1e-8\n error('Measurement matrix A must be a partial isometry: AA''=I');\n end\nend\n\n% -- Find a initial guess if not already provided.\n% Use least-squares solution: x_ref = A'*inv(A*A')*b\n% If A is a projection, the least squares solution is trivial\nif isempty(xplug) || norm(xplug) < 1e-12\n if ~isempty(USV) && isempty(AAtinv)\n AAtinv = Q*diag( s.^(-2) )*Q';\n end\n if ~isempty(AAtinv)\n if delta > 0 && isempty(USV)\n error('delta must be zero for non-projections');\n end\n if isa(AAtinv,'function_handle')\n x_ref = AAtinv(b);\n else\n x_ref = AAtinv * b;\n end\n else\n x_ref = b;\n end\n \n if isa(A,'function_handle')\n x_ref=At(x_ref);\n else\n x_ref = A'*x_ref;\n end\n\n if isempty(xplug)\n xplug = x_ref;\n end\n % x_ref itself is used to calculate mu_0\n % in the case that xplug has very small norm\nelse\n x_ref = xplug;\nend\n\n% use x_ref, not xplug, to find mu_0\nif isa(U,'function_handle')\n Ux_ref = U(x_ref);\nelse\n Ux_ref = U*x_ref;\nend\nswitch lower(TypeMin)\n case 'l1'\n mu0 = 0.9*max(abs(Ux_ref));\n case 'tv'\n mu0 = ValMUTv(Ux_ref);\nend\n\n% -- If U was set by the user and normU not supplied, then calcuate norm(U)\nif U_userSet && isempty(normU)\n % simple case: U*U' = I or U'*U = I, in which case norm(U) = 1\n z = randn(size(xplug));\n if isa(U,'function_handle'), UtUz = Ut(U(z)); else UtUz = U'*(U*z); end\n if norm( UtUz - z )/norm(z) < 1e-8\n normU = 1;\n else\n z = randn(size(Ux_ref));\n if isa(U,'function_handle')\n UUtz = U(Ut(z)); \n else\n UUtz = U*(U'*z);\n end\n if norm( UUtz - z )/norm(z) < 1e-8\n normU = 1;\n end\n end\n \n if isempty(normU)\n % have to actually calculate the norm\n if isa(U,'function_handle')\n [normU,cnt] = my_normest(U,Ut,length(xplug),1e-3,30);\n if cnt == 30, printf('Warning: norm(U) may be inaccurate\\n'); end\n else\n [mU,nU] = size(U);\n if mU < nU, UU = U*U'; else UU = U'*U; end \n % last resort is to call MATLAB's \"norm\", which is slow\n if norm( UU - diag(diag(UU)),'fro') < 100*eps\n % this means the matrix is diagonal, so norm is easy:\n normU = sqrt( max(abs(diag(UU))) );\n elseif issparse(UU)\n normU = sqrt( normest(UU) );\n else\n if min(size(U)) > 2000\n % norm(randn(2000)) takes about 5 seconds on my PC\n printf('Warning: calculation of norm(U) may be slow\\n');\n end\n normU = sqrt( norm(UU) );\n end\n end\n end\n opts.normU = normU;\nend\n \n\nniter = 0;\nGamma = (muf/mu0)^(1/MaxIntIter);\nmu = mu0;\nGammat= (TolVar/0.1)^(1/MaxIntIter);\nTolVar = 0.1;\n \nfor nl=1:MaxIntIter\n \n mu = mu*Gamma;\n TolVar=TolVar*Gammat; opts.TolVar = TolVar;\n opts.xplug = xplug;\n if Verbose, printf('\\tBeginning %s Minimization; mu = %g\\n',opts.TypeMin,mu); end\n [xk,niter_int,res,out,optsOut] = Core_Nesterov(...\n A,At,b,mu,delta,opts);\n \n xplug = xk;\n niter = niter_int + niter;\n \n residuals = [residuals; res];\n outputData = [outputData; out];\n\nend\nopts = optsOut;\n\n\n%---- internal routine for setting defaults\nfunction [var,userSet] = setOpts(field,default,mn,mx)\n var = default;\n % has the option already been set?\n if ~isfield(opts,field) \n % see if there is a capitalization problem:\n names = fieldnames(opts);\n for i = 1:length(names)\n if strcmpi(names{i},field)\n opts.(field) = opts.(names{i});\n opts = rmfield(opts,names{i});\n break;\n end\n end\n end\n if isfield(opts,field) && ~isempty(opts.(field))\n var = opts.(field); % override the default\n userSet = true;\n else\n userSet = false;\n end\n % perform error checking, if desired\n if nargin >= 3 && ~isempty(mn)\n if var < mn\n printf('Variable %s is %f, should be at least %f\\n',...\n field,var,mn); error('variable out-of-bounds');\n end\n end\n if nargin >= 4 && ~isempty(mx)\n if var > mx\n printf('Variable %s is %f, should be at least %f\\n',...\n field,var,mn); error('variable out-of-bounds');\n end\n end\n opts.(field) = var;\nend\n\n\n\n\n%---- internal routine for setting mu0 in the tv minimization case\nfunction th=ValMUTv(x)\n\n N = length(x);n = floor(sqrt(N));\n Dv = spdiags([reshape([-ones(n-1,n); zeros(1,n)],N,1) ...\n reshape([zeros(1,n); ones(n-1,n)],N,1)], [0 1], N, N);\n Dh = spdiags([reshape([-ones(n,n-1) zeros(n,1)],N,1) ...\n reshape([zeros(n,1) ones(n,n-1)],N,1)], [0 n], N, N);\n D = sparse([Dh;Dv]);\n\n\n Dhx = Dh*x;\n Dvx = Dv*x;\n \n sk = sqrt(abs(Dhx).^2 + abs(Dvx).^2);\n th = max(sk);\n\nend\n\nend %-- end of NESTA function\n\n%%%%%%%%%%%% POWER METHOD TO ESTIMATE NORM %%%%%%%%%%%%%%%\n% Copied from MATLAB's \"normest\" function, but allows function handles, not just sparse matrices\nfunction [e,cnt] = my_normest(S,St,n,tol, maxiter)\n%MY_NORMEST Estimate the matrix 2-norm via power method.\n if nargin < 4, tol = 1.e-6; end\n if nargin < 5, maxiter = 20; end\n if isempty(St)\n St = S; % we assume the matrix is symmetric;\n end\n x = ones(n,1);\n cnt = 0;\n e = norm(x);\n if e == 0, return, end\n x = x/e;\n e0 = 0;\n while abs(e-e0) > tol*e && cnt < maxiter\n e0 = e;\n Sx = S(x);\n if nnz(Sx) == 0\n Sx = rand(size(Sx));\n end\n e = norm(Sx);\n x = St(Sx);\n x = x/norm(x);\n cnt = cnt+1;\n end\nend\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/NESTA-1.1/NESTA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7394787583399118}} {"text": "function normals = faceNormal(nodes, faces)\n%FACENORMAL Compute normal vector of faces in a 3D mesh.\n%\n% NORMALS = faceNormal(VERTICES, FACES)\n% VERTICES is a set of 3D points (as a N-by-3 array), and FACES is either\n% a N-by-3 index array or a cell array of indices. The function computes\n% the normal vector of each face.\n% The orientation of the normal is defined by the sign of cross product\n% between vectors joining vertices 1 to 2 and 1 to 3.\n%\n%\n% Example\n% [v e f] = createIcosahedron;\n% normals1 = faceNormal(v, f);\n% centros1 = faceCentroids(v, f);\n% figure; drawMesh(v, f); \n% hold on; axis equal; view(3);\n% drawVector3d(centros1, normals1);\n%\n% pts = rand(50, 3);\n% hull = minConvexHull(pts);\n% normals2 = faceNormal(pts, hull);\n%\n% See also\n% meshes3d, drawMesh, convhull, convhulln, drawVector3d\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2006-07-05\n% Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas)\n\n% deprecation warning\nwarning('geom3d:deprecated', ...\n [mfilename ' is deprecated, use ''meshFaceNormals'' instead']);\n\nif isnumeric(faces)\n % compute vector of first edges\n\tv1 = nodes(faces(:,2),1:3) - nodes(faces(:,1),1:3);\n v2 = nodes(faces(:,3),1:3) - nodes(faces(:,1),1:3);\n \n% % normalize vectors\n% v1 = normalizeVector3d(v1);\n% v2 = normalizeVector3d(v2);\n \n % compute normals using cross product (nodes have same size)\n\tnormals = normalizeVector3d(cross(v1, v2, 2));\n\nelse\n % initialize empty array\n normals = zeros(length(faces), 3);\n \n for i = 1:length(faces)\n face = faces{i};\n % compute vector of first edges\n v1 = nodes(face(2),1:3) - nodes(face(1),1:3);\n v2 = nodes(face(3),1:3) - nodes(face(1),1:3);\n \n% % normalize vectors\n% v1 = normalizeVector3d(v1);\n% v2 = normalizeVector3d(v2);\n \n % compute normals using cross product\n normals(i, :) = normalizeVector3d(cross(v1, v2, 2));\n end\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/deprecated/meshes3d/faceNormal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8198933381139646, "lm_q1q2_score": 0.7394787498708293}} {"text": "function pce_burgers ( )\n\n%*****************************************************************************80\n%\n%% PCE_BURGERS applies the polynomial chaos expansion to the Burgers equation.\n%\n% Discussion:\n%\n% The time-dependent viscous Burgers equation to be solved is:\n%\n% du/dt = - d ( u*(1/2-u)) /dx + nu d2u/dx2\n%\n% with boundary conditions\n%\n% u(-3.0) = 0.0, u(+3.0) = 1.0.\n%\n% The viscosity nu is assumed to be an uncertain quantity with\n% normal distribution of known mean and variance.\n%\n% A polynomial chaos expansion is to be used, with Hermite polynomial\n% basis functions h(i,x), 0 <= i <= n.\n%\n% Because the first two Hermite polynomials are simply 1 and x, \n% we have that \n%\n% nu = nu_mean * h(0,x) + nu_variance * h(1,x).\n%\n% We replace the time derivative by an explicit Euler approximation,\n% so that the equation now describes the value of U(x,t+dt) in terms\n% of known data at time t.\n%\n% Now assume that the solution U(x,t) can be approximated\n% by the truncated expansion:\n%\n% U(x,t) = sum ( 0 <= i <= n ) c(i,t) * h(i,x)\n%\n% In the equation, we replace U by its expansion, and then multiply\n% successively by each of the basis functions h(*,x) to get a set of\n% n+1 equations that can be used to determine the values of c(i,t+dt).\n%\n% This process is repeated until the desired final time is reached.\n%\n% At any time, the coefficients c(0,t) contain information definining\n% the expected value of u(x,t) at that time, while the higher order coefficients\n% can be used to deterimine higher moments.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 March 2012\n%\n% Author:\n%\n% Original FORTRAN90 version by Gianluca Iaccarino.\n% This MATLAB version is by John Burkardt.\n%\n% Local parameters:\n%\n% Local, real DT, the timestep.\n%\n% Local, real DX, the spacing between grid points.\n%\n% Local, integer N, the number of intervals in the spatial domain.\n%\n% Local, real NUMEAN, the mean of viscosity.\n%\n% Local, real NUVARIANCE, the variance of viscosity.\n%\n% Local, integer P, the order of the PC expansion.\n%\n% Local, real T, the current time.\n%\n% Local, real TF, the final integration time.\n%\n% Local, real U1(N+1,P+1), the PCE representation at the current time.\n%\n% Local, real U2(N+1,P+1), the PCE representation for the next time.\n%\n% Local, real X(N+1,1), the grid points.\n%\n p = 5;\n n = 32;\n nt = 2000;\n ti = 0.0;\n tf = 2.0;\n dt = ( tf - ti ) / nt;\n numean = 0.25;\n nuvariance = 0.08;\n\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PCE_BURGERS\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Polynomial Chaos Expansion\\n' );\n fprintf ( 1, ' 1D Burgers equation\\n' );\n fprintf ( 1, ' Original version by Gianluca Iaccarino\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PCE order = %d\\n', p );\n fprintf ( 1, ' Number of cells = %d\\n', n );\n fprintf ( 1, ' Time step = %g\\n', dt );\n fprintf ( 1, ' Initial time = %g\\n', ti );\n fprintf ( 1, ' Final time = %g\\n', tf );\n fprintf ( 1, ' Viscosity Mean = %g\\n', numean );\n fprintf ( 1, ' Viscosity Var = %g\\n', nuvariance );\n fprintf ( 1, '\\n' );\n%\n% Define some numerical parameters.\n%\n dx = 6.0 / n;\n conv = dt / ( 2.0 * dx );\n\n visc = zeros ( p + 1, 1 );\n visc(1) = numean * dt / ( dx * dx );\n visc(2) = nuvariance * dt / ( dx * dx );\n%\n% Define a uniform grid.\n%\n x = ( linspace ( - 3.0, + 3.0, n + 1 ) )';\n%\n% Set the initial conditions.\n%\n u1 = zeros ( n + 1, p + 1 );\n u1(1:n+1,1) = 0.5 + x(1:n+1,1) / 6.0;\n\n u2 = zeros ( n + 1, p + 1 );\n%\n% Time integration.\n%\n t1 = ti;\n%\n% Write the current solution.\n%\n output_filename = 'burgers.history.txt';\n output_unit = fopen ( output_filename, 'wt' );\n fprintf ( output_unit, '----------\\n' );\n fprintf ( output_unit, 'T = %g\\n', t1 );\n for i = 1 : n + 1\n fprintf ( output_unit, ' %10g', x(i) );\n for k = 1 : p + 1\n fprintf ( output_unit, ' %10g', u1(i,k) );\n end\n fprintf ( output_unit, '\\n' );\n end\n%\n% Time integration.\n%\n for it = 1 : nt\n\n t2 = ( ( nt - it ) * ti ...\n + ( it ) * tf ) ...\n / ( nt );\n%\n% Boundary conditions.\n%\n u2(1,1:p+1) = 0.0;\n u2(n+1,1) = 1.0;\n u2(n+1,2:p+1) = 0.0;\n\n for k = 1 : p + 1\n\n dp = he_double_product_integral ( k - 1, k - 1 );\n\n for ix = 2 : n\n%\n% Viscous term.\n%\n term1 = visc(1) * ( u1(ix+1,k) - 2.0 * u1(ix,k) + u1(ix-1,k) );\n i = 2;\n for j = 1 : p + 1\n tp = he_triple_product_integral ( i - 1, j - 1, k - 1 );\n term1 = term1 + visc(i) * ( u1(ix+1,j) - 2.0 * u1(ix,j) + u1(ix-1,j) ) * tp / dp;\n end\n%\n% Convective term.\n%\n term2 = - conv * 0.5 * ( u1(ix+1,k) - u1(ix-1,k) );\n for j = 1 : p + 1\n for i = 1 : p + 1\n tp = he_triple_product_integral ( i - 1, j - 1, k - 1 );\n term2 = term2 + ( conv * u1(ix,i) * ( u1(ix+1,j) - u1(ix-1,j) ) * tp ) / dp;\n end\n end\n\n u2(ix,k) = u1(ix,k) + term1 + term2;\n\n end\n\n end\n\n t1 = t2;\n u1(1:n+1,1:p+1) = u2(1:n+1,1:p+1);\n%\n% Print solution every 100 time steps.\n%\n if ( mod ( it, 100 ) == 0 )\n fprintf ( output_unit, '----------\\n' );\n fprintf ( output_unit, 'T = %g\\n', t1 );\n for i = 1 : n + 1\n fprintf ( output_unit, ' %10g', x(i) );\n for k = 1 : p + 1\n fprintf ( output_unit, ' %10g', u1(i,k) );\n end\n fprintf ( output_unit, '\\n' );\n end\n end\n\n end\n\n fclose ( output_unit );\n fprintf ( 1, ' Time history in \"%s\".\\n', output_filename );\n%\n% Compute the mean and variance.\n%\n umean(1:n+1,1) = u1(1:n+1,1);\n\n uvariance = zeros ( n + 1, 1 );\n\n for i = 1 : n + 1\n for j = 2 : p + 1\n dp = he_double_product_integral ( j - 1, j - 1 );\n uvariance(i) = uvariance(i) + u1(i,j).^2 * dp;\n end\n end\n%\n% Save the solution at the final time.\n%\n output_filename = 'burgers.moments.txt';\n output_unit = fopen ( output_filename, 'wt' );\n fprintf ( output_unit, ' X E[U] Var[U]\\n' );\n for i = 1 : n + 1\n fprintf ( output_unit, ' %18.8g %18.8g %18.8g\\n', ...\n x(i), umean(i), uvariance(i) );\n end\n fclose ( output_unit );\n fprintf ( 1, ' Moments in \"%s\".\\n', output_filename );\n\n output_filename = 'burgers.modes.txt';\n output_unit = fopen ( output_filename, 'wt' );\n fprintf ( output_unit, ' X U_0 ... U_P \\n' );\n for i = 1 : n + 1\n fprintf ( output_unit, ' %10g', x(i) );\n for k = 1 : p + 1\n fprintf ( output_unit, ' %10g', u1(i,k) );\n end\n fprintf ( output_unit, '\\n' );\n end\n fclose ( output_unit );\n fprintf ( 1, ' Final modes in \"%s\".\\n', output_filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PCE_BURGERS:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\n", "meta": {"author": "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_burgers/pce_burgers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7393633870433359}} {"text": "function [X,Y,Z]=cone0(z,t,p) \n% [X,Y,Z]=cone0 defines a non-orthogonal\n% coordinate system using a conical surface\n% with a planar base\nX=z.*tan(t).*cos(p); Y=z.*tan(t).*sin(p); Z=z;", "meta": {"author": "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/cone0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9579122708828602, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7393583628085344}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n% \n% z-Transform properties\n\n\n%linearity \n\nsyms n z\n\nx1=n^2;\nx2=2^n;\na1=3;\na2=4;\n\nLe=a1*x1+a2*x2;\nLeft=ztrans(Le,z)\n\nX1=ztrans(x1);\nX2=ztrans(x2);\nRight=a1*X1+a2*X2\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/10/c105a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.88720460564669, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7393294244682133}} {"text": "function [OBrientest] = OBrientest(X,alpha)\n%O'Brien's Test for Homogeneity of Variances.\n%[In the Obrien's test the data are transforming to \n%yij = ((nj-1.5)*nj*((xij-mean(xj))**2)-((0.5)*(var(xj))*(nj-1)))/((nj-1)*(nj-2))\n%and uses the F distribution performing an one-way ANOVA using y as the \n%dependent variable (O'Brien, 1979)].\n%\n% Syntax: function [OBrientest] = OBrientest(X,alpha) \n% \n% Inputs:\n% X - data matrix (Size of matrix must be n-by-2; data=column 1, sample=column 2). \n% alpha - significance level (default = 0.05).\n% Outputs:\n% - Sample variances vector.\n% - Whether or not the homoscedasticity was met.\n%\n% Example: From the example 10.1 of Zar (1999, p.180), to test the O'Brien's\n% homoscedasticity of data with a significance level = 0.05.\n%\n% Diet\n% ---------------------------------\n% 1 2 3 4\n% ---------------------------------\n% 60.8 68.7 102.6 87.9\n% 57.0 67.7 102.1 84.2\n% 65.0 74.0 100.2 83.1\n% 58.6 66.3 96.5 85.7\n% 61.7 69.8 90.3\n% ---------------------------------\n% \n% Data matrix must be:\n% X=[60.8 1;57.0 1;65.0 1;58.6 1;61.7 1;68.7 2;67.7 2;74.0 2;66.3 2;69.8 2;\n% 102.6 3;102.1 3;100.2 3;96.5 3;87.9 4;84.2 4;83.1 4;85.7 4;90.3 4];\n%\n% Calling on Matlab the function: \n% OBrientest(X)\n%\n% Answer is:\n%\n% The number of samples are: 4\n%\n% ----------------------------\n% Sample Size Variance\n% ----------------------------\n% 1 5 9.3920\n% 2 5 8.5650\n% 3 4 7.6567\n% 4 5 8.3880\n% ----------------------------\n% \n% O'Brien's Test for Equality of Variances F=0.0171, df1= 3, df2=15\n% Probability associated to the F statistic = 0.9968\n% The associated probability for the F test is larger than 0.05\n% So, the assumption of homoscedasticity was met. \n%\n\n% Created by A. Trujillo-Ortiz and R. Hernandez-Walls\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% April 18, 2003.\n%\n% To cite this file, this would be an appropriate format:\n% Trujillo-Ortiz, A. and R. Hernandez-Walls. (2003). Obrientest: O'Brien's test for \n% homogeneity of variances. A MATLAB file. [WWW document]. URL http://www.mathworks.com/\n% matlabcentral/fileexchange/loadFile.do?objectId=3335&objectType=FILE\n%\n% References:\n% \n% O'Brien, R. G. (1979), A General ANOVA Method for Robust Tests of \n% Additive Models for Variances. Journal of the American\n% Statistical Association, 74:877-880.\n% Zar, J. H. (1999), Biostatistical Analysis (2nd ed.).\n% NJ: Prentice-Hall, Englewood Cliffs. p. 180. \n%\n\nif nargin < 2,\n alpha = 0.05;\nend\n\nY=X;\nk=max(Y(:,2));\nfprintf('The number of samples are:%2i\\n\\n', k);\n\n%O'Brien Procedure.\nn=[];s2=[];Z=[];\nindice=Y(:,2);\nfor i=1:k\n Ye=find(indice==i);\n eval(['Y' num2str(i) '=Y(Ye,1);']);\n eval(['mY' num2str(i) '=mean(Y(Ye,1));']);\n eval(['n' num2str(i) '=length(Y' num2str(i) ') ;'])\n eval(['s2' num2str(i) '=(std(Y' num2str(i) ').^2) ;'])\n eval(['xn= n' num2str(i) ';'])\n eval(['xs2= s2' num2str(i) ';'])\n eval(['Z' num2str(i) '= ((n' num2str(i) ' - 1.5)*(n' num2str(i) ')*((Y' num2str(i) ' - mY' num2str(i) ').^2)-((0.5)*(s2' num2str(i) ')*(n' num2str(i) ' - 1)))/((n' num2str(i) ' - 1)*(n' num2str(i) ' - 2));']);\n eval(['x= Z' num2str(i) ';']);\n n=[n;xn];s2=[s2;xs2];Z=[Z;x];\nend\n\nfor i=1:k\n if n(i)==2\n error('Requires sample sizes greater than two. Please, redefine the data matrix.');\n end\nend\n\nY=[Z Y(:,2)];\n\nfprintf('-----------------------------\\n');\ndisp(' Sample Size Variance')\nfprintf('-----------------------------\\n');\nfor i=1:k\n fprintf(' %d %2i %.4f\\n',i,n(i),s2(i))\nend\nfprintf('-----------------------------\\n');\ndisp(' ')\n\nC=(sum(Y(:,1)))^2/length(Y(:,1)); %correction term.\nSST=sum(Y(:,1).^2)-C; %total sum of squares.\ndfT=length(Y(:,1))-1; %total degrees of freedom.\n\nindice=Y(:,2);\nfor i=1:k\n Ye=find(indice==i);\n eval(['A' num2str(i) '=Y(Ye,1);']);\nend\n\nA=[];\nfor i=1:k\n eval(['x =((sum(A' num2str(i) ').^2)/length(A' num2str(i) '));']);\n A=[A,x];\nend\n\nSSA=sum(A)-C; %sample sum of squares.\ndfA=k-1; %sample degrees of freedom.\nSSE=SST-SSA; %error sum of squares.\ndfE=dfT-dfA; %error degrees of freedom.\nMSA=SSA/dfA; %sample mean squares.\nMSE=SSE/dfE; %error mean squares.\nF=MSA/MSE; %F-statistic.\nv1=dfA;df1=v1;\nv2=dfE;df2=v2;\n\nP = 1 - fcdf(F,v1,v2); %probability associated to the F-statistic. \n\nfprintf('O''Brien''s Test for Equality of Variances F=%3.4f, df1=%2i, df2=%2i\\n', F,df1,df2);\nfprintf('Probability associated to the F statistic = %3.4f\\n', P);\n\nif P >= alpha;\n fprintf('The associated probability for the F test is equal or larger than% 3.2f\\n', alpha);\n fprintf('So, the assumption of homoscedasticity was met.\\n');\nelse\n fprintf('The associated probability for the F test is smaller than% 3.2f\\n', alpha);\n fprintf('So, the assumption of homoscedasticity was not met.\\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/3510-homvar/OBrientest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7393014632635212}} {"text": "function point = circle3dPoint(circle, pos)\n%CIRCLE3DPOINT Coordinates of a point on a 3D circle from its position.\n%\n% output = circle3dPoint(input)\n%\n% Example\n% % Draw some points on a 3D circle\n% figure('color','w'); hold on; view(130,-10);\n% circle = [10 20 30 50 90 45 0];\n% drawCircle3d(circle)\n% % origin point\n% pos1 = 0;\n% drawPoint3d(circle3dPoint(circle, pos1), 'ro')\n% % few points regularly spaced\n% drawPoint3d(circle3dPoint(circle, 10:10:40), '+')\n% % Draw point opposite to origin\n% drawPoint3d(circle3dPoint(circle, 180), 'k*')\n% \n%\n% See also\n% circles3d, circle3dPosition\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-06-21, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\npos=pos(:);\n\n% extract circle coordinates\nxc = circle(1);\nyc = circle(2);\nzc = circle(3);\nr = circle(4);\n\ntheta = circle(5);\nphi = circle(6);\npsi = circle(7);\n\n% convert position to angle\nt = pos * pi / 180;\n\n% compute position on base circle\nx = r * cos(t);\ny = r * sin(t);\nz = zeros(length(pos),1);\npt0 = [x y z];\n\n% compute transformation from local basis to world basis\ntrans = localToGlobal3d(xc, yc, zc, theta, phi, psi);\n\n% compute points of transformed circle\npoint = transformPoint3d(pt0, trans);\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/circle3dPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7393014627846424}} {"text": "function [val,idx] = of_PCMARE(obs,sim,idx)\n% of_MARE Calculates a version of the Mean Absolute Relative Error (MARE)\n% of simulated streamflow as a percentage of the MARE of the mean \n% observed flow. Ignores time steps with negative flow values. Adds a\n% constant e of 1/100 of mean(obs) to avoid issues with zero flows \n% (Pushpalatha et al., 2012).\n\n% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter\n% This file is part of the Modular Assessment of Rainfall-Runoff Models\n% Toolbox (MARRMoT).\n% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY\n% WARRANTY. See for details.\n\n% In:\n% obs - time series of observations [nx1]\n% sim - time series of simulations [nx1]\n% idx - optional vector of indices to use for calculation, can be\n% logical vector [nx1] or numeric vector [mx1], with m <= n\n%\n% Out:\n% val - objective function value [1x1]\n% idx - vector of indices used for calculation\n\n% Pushpalatha, R.; Perrin, C.; le Moine, N. and Andréassian V. (2012). \"A\n% review of efficiency criteria suitable for evaluating low-flow\n% simulations\". Journal of Hydrology. 420-421, 171-182. \n% doi:10.1016/j.jhydrol.2011.11.055\n\n%% Check inputs and select timesteps\nif nargin < 2\n error('Not enugh input arguments') \nend\n\nif nargin < 3; idx = []; end\n[sim, obs, idx] = check_and_select(sim, obs, idx); \n\n%% Find the constant e\nm = mean(obs);\ne = m/100;\n\n%% Apply constant and transform flows\nobs = obs+e;\nsim = sim+e;\n\n%% Calculate metric\nMARE = mean(abs((sim-obs)/obs));\nMARE_mean = mean(abs((sim-m)/m));\n\nval = MARE/MARE_mean;\nend\n", "meta": {"author": "wknoben", "repo": "MARRMoT", "sha": "442622b3fd89bdd88420e96cfc6605770202dae9", "save_path": "github-repos/MATLAB/wknoben-MARRMoT", "path": "github-repos/MATLAB/wknoben-MARRMoT/MARRMoT-442622b3fd89bdd88420e96cfc6605770202dae9/MARRMoT/Functions/Objective functions/of_PCMARE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7393014599924416}} {"text": "function c = p_polynomial_coefficients ( n )\n\n%*****************************************************************************80\n%\n%% P_POLYNOMIAL_COEFFICIENTS: coefficients of Legendre polynomials P(n,x).\n%\n% First terms:\n%\n% 1\n% 0 1\n% -1/2 0 3/2\n% 0 -3/2 0 5/2\n% 3/8 0 -30/8 0 35/8\n% 0 15/8 0 -70/8 0 63/8\n% -5/16 0 105/16 0 -315/16 0 231/16\n% 0 -35/16 0 315/16 0 -693/16 0 429/16\n%\n% 1.00000\n% 0.00000 1.00000\n% -0.50000 0.00000 1.50000\n% 0.00000 -1.50000 0.00000 2.5000\n% 0.37500 0.00000 -3.75000 0.00000 4.37500\n% 0.00000 1.87500 0.00000 -8.75000 0.00000 7.87500\n% -0.31250 0.00000 6.56250 0.00000 -19.6875 0.00000 14.4375\n% 0.00000 -2.1875 0.00000 19.6875 0.00000 -43.3215 0.00000 26.8125\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 July 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% Daniel Zwillinger, editor,\n% CRC Standard Mathematical Tables and Formulae,\n% 30th Edition,\n% CRC Press, 1996.\n%\n% Parameters:\n%\n% Input, integer N, the highest order polynomial to evaluate.\n% Note that polynomials 0 through N will be evaluated.\n%\n% Output, real C(1:N+1,1:N+1), the coefficients of the Legendre polynomials \n% of degree 0 through N. Each polynomial is stored as a row.\n%\n if ( n < 0 )\n c = [];\n return\n end\n\n c(1:n+1,1:n+1) = 0.0;\n\n c(1,1) = 1.0;\n\n if ( n <= 0 )\n return\n end\n\n c(2,2) = 1.0;\n \n for i = 2 : n\n c(i+1,1:i-1) = ( - i + 1 ) * c(i-1,1:i-1) / ( i );\n c(i+1,2:i+1) = c(i+1,2:i+1) + ( i + i - 1 ) * c(i ,1: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/legendre_polynomial/p_polynomial_coefficients.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7392567700657834}} {"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\nprob = sigmoid(X * theta);\npos = find(prob >= 0.5);\np(pos,1) = 1;\n\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "scruel", "repo": "Notes-ML-AndrewNg", "sha": "916852d35684dcc77047ed861650aca36b62b98d", "save_path": "github-repos/MATLAB/scruel-Notes-ML-AndrewNg", "path": "github-repos/MATLAB/scruel-Notes-ML-AndrewNg/Notes-ML-AndrewNg-916852d35684dcc77047ed861650aca36b62b98d/assignments/machine-learning-ex2/ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213880824791, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.739247826425115}} {"text": "function [ x, w ] = rule_adjust ( a, b, c, d, n, x, w )\n\n%*****************************************************************************80\n%\n%% RULE_ADJUST maps a quadrature rule from [A,B] to [C,D].\n%\n% Discussion:\n%\n% Most quadrature rules are defined on a special interval, like\n% [-1,1] or [0,1]. To integrate over an interval, the abscissas\n% and weights must be adjusted. This can be done on the fly,\n% or by calling this routine.\n%\n% If the weight function W(X) is not 1, then the W vector will\n% require further adjustment by the user.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 October 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the endpoints of the definition interval.\n%\n% Input, real C, D, the endpoints of the integration interval.\n%\n% Input, integer N, the number of abscissas and weights.\n%\n% Input, real X(N), the abscissas.\n%\n% Input, real W(N), the weights.\n%\n% Output, real X(N), the adjusted abscissas.\n%\n% Output, real W(N), the adjusted weights.\n%\n x(1:n) = ( ( b - x(1:n) ) * c ...\n + ( x(1:n) - a ) * d ) ...\n / ( b - a );\n\n w(1:n) = ( ( d - c ) / ( b - a ) ) * w(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/quadrule/rule_adjust.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7392478258975456}} {"text": "% KM_DEMO_KPCA_U Kernel principal component analysis (KPCA) on a U-shaped\n% two-dimensional data set. \n%\n% This program implements the example shown in Figure 2.4 of \"Kernel\n% Methods for Nonlinear Identification, Equalization and Separation of\n% Signals\", Ph.D. dissertation by S. Van Vaerenbergh.\n%\n% Author: Steven Van Vaerenbergh (steven *at* gtas.dicom.unican.es), 2010.\n%\n% This file is part of the Kernel Methods Toolbox for MATLAB.\n% https://github.com/steven2358/kmbox\n\nclose all\nclear\n\n%% PARAMETERS\n\nN_split = [30, 30, 60];\t\t% number of data points in 2 straight parts and curve of \"U\"\ncorners = [3 4 2 4];\t% corners: x1 x2 y1 y2\nnvar = 0.05;\t% noise variance\n\nkernel.type = 'gauss';\nkernel.par = .5;\nnumeig = 4;\t% number of eigenvalues to plot\n\nNtest = [50,50];\t% number of test grid divisions, in each dimension\nborder = [0 6 0 6];\t% test grid border\n \n%% PROGRAM\ntic\n\n%% generate data\nN = sum(N_split);\nN1 = N_split(1); N2 = N_split(2); N3 = N_split(3);\n\nX1 = [linspace(corners(1),corners(2),N1)' repmat(corners(3),N1,1)];\t% lower straight part\nX2 = [linspace(corners(1),corners(2),N2)' repmat(corners(4),N2,1)];\t% upper straight part\n\nangles = linspace(pi/2,3*pi/2,N3)';\nrad = (corners(4)-corners(3))/2;\nm3 = [corners(1) corners(3)+rad];\nX3 = repmat(m3,N3,1) + rad*[cos(angles) sin(angles)];\n\nn = nvar*randn(N,2);\nX = [X1; X2; X3] + n;\n\n%% generate test grid data\nNt1 = Ntest(1); Nt2 = Ntest(2);\nXtest = zeros(Nt1*Nt2,2);\nabsc = linspace(border(1),border(2),Nt1);\nordi = linspace(border(3),border(4),Nt2);\nfor i=1:Nt1,\n\tfor j=1:Nt2,\n\t\tXtest((i-1)*Nt2+j,:) = [absc(i) ordi(j)];\n\tend\nend\n\n%% calculate kernel principal components and projections of Xtest\n[E,v] = km_kpca(X,numeig,kernel.type,kernel.par);\n\nKt = km_kernel(X,Xtest,kernel.type,kernel.par);\t% kernels of test data set\nXtestp = E'*Kt;\t % projections of test data set on the principal directions\n\nY = cell(numeig,1);\nfor i=1:numeig,\n \tY{i} = reshape(Xtestp(i,:),Nt2,Nt1);\t% shape into 2D grid\nend\n\ntoc\n%% OUTPUT\n\nfigure;\nplot(X(:,1),X(:,2),'.')\naxis(border)\n\n% fireworks!\nfor i=1:numeig,\n\tfigure; hold on\n\t[C,h] = contourf(-interp2(Y{i},2),25);\n\tplot(X(:,1)/border(2)*(Nt1*4-1)+1,X(:,2)/border(4)*(Nt2*4-1)+1,'o',...\n\t\t'MarkerFaceColor','White','MarkerEdgeColor','Black')\n\tset(gca, 'XTick', [])\n\tset(gca, 'YTick', [])\nend\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/toolboxes/kmbox/demo/km_demo_kpca_u.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7392478248424058}} {"text": "function [ x, error_norm, iter, flag ] = sor ( A, x, b, w, max_it, tol )\n\n%*****************************************************************************80\n%\n%% SOR solves the linear system Ax=b using the Successive Over-Relaxation Method. \n%\n% Discussion:\n%\n% When the parameter W\n% is set to 1, this is equivalent to the Gauss-Seidel iteration.\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 symmetric 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 W, the relaxation scalar, between 0 and 2.\n%\n% Input, integer MAX_IT, the maximum number of iterations.\n%\n% Input, real TOL, an error tolerance.\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\n%\n% Initialization.\n%\n flag = 1;\n iter = 0;\n\n bnrm2 = norm ( b );\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 flag = 0;\n return\n end\n%\n% Split the matrix.\n%\n [ M, N, b ] = split ( A, b, w, 2 );\n\n for iter = 1 : max_it\n\n x_1 = x;\n%\n% Update the approximation.\n%\n x = M \\ ( N * x + b );\n%\n% Compute the error.\n%\n error_norm = norm ( x - x_1 ) / norm ( x );\n errorhist(iter+1) = error_norm;\n%\n% Check for convergence.\n%\n if ( error_norm <= tol )\n flag = 0;\n break \n end\n\n end\n%\n% Restore the right hand side.\n%\n b = b / w;\n\n error_norm = errorhist;\n\n return\nend\n", "meta": {"author": "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/sor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7391392041121155}} {"text": "%%%% discretization of direct space, to be used for plotting the field\n%%%% distribution; X,Y = vectors to be used for FFT; Xi,Yi = vectors to be\n%%%% used for interpolation\nfunction [X,Y,Xi,Yi]=prcellgrid(a1,a2,N1,N2)\nX=[]; Y=[]; %spatial coordinates after FFT \nfor l=1:N1\n for m=1:N2\n X(l,m)=(l-1-(N1-1)/2)*a1(1)/N1 + (m-1-(N2-1)/2)*a2(1)/N2;\n Y(l,m)=(l-1-(N1-1)/2)*a1(2)/N1 + (m-1-(N2-1)/2)*a2(2)/N2; \n end\nend\n\nM=501; \nXi=[]; Yi=[]; %finer discretization for field interpolation\nfor l=1:M\n for m=1:M\n Xi(l,m)=(l-1-(M-1)/2)*a1(1)/M + (m-1-(M-1)/2)*a2(1)/M;\n Yi(l,m)=(l-1-(M-1)/2)*a1(2)/M + (m-1-(M-1)/2)*a2(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/22808-eigenmodes-in-a-2d-photonic-crystal/prcellgrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7390700762839042}} {"text": "function [area,centroids] = calcVoronoiArea(v,varargin)\n% compute the spherical area of the Voronoi decomposition\n%\n% Input\n% v - @vector3d\n%\n% Output\n% area - area of the corresponding Voronoi cells\n% centroids - centroid of the voronoi cell\n%\n% Options\n% incomplete -\n\nv = reshape(v,[],1);\nN = length(v);\n\n% in case of antipodal symmetry - add antipodal points\nantipodal = v.antipodal || check_option(varargin, 'antipodal');\nif antipodal\n v.antipodal = false;\n [v,~,IC] = unique([v;-v],'noSymmetry');\nend\n\n[V,C] = calcVoronoi(v);\n\nnd = ~cellfun('isempty',C);\nv = v.subSet(nd);\n\nlast = cumsum(cellfun('prodofsize',C(nd)));\n\nleft = [C{nd}];\nshift = 2:last(end)+1; % that is the shift\nshift(last) = [0;last(1:end-1)]+1; % and the last gets the first\nright = left(shift);\n\ncenter = cumsum([1 diff(shift)>1]);\n\nva = v.subSet(center);\nvb = V.subSet(left);\nvc = V.subSet(right); % next vertex around\n\n% calculate the area for each triangle around generator (va)\nA = real(sphericalTriangleArea(va,vb,vc));\n\nif nargout>1\n [x,y,z]= double(A.*(va+vb+vc));\n x = full(sparse(center,1,x,length(S2G),1));\n y = full(sparse(center,1,y,length(S2G),1));\n z = full(sparse(center,1,z,length(S2G),1));\n centroids = vector3d(x,y,z);\nend\n\n% accumulate areas of spherical triangles around generator\nA = full(sparse(center,1,A,length(v),1));\n\narea = zeros(size(nd));\narea(nd) = A(1:nnz(nd));\n\nif antipodal\n idx = ( accumarray(IC,ones(size(IC))) == 2 ); % find all double occurences\n area(idx) = area(idx)/2; % halve their weight\n area = area(IC); % go back to original order\n area = area(1:N); % only the original nodes\nend\n\n\n\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@vector3d/calcVoronoiArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7390700718939456}} {"text": "% Peak of Wigner-Ville Frequency Estimation\n%\n% Estimates the instantaneous frequency of the input signal by\n% extracting the peaks of the Wigner-Ville distribution.\n%\n%\n% Usage:\n%\n% ife = wvpe( signal, lag_window_length, time_res [, fft_length] )\n%\n% Parameters:\n%\n% signal\n%\n%\t Input one dimensional signal to be analysed. An analytic signal\n%\t is required for this function, however, if signal is real, a\n%\t default analytic transformer routine will be called from this\n%\t function before computing tfd.\n%\n% lag_window_length\n%\n%\t This is the data window length and controls the size of\n%\t the kernel used for analysis (lag_window_length must be\n%\t odd). The kernel used will be defined from -(lag_window_length+1)/2\n%\t to +(lag_window_length+1)/2 in both time and lag dimensions.\n%\n% time_res\n%\n%\t The number of time samples to skip between successive slices.\n%\t Default vaule is 1.\n%\n% fft_length\n%\n%\t Zero-padding at the FFT stage of the analysis may be specified by\n%\t giving an fft_length larger than lag_window_length. If fft_length\n%\t is not specified, or is smaller than the lag_window_length, then the\n%\t next highest power of two above lag_window_length is used. If\n%\t fft_length is not a power of two, the next highest power of two is\n%\t used.\n%\n% tfd\n%\n%\t The computed time-frequency distribution. size(tfd) will\n%\t return [a, b], where a is the next largest power of two above\n%\t fft_length, and b is floor(length(signal)/time_res) - 1.\n%\n%\n%\n% See Also: wvd\n% TFSAP 7.0\n% Copyright Prof. B. Boashash\n% Qatar University, Doha\n% email: tfsap.research@gmail.com\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/tfsa_7.0/win64_bin/wvpe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8056321983146849, "lm_q1q2_score": 0.7390085618046316}} {"text": "function dz = doublePendulumDynamics(~,z,u,P) \n%DZ = DOUBLEPENDULUMDYNAMICS(T,Z,U,P)\n% \n%FUNCTION: This function computes the dynamics of a double\n% pendulum, and is designed to be called from ode45. The\n% model allows for arbitrary mass and inertia for each\n% link, but no friction or actuation\n% \n%INPUTS: \n% t = time. Dummy input for ode45. Not used.\n% z = [4xn] matrix of states.\n% u = [2xn] matrix of inputs\n% P = struct of parameters\n%OUTPUTS: \n% dz = [4xn] matrix of state derivatives\n% \n%NOTES:\n% This file was automatically generated by writeDoublePendulumDynamics\n\nm1 = P.m1; %link one mass\nm2 = P.m2; %link two mass\ng = P.g ; %gravity\nl1 = P.l1; %link one length\nl2 = P.l2; %link two length\nI1 = P.I1; %link one moment of inertia about its center of mass\nI2 = P.I2; %link two moment of inertia about its center of mass\nd1 = P.d1; %distance between link one center of mass and parent joint\nd2 = P.d2; %distance between link two center of mass and parent joint\n\nth1 = z(1,:); %link one absolute angle\ndth1 = z(2,:); %link one angular rate\nth2 = z(3,:); %link two absolute angle\ndth2 = z(4,:); %link two angular rate\n\nu1 = u(1,:); %torque acting on link 1 wrt ground\nu2 = u(2,:); %torque acting on link 2 wrt ground\n\nf1 = u1 - m2.*(d2.*dth2.^2.*cos(th2) + dth1.^2.*l1.*cos(th1)).*(d2.*sin(th2) + l1.*sin(th1)) + m2.*(d2.*dth2.^2.*sin(th2) + dth1.^2.*l1.*sin(th1)).*(d2.*cos(th2) + l1.*cos(th1)) - g.*m2.*(d2.*cos(th2) + l1.*cos(th1)) - d1.*g.*m1.*cos(th1);\nf2 = u2 - d2.*g.*m2.*cos(th2) + d2.*dth1.^2.*l1.*m2.*sin(th1 - th2);\n\nM11 = - I1 - d1.^2.*m1.*cos(th1).^2 - d1.^2.*m1.*sin(th1).^2 - l1.*m2.*cos(th1).*(d2.*cos(th2) + l1.*cos(th1)) - l1.*m2.*sin(th1).*(d2.*sin(th2) + l1.*sin(th1));\nM12 = - I2 - d2.*m2.*cos(th2).*(d2.*cos(th2) + l1.*cos(th1)) - d2.*m2.*sin(th2).*(d2.*sin(th2) + l1.*sin(th1));\nM21 = -d2.*l1.*m2.*cos(th1 - th2);\nM22 = - I2 - d2.^2.*m2;\n\nD = M11.*M22 - M12.*M21;\n\nddth1 = (f2.*M12 - f1.*M22)./D;\nddth2 = -(f2.*M11 - f1.*M21)./D;\n\ndz = [...\n dth1; %derivative of link one absolute angle\n ddth1; %derivative of link one angular rate\n dth2; %derivative of link two absolute angle\n ddth2; %derivative of link two angular rate\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/doublePendulumForced/doublePendulumDynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.739008553881161}} {"text": "function [dy,dh] = checkgrad(X_struct, f, e, varargin)\n\n% checkgrad checks the derivatives in a function, by comparing them to finite\n% differences approximations. The partial derivatives and the approximation\n% are printed and the norm of the diffrence divided by the norm of the sum is\n% returned as an indication of accuracy.\n%\n% usage: checkgrad('f', X, e, P1, P2, ...)\n%\n% where X is the argument and e is the small perturbation used for the finite\n% differences. and the P1, P2, ... are optional additional parameters which\n% get passed to f. The function f should be of the type \n%\n% [fX, dfX] = f(X, P1, P2, ...)\n%\n% where fX is the function value and dfX is a vector of partial derivatives.\n%\n% d - norm error\n% dy - analytic \n% dh - numerical\n% \n% Carl Edward Rasmussen, 2001-08-01.\n\n[X_vec, X_template] = struct2vector(X_struct);\n\n% [y, dy] = feval(f, vector2struct(X_vec + val*grad, X_template), varargin{:});\ntic\n[y, dy_struct] = feval(f, X_struct, varargin{:});\ny = sum(y);\ndy = struct2vector(dy_struct);\ntime1 = toc;\n\n% keyboard\n\nfig = figure;\ndh = nan(length(X_vec),1) ;\nt = cputime;\nn_char = 0;\ntime_step = 5;\nDIRECTION = 'forwards';\n% DIRECTION = 'backwards';\n% if length(X_vec) > 50000\n% \n% % SKIP = 10;\n% % START = 1;%14400;%1;\n% \n% SKIP = 2000;\n% START = 1;%14400;%1;\n% \n% % SKIP = 1000;\n% % START = 30000;%14400;%1;\n% else\n% SKIP = 1;%100;\n% START = 1;%4300;%1;\n% end\n\nSTART = 1;\nn = max(40, 30/time1) % Evalulate for ~15 seconds\nSKIP = ceil(length(X_vec)/n);\n\n% START = 20210;\n% SKIP = 1;\n\nif strcmp(DIRECTION, 'backwards');\n idx = length(X_vec):-SKIP:1;\nelseif strcmp(DIRECTION, 'forwards');\n idx = START:SKIP:length(X_vec);\nend\n\n% idx = length(X_vec):-1:(length(X_vec)-8);\n% DIRECTION = 'backwards';\n% SKIP = 1;\n\nfor j = idx\n \n dx = zeros(length(X_vec),1);\n dx(j) = dx(j) + e; % perturb a single dimension\n \n [y2] = feval(f, vector2struct(X_vec + dx, X_template), varargin{:});\n [y1] = feval(f, vector2struct(X_vec - dx, X_template), varargin{:});\n \n y1 = sum(y1(:));\n y2 = sum(y2(:));\n \n dh(j) = (y2 - y1)/(2*e);\n\n if ((cputime - t) > time_step) || (j == idx(end))\n t = cputime;\n figure(fig)\n clf\n subplot(2,1,1);\n if strcmp(DIRECTION, 'backwards');\n plot(j:SKIP:length(dy), dy(j:SKIP:end), 'bx-'); hold on;\n plot(j:SKIP:length(dy), dh(j:SKIP:end), 'r-');\n elseif strcmp(DIRECTION, 'forwards');\n plot(START:SKIP:j, dy(START:SKIP:j), 'bx-'); hold on;\n plot(START:SKIP:j, dh(START:SKIP:j), 'r-');\n end\n legend('analytical', 'numerical');\n ylabel('gradient');\n subplot(2,1,2);\n if strcmp(DIRECTION, 'backwards');\n plot(j:SKIP:length(dy), dy(j:SKIP:end) - dh(j:SKIP:end), 'gx-');\n elseif strcmp(DIRECTION, 'forwards');\n plot(START:SKIP:j, dy(START:SKIP:j) - dh(START:SKIP:j), 'gx-');\n end\n ylabel('error')\n drawnow\n\n s = [num2str(100*j/length(X_vec), '%0.1f'), '%, '];\n if n_char + length(s) >= 80\n fprintf('\\n')\n n_char = 0;\n end\n fprintf('%s', s);\n n_char = n_char + length(s);\n \n end\nend\nfprintf('\\n');\n\n% 'numerical:'\n% dh(idx)'\n% \n% 'analytical:'\n% dy(idx)'\n\n'delta:'\nerr = dy(idx)' - dh(idx)';\n\n'mult:'\nmult = dy(idx)' ./ dh(idx)';\n\nfor p = [1, 5, 20, 50, 90, 95, 99, 99.9, 99.99]\n fprintf('%g percentile err: \\t%e\\n', p, prctile(abs(err), p));\nend\n\n\n% % disp([dy dh]) % print the two vectors\n% d = norm(dh-dy)/norm(dh+dy); % return norm of diff divided by norm of sum\n", "meta": {"author": "akar43", "repo": "CategoryShapes", "sha": "55c9dab2293bcaceaaa3bf5fea782fdbf930fadb", "save_path": "github-repos/MATLAB/akar43-CategoryShapes", "path": "github-repos/MATLAB/akar43-CategoryShapes/CategoryShapes-55c9dab2293bcaceaaa3bf5fea782fdbf930fadb/external/SIRFS/minFunc_2012/checkgrad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7390000034622006}} {"text": "function phasediag\n% Phase diagram visualisation \n% using MATLAB expm \n%\n% $Ekkehard Holzbecher $Date: 2006/04/15 $\n%--------------------------------------------------------------------------\nT = 10; % maximum time\nC = [-1 1; 1 -3]; % matrix\nf = [1; 0]; % input vector\ncc = 1; % initial concentrations (absolute value of the vector)\nN = 60; % discretization of time\nM = 16; % no. of trajectories \n\n%----------------------execution & output----------------------------------\nequilibrium = -(inv(C)*f);\nt = linspace (0,T,N);\nfor angle = linspace (0,pi+pi,M)\n c0 = equilibrium + cc*[sin(angle); cos(angle)]; c = c0;\n for i = 2:N\n E = expm(C*t(i));\n c = [c E*c0-(eye(size(C,1))-E)*inv(C)*f];\n end \n plot (c(1,:)',c(2,:)'); hold on;\nend\n\nplot (equilibrium(1),equilibrium(2),'s');\nxlabel ('variable 1'); ylabel ('variable 2')\ntitle ('phase diagram')", "meta": {"author": "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/phasediag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810466522863, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7389504950691813}} {"text": "function nsub = subset_enum ( n )\n\n%*****************************************************************************80\n%\n%% SUBSET_ENUM enumerates the subsets of a set with N elements.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of elements in the set.\n% N must be at least 0.\n%\n% Output, integer NSUB, the number of distinct elements.\n%\n nsub = 2^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_enum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8633916152464017, "lm_q1q2_score": 0.7389347041905476}} {"text": "function perf=mse(e)\n%\n% calculate the mean squared error of the given errors\n% \n% 'perf = mse(E);'\n%\n% see also:\n% mae, linf, trimmedmse\n%\n\n% Copyright (c) 2011, KULeuven-ESAT-SCD, License & help @ http://www.esat.kuleuven.be/sista/lssvmlab\n\n\nperf = sum(sum(e.^2)) / numel(e);", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v3.0/Algorithms/extract_resp_sig/feat_based_extraction/LSSVMlabv1_8_R2009b_R2011a/mse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.738925134315186}} {"text": "function s = fastSampen(y,m,r)\n% INPUTS\n% y num_var x num_samples\n% m template length\n% r radius\n% OUTPUTS\n% s Sample Entropy\n%\n% Written by Shamim Nemati \n%\n% 01-31-2018 : modified by Giulia Da Poian , see\n% comments in the code \n% NOTE : Sample entropy quantifies the likelihood that a \n% sequence of m consecutive data points that matches another\n% sequence of the same length (match within a tolerance of r) \n% will still match the other sequence when their length is \n% increased of one sample (sequences of length m + 1); \n% References : \n% 1. Richman JS, Moorman JR. Physiological time-series \n% analysis using approximate entropy and sample entropy. \n% American Journal of Physiology-Heart and Circulatory \n% Physiology. 2000 Jun 1;278(6):H2039-49.\n% 2. Humeau-Heurtier A. The multiscale entropy \n% algorithm and its variants: A review. Entropy. 2015 May \n% 12;17(5):3110-23.\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% Ensure y is a row vector\nif size(y, 1) > size(y,2)\n y = y';\nend\n\nxx = convert_to_lagged_form(y, m)'; % Giulia: replaced m-1 with m to match SampEn definition\nDxx = pdist(xx,'chebychev');\n\nyy = convert_to_lagged_form(y, m+1)'; % Giulia: replaced m with m+1 to match SampEn definition\nDyy = pdist(yy,'chebychev');\n\nA = mean( Dxx < r ) ;\nB = mean( Dyy < r );\n\ns = -log(B/A);\n\n\nfunction yy = convert_to_lagged_form(y, k)\n% Create an observation vector yy(:,t) containing the last k values of y, newest first\n% e.g., k=2, y = (a1 a2 a3) yy = a2 a3\n% (b1 b2 b3) b2 b2\n% a1 a2\n% b1 b2\n[s, T] = size(y);\nbs = s*ones(1,k);\nyy = zeros(k*s, T-k+1);\nfor i=1:k, yy(block(i,bs), :) = y(:, k-i+1:end-i+1); end\n\nfunction sub = block(blocks, block_sizes)\n% BLOCK Return a vector of subscripts corresponding to the specified blocks.\n% sub = block(blocks, block_sizes)\n%\n% e.g., block([2 5], [2 1 2 1 2]) = [3 7 8].\nblocks = blocks(:)';\nblock_sizes = block_sizes(:)';\nskip = [0 cumsum(block_sizes)];\nstart = skip(blocks)+1;\nfin = start + block_sizes(blocks) - 1;\nsub = [];\nfor j=1:length(blocks)\n sub = [sub start(j):fin(j)];\nend\n", "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/Entropy_Tools/fastSampen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.7389251251763077}} {"text": "function value = i4_gcdb ( i, j, k )\n\n%*****************************************************************************80\n%\n%% I4_GCDB finds the greatest common divisor of the form K**N of two numbers.\n%\n% Discussion:\n%\n% Note that if J is negative, I4_GCDB will also be negative.\n% This is because it is likely that the caller is forming\n% the fraction I/J, and so any minus sign should be\n% factored out of J.\n%\n% If I and J are both zero, I4_GCDB is returned as 1.\n%\n% If I is zero and J is not, I4_GCDB is returned as J,\n% and vice versa.\n%\n% If I and J are nonzero, and have no common divisor of the\n% form K**N, I4_GCDB is returned as 1.\n%\n% Otherwise, I4_GCDB is returned as the largest common divisor\n% of the form K**N shared by I and J.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, J, two numbers whose greatest common divisor K**N\n% is desired.\n%\n% Input, integer K, the possible divisor of I and J.\n%\n% Output, integer VALUE, the greatest common divisor of\n% the form K^N shared by I and J.\n%\n value = 1;\n%\n% If both I and J are zero, I4_GCDB is 1.\n%\n if ( i == 0 && j == 0 )\n value = 1;\n return\n end\n%\n% If just one of I and J is zero, I4_GCDB is the other one.\n%\n if ( i == 0 )\n value = j;\n return\n elseif ( j == 0 )\n value = i;\n return\n end\n%\n% Divide out K as long as you can.\n%\n if ( 0 < j )\n value = 1;\n else\n value = -1;\n end\n\n while\n\n if ( mod ( i, k ) ~= 0 || mod ( j, k ) ~= 0 )\n break\n end\n\n value = value * k;\n i = i / k;\n j = j / k;\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/i4lib/i4_gcdb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.8539127585282745, "lm_q1q2_score": 0.7388258801308644}} {"text": "function result = is_symmetric_matrix(A)\n%\n% Symmetric Matrices\n% \n% is_symmetric_matrix(A) determines if the matrix A is a symmetric\n% matrix. An error is returned if a matrix that is not square is attempted\n% to be determined for symmetry.\n\nmatrix_size = size(A);\n\nm = matrix_size(1,1);\nn = matrix_size(1,2);\n\nif m ~= n\n error('Only square matrices can be symmetric.');\nelse\n if A == A'\n result = 1;\n else\n result = 0;\n end\nend", "meta": {"author": "xiuyechen", "repo": "FishExplorer", "sha": "c61392cf0835480d64fc03c15f1992935fdc7106", "save_path": "github-repos/MATLAB/xiuyechen-FishExplorer", "path": "github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/ref functions/Gram-Schmidt Process/is_symmetric_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7388258798818034}} {"text": "function [ vX ] = ProjectOntoHalfSpace( vY, vA, valB )\n% ----------------------------------------------------------------------------------------------- %\n% [ vX ] = OrthogonalProjectionOntoConvexSets( cProjFun, vY, numIterations, stopThr )\n% Solves \\arg \\min_{x} 0.5 || x - y ||, s.t. x \\in \\bigcap {C}_{i} using\n% Dykstra's Projection Algorithm.\n% Input:\n% - mA - Model Matrix.\n% Input model matrix.\n% Structure: Matrix (m x n).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% Output:\n% - vX - Solution Vector.\n% The solution to the optimization problem..\n% Structure: Vector (m x 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References\n% 1. Orthogonal Projection onto a Half Space - https://math.stackexchange.com/questions/318740.\n% Remarks:\n% 1. B\n% TODO:\n% 1. C\n% Release Notes:\n% - 1.0.000 19/03/2020 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\nvalR = (vA.' * vY) - valB;\n\nif(valR > 0)\n vX = vY - ((valR / (vA.' * vA)) * vA);\nelse\n vX = vY;\nend\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/Mathematics/Q3599020/ProjectOntoHalfSpace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731765, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7387484537665019}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n%Fourier Transfrom properties\n\n%\tconvolution \n\n%x1(t)=u(t)-u(t-2) and x2(t)=u(t)-u(t-4) \n\n\n% F^-1{X1(w)X2(w)}\nsyms t w\nx1=heaviside(t)-heaviside(t-2);\nx2=heaviside(t)-heaviside(t-4);\nX1=fourier(x1,w);\nX2=fourier(x2,w);\nright =ifourier(X1*X2,t);\nezplot(right,[0 8]);\n\n% convolution of x1(t) with x2(t)\nfigure\nt1=0:.01:2;\nt2=2.01:.01:4;\nx1=[ones(size(t1)) zeros(size(t2))];\nx2=ones(size([t1 t2]));\ny=conv(x1,x2)*.01;\nplot(0:.01:8,y);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/6/c65.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7386959899825564}} {"text": "function f = p01_f ( x )\n\n%*****************************************************************************80\n%\n%% P01_F evaluates the objective function for problem 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 February 2002\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the objective function.\n%\n% Output, real F, the value of the objective function.\n%\n f = ( x - 2.0 ) * ( x - 2.0 ) + 1.0;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_min/p01_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8887587949656841, "lm_q1q2_score": 0.7386856936586635}} {"text": "% MultiQuadrics scattered data INTERPOLATION. \n% \n% SYNTAX: [fi, coefficients] = mq_interpolation( r, f, ri, c )\n%\n% where r and f are the scattered argument and function\n% values, fi is the data interpolated at ri, c is the \n% multiquadric parameter and coefficients is a vector \n% containing the coefficients of the MQ expansion. \n%\n% Examples: \n% N = 51; c = 0.2;\n% x = 2*pi*sort( rand([1 N]) ); f = sin(x);\n% xi = linspace(0,2*pi,N);\n% [fi,coefficients] = mq_interpolation(x(:),f(:),xi(:),c);\n% figure(1), plot(x,f,xi,fi,'o')\n% \n%\t N = 51; c = 0;\n%\t x = 2*rand([1 N]) - 1; y = 2*rand([1 N]) - 1; r = [x(:) y(:)];\n%\t for i = 1:N, f(i) = exp( -x(i)^2 -y(i)^2 ); end\n%\t xi = linspace(-1.1,1.1,N); yi = linspace(-1.1,1.1,N);\n%\t [Xi,Yi] = meshgrid(xi,yi);\n%\t for i = 1:N*N, ri(i,:) = [Xi(i) Yi(i)]; end\n%\t [fi,coefficients] = mq_interpolation(r,f(:),ri,c);\n%\t S = reshape(fi,N,N);\n%\t figure(2)\n%\t mesh(xi,yi,S), hold on, plot3(x,y,f,'o'), hold off\n\n\n% Written by Orlando Camargo Rodriguez\n\nfunction [fi,coefficients] = mq_interpolation(r,f,ri,c)\n\nfi = [];\ncoefficients = [];\n\nN = length( r(:,1) ); \n\nfor i = 1:N \n\n rj_minus_ri = ( r(i,:)'*ones([1 N]) )' - r;\n \n Phi(:,i) = sqrt( sum( rj_minus_ri.^2 , 2 ) + c*c );\n \nend\n\ncoefficients = Phi\\f(:); % Calculate the coefficients through Gaussian elimination\n\nNi = length( ri(:,1) );\n\nfor i = 1:Ni\n\n ri_minus_r = ( ri(i,:)'*ones([1 N]) )' - r;\n \n phi_at_ri = sqrt( sum( ri_minus_r.^2 , 2 ) + c*c );\n \n fi(i) = coefficients'*phi_at_ri(:);\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/8662-mqinterpolation-m/mq_interpolation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7386677125237869}} {"text": " function y = mod0(x,b)\n%function y = mod0(x,b)\n%\tthe usual mod function returns values in the range [0,b)\n%\twhereas this mod function returns values in the range [-b/2,b/2)\n%\twhich frequently arises in signal processing problems!\n%\tJeff Fessler\n\ny = mod(x + b/2, b) - b/2;\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/mod0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.8031737987125613, "lm_q1q2_score": 0.7386327905304231}} {"text": "function par_est2a\n% parameter estimation with derivatives Holzbecher September 2005\n% using differential equations\n% Idea from FEMLAB - there R instead of Q \n% see COMSOL News, Nr. 1, 2005, page 15\nglobal xfit cfit Q\n\n% specify fitting data\nxfit = [0.05:0.1:0.95];\ncfit = [0.9256859756097451 0.7884908536585051 0.6665396341462926...\n 0.559832317073104 0.4683689024389414 0.39214939024380824...\n 0.33117378048770196 0.28544207317062964 0.25495426829258294 0.23971036585356142]; \nQ = -2;\nD = fzero(@myfun,1.8);\ndisplay (['Best fit for D = ' num2str(D)]);\nx = [0:0.01:1];\nplot (xfit,cfit,'o',x,-(Q/D/2)*x.*x + (Q/D)*x + 1,'-');\nlegend ('given','modelled');\nxlabel ('x'); ylabel ('c');\n\nfunction f = myfun(D); \nglobal xfit cfit Q\n\noptions = bvpset;\n% solve diffusion equation for c with c(0)=1 and dc/dx(1)=0 \nsolinit = bvpinit([0 xfit 1],@guess);\nc = bvp4c (@mat4ode,@mat4bc,solinit,options,Q/D,1);\n%plot (c.x,c.y(1,:),'r',xfit,-(Q/D/D)*xfit.*xfit+(Q/D)*xfit+ones(1,size(xfit,2)));\n\n% solve Poisson equation for dc/dD (cD) with boundary conditions\nsolinit = bvpinit([0 xfit 1],@guess1);\ncD = bvp4c (@mat4ode,@mat4bc,solinit,options,Q/D/D,0);\n\n% specify function f to vanish\nf = 2*(c.y(1,2:size(c.y,2)-1)-cfit)*cD.y(1,2:size(c.y,2)-1)';\n\nfunction dydx = mat4ode(x,y,Q,c0)\ndydx = [y(2); -Q];\n% ------------------------------------------------------------\nfunction res = mat4bc(y0,y1,Q,c0)\nres = [y0(1)-c0; y1(2)];\n% ------------------------------------------------------------\nfunction v = guess(x)\nv = [x*(x-2)+1; 2*(x-1)];\n% ------------------------------------------------------------\nfunction v = guess1(x)\nv = [x*(x-2); 2*(x-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/15646-environmental-modeling/par_est2a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.738632769085158}} {"text": " function [fwhm_best, costs, im_best] = ...\n\tfwhm_match(true_image, blurred_image, fwhms)\n%|function [fwhm_best, costs, im_best] = ...\n%|\tfwhm_match(true_image, blurred_image, fwhms)\n%|\n%| given a blurred_image of a true_image, find the FHWM of a Gaussian kernel\n%| that, when convolved to the true_image, yields the smoothed image\n%| that best matches blurred_image.\n%|\n%| the set of FWHM values given in the array fwhms is tried.\n%|\n%| Copyright 2001-8-30, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(true_image, 'test'), fwhm_match_test, return, end\nif nargin < 2, ir_usage, end\n\nif nargin < 3\n\tfwhms = 0:0.5:4;\nend\n\ncosts = zeros(size(fwhms));\ncost_min = Inf;\nfor ii=1:length(fwhms)\n\tfwhm = fwhms(ii);\n\tkern = gaussian_kernel(fwhm);\n\tpsf = kern * kern';\n\ttmp = conv2(true_image, psf, 'same');\n\tcosts(ii) = norm(tmp(:) - blurred_image(:)) / norm(true_image(:));\n\tif costs(ii) < cost_min\n\t\tim_best = tmp;\n\tend\nend\n\n[dummy ibest] = min(costs);\nif ibest == 1 || ibest == length(fwhms)\n\twarning 'need wider range of fwhms'\nend\nfwhm_best = fwhms(ibest);\n\n\n% fwhm_match_test\nfunction fwhm_match_test\n\n% pyramidal PSF to stress the approach\npsf1 = [0:5 4:-1:0]; psf1 = psf1 / sum(psf1); psf = psf1' * psf1;\ntrue_image = zeros(128); true_image(64:96,64:96) = 1;\nblurred_image = conv2(true_image, psf, 'same');\nim plc 2 2\nim(1, true_image, 'True Image')\nim(2, blurred_image, 'Blurred Image')\n\nfwhms = [2:0.25:8];\n[fwhm_best, costs] = fwhm_match(true_image, blurred_image, fwhms);\nnp = length(psf);\tip = -(np-1)/2:(np-1)/2;\nkern = gaussian_kernel(fwhm_best);\nnk = length(kern);\tik = -(nk-1)/2:(nk-1)/2;\n\nif im\n\tim subplot 3\n\tplot(fwhms, costs, 'c-o', fwhm_best, min(costs), 'yx')\n\txlabel FWHM, ylabel Cost, title 'Cost vs FWHM' \n\tim subplot 4\n\tplot(ip, psf1, '-o', ik, kern(:), '-+')\n\txlabel pixel, title 'PSF profile: actual and Gaussian fit'\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/fwhm_match.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7386002696728945}} {"text": "function ex3bvp\n%EX3BVP Example 3 of the BVP tutorial.\n% This is the example for D02KAF from the NAG library. D02KAF is a code\n% for Sturm-Liouville problems that takes advantage of special features of\n% the problem. The task is to find the fourth eigenvalue of Mathieu's\n% equation \n% \n% y'' + (lambda -2*q*cos(2*x))*y = 0\n% \n% on the interval [0, pi] with boundary conditions y'(0) = 0, y'(pi) = 0.\n% The parameter q = 5.\n% \n% A code that exploits fully the special nature of the Sturm-Liouville\n% problem can compute a specific eigenvalue. Of course using BVP4C we can\n% only compute an eigenvalue near to a guessed value. We can make it much\n% more likely that we compute the desired eigenfunction by supplying a\n% guess that has the correct qualitative behavior. We use here the same\n% guess lambda = 15 as the example. The eigenfunction is determined only\n% to a constant multiple, so the normalizing condition y(0) = 1 is used to\n% specify a particular solution.\n%\n% Plotting the solution on the mesh found by BVP4C does not result in a\n% smooth graph. The solution S(x) is continuous and has a continuous\n% derivative. It can be evaluated inexpensively using DEVAL at as many\n% points as necessary to get a smooth graph. \n\n% Copyright 2002, The MathWorks, Inc.\n\n% BVPINT is used to form an initial guess for a mesh of 10 equally\n% spaced points. The guess cos(4x) for y(x) and its derivative as guess \n% for y'(x) are evaluated in EX3INIT. The desired eigenvalue is the one\n% nearest the guess lambda = 15. A guess for unknown parameters is the\n% (optional) last argument of BVPINIT.\nsolinit = bvpinit(linspace(0,pi,10),@ex3init,15);\n\noptions = bvpset('stats','on'); \n\nsol = bvp4c(@ex3ode,@ex3bc,solinit,options);\n\n% BVP4C returns the solution as the structure 'sol'. The computed eigenvalue \n% is returned in the field sol.parameters.\nfprintf('\\n');\nfprintf('D02KAF computed lambda = 17.097.\\n')\nfprintf('bvp4c computed lambda =%7.3f.\\n',sol.parameters)\n\nfigure\nplot(sol.x,sol.y(1,:),sol.x,sol.y(1,:),'*')\naxis([0 pi -1 1])\ntitle('Eigenfunction for Mathieu''s equation.') \nxlabel('Solution at mesh points only.')\n\n% Plotting the solution just at the mesh points does not result in a \n% smooth graph near the ends of the interval. The approximate solution \n% S(x) is continuous and has a continuous derivative. DEVAL is used to\n% evaluate it at enough points to get a smooth graph.\nfigure\nxint = linspace(0,pi);\nSxint = deval(sol,xint); \nplot(xint,Sxint(1,:))\naxis([0 pi -1 1])\ntitle('Eigenfunction for Mathieu''s equation.') \nxlabel('Solution evaluated on a finer mesh with DEVAL.')\n\n% --------------------------------------------------------------------------\n\nfunction dydx = ex3ode(x,y,lambda)\n%EX3ODE ODE function for Example 3 of the BVP tutorial.\nq = 5;\ndydx = [ y(2)\n -(lambda - 2*q*cos(2*x))*y(1) ];\n\n% --------------------------------------------------------------------------\n \nfunction res = ex3bc(ya,yb,lambda)\n%EX3BC Boundary conditions for Example 3 of the BVP tutorial.\nres = [ ya(2) \n yb(2) \n ya(1) - 1 ];\n \n% --------------------------------------------------------------------------\n \nfunction v = ex3init(x)\n%EX3INIT Guess for the solution of Example 3 of the BVP tutorial.\nv = [ cos(4*x)\n -4*sin(4*x) ];\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_65/ex3bvp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7386002657246074}} {"text": "%DEMGMM3 Demonstrate density modelling with a Gaussian mixture model.\n%\n%\tDescription\n%\t The problem consists of modelling data generated by a mixture of\n%\tthree Gaussians in 2 dimensions with a mixture model using diagonal\n%\tcovariance matrices. The priors are 0.3, 0.5 and 0.2; the centres\n%\tare (2, 3.5), (0, 0) and (0,2); the covariances are all axis aligned\n%\t(0.16, 0.64), (0.25, 1) and the identity matrix. The first figure\n%\tcontains a scatter plot of the data.\n%\n%\tA Gaussian mixture model with three components is trained using EM.\n%\tThe parameter vector is printed before training and after training.\n%\tThe user should press any key to continue at these points. The\n%\tparameter vector consists of priors (the column), and centres (given\n%\tas (x, y) pairs as the next two columns). The diagonal entries of\n%\tthe covariance matrices are printed separately.\n%\n%\tThe second figure is a 3 dimensional view of the density function,\n%\twhile the third shows the axes of the 1-standard deviation circles\n%\tfor the three components of the mixture model.\n%\n%\tSee also\n%\tGMM, GMMINIT, GMMEM, GMMPROB, GMMUNPAK\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n% Generate the data\nndata = 500;\n\n% Fix the seeds for reproducible results\nrandn('state', 42);\nrand('state', 42);\ndata = randn(ndata, 2);\nprior = [0.3 0.5 0.2];\n% Mixture model swaps clusters 1 and 3\ndatap = [0.2 0.5 0.3];\ndatac = [0 2; 0 0; 2 3.5];\ndatacov = [1 1;1 0.25; 0.4*0.4 0.8*0.8];\ndata1 = data(1:prior(1)*ndata,:);\ndata2 = data(prior(1)*ndata+1:(prior(2)+prior(1))*ndata, :);\ndata3 = data((prior(1)+prior(2))*ndata +1:ndata, :);\n\n% First cluster has axis aligned variance and centre (2, 3.5)\ndata1(:, 1) = data1(:, 1)*0.4 + 2.0;\ndata1(:, 2) = data1(:, 2)*0.8 + 3.5;\n\n% Second cluster has axis aligned variance and centre (0, 0)\ndata2(:,2) = data2(:, 2)*0.5;\n\n% Third cluster is at (0,2) with identity matrix for covariance\ndata3 = data3 + repmat([0 2], prior(3)*ndata, 1);\n\n% Put the dataset together again\ndata = [data1; data2; data3];\n\nclc\ndisp('This demonstration illustrates the use of a Gaussian mixture model')\ndisp('with diagonal covariance matrices to approximate the unconditional')\ndisp('probability density of data in a two-dimensional space.')\ndisp('We begin by generating the data from a mixture of three Gaussians')\ndisp('with axis aligned covariance structure and plotting it.')\ndisp(' ')\ndisp('The first cluster has centre (0, 2).')\ndisp('The second cluster has centre (0, 0).')\ndisp('The third cluster has centre (2, 3.5).')\ndisp(' ')\ndisp('Press any key to continue')\npause\n\nfh1 = figure;\nplot(data(:, 1), data(:, 2), 'o')\nset(gca, 'Box', 'on')\n\n% Set up mixture model\nncentres = 3;\ninput_dim = 2;\nmix = gmm(input_dim, ncentres, 'diag');\n\noptions = foptions;\noptions(14) = 5;\t% Just use 5 iterations of k-means in initialisation\n% Initialise the model parameters from the data\nmix = gmminit(mix, data, options);\n\n% Print out model\ndisp('The mixture model has three components and diagonal covariance')\ndisp('matrices. The model parameters after initialisation using the')\ndisp('k-means algorithm are as follows')\ndisp(' Priors Centres')\ndisp([mix.priors' mix.centres])\ndisp('Covariance diagonals are')\ndisp(mix.covars)\ndisp('Press any key to continue.')\npause\n\n% Set up vector of options for EM trainer\noptions = zeros(1, 18);\noptions(1) = 1;\t\t% Prints out error values.\noptions(14) = 20;\t\t% Number of iterations.\n\ndisp('We now train the model using the EM algorithm for 20 iterations.')\ndisp(' ')\ndisp('Press any key to continue.')\npause\n\n[mix, options, errlog] = gmmem(mix, data, options);\n\n% Print out model\ndisp(' ')\ndisp('The trained model has priors and centres:')\ndisp(' Priors Centres')\ndisp([mix.priors' mix.centres])\ndisp('The data generator has priors and centres')\ndisp(' Priors Centres')\ndisp([datap' datac])\ndisp('Model covariance diagonals are')\ndisp(mix.covars)\ndisp('Data generator covariance diagonals are')\ndisp(datacov)\ndisp('Note the close correspondence between these parameters and those')\ndisp('of the distribution used to generate the data.')\ndisp(' ')\ndisp('Press any key to continue.')\npause\n\nclc\ndisp('We now plot the density given by the mixture model as a surface plot.')\ndisp(' ')\ndisp('Press any key to continue.')\npause\n\n% Plot the result\nx = -4.0:0.2:5.0;\ny = -4.0:0.2:5.0;\n[X, Y] = meshgrid(x,y);\nX = X(:);\nY = Y(:);\ngrid = [X Y];\nZ = gmmprob(mix, grid);\nZ = reshape(Z, length(x), length(y));\nc = mesh(x, y, Z);\nhold on\ntitle('Surface plot of probability density')\nhold off\ndrawnow\n\nclc\ndisp('The final plot shows the centres and widths, given by one standard')\ndisp('deviation, of the three components of the mixture model. The axes')\ndisp('of the ellipses of constant density are shown.')\ndisp(' ')\ndisp('Press any key to continue.')\npause\n\n% Try to calculate a sensible position for the second figure, below the first\nfig1_pos = get(fh1, 'Position');\nfig2_pos = fig1_pos;\nfig2_pos(2) = fig2_pos(2) - fig1_pos(4);\nfh2 = figure('Position', fig2_pos);\n\nh = plot(data(:, 1), data(:, 2), 'bo');\nhold on\naxis('equal');\ntitle('Plot of data and covariances')\nfor i = 1:ncentres\n v = [1 0];\n for j = 1:2\n start=mix.centres(i,:)-sqrt(mix.covars(i,:).*v);\n endpt=mix.centres(i,:)+sqrt(mix.covars(i,:).*v);\n linex = [start(1) endpt(1)];\n liney = [start(2) endpt(2)];\n line(linex, liney, 'Color', 'k', 'LineWidth', 3)\n v = [0 1];\n end\n % Plot ellipses of one standard deviation\n theta = 0:0.02:2*pi;\n x = sqrt(mix.covars(i,1))*cos(theta) + mix.centres(i,1);\n y = sqrt(mix.covars(i,2))*sin(theta) + mix.centres(i,2);\n plot(x, y, 'r-');\nend\nhold off\n\ndisp('Note how the data cluster positions and widths are captured by')\ndisp('the mixture model.')\ndisp(' ')\ndisp('Press any key to end.')\npause\n\nclose(fh1);\nclose(fh2);\nclear 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/demgmm3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.738600264567839}} {"text": "% Distribution code Version 1.0 -- 02/31/2020 by Wei Liu Copyright 2020\n%\n% The code is created based on the method described in the following paper \n% [1] \"Real-time Image Smoothing via Iterative Least Squares\", Wei Liu, Pingping Zhang, \n% Xiaolin Huang, Jie Yang, Chunhua Shen and Ian Reid, ACM Transactions on Graphics, \n% presented at SIGGRAPH 2020. \n% \n% The code and the algorithm are for non-comercial use only.\n\n\n% ---------------------- Input------------------------\n% F: input image, can be gray image or RGB color image\n% lambda: \\lambda in Eq.(1), control smoothing strength\n% p: the power norm in the Charbonnier penalty in Eq. (2)\n% eps: the small constant number in the Charbonnier penalty in Eq. (2)\n% iter: iteration number of the ILS in Eq. (8)\n\n% ---------------------- Output------------------------\n% U: smoothed image\n\nfunction U =ILS_LNorm(F, lambda, p, eps, iter)\n\nF = single(F); % 'single' precision is very important to reduce the computational cost\n\ngamma = 0.5 * p - 1;\nc = p * eps^gamma;\n\n[N, M, D] = size(F);\nsizeI2D = [N, M];\n\notfFx = psf2otf_Dx(sizeI2D); % equal to otfFx = psf2otf(fx, sizeI2D) where fx = [1, -1];\notfFy = psf2otf_Dy(sizeI2D); % equal to otfFy = psf2otf(fy, sizeI2D) where fy = [1; -1];\n\nDenormin = abs(otfFx).^2 + abs(otfFy ).^2;\nDenormin = repmat(Denormin, [1, 1, D]);\nDenormin = 1 + 0.5 * c * lambda * Denormin;\n\nU = F; % smoothed image\n\nNormin1 = fft2(U);\n\nfor k = 1: iter\n \n % Intermediate variables \\mu update, in x-axis and y-axis direction\n u_h = [diff(U,1,2), U(:,1,:) - U(:,end,:)];\n u_v = [diff(U,1,1); U(1,:,:) - U(end,:,:)];\n \n mu_h = c .* u_h - p .* u_h .* (u_h .* u_h + eps) .^ gamma;\n mu_v = c .* u_v - p .* u_v .* (u_v .* u_v + eps) .^ gamma;\n \n % Update the smoothed image U\n Normin2_h = [mu_h(:,end,:) - mu_h(:, 1,:), - diff(mu_h,1,2)];\n Normin2_v = [mu_v(end,:,:) - mu_v(1, :,:); - diff(mu_v,1,1)];\n \n FU = (Normin1 + 0.5 * lambda * (fft2(Normin2_h + Normin2_v))) ./ Denormin;\n U = real(ifft2(FU));\n \n Normin1 = FU; % This helps to further enlarge the smoothing strength\n \nend\n", "meta": {"author": "wliusjtu", "repo": "Real-time-Image-Smoothing-via-Iterative-Least-Squares", "sha": "b6c01cb519050614433b3939c82819588e79f206", "save_path": "github-repos/MATLAB/wliusjtu-Real-time-Image-Smoothing-via-Iterative-Least-Squares", "path": "github-repos/MATLAB/wliusjtu-Real-time-Image-Smoothing-via-Iterative-Least-Squares/Real-time-Image-Smoothing-via-Iterative-Least-Squares-b6c01cb519050614433b3939c82819588e79f206/ILS_LNorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7385923448044727}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Main problem is minimize \\| A x \\|_1 subject to A x = b\n% We introduce z = A x - b\n% x \\in R^n A \\in R^{m x n} b \\in R^m\n% m < n\n% ADMM terms\n% minimize f(x) + g(z) subject to A x + B z = c\n% f(x) : {x \\in R^n | Ax = b}\n% g(z) : \\| z \\|_1\n% minimize f(x) + \\| z \\|_1 subject to x - z = 0\n% A : 1\n% B : -1\n% c : 0\n% \n% x update x = proj (z - u) over the set {Ax = b}\n% z update: z = shrinkage(x + u)\n% u update : u = u + x - z\n%\n% Primal residual r = A x + B z - c : x - z\n% Dual residual s = rho A^T B (z_new - z_old) = rho (z_old - z_new)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [x, history] = bp(A, b, options)\n if nargin < 2 || nargin > 3\n error('Invalid arguments');\n end\n if nargin < 3\n options = struct;\n end\n % weight for the quadratic penalty term\n rho = 1;\n if isfield(options, 'rho')\n rho = options.rho;\n end\n % weight for the relaxation\n alpha = 1;\n if isfield(options, 'alpha')\n alpha = options.alpha;\n end\n % size of the matrix\n [M, N] = size(A);\n % Main optimization variable\n if isfield(options, 'x')\n x = options.x;\n else\n x = zeros(N, 1);\n end\n % Auxiliary optimization variable z = Ax - b\n % Goal of ADMM iterations is to bring z closer to Ax - b\n if isfield(options, 'z')\n z = options.z;\n else\n z = zeros(N, 1);\n end\n % scaled Lagrangian variable\n if isfield(options, 'u')\n u = options.u;\n else\n u = zeros(N, 1);\n end\n % verbosity\n verbose = 0;\n if isfield(options, 'verbose')\n verbose = options.verbose;\n end\n % Maximum number of ADMM iterations\n max_iterations = 1000;\n if isfield(options, 'max_iterations')\n max_iterations = options.max_iterations;\n end\n % absolute tolerance\n eps_abs = 1e-4;\n if isfield(options, 'absolute_tolerance')\n eps_abs = options.absolute_tolerance;\n end\n % relative tolerance\n eps_rel = 1e-2;\n if isfield(options, 'relative_tolerance')\n eps_rel = options.relative_tolerance;\n end\n % Compute and cache factorizations\n AAt = A*A';\n P = eye(N) - A' * (AAt\\A);\n % pseudo-inverse based solution of equation Ax=b\n q = A' * (AAt \\b);\n % import relevant functions\n import spx.opt.shrinkage;\n if verbose\n fprintf('%3s\\t%10s\\t%10s\\t%10s\\t%10s\\t%10s\\n', 'iter', ...\n 'r norm', 'eps pri', 's norm', 'eps dual', 'objective');\n end\n % perform ADMM iterations\n for k=1:max_iterations\n % preserve old value of z\n z_old = z;\n % update x as a projection on to the set {Ax = b}\n % we add the projection of (z-u) to the null-space of A and add\n % it to the pseudo-inverse solution of Ax = b\n x = P*(z-u) + q;\n % relaxation\n if alpha ~= 1\n x_hat = alpha*x + (1-alpha)*z;\n else\n x_hat = x;\n end\n % update z\n z = shrinkage(x_hat + u, 1/rho);\n % update u\n u = u + (x_hat - z);\n % primal residual\n r = x - z;\n r_norm = norm(r);\n % dual residual\n s = rho * (z_old - z);\n s_norm = norm(s);\n % upper bound on primal residual\n eps_primal = sqrt(N) * eps_abs + eps_rel * max([norm(x), norm(z)]);\n eps_dual = sqrt(N) * eps_abs + eps_rel * norm(rho*u);\n if verbose\n % value of objective function\n objective_value = objective(x);\n fprintf('%3d\\t%10.4f\\t%10.4f\\t%10.4f\\t%10.4f\\t%10.2f\\n', k, ...\n r_norm, eps_primal, s_norm, eps_dual, objective_value);\n end\n if r_norm < eps_primal && s_norm < eps_dual\n % We have achieved convergence\n break;\n end\n end\nend\n\n% objective value\nfunction obj = objective(x)\n obj = norm(x,1);\nend\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/library/+spx/+opt/+admm/bp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7385923346010239}} {"text": "function quad_error = monomial_quadrature ( dim_num, expon, point_num, ...\n weight, x, rule )\n\n%*****************************************************************************80\n%\n%% MONOMIAL_QUADRATURE applies a quadrature rule to a monomial.\n%\n% Discussion:\n%\n% This routine assumes that the integral being approximated is that of\n% a multidimensional monomial, integrated over the [-1,+1] hypercube,\n% with a Legendre weight (that is, w(x) = 1).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 March 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer EXPON(DIM_NUM), the exponents.\n%\n% Input, integer POINT_NUM, the number of points in the rule.\n%\n% Input, real WEIGHT(POINT_NUM), the quadrature weights.\n%\n% Input, real X(DIM_NUM,POINT_NUM), the quadrature points.\n%\n% Input, integer RULE, the index of the rule.\n% 1, \"CC\", Clenshaw Curtis Closed Fully Nested rule.\n% 2, \"F1\", Fejer 1 Open Fully Nested rule.\n% 3, \"F2\", Fejer 2 Open Fully Nested rule.\n% 4, \"GP\", Gauss Patterson Open Fully Nested rule.\n% 5, \"GL\", Gauss Legendre Open Weakly Nested rule.\n% 6, \"GH\", Gauss Hermite Open Weakly Nested rule.\n% 7, \"LG\", Gauss Laguerre Open Non Nested rule.\n%\n% Output, real QUAD_ERROR, the quadrature error.\n%\n\n%\n% Get the exact value of the integral of the monomial.\n%\n if ( 1 <= rule & rule <= 5 )\n exact = monomial_integral_legendre ( dim_num, expon );\n elseif ( rule == 6 )\n exact = monomial_integral_hermite ( dim_num, expon );\n elseif ( rule == 7 )\n exact = monomial_integral_laguerre ( dim_num, expon );\n end \n%\n% Evaluate the monomial at the quadrature points.\n%\n value = monomial_value ( dim_num, point_num, x, expon );\n%\n% Compute the quadrature sum.\n%\n quad = weight * value';\n%\n% Absolute error if EXACT = 0, relative error otherwise:\n%\n if ( exact == 0.0 )\n quad_error = abs ( quad - exact );\n else\n quad_error = abs ( quad - exact ) / abs ( 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/sandia_sparse/monomial_quadrature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7385923325674941}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n\n% DFT of a circularly shifted sequence\n\n\n\n% circular shift in time \nx=[ 1 0 3 4 7];\nm=2;\nxc=circshift(x',m);\nLeft=dft(xc);\nLeft.'\n\nX=dft(x);\nN=length(x);\nk=0:N-1;\nRight=X.*exp(-j*2*pi*m*k/N);\nRight.'\n\n\n% circular shift in frequency \nx=[ 1 0 3 4 7];\nN=length(x);\nn=0:N-1;\nm=2;\nLeft=dft(x.*exp(j*2*pi*n*m/N));\nLeft.'\n\nX=dft(x);\nRight=circshift(X.',m)\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/7/c77_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.738592330426563}} {"text": "function Res = AccSumK(p,K)\n%ACCSUMK Res represents K-fold faithful rounding of sum(p)\n%\n% Res = AccSumK(p,K)\n%\n%On return, Res represents a K-fold faithful rounding of sum(p), also in the \n% presence of underflow. Input vector p may be single or double precision.\n%\n%Implements Algorithm 6.4 from\n% S.M. Rump, T. Ogita, S. Oishi: Accurate Floating-point Summation II: \n% Sign, K-fold Faithful and Rounding to Nearest, Siam J. Sci. Comput., \n% 31(2):1269-1302, 2008.\n%Requires (4m+5K+3)n flops for m executions of repeat-until loop in the\n% first and one execution of the repeat-until loops in subsequent calls\n% of TransformK.\n%\n%Reference implementation! Slow due to interpretation!\n%\n\n% written 03/03/07 S.M. Rump\n% modified 05/09/09 S.M. Rump rounding to nearest, complex input\n%\n\n if ~isreal(p)\n Res = complex(AccSumK(real(p),K),AccSumK(imag(p),K));\n return\n end\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 isa(p,'double')\n nmax = 2^26-2; % nmax = 67,108,864\n else\n nmax = 2^12-2; % nmax = 4,094\n end\n if length(p)>nmax\n error(['maximum length of input vector for AccSumK ' int2str(nmax) '.'])\n end\n\n R = 0;\n if isa(p,'double'), prec='double'; else prec='single'; end\n Res = zeros(1,K,prec);\n [Res(1),R,p,sigma,Ms] = TransformK(p,R);\n if abs(Res(1))<=realmin(prec)\n if rndold, setround(rndold); end\n return\n end\n for k=2:K\n [Res(k),R,p,sigma,Ms] = TransformK(p,R,sigma,Ms);\n if abs(Res(k))<=realmin(prec)\n if rndold, setround(rndold); end\n return\n end\n end\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/AccSumK.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7385858029244019}} {"text": "%% Transient diffusion equation evaluated using FVTool\n%\n% adapted from A.A. Eftekhari by M.H.V. Werts (2020) \n%\n% GNU Octave 4.2.2 was used for development\n%\n% This script is intended to be run from the command line interface. \n% It is called in this manner from within the accompanying Jupyter \n% Python notebook. \n%\n% It should be inside the 'FVTool' directory tree as downloaded/cloned\n% from Github, under \n% './Examples/External/Diffusion1DSpherical_Analytic-vs-FVTool-vs-Fipy'\n%\n% Script calculates diffusion in a 1D spherical geometry for an 'infinite' \n% medium, with the initial condition that all mass at $t = 0$ is \n% homogeneously confined inside a sphere of radius $a$. This is sometimes\n% called a 'spherical initial condition'.\n%\n% see J. Crank (1975) \"The Mathematics of Diffusion\", 2nd Ed., \n% Clarendon Press (Oxford), pages 29-30 \n% Equation 3.8, Figure 3.1\n%\n% The transient diffusion equation reads\n%\n% $$\\alpha\\frac{\\partial c}{\\partial t}+\\nabla.\\left(-D\\nabla c\\right)=0,$$\n%\n% where $c$ is the independent variable (concentration, temperature, etc),\n% $D$ is the diffusion coefficient, and $\\alpha$ is a constant (1, here).\n%\n%\nclc; clear;\nmore off;\nrun('../../../FVToolStartUp.m')\n\n%% Define the domain and create a mesh structure\n% Here we work in a 1D spherical coordinate system (r coordinate)\nL = 10.0; % domain length\nNx = 2000; % number of cells\nm = createMeshSpherical1D(Nx, L);\n\n%% Create the boundary condition structure\nBC = createBC(m); % all Neumann boundary condition structure\n\n%% define the transfer coeffs\nD = createCellVariable(m, 1.0);\nalfa = createCellVariable(m, 1.0);\n\n%% define initial condition\nc_init = 0;\nc_old = createCellVariable(m, c_init, BC); % initial values\nr = c_old.domain.cellcenters.x;\nc_old.value(r<1.0) = 1.0;\n\n%% calculate volumes of FV cellslices\n% We use this for demonstrating mass conservation\ncellA = m.facecenters.x(1:end-1);\ncellB = m.facecenters.x(2:end);\ncellvol = 4/3 .* pi .* (cellB.^3 - cellA.^3);\ncellsum = sum(cellvol)\n\nc = c_old; % assign the old value of the cells to the current values\n\nt = 0.0; % master time\ndeltat = 0.0625/20; % time step\n\n% output total mass in the system\nm_tot = sum(c.value(2:end-1) .* cellvol);\nt,m_tot\n\n%% loop for \"time-stepping\" the solution\n% It outputs the spatial profile C(r) after\n% 20, 80 and 320 time-steps\n% This corresponds to t=0.0625, t=0.25 and t=1, respectively.\nti = 0\nfor s=[20,60,240]\n for n=1:s\n [M_trans, RHS_trans] = transientTerm(c, deltat, alfa);\n Dave = harmonicMean(D);\n Mdiff = diffusionTerm(Dave);\n [Mbc, RHSbc] = boundaryCondition(BC);\n M = M_trans-Mdiff+Mbc;\n RHS = RHS_trans+RHSbc;\n c = solvePDE(m,M, RHS);\n t += deltat;\n c_old = c;\n endfor\n m_tot = sum(c.value(2:end-1) .* cellvol);\n n,t,m_tot\n % The following writes the result to a file\n % adapted from visualizeCells with domain.dimension = 1.8\n x = [c.domain.facecenters.x(1); c.domain.cellcenters.x; c.domain.facecenters.x(end)];\n cval = [0.5*(c.value(1)+c.value(2)); c.value(2:end-1); 0.5*(c.value(end-1)+c.value(end))];\n ti += s;\n filename = [\"diffusion1Dspherical_FVTool_tstep\",num2str(ti),\".mat\"]\n save('-6',filename,'x','cval');\nendfor\n\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Examples/External/Diffusion1DSpherical_Analytic-vs-FVTool-vs-Fipy/diffusion1Dspherical_FVTool.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7385857947343116}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n% \n% \tSystem response to sinusoidal inputs \n\n\nt=0:.1:30;\nx1=3*cos(t+pi/3);\nplot(t,x1);\nlegend('input signal x(t)')\nylim([-4 4]);\n\nfigure\nw0=1;\nHw0=(3*(j*w0)^2+4j*w0+2)/(-w0^2+j*w0+3)\nmagn=abs(Hw0)\nphas=angle(Hw0)\ny1=3*abs(Hw0)*cos(t+pi/3+angle(Hw0));\nplot(t,y1);\nlegend('system response')\nylim([-7 7]);\n\nfigure\nnum=[3 4 2];\nden=[1 1 3];\nyls=lsim(num,den,x1,t);\nplot(t,yls);\nlegend('system response by lsim')\n\n\nfigure\nplot(t,x1,t,y1,'o')\nlegend('x(t)','y(t)')\nylim([-7 9]);\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/8/c84a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.7385857826174508}} {"text": "% l1qc_logbarrier.m\n%\n% Solve quadratically constrained l1 minimization:\n% min ||x||_1 s.t. ||Ax - b||_2 <= \\epsilon\n%\n% Reformulate as the second-order cone program\n% min_{x,u} sum(u) s.t. x - u <= 0,\n% -x - u <= 0,\n% 1/2(||Ax-b||^2 - \\epsilon^2) <= 0\n% and use a log barrier algorithm.\n%\n% Usage: xp = l1qc_logbarrier(x0, A, At, b, epsilon, lbtol, mu, cgtol, cgmaxiter)\n%\n% x0 - Nx1 vector, initial point.\n%\n% A - Either a handle to a function that takes a N vector and returns a K \n% vector , or a KxN matrix. If A is a function handle, the algorithm\n% operates in \"largescale\" mode, solving the Newton systems via the\n% Conjugate Gradients algorithm.\n%\n% At - Handle to a function that takes a K vector and returns an N vector.\n% If A is a KxN matrix, At is ignored.\n%\n% b - Kx1 vector of observations.\n%\n% epsilon - scalar, constraint relaxation parameter\n%\n% lbtol - The log barrier algorithm terminates when the duality gap <= lbtol.\n% Also, the number of log barrier iterations is completely\n% determined by lbtol.\n% Default = 1e-3.\n%\n% mu - Factor by which to increase the barrier constant at each iteration.\n% Default = 10.\n%\n% cgtol - Tolerance for Conjugate Gradients; ignored if A is a matrix.\n% Default = 1e-8.\n%\n% cgmaxiter - Maximum number of iterations for Conjugate Gradients; ignored\n% if A is a matrix.\n% Default = 200.\n%\n% Written by: Justin Romberg, Caltech\n% Email: jrom@acm.caltech.edu\n% Created: October 2005\n%\n\nfunction xp = l1qc_logbarrier(x0, A, At, b, epsilon, lbtol, mu, cgtol, cgmaxiter) \n\nlargescale = isa(A,'function_handle');\n\nif (nargin < 6), lbtol = 1e-3; end\nif (nargin < 7), mu = 10; end\nif (nargin < 8), cgtol = 1e-8; end\nif (nargin < 9), cgmaxiter = 200; end\n\nnewtontol = lbtol;\nnewtonmaxiter = 50;\n\nN = length(x0);\n\n% starting point --- make sure that it is feasible\nif (largescale)\n if (norm(A(x0)-b) > epsilon)\n disp('Starting point infeasible; using x0 = At*inv(AAt)*y.');\n AAt = @(z) A(At(z));\n [w, cgres] = cgsolve(AAt, b, cgtol, cgmaxiter, 0);\n if (cgres > 1/2)\n disp('A*At is ill-conditioned: cannot find starting point');\n xp = x0;\n return;\n end\n x0 = At(w);\n end\nelse\n if (norm(A*x0-b) > epsilon)\n disp('Starting point infeasible; using x0 = At*inv(AAt)*y.');\n opts.POSDEF = true; opts.SYM = true;\n [w, hcond] = linsolve(A*A', b, opts);\n if (hcond < 1e-14)\n disp('A*At is ill-conditioned: cannot find starting point');\n xp = x0;\n return;\n end\n x0 = A'*w;\n end \nend\nx = x0;\nu = (0.95)*abs(x0) + (0.10)*max(abs(x0));\n\n% disp(sprintf('Original l1 norm = %.3f, original functional = %.3f', sum(abs(x0)), sum(u)));\n\n% choose initial value of tau so that the duality gap after the first\n% step will be about the origial norm\ntau = max((2*N+1)/sum(abs(x0)), 1);\n \nlbiter = ceil((log(2*N+1)-log(lbtol)-log(tau))/log(mu));\n% disp(sprintf('Number of log barrier iterations = %d\\n', lbiter));\n\ntotaliter = 0;\ndispProgress('Log barrier', 0, lbiter);\nfor ii = 1:lbiter\n\n [xp, up, ntiter] = l1qc_newton(x, u, A, At, b, epsilon, tau, newtontol, newtonmaxiter, cgtol, cgmaxiter);\n totaliter = totaliter + ntiter;\n \n% disp(sprintf('\\nLog barrier iter = %d, l1 = %.3f, functional = %8.3f, tau = %8.3e, total newton iter = %d\\n', ...\n% ii, sum(abs(xp)), sum(up), tau, totaliter));\n dispProgress('Log barrier',ii/lbiter);\n \n x = xp;\n u = up;\n \n tau = mu*tau;\n \nend\ndispProgress('Log barrier', 'Close');\n\nend\n \n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/@L1_Magic/private/l1qc_logbarrier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8175744717487329, "lm_q1q2_score": 0.7385102796227562}} {"text": "function [f_alias, cond_N] = sphArrayAliasLim(R, Nmic, maxN, mic_dirs_rad, mic_weights)\n%SPHARRAYALIASLIM Get estimates of the aliasing limit of a spherical array\n% \n% First estimate takes into account only the radius and a nominal order\n% that the array is expected to support, it is the simplest one and it\n% expresses the kR = maxN rule.\n% The second estimate is based on the number of microphones, and it can\n% be more relaxed than the first, if the nominal supported order is less\n% than maxN\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/gauss_kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7385094292251615}} {"text": "function [ v, more ] = tetrahedron_lattice_layer_point_next ( c, v, more )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_LATTICE_LAYER_POINT_NEXT: next tetrahedron lattice layer point.\n%\n% Discussion:\n%\n% The tetrahedron lattice layer L is bounded by the lines\n%\n% 0 <= X,\n% 0 <= Y,\n% 0 <= Z,\n% L - 1 < X / C(1) + Y / C(2) + Z/C(3) <= L.\n%\n% In particular, layer L = 0 always contains the single point (0,0).\n%\n% This function returns, one at a time, the points that lie within \n% a given tetrahedron 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 C(4), coefficients defining the \n% lattice layer in entries 1 to 3, and the laver index in C(4). \n% The coefficients should be positive, and C(4) must be nonnegative.\n%\n% Input/output, integer V(3). 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 = 3;\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:3) = 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% Can we simply increase X?\n%\n v(1) = v(1) + 1;\n\n lhs = ( c1n / c(1) ) * v(1) ...\n + ( c1n / c(2) ) * v(2) ...\n + ( c1n / c(3) ) * v(3);\n\n if ( lhs <= rhs2 )\n%\n% No. Increase Y, and set X so we just exceed RHS1...if possible.\n%\n else\n\n v(2) = v(2) + 1;\n\n v(1) = floor ( ( c(1) * ( rhs1 - ( c1n / c(2) ) * v(2) ...\n - ( c1n / c(3) ) * v(3) ) ) / c1n );\n v(1) = max ( v(1), 0 );\n\n lhs = ( c1n / c(1) ) * v(1) ...\n + ( c1n / c(2) ) * v(2) ...\n + ( c1n / c(3) ) * v(3);\n\n if ( lhs <= rhs1 )\n v(1) = v(1) + 1;\n lhs = lhs + c1n / c(1);\n end\n%\n% We have increased Y by 1. Have we stayed below the upper bound?\n%\n if ( lhs <= rhs2 )\n\n else\n%\n% No. Increase Z, and set X so we just exceed RHS1...if possible.\n%\n v(3) = v(3) + 1;\n v(2) = 0;\n v(1) = floor ( ( c(1) * ( rhs1 - ( c1n / c(2) ) * v(2) ...\n - ( c1n / c(3) ) * v(3) ) ) / c1n );\n v(1) = max ( v(1), 0 );\n\n lhs = ( c1n / c(1) ) * v(1) ...\n + ( c1n / c(2) ) * v(2) ...\n + ( c1n / c(3) ) * v(3);\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\n else\n more = 0;\n v(1:n) = 0;\n end\n\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/tetrahedron_lattice_layer_point_next.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7385094227639556}} {"text": "function [ n_data, x, fx ] = cin_values ( n_data )\n\n%*****************************************************************************80\n%\n%% CIN_VALUES returns some values of the alternate cosine integral function.\n%\n% Discussion:\n%\n% The alternate cosine integral is defined by\n%\n% CIN(X) = gamma + log(X) + integral ( 0 <= T <= X ) ( cos ( T ) - 1 ) / T dT\n%\n% In Mathematica, the function can be evaluated by:\n%\n% EulerGamma + Log[x] - CosIntegral[x]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 16;\n\n fx_vec = [ ...\n 0.6185256314820045E-01, ...\n 0.8866074809482194E-01, ...\n 0.1200260139539026E+00, ...\n 0.1557934976348559E+00, ...\n 0.1957873187759337E+00, ...\n 0.2398117420005647E+00, ...\n 0.3390780388012470E+00, ...\n 0.4516813164280685E+00, ...\n 0.5754867772153906E+00, ...\n 0.7081912003853150E+00, ...\n 0.8473820166866132E+00, ...\n 0.1207635200410304E+01, ...\n 0.1556198167561642E+01, ...\n 0.1862107181909382E+01, ...\n 0.2104491723908354E+01, ...\n 0.2274784183779546E+01 ];\n\n x_vec = [ ...\n 0.5E+00, ...\n 0.6E+00, ...\n 0.7E+00, ...\n 0.8E+00, ...\n 0.9E+00, ...\n 1.0E+00, ...\n 1.2E+00, ...\n 1.4E+00, ...\n 1.6E+00, ...\n 1.8E+00, ...\n 2.0E+00, ...\n 2.5E+00, ...\n 3.0E+00, ...\n 3.5E+00, ...\n 4.0E+00, ... \n 4.5E+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 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/cin_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927838, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7385094104396829}} {"text": "function [w, A, C, sbc, fpe, th]=ARFIT_arfit(v, pmin, pmax, selector, no_const)\n%ARFIT\tStepwise least squares estimation of multivariate AR model.\n%\n% [w,A,C,SBC,FPE,th]=ARFIT(v,pmin,pmax) produces estimates of the\n% parameters of an m-variate AR model of order p,\n%\n% v(k,:)' = w' + A1*v(k-1,:)' +...+ Ap*v(k-p,:)' + noise(C),\n%\n% where w is the (m x 1) intercept vector, A1, ..., Ap are (m x m)\n% coefficient matrices, and C is a (m x m) noise covariance\n% matrix. The estimated order p lies between pmin and pmax and is\n% chosen as the optimizer of Schwarz's Bayesian Criterion. \n% \n% The input matrix v must contain the time series data, with\n% columns v(:,l) representing m variables l=1,...,m and rows\n% v(k,:) representing n observations at different (equally\n% spaced) times k=1,..,n. Optionally, v can have a third\n% dimension, in which case the matrices v(:,:, itr) represent \n% the realizations (e.g., measurement trials) itr=1,...,ntr of the\n% time series. ARFIT returns least squares estimates of the\n% intercept vector w, of the coefficient matrices A1,...,Ap (as\n% A=[A1 ... Ap]), and of the noise covariance matrix C.\n%\n% As order selection criteria, ARFIT computes approximations to\n% Schwarz's Bayesian Criterion and to the logarithm of Akaike's Final\n% Prediction Error. The order selection criteria for models of order\n% pmin:pmax are returned as the vectors SBC and FPE.\n%\n% The matrix th contains information needed for the computation of\n% confidence intervals. ARMODE and ARCONF require th as input\n% arguments.\n% \n% If the optional argument SELECTOR is included in the function call,\n% as in ARFIT(v,pmin,pmax,SELECTOR), SELECTOR is used as the order\n% selection criterion in determining the optimum model order. The\n% three letter string SELECTOR must have one of the two values 'sbc'\n% or 'fpe'. (By default, Schwarz's criterion SBC is used.) If the\n% bounds pmin and pmax coincide, the order of the estimated model\n% is p=pmin=pmax. \n%\n% If the function call contains the optional argument 'zero' as the\n% fourth or fifth argument, a model of the form\n%\n% v(k,:)' = A1*v(k-1,:)' +...+ Ap*v(k-p,:)' + noise(C) \n%\n% is fitted to the time series data. That is, the intercept vector w\n% is taken to be zero, which amounts to assuming that the AR(p)\n% process has zero mean.\n%\n% Modified 14-Oct-00\n% 24-Oct-10 Tim Mullen (added support for multiple realizatons)\n%\n% Authors: Tapio Schneider\n% tapio@gps.caltech.edu\n%\n% Arnold Neumaier\n% neum@cma.univie.ac.at\n\n % n: number of time steps (per realization)\n % m: number of variables (dimension of state vectors) \n % ntr: number of realizations (trials)\n [n,m,ntr] = size(v); \n\n if (pmin ~= round(pmin) | pmax ~= round(pmax))\n error('Order must be integer.');\n end\n if (pmax < pmin)\n error('PMAX must be greater than or equal to PMIN.')\n end\n\n % set defaults and check for optional arguments\n if (nargin == 3) % no optional arguments => set default values\n mcor = 1; % fit intercept vector\n selector = 'sbc';\t % use SBC as order selection criterion\n elseif (nargin == 4) % one optional argument\n if strcmp(selector, 'zero')\n mcor = 0; % no intercept vector to be fitted\n selector = 'sbc';\t % default order selection \n else\n mcor = 1; \t\t % fit intercept vector\n end\n elseif (nargin == 5) % two optional arguments\n if strcmp(no_const, 'zero')\n mcor = 0; % no intercept vector to be fitted\n else\n error(['Bad argument. Usage: ', ...\n\t '[w,A,C,SBC,FPE,th]=AR(v,pmin,pmax,SELECTOR,''zero'')'])\n end\n end\n\n ne \t= ntr*(n-pmax); % number of block equations of size m\n npmax\t= m*pmax+mcor; % maximum number of parameter vectors of length m\n\n if (ne <= npmax)\n error('Time series (N = %u) too short.',size(v,1))\n end\n\n % compute QR factorization for model of order pmax\n [R, scale] = ARFIT_arqr(v, pmax, mcor);\n\n % compute approximate order selection criteria for models \n % of order pmin:pmax\n [sbc, fpe] = ARFIT_arord(R, m, mcor, ne, pmin, pmax);\n\n % get index iopt of order that minimizes the order selection \n % criterion specified by the variable selector\n [val, iopt] = min(eval(selector)); \n\n % select order of model\n popt = pmin + iopt-1; % estimated optimum order \n np = m*popt + mcor; % number of parameter vectors of length m\n\n % decompose R for the optimal model order popt according to \n %\n % | R11 R12 |\n % R=| |\n % | 0 R22 |\n %\n R11 = R(1:np, 1:np);\n R12 = R(1:np, npmax+1:npmax+m); \n R22 = R(np+1:npmax+m, npmax+1:npmax+m);\n\n % get augmented parameter matrix Aaug=[w A] if mcor=1 and Aaug=A if mcor=0\n if (np > 0) \n if (mcor == 1)\n % improve condition of R11 by re-scaling first column\n con \t= max(scale(2:npmax+m)) / scale(1); \n R11(:,1)\t= R11(:,1)*con; \n end;\n Aaug = (R11\\R12)';\n \n % return coefficient matrix A and intercept vector w separately\n if (mcor == 1)\n % intercept vector w is first column of Aaug, rest of Aaug is \n % coefficient matrix A\n w = Aaug(:,1)*con; % undo condition-improving scaling\n A = Aaug(:,2:np);\n else\n % return an intercept vector of zeros \n w = zeros(m,1);\n A = Aaug;\n end\n else\n % no parameters have been estimated \n % => return only covariance matrix estimate and order selection \n % criteria for ``zeroth order model'' \n w = zeros(m,1);\n A = [];\n end\n \n % return covariance matrix\n dof = ne-np; % number of block degrees of freedom\n C = R22'*R22./dof; % bias-corrected estimate of covariance matrix\n \n % for later computation of confidence intervals return in th: \n % (i) the inverse of U=R11'*R11, which appears in the asymptotic \n % covariance matrix of the least squares estimator\n % (ii) the number of degrees of freedom of the residual covariance matrix \n invR11 = inv(R11);\n if (mcor == 1)\n % undo condition improving scaling\n invR11(1, :) = invR11(1, :) * con;\n end\n Uinv = invR11*invR11';\n th = [dof zeros(1,size(Uinv,2)-1); Uinv];\n\n\n\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/ARFIT/ARFIT_arfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7385094089739165}} {"text": "function BPI = myFilteredBackprojectionCentralSlice(sinogram,thetas)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% filtered back projection in the frequency domain applying central slice\n% theorem-> schlegel & bille 9.2.3\n% modified by: Mark Bangert\n% m.bangert@dkfz.de 2011\n%\n% note: a) matlab puts the 0 frequency component of a fourier spectrum _not_\n% in the middle. we need to fumble around with fftshift.\n\n% figure out how big our picture is going to be.\nnumOfParallelProjections = size(sinogram,1);\nnumOfAngularProjections = length(thetas); \n\n% convert thetas to radians\nthetas = (pi/180)*thetas;\n\n% set up the backprojected image\nBPI = zeros(numOfParallelProjections,numOfParallelProjections);\n\n% find the middle index of the projections\nmidindex = floor(numOfParallelProjections/2) + 1;\n\n% set up the coords of the image\n[xCoords,yCoords] = meshgrid(ceil(-numOfParallelProjections/2):ceil(numOfParallelProjections/2-1));\n\n% set up filter\nrampFilter = [floor(numOfParallelProjections/2):-1:0 1:ceil(numOfParallelProjections/2-1)]';\n\n% loop over each projection\nfor i = 1:numOfAngularProjections\n\n % figure out which projections to add to which spots\n rotCoords = round(midindex + xCoords*sin(thetas(i)) + yCoords*cos(thetas(i)));\n\n % check which coords are in bounds\n indices = find((rotCoords > 0) & (rotCoords <= numOfParallelProjections));\n newCoords = rotCoords(indices);\n \n % filter\n filteredProfile = real( ifft( ifftshift( rampFilter.*fftshift(fft(sinogram(:,i)) ) ) ) );\n\n % summation\n BPI(indices) = BPI(indices) + filteredProfile(newCoords)./numOfAngularProjections;\n \n % visualization on the fly\n imagesc(BPI)\n drawnow\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/34608-ct-reconstruction-package/ctRecontruction/myFilteredBackprojectionCentralSlice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.798186784940666, "lm_q1q2_score": 0.7385063214908264}} {"text": "function dq = dqconj(dv,WHICHCONJ)\n\n% DQCONJ Dual quaternion conjugate\n%\n% DQ = DQCONJ(DV) returns the dual quaternion conjugate of the dual\n% quaternion DV. DV (resp. DQ) is a 8-vector representing a dual \n% quaternion or an array 8*N (column i represents dual quaternion i)\n% where N is the number of dual quaternions. The default type of \n% conjugate is 'point' (see below). DQ has the same size as DV.\n%\n% DQ = DQCONJ(DV,WHICHCONJ) returns the type of dual quaternion conjugate\n% corresponding to WHICHCONJ (DV = Q0+eps*Q1):\n% - 'point': mixed conjugate: dV* = Q0*-eps*Q1* (used for point\n% transformations).\n% - 'line': quaternion conjugate: dV* = Q0*+eps*Q1* (used for line\n% transformations).\n% - 'other': dual number conjugate: dV* = Q0-eps*Q1\n%\n% See also QCONJ, DQMULT\n\nif nargin < 2\n WHICHCONJ = 'point'; % default is 'mixed' conjugate' (point transformation)\nend\n\n\nsdv = size(dv);\nif sdv == [1 8]\n dv = dv.'; \n sdv = size(dv); \nend\n\n% wrong size\nif sdv(1) ~= 8 \n error('DualQuaternion:DQconj:wrongsize',...\n '%d rows in array dv. It should be 8.',sdv(1));\nend\n\nn = sdv(2);\ndq = sym(zeros(8,n));\nswitch WHICHCONJ\n case 'point' % % case of point transformation\n dq(1:4,:) = qconj(dv(1:4,:));\n dq(5:8,:) = -qconj(dv(5:8,:));\n case 'line' % case of line transformation\n dq(1:4,:) = qconj(dv(1:4,:));\n dq(5:8,:) = qconj(dv(5:8,:));\n case 'other' % dual number conjugate\n dq(1:4,:) = dv(1:4,:);\n dq(5:8,:) = -dv(5:8,:);\n otherwise\n error('DualQuaternion:DQconj:wrongsize',...\n 'WHICHCONJ must be ''point'', ''line'' or ''other'' ');\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/43393-dual-quaternion-symbolic-toolbox/Dual quaternion symbolic toolbox/dqconj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7384919450537003}} {"text": "function y = fshift(x,s)\n% FSHIFT Fractional circular shift\n% Syntax:\n%\n% >> y = fshift(x,s)\n%\n% FSHIFT circularly shifts the elements of vector x by a (possibly\n% non-integer) number of elements s. FSHIFT works by applying a linear\n% phase in the spectrum domain and is equivalent to CIRCSHIFT for integer\n% values of argument s (to machine precision).\n\n% (c) 2005 Francois Bouffard\n% fbouffar@gel.ulaval.ca\n\nneedtr = 0; if size(x,1) == 1; x = x(:); needtr = 1; end;\nN = size(x,1); \nr = floor(N/2)+1; f = ((1:N)-r)/(N/2); \np = exp(-j*s*pi*f)'; \ny = ifft(fft(x).*ifftshift(p)); if isreal(x); y = real(y); end;\nif needtr; y = y.'; 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/7886-fshift/fshift.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476385, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7384919428373989}} {"text": "function polygon_solid_angle_3d_test ( )\n\n%*****************************************************************************80\n%\n%% POLYGON_SOLID_ANGLE_3D_TEST tests POLYGON_SOLID_ANGLE_3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 May 2015\n%\n% Author:\n%\n% John Burkardt\n%\n dim_num = 3;\n test_num = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'POLYGON_SOLID_ANGLE_3D_TEST\\n' );\n fprintf ( 1, ' POLYGON_SOLID_ANGLE_3D computes the solid angle\\n' );\n fprintf ( 1, ' subtended by a planar polygon in 3D as viewed from\\n' );\n fprintf ( 1, ' a point P.\\n' );\n\n for test = 1 : test_num\n%\n% One eighth of sphere surface, on the unit sphere surface.\n%\n if ( test == 1 )\n\n n = 3;\n\n v = [ ...\n 1.0, 0.0, 0.0; ...\n 0.0, 1.0, 0.0; ...\n 0.0, 0.0, 1.0 ]';\n\n p(1:3,1) = [ 0.0; 0.0; 0.0 ];\n%\n% Reverse order of vertices.\n%\n elseif ( test == 2 )\n\n n = 3;\n\n v = [ ...\n 1.0, 0.0, 0.0; ...\n 0.0, 0.0, 1.0; ...\n 0.0, 1.0, 0.0 ]';\n\n p(1:3,1) = [ 0.0; 0.0; 0.0 ];\n%\n% One eighth of sphere surface, on the unit sphere surface, \n% translated by (1,2,3).\n%\n elseif ( test == 3 )\n\n n = 3;\n\n v = [ ...\n 2.0, 2.0, 3.0; ...\n 1.0, 3.0, 3.0; ...\n 1.0, 2.0, 4.0 ]';\n\n p(1:3,1) = [ 1.0; 2.0; 3.0 ];\n%\n% One eighth of sphere surface, but on sphere of radius 2.\n%\n elseif ( test == 4 )\n\n n = 3;\n\n v = [ ...\n 2.0, 0.0, 0.0; ...\n 0.0, 2.0, 0.0; ...\n 0.0, 0.0, 2.0 ]';\n\n p(1:3,1) = [ 0.0; 0.0; 0.0 ];\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' TEST # %d\\n', test );\n fprintf ( 1, '\\n' );\n\n r8vec_print ( dim_num, p, ' The viewing point P:' );\n\n r8mat_transpose_print ( dim_num, n, v, ' The polygon vertices V:' );\n\n solid_angle = polygon_solid_angle_3d ( n, v, p );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solid angle subtended: %f\\n', solid_angle );\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/polygon_solid_angle_3d_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8499711813581708, "lm_q1q2_score": 0.7384777271685933}} {"text": "function coeffs=terms2MultiDimPolyMat(termMat)\n%%TERMS2MULTIDIMPOLYMAT Given a multidimensional polynomial represented as\n% a 2D matrix of terms (monomials), convert it into a\n% hypermatrix of coefficients suitable for use with\n% functions such as polyValMultiDim and where convn can\n% be used to multiply two such polynomials.\n%\n%INPUTS: termMat An (n+1)XnumTerms matrix such that\n% termMat(:,i)=[c,a1,a2,...,an] is a monomial term where c\n% is the value of of the monomial coefficient and the\n% monomial is\n% x1^(a1-1)*x2^(a2-1)*x3^(a3-1)...xn^(an-1). The ordering\n% of the terms in termMat does not matter.\n%\n%OUTPUTS: coeffs A hypermatrix of the coefficients for the multivariate\n% polynomial. These are arranged such that\n% coeffs(a1,a2,a3...an) corresponds to the coefficient of an\n% x1^(a1-1)*x2^(a2-1)*x3^(a3-1)...xn^(an-1) term. Thus, the\n% number of indices coeffs takes is equal to the\n% dimensionality of x (not counting singleton dimensions at\n% the end of coeffs). Note that this ordering is the reverse\n% that used in the 1D polyval function that is built into\n% Matlab. The number of elements for each index in coeffs is\n% the maximum order of that dimension +1.\n%\n%This function is the opposite of multiDimHyperMat2Terms. See\n%multiDimHyperMat2Terms for usage examples.\n%\n%January 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumTerms=size(termMat,2);\nnumIdx=size(termMat,1)-1;\n\nnumDims=zeros(1,numIdx);\n\nif(isscalar(numDims))\n numDims=[numDims,1];\nend\n\nfor idx=1:numIdx\n numDims(idx)=max(termMat(idx+1,:))+1; \nend\n\ncoeffs=zeros(numDims);\nfor curTerm=1:numTerms \n idx=nDim2Index(numDims,termMat(2:end,curTerm)+1);\n coeffs(idx)=coeffs(idx)+termMat(1,curTerm);\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Polynomials/Generic_Multivariate_Polynomials/terms2MultiDimPolyMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7384777133385733}} {"text": "function FD = FermiDiract(z,nu)\n%% Fermi-Diract function\n% Implementation of the Fermi-Diract Statistical function\n% in latex words:\n%\n% $$F_\\nu(z)=\\frac{1}{\\Gamma(\\nu)} \\int_{0}^{\\infty}\\frac{x^{\\nu-1}}{z^{-1}e^x+1}\n% \\approx \\sum_{l=1}^{\\infty}(-1)^{l-1}\\frac{z^l}{l^\\nu}$$\n%\n% As we can notice this function is of the order $\\nu$ \n\nl = 1:50; % up to l = 50 to ensure a fair accuaracy\nfd = (-1).^(l-1) .* (z.^l) ./ (l.^nu);\nFD = sum(fd);\nreturn", "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/Coupled/FD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7384576166758502}} {"text": "function [Az, El, D] = topocent(X,dx)\n%TOPOCENT Transformation of vector dx into topocentric coordinate\n% system with origin at X.\n% Both parameters are 3 by 1 vectors.\n% Output: D vector length in units like the input\n% Az azimuth from north positive clockwise, degrees\n% El elevation angle, degrees\n\n%Kai Borre 11-24-96\n%Copyright (c) by Kai Borre\n%$Revision: 1.0 $ $Date: 1997/09/26 $\n\ndtr = pi/180;\n[phi,lambda,~] = togeod(6378137,298.257223563,X(1),X(2),X(3));\ncl = cos(lambda*dtr); sl = sin(lambda*dtr);\ncb = cos(phi*dtr); sb = sin(phi*dtr);\nF = [-sl -sb*cl cb*cl;\n cl -sb*sl cb*sl;\n 0 cb sb];\nlocal_vector = F'*dx;\nE = local_vector(1);\nN = local_vector(2);\nU = local_vector(3);\nhor_dis = sqrt(E^2+N^2);\nif hor_dis < 1.e-20\n Az = 0;\n El = 90;\nelse\n Az = atan2(E,N)/dtr;\n El = atan2(U,hor_dis)/dtr;\nend\nif Az < 0\n Az = Az+360;\nend\nD = sqrt(dx(1)^2+dx(2)^2+dx(3)^2);\n%%%%%%%%% end topocent.m %%%%%%%%%\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/example/gps_spp_test/easysuite/topocent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750413739075, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7383910075873585}} {"text": "clear all; close all;\nfigure(1)\n% underdetermined\nn=20; m=100\nA=rand(n,m); b=rand(n,1);\n\ncvx_begin;\nvariable x2(m)\nminimize( norm(x2,2) );\nsubject to\nA*x2 == b;\ncvx_end;\n\ncvx_begin;\nvariable x1(m)\nminimize( norm(x1,1) );\nsubject to\nA*x1 == b;\ncvx_end;\n\nsubplot(3,1,1), bar(x2,'FaceColor',[.6 .6 .6],'EdgeColor','k')\nsubplot(3,1,2), bar(x1,'FaceColor',[.6 .6 .6],'EdgeColor','k')\nsubplot(3,2,5), hist(x2,40)\nsubplot(3,2,6), hist(x1,40)\n\nsubplot(3,1,1), axis([0 100 -.2 .2]), subplot(3,1,2), axis([0 100 -.4 .4])\nsubplot(3,2,5), axis([-.15 .15 0 82]), set(gca,'Ytick',[0 40 80],'Xtick',[-0.1 0 0.1])\nh = findobj(gca,'Type','patch'); h.FaceColor = [0.6 0.6 0.6]; h.EdgeColor = 'k';\nsubplot(3,2,6), axis([-.15 .15 0 82]), set(gca,'Ytick',[0 40 80],'Xtick',[-0.1 0 0.1])\nh = findobj(gca,'Type','patch'); h.FaceColor = [0.6 0.6 0.6]; h.EdgeColor = 'k';\n\n%%\nclear A\nclear b\nclear x\nfigure(2)\n\n% overdetermined\nn=500; m=100;\nA=rand(n,m);\nb=rand(n,1);\nxdag=pinv(A)*b;\n\nlam=[0 0.1 0.5];\nfor j=1:3\n \n cvx_begin;\n variable x(m)\n minimize( norm(A*x-b,2) + lam(j)*norm(x,1) );\n cvx_end;\n \n subplot(4,1,j),bar(x,'FaceColor',[.6 .6 .6],'EdgeColor','k')\n subplot(4,3,9+j), hist(x,20)\nend\n\n\nfor j=1:3\n \n \n subplot(4,1,j), axis([0 100 -.15 .15])\n subplot(4,3,9+j), axis([-.15 .15 0 80]), set(gca,'Ytick',[0 40 80])\n h = findobj(gca,'Type','patch');\n h.FaceColor = [0.6 0.6 0.6];\n h.EdgeColor = 'k';\nend\n\n\n%%\n% matrix overdetermined system\n\nclear A\nclear b\nclear x\nfigure(3)\n\n% overdetermined\nn=300; m=60; p=20;\nA=rand(n,m); b=rand(n,p);\n\nlam=[0 0.1];\nfor j=1:2\n cvx_begin;\n variable x(m,p)\n minimize(norm(A*x-b,2) + lam(j)*norm(x,1));\n cvx_end;\n subplot(2,1,j), pcolor(x.'), colormap(hot), colorbar\nend\n\n%%\nsubplot(2,1,1), set(gca,'Fontsize',[15],'Xtick',[1 20 40 60],'Ytick',[1 10 20])\nsubplot(2,1,2), set(gca,'Fontsize',[15],'Xtick',[1 20 40 60],'Ytick',[1 10 20])\n\n\n\n\n\n\n\n", "meta": {"author": "dynamicslab", "repo": "databook_matlab", "sha": "d390d39d18489a4804ee87a143ae8db8a1f3010b", "save_path": "github-repos/MATLAB/dynamicslab-databook_matlab", "path": "github-repos/MATLAB/dynamicslab-databook_matlab/databook_matlab-d390d39d18489a4804ee87a143ae8db8a1f3010b/CH04/CH04_SEC03_1_OverUnderDetermined_production.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263737, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.738338677178543}} {"text": "function [x, y, z] = geodetic_to_ecf(lat, lon, alt)\n%GEODETIC_TO_ECF Convert geodetic coordinates to ECF\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n%\n%\n% Convert geodetic latitude, longitude, and altitude to ECF (Earth \n% Centered Fixed) coordinates.\n%\n% USAGE:\n% pos_ecf = geodetic_to_ecf(pos_lla)\n% [pos_ecf_x, pos_ecf_y, pos_ecf_z] = geodetic_to_ecf(lat, lon, alt)\n%\n% INPUTS:\n% pos_lla - required : geodetic latitude, longitude, and altitude [deg, deg, m]\n%\n% OUTPUTS:\n% pos_ecf - required : ecf x, y, z coordinates [m, m, m]\n%\n% NOTES:\n% Zhu, J. Conversion of Earth-centered, Earth-fixed coordinates to \n% geodetic coordinates. IEEE Transactions on Aerospace and Electronic\n% Systems, 30, 3 (July 1994), 957-962.\n%\n% VERSION:\n% 1.0\n% - Sean Hatch 20070911\n% - initial version\n% 1.1\n% - Wade Schwartzkopf 20130708\n% - vectorized and componentwise data handling\n%\n% TODO:\n\n% define constants\ne2 = 6.6943799901377997e-3; % eccentricity squared of Earth (WGS 84 value)\na = 6378137.0; % semimajor radius of the Earth (WGS 84 value)\n\n% Handle different forms in input arguments\nif nargin==3 % Componentwise inputs, separate arguments for lat,lon,alt\n % Nothing to do. Processing uses this form.\nelseif size(lat,1)==3 % Array of 3-element vectors\n alt = lat(3,:);\n lon = lat(2,:);\n lat = lat(1,:);\nelseif numel(lat)==3 % Horizontal 3-element vector\n alt = lat(3);\n lon = lat(2);\n lat = lat(1);\nelse\n error('WGS_84_NORM:INVALID_INPUTS', 'Invalid inputs.');\nend\n\n% calculate distance to surface of ellipsoid\nR = a ./ sqrt(1.0 - e2 .* sind(lat) .* sind(lat));\n\n% calculate coordinates\nx = (R + alt) .* cosd(lat) .* cosd(lon);\ny = (R + alt) .* cosd(lat) .* sind(lon);\nz = (R + alt - e2 .* R) .* sind(lat);\n\nif nargout < 2 % Matrix/vector form, rather than componentwise form, was requested\n x = [x; y; z];\nend\n\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Geometry/coordinates/geodetic_to_ecf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7383383787703296}} {"text": "function [L, D, P, rho] = ldlt_skew(A)\n%LDLT_SKEW Block LDL^T factorization for a skew-symmetric matrix.\n% Given a real, skew-symmetric A,\n% [L, D, P, RHO] = LDLT_SKEW(A) computes a permutation P,\n% a unit lower triangular L, and a block diagonal D\n% with 1x1 and 2x2 diagonal blocks, such that P*A*P' = L*D*L'.\n% A partial pivoting strategy of Bunch is used.\n% RHO is the growth factor.\n\n% Reference:\n% J. R. Bunch, A note on the stable decomposition of skew-symmetric\n% matrices. Math. Comp., 38(158):475-479, 1982.\n% N. J. Higham, Accuracy and Stability of Numerical Algorithms,\n% Second edition, Society for Industrial and Applied Mathematics,\n% Philadelphia, PA, 2002; chap. 11.\n\n% This routine does not exploit skew-symmetry and is not designed to\n% be efficient.\n\nif ~isreal(A) | ~isequal(triu(A,1)',-tril(A,-1))\n error('Must supply real, skew-symmetric matrix.')\nend\n\nn = length(A);\nk = 1;\nD = zeros(n);\nL = eye(n);\npp = 1:n;\nif nargout >= 4\n maxA = norm(A(:), inf);\n rho = maxA;\nend\n\nwhile k < n\n\n if max( abs(A(k+1:n,k)) ) == 0\n\n s = 1;\n % Nothing to do.\n\n else\n\n s = 2;\n\n if k < n-1\n [colmaxima, rowindices] = max( abs(A(k+1:n, k:k+1)) );\n [biggest, colindex] = max(colmaxima);\n row = rowindices(colindex)+k; col = colindex+k-1;\n\n % Permute largest element into (k+1,k) position.\n % NB: k<->col permutation must be done before k+1<->row one.\n A( [k, col], : ) = A( [col, k], : );\n A( :, [k, col] ) = A( :, [col, k] );\n A( [k+1, row], : ) = A( [row, k+1], : );\n A( :, [k+1, row] ) = A( :, [row, k+1] );\n L( [k, col], : ) = L( [col, k], : );\n L( :, [k, col] ) = L( :, [col, k] );\n L( [k+1, row], : ) = L( [row, k+1], : );\n L( :, [k+1, row] ) = L( :, [row, k+1] );\n pp( [k, col] ) = pp( [col, k] );\n pp( [k+1, row] ) = pp( [row, k+1] );\n end\n\n E = A(k:k+1,k:k+1);\n D(k:k+1,k:k+1) = E;\n C = A(k+2:n,k:k+1);\n temp = C/E;\n L(k+2:n,k:k+1) = temp;\n A(k+2:n,k+2:n) = A(k+2:n,k+2:n) + temp*C'; % Note the plus sign.\n % Restore skew-symmetry.\n A(k+2:n,k+2:n) = 0.5 * (A(k+2:n,k+2:n) - A(k+2:n,k+2:n)');\n\n if nargout >= 4, rho = max(rho, max(max(abs(A(k+2:n,k+2:n)))) ); end\n\n end\n\n k = k + s;\n if k >= n-2, D(k:n,k:n) = A(k:n,k:n); break, end;\n\nend\n\nif nargout >= 3, P = eye(n); P = P(pp,:); end\nif nargout >= 4, rho = rho/maxA; end\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/matrixcomp/ldlt_skew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7383383752216482}} {"text": "function mbasis = basis_matrix_overhauser_nonuni ( alpha, beta )\n\n%*****************************************************************************80\n%\n%% BASIS_MATRIX_OVERHAUSER_NONUNI sets up the nonuniform Overhauser spline basis matrix.\n%\n% Discussion:\n%\n% This basis matrix assumes that the data points P1, P2, P3 and\n% P4 are not uniformly spaced in T, and that P2 corresponds to T = 0,\n% and P3 to T = 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real ALPHA, BETA.\n% ALPHA = || P2 - P1 || / ( || P3 - P2 || + || P2 - P1 || )\n% BETA = || P3 - P2 || / ( || P4 - P3 || + || P3 - P2 || ).\n%\n% Output, real MBASIS(4,4), the basis matrix.\n%\n mbasis(1,1) = - ( 1.0 - alpha ) * ( 1.0 - alpha ) / alpha;\n mbasis(1,2) = beta + ( 1.0 - alpha ) / alpha;\n mbasis(1,3) = alpha - 1.0 / ( 1.0 - beta );\n mbasis(1,4) = beta * beta / ( 1.0 - beta );\n\n mbasis(2,1) = 2.0 * ( 1.0 - alpha ) * ( 1.0 - alpha ) / alpha;\n mbasis(2,2) = ( - 2.0 * ( 1.0 - alpha ) - alpha * beta ) / alpha;\n mbasis(2,3) = ( 2.0 * ( 1.0 - alpha ) ...\n - beta * ( 1.0 - 2.0 * alpha ) ) / ( 1.0 - beta );\n mbasis(2,4) = - beta * beta / ( 1.0 - beta );\n\n mbasis(3,1) = - ( 1.0 - alpha ) * ( 1.0 - alpha ) / alpha;\n mbasis(3,2) = ( 1.0 - 2.0 * alpha ) / alpha;\n mbasis(3,3) = alpha;\n mbasis(3,4) = 0.0;\n\n mbasis(4,1) = 0.0;\n mbasis(4,2) = 1.0;\n mbasis(4,3) = 0.0;\n mbasis(4,4) = 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/basis_matrix_overhauser_nonuni.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7383383743928051}} {"text": "function mean = dirichlet_mix_mean ( comp_num, elem_num, a, comp_weight )\n\n%*****************************************************************************80\n%\n%% DIRICHLET_MIX_MEAN returns the means of a Dirichlet mixture PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer COMP_NUM, the number of components in the Dirichlet\n% mixture density, that is, the number of distinct Dirichlet PDF's\n% that are mixed together.\n%\n% Input, integer ELEM_NUM, the number of elements of an observation.\n%\n% Input, real A(ELEM_NUM,COMP_NUM), the probabilities for\n% element ELEM_NUM in component COMP_NUM.\n% Each A(I,J) should be positive.\n%\n% Input, real COMP_WEIGHT(COMP_NUM), the mixture weights of the densities.\n% These do not need to be normalized. The weight of a given component is\n% the relative probability that that component will be used to generate\n% the sample.\n%\n% Output, real MEAN(ELEM_NUM), the means for each element.\n%\n comp_weight_sum = sum ( comp_weight );\n\n mean(1:elem_num) = 0.0;\n\n for comp_i = 1 : comp_num\n comp_mean(1:elem_num) = dirichlet_mean ( elem_num, a(1:elem_num,comp_i) );\n mean(1:elem_num) = mean(1:elem_num) ...\n + comp_weight(comp_i) * comp_mean(1:elem_num);\n end\n\n mean(1:elem_num) = mean(1:elem_num) / comp_weight_sum;\n\n return\nend\n", "meta": {"author": "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/dirichlet_mix_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7383383644850482}} {"text": "% SUMMARY: Calculate probability of gauss mix model\n% AUTHOR: QIUQIANG KONG, Queen Mary University of London\n% Created: 19-09-2015\n% Modified: 15-11-2015 Modify output size\n% 20-11-2015 debug the order of [p,M]\n% -----------------------------------------------------------\n% input\n% X input data; size: N*p; dim 1: num of data, dim 2: feature dim\n% pi prior of mix; dim 1: mix num\n% mu size: p*M; dim 1: feature dim, dim 2: mix num\n% Sigma size: p*p*M; dim 1,2: feature dim, dim 3: mix num\n% output\n% probs probability of input data, size: N*1\n% ===========================================================\nfunction probs = Gmmpdf(X, prior, mu, Sigma)\nN = size(X,1); % num of data\n[p,M] = size(mu); % mix num & feature dim\nprobs = zeros(N,1); % init output array\nfor m = 1:M\n probs = probs + prior(m) * mvnpdf(X, mu(:,m)', Sigma(:,:,m));\nend\nend", "meta": {"author": "qiuqiangkong", "repo": "matlab-hmm", "sha": "4d8d24199956c3c713b56e70be1d40f6ae4c550d", "save_path": "github-repos/MATLAB/qiuqiangkong-matlab-hmm", "path": "github-repos/MATLAB/qiuqiangkong-matlab-hmm/matlab-hmm-4d8d24199956c3c713b56e70be1d40f6ae4c550d/matlab-gmm/Gmmpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629193, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7383227658734349}} {"text": "function M = spm_meanm(A)\n% Compute barycentre of matrix exponentials\n% FORMAT M = spm_meanm(A)\n% A - A 3D array, where each slice is a matrix\n% M - the resulting mean\n%\n% Note that matrices should not be too dissimilar to each other or the\n% procedure fails.\n% See http://hal.archives-ouvertes.fr/hal-00699361/\n%__________________________________________________________________________\n% Copyright (C) 2012-2019 Wellcome Trust Centre for Neuroimaging\n\n% John Ashburner\n% $Id: spm_meanm.m 7563 2019-04-01 10:39:24Z guillaume $\n\n\nN = size(A,3);\nM = eye(size(A,1),size(A,2));\n\nfor iter = 1:1024\n S = zeros(size(M));\n for i=1:N\n L = real(logm(M\\A(:,:,i)));\n S = S + L;\n end\n S = S/N;\n M = M*expm(S);\n %imagesc(M); drawnow\n %fprintf('%d\\t%g\\n', iter,sum(S(:).^2));\n if sum(S(:).^2)<1e-20\n break;\n end\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/Longitudinal/spm_meanm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693674025232, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7381778723431107}} {"text": "function LL = dirichlet_score_family(counts, prior)\n% DIRICHLET_SCORE Compute the log marginal likelihood of a single family\n% LL = dirichlet_score(counts, prior)\n%\n% counts(a, b, ..., z) is the number of times parent 1 = a, parent 2 = b, ..., child = z\n% prior is an optional multidimensional array of the same shape as counts.\n% It defaults to a uniform prior.\n% \n% We marginalize out the parameters:\n% LL = log \\int \\prod_m P(x(i,m) | x(Pa_i,m), theta_i) P(theta_i) d(theta_i)\n\n\n% LL = log[ prod_j gamma(alpha_ij)/gamma(alpha_ij + N_ij) *\n% prod_k gamma(alpha_ijk + N_ijk)/gamma(alpha_ijk) ]\n% Call the prod_k term U and the prod_j term V.\n% We reshape all quantities into (j,k) matrices\n% This formula was first derived by Cooper and Herskovits, 1992.\n% See also \"Learning Bayesian Networks\", Heckerman, Geiger and Chickering, MLJ 95.\n\nns = mysize(counts);\nns_ps = ns(1:end-1);\nns_self = ns(end);\n\nif nargin < 2, prior = normalise(myones(ns)); end\n\n\nif 1\n prior = reshape(prior(:), [prod(ns_ps) ns_self]);\n counts = reshape(counts, [prod(ns_ps) ns_self]);\n %U = prod(gamma(prior + counts) ./ gamma(prior), 2); % mult over k\n LU = sum(gammaln(prior + counts) - gammaln(prior), 2);\n alpha_ij = sum(prior, 2); % sum over k\n N_ij = sum(counts, 2);\n %V = gamma(alpha_ij) ./ gamma(alpha_ij + N_ij);\n LV = gammaln(alpha_ij) - gammaln(alpha_ij + N_ij);\n %L = prod(U .* V);\n LL = sum(LU + LV);\nelse\n CPT = mk_stochastic(prior + counts);\n LL = sum(log(CPT(:) .* counts(:)));\nend\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/learning/dirichlet_score_family.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693716759488, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7381778609670254}} {"text": "function quality=meshquality(node,elem)\n%\n% quality=meshquality(node,elem)\n%\n% compute the Joe-Liu mesh quality measure of a tetrahedral mesh\n%\n% author: Qianqian Fang (fangq nmr.mgh.harvard.edu)\n% date: 2011/02/26\n%\n% input:\n% node: node coordinates of the mesh (nn x 3)\n% elem: element table of a tetrahedral mesh (ne x 4)\n%\n% output:\n% quality: a vector of the same length as size(elem,1), with \n% each element being the Joe-Liu mesh quality metric (0-1) of \n% the corresponding element. A value close to 1 represents\n% higher mesh quality (1 means equilateral tetrahedron); \n% a value close to 0 means nearly degenerated element.\n%\n% reference:\n% A. Liu, B. Joe, Relationship between tetrahedron shape measures, \n% BIT 34 (2) (1994) 268-287.\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nif(size(elem,2)>4)\n elem=elem(:,1:4);\nend\nenum=size(elem,1);\nvol=elemvolume(node,elem);\nedges=meshedge(elem);\ned=node(edges(:,1),:)-node(edges(:,2),:);\ned=sum((ed.*ed)');\ned=sum(reshape(ed,[enum length(ed)/enum])')';\n\nquality=12*((3*vol).^(2/3))./ed;\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/iso2mesh/meshquality.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.738175439726065}} {"text": "function [x, y] = findLinePoints(p1,p2);\n% \n% [x, y] = findLinePoints(p1,p2)\n%\n% Author: I think it was me. \n% Purpose:\n% Find the x,y values that fall along a line between p1 and p2.\n% \n% 2002.07.24 RFD & FWC- fixed bug in vertical and horizontal special cases.\n% (Was returning column vectors instead of row.)\n\nx1 = p1(1); y1 = p1(2);\nx2 = p2(1); y2 = p2(2);\n\nif y2 == y1\n if x1 == x2\n error;\n return;\n end\n x = [x1:x2]; y = y1*ones(1,length(x));\nelseif x1 == x2\n if y1 == y2\n error;\n return;\n end\n y = [y1:y2]; x = x1*ones(1,length(y));\nelse\n slope = (y2-y1)/(x2-x1);\n b = y1 - slope*x1; \n if abs(y2 - y1) > abs(x2 - x1)\n if y1 < y2, y = y1:y2;\n else, y = y2:y1;\n end\n x = round( (y - b) / slope);\n else\n if x1 < x2, x = x1:x2;\n else x = x2:x1;\n end\n y = round(slope*x + b);\n end\nend\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/ROI/findLinePoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.738175436584434}} {"text": "% A SYMBOLIC DERIVATION OF THE JACOBIAN MANIPULATOR OF A KUKA LBR IIWA 14\n%\n% Copyright (C) 2016, 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 jacobian_symbolic_kuka_iiwa\n% link lengths\n\nsyms q1 q2 q3 q4 q5 q6 q7\nrobot = load_robot('KUKA', 'LBR_IIWA_R820_COP')\n\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalpha = eval(robot.DH.alpha);\n\n% matrices DH\nA01 = dh_sym(q1, d(1), a(1), alpha(1));\nA12 = dh_sym(q2, d(2), a(2), alpha(2));\nA23 = dh_sym(q3, d(3), a(3), alpha(3));\nA34 = dh_sym(q4, d(4), a(4), alpha(4));\nA45 = dh_sym(q5, d(5), a(5), alpha(5));\nA56 = dh_sym(q6, d(6), a(6), alpha(6));\nA67 = dh_sym(q7, d(7), a(7), alpha(7));\n\nA02 = A01*A12;\nA03 = A02*A23;\nA04 = A03*A34;\nA05 = A04*A45;\nA06 = A05*A56;\nA07 = A06*A67;\nA07 = simplify(A07)\n \nz0 = [0 0 1]';\nz1 = A01(1:3,3);\nz2 = A02(1:3,3);\nz3 = A03(1:3,3);\nz4 = A04(1:3,3);\nz5 = A05(1:3,3);\nz6 = A06(1:3,3);\n\n% simplify expressions\nz2 = simplify(z2);\nz3 = simplify(z3);\nz4 = simplify(z4);\nz5 = simplify(z5);\nz6 = simplify(z6);\n\n\n\n \np07=A07(1:3,4);\np17=A07(1:3,4)-A01(1:3,4);\np27=A07(1:3,4)-A02(1:3,4);\np37=A07(1:3,4)-A03(1:3,4);\np47=A07(1:3,4)-A04(1:3,4);\np57=A07(1:3,4)-A05(1:3,4);\np67=A07(1:3,4)-A06(1:3,4);\n\n% Jacobian in linear speed\nJv = [cross(z0, p07) cross(z1, p17) cross(z2, p27) cross(z3, p37) cross(z4, p47) cross(z5, p57) cross(z6, p67)];\n% Jacobian in angular speed\nJw = [z0 z1 z2 z3 z4 z5 z6];\n\nJw = simplify(Jw)\nJv = simplify(Jv)\n% singularities = det(Jv)\nJs = [Jv; Jw]; \n\nq1 = 0.1\nq2 = 0.1\nq3 = 0.1\nq4 = 0.1\nq5 = 0.1\nq6 = 0.1\nq7 = 0.1\n\nJs = eval(Js)\n\nq = [q1 q2 q3 q4 q5 q6 q7]\nJ = manipulator_jacobian(robot, q)\n\nJ-Js\n\n\n\nTs = eval(A07)\nT = directkinematic(robot, q)\n\nT-Ts\n\n\n\n\n\n\n\nfunction A = dh_sym(theta, d, a, alpha)\nsyms q1 q2 q3 q4 q5 q6 q7\n% avoid almost zero elements in cos(alpha) and sin(alpha)\nca = cos(alpha);\nsa = sin(alpha);\nif abs(ca) < 1e-6\n ca = 0;\nend\nif abs(sa) < 1e-6\n sa = 0;\nend\n\n\nA=[cos(theta) -ca*sin(theta) sa*sin(theta) a*cos(theta);\n sin(theta) ca*cos(theta) -sa*cos(theta) a*sin(theta);\n 0 sa ca d;\n 0 0 0 1];\n \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/book/jacobian_symbolic_kuka_iiwa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7381754297137609}} {"text": "function [ grid_weight, grid_point ] = sparse_grid ( dim_num, level_max, ...\n rule, point_num )\n\n%*****************************************************************************80\n%\n%% SPARSE_GRID computes a sparse grid.\n%\n% Discussion:\n%\n% A Smolyak construction is used to create a multidimensional sparse grid.\n%\n% The user specifies:\n% * the spatial dimension of the quadrature region,\n% * the level that defines the Smolyak grid.\n% * the 1D quadrature rule.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 March 2008\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, controls the size of the final\n% sparse grid.\n%\n% Input, integer RULE, the index of the rule.\n% 1, \"CC\", Clenshaw Curtis Closed Fully Nested rule.\n% 2, \"F1\", Fejer 1 Open Fully Nested rule.\n% 3, \"F2\", Fejer 2 Open Fully Nested rule.\n% 4, \"GP\", Gauss Patterson Open Fully Nested rule.\n% 5, \"GL\", Gauss Legendre Open Weakly Nested rule.\n% 6, \"GH\", Gauss Hermite Open Weakly Nested rule.\n% 7, \"LG\", Gauss Laguerre Open Non Nested rule.\n%\n% Input, integer POINT_NUM, the number of points in the grid,\n% as determined by LEVELS_INDEX_SIZE.\n%\n% Output, real GRID_WEIGHT(POINT_NUM), the weights.\n%\n% Output, real GRID_POINT(DIM_NUM,POINT_NUM), the points.\n%\n if ( rule == 1 )\n [ grid_weight, grid_point ] = sparse_grid_cfn ( dim_num, level_max, ...\n rule, point_num );\n elseif ( 2 <= rule & rule <= 4 )\n [ grid_weight, grid_point ] = sparse_grid_ofn ( dim_num, level_max, ...\n rule, point_num );\n elseif ( 5 <= rule & rule <= 6 )\n [ grid_weight, grid_point ] = sparse_grid_own ( dim_num, level_max, ...\n rule, point_num );\n elseif ( 7 == rule ) \n [ grid_weight, grid_point ] = sparse_grid_onn ( dim_num, level_max, ...\n rule, point_num );\n else\n grid_weight = [];\n grid_point = [];\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPARSE_GRID - Fatal error!\\n' );\n fprintf ( 1, ' Illegal input rule index = %d\\n', rule );\n error ( 'SPARSE_GRID - 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/sandia_sparse/sparse_grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.73807530523513}} {"text": "function [p,f] = oct3bank(x); \n% OCT3BANK Simple one-third-octave filter bank. \n% OCT3BANK(X) plots one-third-octave power spectra of signal vector X. \n% Implementation based on ANSI S1.11-1986 Order-3 filters. \n% Sampling frequency Fs = 44100 Hz. Restricted one-third-octave-band \n% range (from 100 Hz to 5000 Hz). RMS power is computed in each band \n% and expressed in dB with 1 as reference level. \n%\n% [P,F] = OCT3BANK(X) returns two length-18 row-vectors with \n% the RMS power (in dB) in P and the corresponding preferred labeling \n% frequencies (ANSI S1.6-1984) in F. \n% \t\t\t\t\t\n% See also OCT3DSGN, OCT3SPEC, OCTDSGN, OCTSPEC.\n\n% Author: Christophe Couvreur, Faculte Polytechnique de Mons (Belgium)\n% couvreur@thor.fpms.ac.be\n% Last modification: Aug. 23, 1997, 10:30pm.\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% [2] S. J. Orfanidis, Introduction to Signal Processing, \n% Prentice Hall, Englewood Cliffs, 1996.\n\n\npi = 3.14159265358979; \nFs = 44100; \t\t\t\t% Sampling Frequency\nN = 3; \t\t\t\t\t% Order of analysis filters. \nF = [ 100 125 160, 200 250 315, 400 500 630, 800 1000 1250, ... \n\t1600 2000 2500, 3150 4000 5000 ]; % Preferred labeling freq. \nff = (1000).*((2^(1/3)).^[-10:7]); \t% Exact center freq. \t\nP = zeros(1,18);\nm = length(x); \n\n% Design filters and compute RMS powers in 1/3-oct. bands\n% 5000 Hz band to 1600 Hz band, direct implementation of filters. \nfor i = 18:-1:13\n [B,A] = oct3dsgn(ff(i),Fs,N);\n y = filter(B,A,x); \n P(i) = sum(y.^2)/m; \nend\n% 1250 Hz to 100 Hz, multirate filter implementation (see [2]). \n[Bu,Au] = oct3dsgn(ff(15),Fs,N); \t% Upper 1/3-oct. band in last octave. \n[Bc,Ac] = oct3dsgn(ff(14),Fs,N); \t% Center 1/3-oct. band in last octave. \n[Bl,Al] = oct3dsgn(ff(13),Fs,N); \t% Lower 1/3-oct. band in last octave. \nfor j = 3:-1:0\n x = decimate(x,2); \n m = length(x); \n y = filter(Bu,Au,x); \n P(j*3+3) = sum(y.^2)/m; \n y = filter(Bc,Ac,x); \n P(j*3+2) = sum(y.^2)/m; \n y = filter(Bl,Al,x); \n P(j*3+1) = sum(y.^2)/m; \nend\n\n% Convert to decibels. \nPref = 1; \t\t\t\t% Reference level for dB scale. \nidx = (P>0);\nP(idx) = 10*log10(P(idx)/Pref);\nP(~idx) = NaN*ones(sum(~idx),1);\n\n% Generate the plot\nif (nargout == 0) \t\t\t\n bar(P);\n ax = axis; \n axis([0 19 ax(3) ax(4)]) \n set(gca,'XTick',[2:3:18]); \t\t% Label frequency axis on octaves. \n set(gca,'XTickLabels',F(2:3:length(F))); % MATLAB 4.1c\n% set(gca,'XTickLabel',F(2:3:length(F))); % MATLAB 5.1\n xlabel('Frequency band [Hz]'); ylabel('Power [dB]');\n title('One-third-octave spectrum')\n% Set up output parameters\nelseif (nargout == 1) \t\t\t\n p = P; \nelseif (nargout == 2) \t\t\t\n p = P; \n f = F;\nend\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/oct3bank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7380474013084651}} {"text": "%[2016]-\"The whale optimization algorithm\"\n\n% (9/12/2020)\n\nfunction WOA = jWhaleOptimizationAlgorithm(feat,label,opts)\n% Parameters\nlb = 0;\nub = 1; \nthres = 0.5; \nb = 1; % constant\n\nif isfield(opts,'T'), max_Iter = opts.T; end\nif isfield(opts,'N'), N = opts.N; end\nif isfield(opts,'b'), b = opts.b; 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); \nfor i = 1:N\n\tfor d = 1:dim\n X(i,d) = lb + (ub - lb) * rand();\n\tend\nend\n% Fitness\nfit = zeros(1,N);\nfitG = inf;\nfor i = 1:N\n fit(i) = fun(feat,label,(X(i,:) > thres),opts);\n % Global best\n if fit(i) < fitG\n fitG = fit(i); \n Xgb = X(i,:);\n end\nend\n% Pre\ncurve = zeros(1,max_Iter);\ncurve(1) = fitG; \nt = 2; \nwhile t <= max_Iter\n\t% Define a, linearly decreases from 2 to 0 \n a = 2 - t * (2 / max_Iter);\n for i = 1:N\n % Parameter A (2.3)\n A = 2 * a * rand() - a;\n % Paramater C (2.4)\n C = 2 * rand();\n % Parameter p, random number in [0,1]\n p = rand();\n % Parameter l, random number in [-1,1]\n l = -1 + 2 * rand(); \n % Whale position update (2.6)\n if p < 0.5\n % {1} Encircling prey\n if abs(A) < 1\n for d = 1:dim\n % Compute D (2.1)\n Dx = abs(C * Xgb(d) - X(i,d));\n % Position update (2.2)\n X(i,d) = Xgb(d) - A * Dx;\n end\n % {2} Search for prey\n elseif abs(A) >= 1\n for d = 1:dim\n % Select a random whale\n k = randi([1,N]);\n % Compute D (2.7)\n Dx = abs(C * X(k,d) - X(i,d));\n % Position update (2.8)\n X(i,d) = X(k,d) - A * Dx;\n end\n end\n % {3} Bubble-net attacking \n elseif p >= 0.5\n for d = 1:dim\n % Distance of whale to prey\n dist = abs(Xgb(d) - X(i,d));\n % Position update (2.5)\n X(i,d) = dist * exp(b * l) * cos(2 * pi * l) + Xgb(d);\n end\n end\n % Boundary\n XB = X(i,:); XB(XB > ub) = ub; XB(XB < lb) = lb; \n X(i,:) = XB;\n end\n % Fitness\n for i = 1:N\n % Fitness \n fit(i) = fun(feat,label,(X(i,:) > thres),opts);\n % Global best\n if fit(i) < fitG\n fitG = fit(i);\n Xgb = X(i,:);\n end\n end\n curve(t) = fitG;\n fprintf('\\nIteration %d Best (WOA)= %f',t,curve(t))\n t = t + 1;\nend\n% Select features\nPos = 1:dim; \nSf = Pos((Xgb > thres) == 1);\nsFeat = feat(:,Sf);\n% Store results\nWOA.sf = Sf; \nWOA.ff = sFeat;\nWOA.nf = length(Sf);\nWOA.c = curve;\nWOA.f = feat;\nWOA.l = label;\nend\n\n\n\n\n\n", "meta": {"author": "JingweiToo", "repo": "Wrapper-Feature-Selection-Toolbox", "sha": "91b050142f331d2a58f7127aba91356b397379b3", "save_path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox", "path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox/Wrapper-Feature-Selection-Toolbox-91b050142f331d2a58f7127aba91356b397379b3/jWhaleOptimizationAlgorithm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7380473954804275}} {"text": "function [Pro,Res] = interpolationAMGa(A,isC) \n%% INTERPOLATIONAMGA construct prolongation and restriction matrices\n%\n% [Pro,Res] = INTERPOLATIONAMGA(A,isC) construct prolongation and\n% restriction matrices use matrix-dependent interpolation. Each fine nodes\n% use only one coarse node.\n%\n% In the input, A is a SPD matrix and isC is a logical array to indicate\n% nodes in coarse matrix. In the output Pro and Res are prolongation and\n% restriction matrices satisfying Res = Pro'.\n%\n% The submatrix A_{cf} is used to construct the interpolation of values on\n% fine nodes from that of coarse nodes. The weight is normalized to\n% preserve the constant.\n%\n% Example\n% load lakemesh\n% A = assemblematrix(node,elem);\n% [isC,As] = coarsenAMGc(A);\n% [Pro,Res] = interpolation(As,isC);\n%\n% See also: coarsenAMGc, amg\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details. \n\nN = size(A,1);\n%% Index map between coarse grid and fine grid\nallNode = (1:N)'; \nfineNode = allNode(~isC);\n% Nf = length(fineNode); \nNc = N-length(fineNode);\ncoarseNode = (1:Nc)'; % coarse node index\ncoarseNodeFineIdx = find(isC); % coarse node index in the fine grid\n\n%% Construct prolongation and restriction operator\nAfc = A(fineNode,coarseNodeFineIdx); % matrix-dependent interpolation\n[Dsum,j] = max(abs(Afc),[],2);\nidx = (Dsum ~= 0);\nip = [coarseNodeFineIdx; fineNode(idx)]; % fine node index\njp = [coarseNode; j(idx)]; % coarse node index\nsp = [ones(Nc,1); ones(length(j(idx)),1)]; % weight = 1;\nPro = sparse(ip,jp,sp,N,Nc);\nRes = Pro';", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/solver/interpolationAMGa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7380473948956315}} {"text": "function value = r8_normal_01_sample ( )\n\n%*****************************************************************************80\n%\n%% R8_NORMAL_01_SAMPLE returns a unit pseudonormal R8.\n%\n% Discussion:\n%\n% The standard normal probability distribution function (PDF) has\n% mean 0 and standard deviation 1.\n%\n% The Box-Muller method is used, which is efficient, but\n% generates two values at a time. \n%\n% Typically, we would use one value and save the other for the next call.\n% However, the fact that this function has saved memory makes it difficult\n% to correctly handle cases where we want to re-initialize the code,\n% or to run in parallel. Therefore, we will instead use the first value\n% and DISCARD the second.\n%\n% EFFICIENCY must defer to SIMPLICITY.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real VALUE, a sample of the standard normal PDF.\n%\n r1 = r8_uniform_01_sample ( );\n r2 = r8_uniform_01_sample ( );\n\n x = sqrt ( - 2.0 * log ( r1 ) ) * cos ( 2.0 * pi * r2 );\n\n value = 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/pdflib/r8_normal_01_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7380184940781664}} {"text": "function g=BaylissLinearTapering(sidelobedB,N,xPoints,a)\n%%BAYLISSLINEARTAPERING The Bayliss tapering is a set of complex amplitude\n% weights for a continuous linear (narrowband) aperture antenna\n% that will form a difference beam (odd symmetry about an axis)\n% and hold the four closest sidelobes to a desired level. Such a\n% tapering can be discretized and applied to the elements in a\n% circular phased array (An array of antenna elements can be\n% viewed as a discrete approximation to a continuous aperture).\n% This function will provide the tapering values at a set of\n% discrete points given by xPoints (the origin is taken to be the\n% center of the aperture). The radius of the aperture can either\n% be provided or is taken as value of the farthest point provided.\n%\n%INPUTS: sidelobedB The number of decibels of the ratio of the close-in\n% sidelobe voltages to the main lobe voltage. This must be a \n% negative number. A typical value is -30.\n% N The Bayliss tapering is computed using a certain number of\n% terms. Using too many terms can be undesirable as edge\n% illumination increases, as noted in [1]. If this parameter is\n% omitted or an empty matrix is passed, then the default of 17\n% is used. In [1], it is suggested that N be chosen to be\n% <2*a/lambda, where a is the radius of the aperture and\n% lambda the wavelength.\n% xyPoints An NX1 or 1XN set of N points at which the tapering values\n% should be evaluated. The center of the aperture is taken to\n% be the origin. \n% a The radius of the aperture. Tapering weights for points in\n% xPoints outside of the aperture are taken to be zero. If\n% this parameter is omitted or an empty matrix is passed, then\n% the radius is taken to be the distance of the farthest point\n% from the origin in xPoints.\n%\n%OUTPUTS: g The NX1 set of discretized Bayliss tapering values evaluated at\n% the points given in xPoints. All Bayliss tapering values are\n% imaginary. The coefficients are not normalized.\n%\n%This function implements the algorithm given in the appendix of in [1]\n%using the polynomial interpolation values in the table below Figure 4.\n%This approximation means that low sidelobe patterns (-45 dB and below)\n%will not have good fidelity sidelobes.\n%\n%EXAMPLE 1:\n%Here, we evaluate the tapering values for 30dB down on a fine grid of\n%points to plot what the amplitude and phase of the tapering weights looks\n%like.\n% numPoints=300;\n% xPoints=linspace(-1,1,numPoints);\n% %The Bayliss tapering weights, evaluated across the aperture.\n% a=1;%Aperture radius=1.\n% %gTest=BaylissLinear();\n% gBayliss=BaylissLinearTapering(-30,17,xPoints,a);\n% \n% figure(1)\n% clf\n% plot(xPoints,abs(gBayliss),'-b','linewidth',2)\n% h1=xlabel('x');\n% h2=ylabel('Imaginary Weight');\n% title('Bayliss Tapering Amplitude')\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n% \n% figure(2)\n% clf\n% plot(xPoints,angle(gBayliss),'-b','linewidth',2)\n% h1=xlabel('x');\n% h2=ylabel('Imaginary Weight');\n% title('Bayliss Tapering Phase')\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%EXAMPLE 2:\n%Here, we consider the array response when using tapering values for 30dB\n%sidelobes on a linear array with lambda/2 spacing between elements.\n% N=17;\n% sidelobedB=-30;\n% Nx=41;%There are 2*Nx+1 points total.\n% %Generate points symmetric about the origin.\n% xPoints=(-(Nx-1)/2):1/2:((Nx-1)/2);\n% g=BaylissLinearTapering(sidelobedB,N,xPoints);\n% \n% %Now, display the response with the tapering\n% T=diag(g);\n% [Rsp,U]=standardUVBeamPattern(T,xPoints,'NormRealVal');\n% \n% figure(2)\n% clf\n% plot(U,Rsp,'-b','LineWidth',2);\n% h1=xlabel('u');\n% h2=ylabel('Array Response');\n% title('Bayliss Weighted Array Response')\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%REFERENCES:\n%[1] E. T. Bayliss, \"Design of monopulse antenna difference patterns with\n% low sidelobes,\" The Bell System Technical Journal, vol. 47, no. 5, pp.\n% 623-650, May-Jun. 1968.\n%\n%August 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(N))\n N=17; \nend\n\n%Defined below Equation 41 in [1].\nmu=((0:(N-1))+1/2)';\n\n%This holds the coefficients for the interpolating polynomials given below\n%Figure 4 in [1]. The polynomials all take the desired sidelobe level in\n%decibels as an input parameter. The first row is for the term A, which\n%is a translation of the SNR parameter to a parameter in the paper. The\n%next four rows are xi_1 to xi_4, which are the locations of the first four\n%zeroes in the modified pattern. The final row is for p_0, which is related\n%to the point at which the peak of the asymptotic difference pattern=1.\npolyCoeffTable=[0.30387530,-0.05042922,-0.00027989,-0.00000343,-0.00000002;\n 0.98583020,-0.03338850, 0.00014064, 0.00000190, 0.00000001;\n 2.00337487,-0.01141548, 0.00041590, 0.00000373, 0.00000001;\n 3.00636321,-0.00683394, 0.00029281, 0.00000161, 0;\n 4.00518423,-0.00501795, 0.00021735, 0.00000088, 0;\n 0.47972120,-0.01456692,-0.00018739,-0.00000218,-0.00000001];\n\nA =polyCoeffTable(1,1)+sidelobedB*(polyCoeffTable(1,2)+sidelobedB*(polyCoeffTable(1,3)+sidelobedB*(polyCoeffTable(1,4)+sidelobedB*polyCoeffTable(1,5))));\nxi1=polyCoeffTable(2,1)+sidelobedB*(polyCoeffTable(2,2)+sidelobedB*(polyCoeffTable(2,3)+sidelobedB*(polyCoeffTable(2,4)+sidelobedB*polyCoeffTable(2,5))));\nxi2=polyCoeffTable(3,1)+sidelobedB*(polyCoeffTable(3,2)+sidelobedB*(polyCoeffTable(3,3)+sidelobedB*(polyCoeffTable(3,4)+sidelobedB*polyCoeffTable(3,5))));\nxi3=polyCoeffTable(4,1)+sidelobedB*(polyCoeffTable(4,2)+sidelobedB*(polyCoeffTable(4,3)+sidelobedB*(polyCoeffTable(4,4)+sidelobedB*polyCoeffTable(4,5))));\nxi4=polyCoeffTable(5,1)+sidelobedB*(polyCoeffTable(5,2)+sidelobedB*(polyCoeffTable(5,3)+sidelobedB*(polyCoeffTable(5,4)+sidelobedB*polyCoeffTable(5,5))));\n%p0 =polyCoeffTable(6,1)+sldelobedB*(polyCoeffTable(6,2)+sldelobedB*(polyCoeffTable(6,3)+sldelobedB*(polyCoeffTable(6,4)+sldelobedB*polyCoeffTable(6,5))));\n\nZ=zeros(N+1,1);\n%Equation 15\nZ(1)=0;%The Z(0) term\n%Now, the moved zeros\nZ(2)=xi1;\nZ(3)=xi2;\nZ(4)=xi3;\nZ(5)=xi4;\nfor k=5:N\n %The location of the non-moved zeros as given by Equation 13.\n Z(k+1)=sqrt(A^2+k^2);\nend\n\nsigma=(N+1/2)/Z(N+1);\n\nB=zeros(N,1);\nfor m=0:(N-1)\n %This loop implements Equation 47.\n n=1:(N-1);\n num=prod(1-((m+1/2)./(sigma*Z(1+n))).^2);\n l=[0:(m-1),(m+1):(N-1)];\n denom=prod(1-((m+1/2)./(l+1/2)).^2);\n %We just use C=1.\n B(m+1)=1/(2*1j)*(-1)^m*(m-1/2)^2*num/denom;\nend\n\nnumPoints=length(xPoints);\n\nif(nargin<4||isempty(a))\n %The maximum distance from the origin to a point is taken to be the\n %radius of the aperture.\n a=sqrt(max(sum(xPoints.^2,1)));\nend\n\n%The loop below implements Equation 41 in [1].\ng=zeros(numPoints,1);\nfor curPoint=1:numPoints\n if(abs(xPoints(curPoint))<=a)\n %The normalized radius at this point.\n p=pi*xPoints(curPoint)/a;\n g(curPoint)=g(curPoint)+sum(B.*sin(mu*p));\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/Signal_Processing/Array_Processing/Tapering/BaylissLinearTapering.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7380184895151318}} {"text": "function circle_integrals_test01 ( )\n\n%*****************************************************************************80\n%\n%% CIRCLE_INTEGRALS_TEST01 tests CIRCLE01_SAMPLE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n m = 2;\n n = 4192;\n test_num = 20;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST01\\n' );\n fprintf ( 1, ' Use CIRCLE01_SAMPLE to compare exact and\\n' );\n fprintf ( 1, ' estimated integrals along the circumference \\n' );\n fprintf ( 1, ' of the unit circle in 2D.\\n' );\n%\n% Get sample points.\n%\n seed = 123456789;\n [ x, seed ] = circle01_sample ( n, seed );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of sample points used is %d\\n', n );\n%\n% Randomly choose X, Y exponents.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' If any exponent is odd, the integral is zero.\\n' );\n fprintf ( 1, ' We restrict this test to randomly chosen even exponents.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Ex Ey MC-Estimate Exact Error\\n' );\n fprintf ( 1, '\\n' );\n\n for test = 1 : test_num\n\n [ e, seed ] = i4vec_uniform_ab ( m, 0, 5, seed );\n\n e(1:m) = e(1:m) * 2;\n\n value = monomial_value ( m, n, e, x );\n\n result = circle01_length ( ) * sum ( value(1:n) ) / n;\n exact = circle01_monomial_integral ( e );\n error = abs ( result - exact );\n\n fprintf ( 1, ' %2d %2d %14.6g %14.6g %10.2e\\n', ...\n e(1:m), result, exact, 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/circle_integrals/circle_integrals_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436727, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7380184721212023}} {"text": "function G = get_payoff_G_matrix_from_ygrid_3d( y_1, y_2, y_3, S_0s, sigmas, R, contractParams)\n%UNTITLED5 Summary of this function goes here\n% Detailed explanation goes here\n\npayoff_type = contractParams.payoff_type;\n\nrho12 = R(1,2);\nrho23 = R(2,3);\nrho13 = R(1,3);\n\ngamma = (rho12*rho13 - rho23)/(1 - rho12^2);\n\nif payoff_type == 1 || payoff_type == 2 % G = S_1, or G=S_2, or G=S_3\n dim = contractParams.dim;\n if dim == 1\n payoff = @(y1,y2,y3)S_0s(1)*exp(sigmas(1)*y1);\n elseif dim == 2\n payoff = @(y1,y2,y3)S_0s(2)*exp(sigmas(2)*(y2 + rho12*y1));\n else\n payoff = @(y1,y2,y3)S_0s(3)*exp(sigmas(3)*(rho13*y1 -gamma*y2 + y3));\n end\n \n\nelseif payoff_type == 5 % Geometric Basket Call / Put: G = (sqrt(S_1) * sqrt(S_2) - K)^+ and\n K = contractParams.K;\n if contractParams.call == 1\n payoff = @(y1,y2,y3) max(0, (S_0s(1)*exp(sigmas(1)*y1) * S_0s(2)*exp(sigmas(2)*(y2 + rho12*y1))* S_0s(3)*exp(sigmas(3)*(rho13*y1 -gamma*y2 + y3)))^(1/3) - K);\n else\n payoff = @(y1,y2,y3) max(0, K - (S_0s(1)*exp(sigmas(1)*y1) * S_0s(2)*exp(sigmas(2)*(y2 + rho12*y1))* S_0s(3)*exp(sigmas(3)*(rho13*y1 -gamma*y2 + y3)))^(1/3)); \n end\n \nelseif payoff_type == 6 % Arithmetic Basket Call / Put: G = (sqrt(S_1) * sqrt(S_2) - K)^+\n K = contractParams.K;\n if contractParams.call == 1\n payoff = @(y1,y2,y3) max(0, (1/3)*(S_0s(1)*exp(sigmas(1)*y1) + S_0s(2)*exp(sigmas(2)*(y2 + rho12*y1)) + S_0s(3)*exp(sigmas(3)*(rho13*y1 -gamma*y2 + y3))) - K);\n else\n payoff = @(y1,y2,y3) max(0, K - (1/3)*(S_0s(1)*exp(sigmas(1)*y1) + S_0s(2)*exp(sigmas(2)*(y2 + rho12*y1)) + S_0s(3)*exp(sigmas(3)*(rho13*y1 -gamma*y2 + y3)))); \n end\n \n\n \nend\n \nm_0 = length(y_1);\nG = zeros(m_0, m_0, m_0);\n\nfor i=1:m_0\n for j=1:m_0\n for k=1:m_0\n G(i,j,k) = payoff(y_1(i), y_2(j), y_3(k));\n end\n end\nend\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/CTMC/Diffusion_3D/get_payoff_G_matrix_from_ygrid_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7379519827815603}} {"text": "function v=dlyapsq(a,b)\n% Solves the discrete Lyapunov equation AV'VA' - V'V +BB' =0\n% V is upper triangular with real non-negative diagonal entries\n% this is equivalent to v=chol(dlyap(a,b*b')) but better conditioned numerically\n\n% Copyright (C) Mike Brookes 2002\n% Version: $Id: dlyapsq.m,v 1.4 2007/05/04 07:01:38 dmb Exp $\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[q,s]=schur(a');\n[q,s]=rsf2csf(q,s);\n[qd,r]=qr(b'*q,0);\n% save r for testing\nr0=r;\n[m,n]=size(r);\nu=zeros(n,n);\nif m==1\n for i=1:n-1\n in=i+1:n;\n si=s(i,i);\n aa=sqrt(1-si*si');\n u(i,i)=r(1)/aa;\n u(i,in)=(u(i,i)*si'*s(i,in)+aa*r(2:end))/(eye(n-i)-si'*s(in,in));\n r=aa*(u(i,i)*s(i,in)+u(i,in)*s(in,in))-si*r(2:end);\n end\n u(n,n)=r/sqrt(1-s(n,n)*s(n,n)');\n \nelse\n w=zeros(m,1); w(m)=1;\n em=eye(m);\n for i=1:n-m\n in=i+1:n;\n si=s(i,i);\n aa=sqrt(1-si*si');\n u(i,i)=r(1,1)/aa;\n u(i,in)=(u(i,i)*si'*s(i,in)+aa*r(1,2:end))/(eye(n-i)-si'*s(in,in));\n vv=aa*(u(i,i)*s(i,in)+u(i,in)*s(in,in))-si*r(1,2:end);\n rr=zeros(m,n-i);\n rr(1:m-1,:)=r(2:end,2:end);\n [qq,r]=qrupdate(em,rr,w,vv');\n end\n for i=n-m+1:n-1\n in=i+1:n;\n si=s(i,i);\n aa=sqrt(1-si*si');\n u(i,i)=r(1,1)/aa;\n u(i,in)=(u(i,i)*si'*s(i,in)+aa*r(1,2:end))/(eye(n-i)-si'*s(in,in));\n vv=aa*(u(i,i)*s(i,in)+u(i,in)*s(in,in))-si*r(1,2:end);\n rr=zeros(n-i+1,n-i);\n rr(1:n-i,:)=r(2:end,2:end);\n [qq,rr]=qrupdate(eye(n-i+1),rr,w(m-n+i:end),vv');\n r=rr(1:n-i,:);\n end\n \n u(n,n)=r/sqrt(1-s(n,n)*s(n,n)');\n \nend\n\nv=triu(qr(u*q'));\ndv=diag(v);\nix=dv~=0;\nv(ix,:)=diag(abs(dv(ix))./dv(ix))*v(ix,:);\nif isreal(a) & isreal(b)\n v=real(v);\nend\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/dlyapsq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7379519805064827}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Q = T2quaternion2(T)\n% Returns the quaternion corresponding to an homogeneous transformation \n% matrix T. Only the 3x3 rotation matrix in T is used.\n%\n% See also QPROD, QUATERNION2T.\n% The method implemented here was extracted from:\n% Accurate Computation of Quaternions from Rotation Matrices. \n% Soheil Sarabandi and Federico Thomas\n% http://www.iri.upc.edu/files/scidoc/2068-Accurate-Computation-of-Quaternions-from-Rotation-Matrices.pdf\n% Author: Arturo Gil. Universidad Miguel Hern�ndez de Elche. email:\n% arturo.gil@umh.es date: 21/04/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 Q = T2quaternion2(T)\n% use only the orientation from T\nR = T(1:3, 1:3);\n\nif R(1,1) + R(2,2) + R(3,3) > 0\n Q(1) = 0.5*sqrt(1+R(1,1) + R(2,2) + R(3,3));\nelse\n num = (R(3,2)-R(2,3))^2 + (R(1,3)-R(3,1))^2 + (R(2,1)-R(1,2))^2;\n den = 3 - R(1,1) - R(2,2) - R(3,3);\n Q(1) = 0.5*sqrt(num/den);\nend\n\nif R(1,1) - R(2,2) - R(3,3) > 0\n Q(2) = 0.5*sqrt(1 + R(1,1) - R(2,2) - R(3,3));\nelse\n num = (R(3,2)-R(2,3))^2 + (R(1,3)+R(3,1))^2 + (R(2,1)+R(1,2))^2;\n den = 3 - R(1,1) + R(2,2) + R(3,3);\n Q(2) = 0.5*sqrt(num/den);\nend\n\nif -R(1,1) + R(2,2) - R(3,3) > 0\n Q(3) = 0.5*sqrt(1 - R(1,1) + R(2,2) - R(3,3));\nelse\n num = (R(3,2)+R(2,3))^2 + (R(1,3)-R(3,1))^2 + (R(2,1)+R(1,2))^2;\n den = 3 + R(1,1) - R(2,2) + R(3,3);\n Q(3) = 0.5*sqrt(num/den);\nend\n\nif -R(1,1) - R(2,2) + R(3,3) > 0\n Q(4) = 0.5*sqrt(1 - R(1,1) - R(2,2) + R(3,3));\nelse\n num = (R(3,2)+R(2,3))^2 + (R(1,3)+R(3,1))^2 + (R(2,1)-R(1,2))^2;\n den = 3 + R(1,1) + R(2,2) + R(3,3);\n Q(4) = 0.5*sqrt(num/den);\nend\n\n\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/T2quaternion2_back.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.737951968347353}} {"text": "%computes the spectral spread from the magnitude spectrum\n%> called by ::ComputeFeature\n%>\n%> @param X: spectrogram (dimension FFTLength X Observations)\n%> @param f_s: sample rate of audio data \n%>\n%> @retval vss spectral spread (in Hz)\n% ======================================================================\nfunction [vss] = FeatureSpectralSpread (X, f_s)\n\n % get spectral centroid as index\n vsc = FeatureSpectralCentroid(X, f_s) * 2 / f_s * (size(X, 1)-1);\n\n % allocate memory\n vss = zeros(size(vsc));\n \n % compute spread\n for n = 1:size(X,2)\n vss(n) = (((0:size(X, 1)-1)-vsc(n)).^2 * X(:, n)) ./ sum(X(:, n));\n end\n vss = sqrt(vss);\n \n % convert from index to Hz\n vss = vss / (size(X, 1)-1) * f_s / 2;\n \n % avoid NaN for silence frames\n vss (sum(X, 1) == 0) = 0;\nend\n\n\n", "meta": {"author": "alexanderlerch", "repo": "ACA-Code", "sha": "85d7258d5fcee1ca52bac52f651d26b665717687", "save_path": "github-repos/MATLAB/alexanderlerch-ACA-Code", "path": "github-repos/MATLAB/alexanderlerch-ACA-Code/ACA-Code-85d7258d5fcee1ca52bac52f651d26b665717687/FeatureSpectralSpread.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7379053678008336}} {"text": "% LOWPASSFILTER - Constructs a low-pass butterworth filter.\n%\n% usage: f = lowpassfilter(sze, cutoff, n)\n% \n% where: sze is a two element vector specifying the size of filter \n% to construct [rows cols].\n% cutoff is the cutoff frequency of the filter 0 - 0.5\n% n is the order of the filter, the higher n is the sharper\n% the transition is. (n must be an integer >= 1).\n% Note that n is doubled so that it is always an even integer.\n%\n% 1\n% f = --------------------\n% 2n\n% 1.0 + (w/cutoff)\n%\n% The frequency origin of the returned filter is at the corners.\n%\n% See also: HIGHPASSFILTER, HIGHBOOSTFILTER, BANDPASSFILTER\n%\n\n% Copyright (c) 1999 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% October 1999\n% August 2005 - Fixed up frequency ranges for odd and even sized filters\n% (previous code was a bit approximate)\n\nfunction f = lowpassfilter(sze, cutoff, n)\n \n if cutoff < 0 | cutoff > 0.5\n\terror('cutoff frequency must be between 0 and 0.5');\n end\n \n if rem(n,1) ~= 0 | n < 1\n\terror('n must be an integer >= 1');\n end\n\n if length(sze) == 1\n\trows = sze; cols = sze;\n else\n\trows = sze(1); cols = sze(2);\n end\n\n % Set up X and Y matrices with ranges normalised to +/- 0.5\n % The following code adjusts things appropriately for odd and even values\n % of rows and columns.\n if mod(cols,2)\n\txrange = [-(cols-1)/2:(cols-1)/2]/(cols-1);\n else\n\txrange = [-cols/2:(cols/2-1)]/cols;\t\n end\n\n if mod(rows,2)\n\tyrange = [-(rows-1)/2:(rows-1)/2]/(rows-1);\n else\n\tyrange = [-rows/2:(rows/2-1)]/rows;\t\n end\n \n [x,y] = meshgrid(xrange, yrange);\n radius = sqrt(x.^2 + y.^2); % A matrix with every pixel = radius relative to centre.\n f = ifftshift( 1.0 ./ (1.0 + (radius ./ cutoff).^(2*n)) ); % The filter", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/去噪算法/CGCSF-master/functions/lowpassfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7377732099686376}} {"text": "function term = sdlfmjMeanCompute(sdlfmKern, t , option)\n\n% SDLFMJMEANCOMPUTE Jolt mean for the switching dynamical LFM model.\n% Computes the terms $r_d$ and $q_d$ that appear in the mean function \n% associated with the switching dynamical LFM model. If the mean function \n% is mu(t), then\n%\n% mu(t) = r_d(t)y_d(t_0) + q_d(t)\\dot{y}_d(t_0),\n%\n% where $y_d(t_0)$ is the initial condition associated to the position and\n% $\\dot{y}_d(t_0)$ is the initial condition associated to the velocity.\n% \n% FORMAT\n% DESC\n% ARG sdlfmKern : switching dynamical LFM kernel structure with the\n% parameters.\n% ARG t : input times for which the mean is to be computed.\n% RETURN term : the value of $r_d$.\n%\n% FORMAT\n% DESC\n% Computes the terms that appear in the mean function associated with the\n% switching dynamical LFM model.\n% ARG sdlfmKern : switching dynamical LFM kernel structure with the\n% parameters.\n% ARG t : input times for which the mean is to be computed.\n% ARG option : indicates which term of the mean should be computed. Option\n% 'Pos' computes the term $r_d$ and option 'Vel' computes $q_d$ that \n% accompanies the initial condition of the velocity.\n% RETURN term : the value of $r_d$ or $q_d$ depending of option.\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\n\n% KERN\n\nif nargin < 3\n option = 'Pos';\nend\n \nalpha = sdlfmKern.damper/(2*sdlfmKern.mass);\nomega = sqrt(sdlfmKern.spring/sdlfmKern.mass-alpha^2);\nfreq = omega*t;\n\nswitch option\n case 'Pos' \n term = (alpha^2/omega + omega)*exp(-alpha*t).*...\n ((omega^2 - alpha^2)*sin(freq) + 2*alpha*omega*cos(freq));\n case 'Vel'\n term = exp(-alpha*t).*((3*alpha*omega - alpha^3/omega)*sin(freq)...\n +(3*alpha^2- omega^2)*cos(freq)); \n otherwise\n error('No recognized option') \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/sdlfmjMeanCompute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850039701653, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.7377281719658194}} {"text": "function [W] = amuse(X)\n% BSS using eigenvalue value decomposition\n% Program written by A. Cichocki and R. Szupiluk\n% \n% X [m x N] matrix of observed (measured) signals,\n% W separating matrix,\n% y estimated separated sources\n% p time delay used in computation of covariance matrices\n% optimal time-delay default p= 1\n%\n% First stage: Standard prewhitening\n\n[m,N]=size(X);\nif nargin==1,\n n=m; % \n end;\n\nRxx=(X*X')/N;\n\n[Ux,Dx,Vx]=svd(Rxx);\n Dx=diag(Dx);\n% n=xxx;\n if n1e-199)); %Detection the number of sources\n Q= diag(real(sqrt(1./Dx(1:n))))*Ux(:,1:n)';\nend;\n%\n% else %assumes no noise\n% Q=inv(sqrtm(Rxx));\n% end;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Second stage: Fast separation using sorting EVD\n% notation the same as used in the Chapter 4\nXb=Q*X;\np=1; \n% paramter p can take here value different than 1\n% for example -1 or 2.\nN=max(size(Xb));\nXb=Xb-kron(mean(Xb')',ones(1,N));\n\nRxbxbp=(Xb(:,1:N-1)*Xb(:,2:N)')/(N-1);\nRxbxbp= Rxbxbp+Rxbxbp';\n[Vxb Dxb]=eig(Rxbxbp);\n[D1 perm]=sort(diag(Dxb));\nD1=flipud(D1);\nVxb=Vxb(:,flipud(perm));\nW = Vxb'*Q;\n%y = Vxb' * x1;\n\n\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/NMFLABSP_ver1.2/amuse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7377281547164685}} {"text": "function [U,c] = MgnCalibration(X)\n% performs magnetometer calibration from a set of data\n% using Merayo technique with a non iterative algoritm\n% J.Merayo et al. \"Scalar calibration of vector magnemoters\"\n% Meas. Sci. Technol. 11 (2000) 120-132.\n%\n% X : a Nx3 (or 3xN) data matrix\n% each row (columns) contains x, y, z measurements\n% N must be such that the data set describes\n% as completely as possible the 3D space\n% In any case N > 10\n% \n% The calibration tries to find the best 3D ellipsoid that fits the data set\n% and returns the parameters of this ellipsoid\n%\n% U : shape ellipsoid parameter, (3x3) upper triangular matrix\n% c : ellipsoid center, (3x1) vector\n%\n% Ellipsoid equation : (v-c)'*(U'*U)(v-c) = 1 \n% with v a rough triaxes magnetometer measurement\n%\n% calibrated measurement w = U*(v-c)\n%\n% author : Alain Barraud, Suzanne Lesecq 2008\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n[N,m] = size(X);\nif m>3&&N==3,X = X';N = m;m = 3;end;%check that X is not transposed\nif N<=10,U = [];c = [];return;end;%not enough data no calibration !!\n% write the ellipsoid equation as D*p=0\n% the best parameter is the solution of min||D*p|| with ||p||=1;\n% form D matrix from X measurements\nx = X(:,1); y = X(:,2); z = X(:,3); \nD = [x.^2, y.^2, z.^2, x.*y, x.*z, y.*z, x, y, z, ones(N,1)];\nD=triu(qr(D));%avoids to compute the svd of a large matrix\n[U,S,V] = svd(D);%because usually N may be very large\np = V(:,end);if p(1)<0,p =-p;end;\n% the following matrix A(p) must be positive definite\n% The optimization done by svd does not include such a constraint\n% With \"good\" data the constraint is allways satisfied\n% With too poor data A may fail to be positive definite\n% In this case the calibration fails\n%\nA = [p(1) p(4)/2 p(5)/2;\n p(4)/2 p(2) p(6)/2; \n p(5)/2 p(6)/2 p(3)];\n[U,ok] = fchol(m,A);\nif ~ok,U = [];c = [];return;end%calibration fails too poor data!!\nb = [p(7);p(8);p(9)];\nv = Utsolve(U,b/2,m);\nd = p(10);\ns = 1/sqrt(v*v'-d);\nc =-Usolve(U,v,m)';%ellipsoid center\nU = s*U;%shape ellipsoid parameter\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [A,ok] = fchol(n,A)\n% performs Cholesky factoristation\nA(1,1:n) = A(1,1:n)/sqrt(A(1,1));\nA(2:n,1) = 0;\nfor j=2:n\n A(j,j:n) = A(j,j:n) - A(1:j-1,j)'*A(1:j-1,j:n);\n if A(j,j)<=0,ok=0;break;end%A is not positive definite\n A(j,j:n) = A(j,j:n)/sqrt(A(j,j));\n A(j+1:n,j) = 0;\nend\nok=1;\nfunction x=Utsolve(U,b,n)\n% solves U'*x=b\nx(1) = b(1)/U(1,1);\nfor k=2:n\n x(k) = (b(k)-x(1:k-1)*U(1:k-1,k))/U(k,k);\nend\nfunction x=Usolve(U,b,n)\n% solves U*x=b\nx(n) = b(n)/U(n,n);\nfor k=n-1:-1:1\n x(k) = (b(k)-U(k,k+1:n)*x(k+1:n)')/U(k,k);\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/23398-magnetometers-calibration/MgnCalibration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846918, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.737664640801982}} {"text": "function[f,name]=tidefreq(str)\n%TIDEFREQ Frequencies of the eight major tidal components.\n%\n% [F,NAME]=TIDEFREQ returns the frequencies of the eight major tidal \n% components together with a string matrix containing their names. In\n% order of increasing frequency, these are \n% \n% Mf O1 P1 K1 N2 M2 S2 K2.\n%\n% The units are given in *radians* per hour. See Gill (1982) page 335.\n% \n% F=TIDEFREQ(STR) returns the frequency for the component named STR, \n% if STR is a string. F=TIDEFREQ(N) where N is a number also works.\n% \n% Usage: [f,name]=tidefreq;\n% f=tidefreq(str);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2005--2015 J.M. Lilly --- type 'help jlab_license' for details \n\nname=('MFO1P1K1N2M2S2K2');\n \n%Gill only gives first two decimal points\n%I got the more exact numbers from\n%http://oceanworld.tamu.edu/resources/ocng_textbook/chapter17/chapter17_04.htm\n\np(1)=327.85;\np(2)=25.8194;\np(3)=24.0659;\np(4)=23.9344;\np(5)=12.6584;\np(6)=12.4206;\np(7)=12.0000;\np(8)=11.9673;\n\nf=1./p;\nif nargin==1\n if ~ischar(str)\n f=f(str);\n else\n str=upper(str);\n ii=strfind(name,str);\n f=f((ii-1)/2+1); \n end\n clear name\nelse\n name=reshape(name,2,8)';\nend\n\nf=f*2*pi;", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jsphere/tidefreq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.737637785899797}} {"text": "function [pTS,fmin]=grTravSale(C)\n% Function [pTS,fmin]=grTravSale(C) solve the nonsymmetrical\n% traveling salesman problem.\n% Input parameter: \n% C(n,n) - matrix of distances between cities, \n% maybe, nonsymmetrical;\n% n - number of cities.\n% Output parameters: \n% pTS(n) - the order of cities;\n% fmin - length of way.\n% Uses the reduction to integer LP-problem:\n% Look: Miller C.E., Tucker A. W., Zemlin R. A. \n% Integer Programming Formulation of Traveling Salesman Problems. \n% J.ACM, 1960, Vol.7, p. 326-329.\n% Needed other products: MIQP.M.\n% This software may be free downloaded from site:\n% http://control.ee.ethz.ch/~hybrid/miqp/\n% Author: Sergiy Iglin\n% e-mail: siglin@yandex.ru\n% personal page: http://iglin.exponenta.ru\n\n% ============= Input data validation ==================\nif nargin<1,\n error('There are no input data!')\nend\nif ~isnumeric(C),\n error('The array C must be numeric!') \nend\nif ~isreal(C),\n error('The array C must be real!') \nend\ns=size(C); % size of array C\nif length(s)~=2,\n error('The array C must be 2D!') \nend\nif s(1)~=s(2),\n error('Matrix C must be square!')\nend\nif s(1)<3,\n error('Must be not less than 3 cities!')\nend\n\n% ============ Size of problem ====================\nn=s(1); % number of vertexes\nm=n*(n-1); % number of arrows\n\n% ============ Parameters of integer LP problem ========\nAeq=[]; % for the matrix of the boundary equations\nfor k1=1:n,\n z1=zeros(n);\n z1(k1,:)=1;\n z2=[z1;eye(n)];\n Aeq=[Aeq z2([1:2*n-1],setdiff([1:n],k1))];\nend\nAeq=[Aeq zeros(2*n-1,n-1)];\nA=[]; % for the matrix of the boundary inequations\nfor k1=2:n,\n z1=[];\n for k2=1:n,\n z2=eye(n)*(n-1)*(k2==k1);\n z1=[z1 z2(setdiff([2:n],k1),setdiff([1:n],k2))];\n end\n z2=-eye(n);\n z2(:,k1)=z2(:,k1)+1;\n A=[A;[z1 z2(setdiff([2:n],k1),2:n)]];\nend\nbeq=ones(2*n-1,1); % the right parts of the boundary equations\nb=ones((n-1)*(n-2),1)*(n-2); % the right parts of the boundary inequations\nC1=C'+diag(ones(1,n)*NaN);\nC2=C1(:);\nc=[C2(~isnan(C2));zeros(n-1,1)]; % the factors for objective function\nvlb=[zeros(m,1);-inf*ones(n-1,1)]; % the lower bounds\nvub=[ones(m,1);inf*ones(n-1,1)]; % the upper bounds\nH=zeros(n^2-1); % Hessian\n\n% ============= We solve the MIQP problem ==========\n[xmin,fmin]=MIQP(H,c,A,b,Aeq,beq,[1:m],vlb,vub);\n\n% ============= We return the results ==============\neik=round(xmin(1:m)); % the arrows of the way\ne1=[zeros(1,n-1);reshape(eik,n,n-1)];\ne2=[e1(:);0]; % we add zero to a diagonal\ne3=(reshape(e2,n,n))'; % the matrix of the way\npTS=[1 find(e3(1,:))]; % we build the way\nwhile pTS(end)>1, % we add the city to the way\n pTS=[pTS find(e3(pTS(end),:))];\nend\nreturn", "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/GraphTheory(图论)/basic/grTravSale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7376377842321825}} {"text": "% Test how accurately we can orthogonalize ill-conditioned bases of tangent\n% vectors. We test three metrics:\n% 1) Is Q actually orthonormal (the figure displays log(|Q'Q|); since Q'Q\n% should be identity, we hope to see 0 on diagonal and -inf everywhere\n% else.)\n% 2) Is A = QR? This is in the title of the plots.\n% 3) How much time does it take to compute?\n%\n% Nicolas Boumal, Oct. 5, 2017\n\nclear all;\nclc;\n\nM = spherefactory(100);\n\n% M = stiefelcomplexfactory(200, 56);\n% M = productmanifold(struct('S', spherefactory(5), 'R', rotationsfactory(3, 10)));\n\nx = M.rand();\n\n% Create a poorly conditioned basis\nA = cell(M.dim()-5, 1);\nA{1} = M.randvec(x);\nfor k = 2 : numel(A)\n A{k} = M.lincomb(x, 1, A{k-1}, 1e-6, M.randvec(x));\nend\n\nt1 = tic();\n[Q1, R1] = orthogonalize(M, x, A);\nt1 = toc(t1);\n\nt2 = tic();\n[Q2, R2] = orthogonalizetwice(M, x, A);\nt2 = toc(t2);\n\nt3 = tic();\n[Q3, R3] = orthogonalize_legacy(M, x, A);\nt3 = toc(t3);\n\n% To check if Q is really orthonormal\nG1 = grammatrix(M, x, Q1);\nG2 = grammatrix(M, x, Q2);\nG3 = grammatrix(M, x, Q3);\n\n% To check of QR = A\ndistsq = 0;\nfor k = 1 : numel(A)\n distsq = distsq + M.norm(x, M.lincomb(x, 1, lincomb(M, x, Q1(1:k), R1(1:k, k)), -1, A{k}))^2;\nend\ndist1 = sqrt(distsq);\n\ndistsq = 0;\nfor k = 1 : numel(A)\n distsq = distsq + M.norm(x, M.lincomb(x, 1, lincomb(M, x, Q2(1:k), R2(1:k, k)), -1, A{k}))^2;\nend\ndist2 = sqrt(distsq);\n\ndistsq = 0;\nfor k = 1 : numel(A)\n distsq = distsq + M.norm(x, M.lincomb(x, 1, lincomb(M, x, Q3(1:k), R3(1:k, k)), -1, A{k}))^2;\nend\ndist3 = sqrt(distsq);\n\n\nsubplot(1, 3, 1);\nimagesc(log10(abs(G1))); axis equal, axis tight; colorbar; set(gca, 'CLim', [-20, 0]);\ntitle(sprintf('MGS: CPU time: %g\\n||A - QR|| = %g', t1, dist1));\nsubplot(1, 3, 2);\nimagesc(log10(abs(G2))); axis equal, axis tight; colorbar; set(gca, 'CLim', [-20, 0]);\ntitle(sprintf('MGS-twice: CPU time: %g\\n||A - QR|| = %g', t2, dist2));\nsubplot(1, 3, 3);\nimagesc(log10(abs(G3))); axis equal, axis tight; colorbar; set(gca, 'CLim', [-20, 0]);\ntitle(sprintf('Legacy: CPU time: %g\\n||A - QR|| = %g', t3, dist3));\n", "meta": {"author": "NicolasBoumal", "repo": "manopt", "sha": "b8b54a6af8b965f7ae572972ba0d15787427744b", "save_path": "github-repos/MATLAB/NicolasBoumal-manopt", "path": "github-repos/MATLAB/NicolasBoumal-manopt/manopt-b8b54a6af8b965f7ae572972ba0d15787427744b/tests/test_orthogonalize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.737637780912625}} {"text": "function box_display_test06 ( )\n\n%*****************************************************************************80\n%\n%% BOX_DISPLAY_TEST06 compares several methods that reach degree 4 in X, 8 in Y.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BOX_DISPLAY_TEST06:\\n' );\n fprintf ( 1, ' Plot index sets for various anisotropic methods\\n' );\n fprintf ( 1, ' that reach degree 4 in X, 8 in Y.\\n' );\n fprintf ( 1, '\\n' );\n\n m = 10;\n n = 10;\n title_string = '';\n%\n% Total degree <= 8.\n%\n box_display ( m, n, @(x,y)x+y<=-1, @(x,y)2*x+y<=8, title_string );\n filename = 'degree48_total.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Created \"%s\".\\n', filename );\n%\n% Maximum degree <= 8.\n%\n box_display ( m, n, @(x,y)x+y<=-1, @(x,y)max(2*x,y)<=8, title_string );\n filename = 'degree48_max.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Created \"%s\".\\n', filename );\n%\n% Hyperbolic cross.\n%\n box_display ( m, n, @(x,y)x+y<=-1, @(x,y)(2*x+1)*(y+1)<=9, title_string );\n filename = 'degree48_hyper.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Created \"%s\".\\n', filename );\n%\n% Clenshaw-Curtis sparse grid.\n%\n% box_display ( m, n, @(x,y)x+y<=-1, @cc_aniso, title_string );\n% filename = 'degree48_cc.png';\n% print ( '-dpng', filename );\n% fprintf ( 1, ' Created \"%s\".\\n', filename );\n%\n% Smolyak: Log2(2*x) + Log2(y) <= Log2(L)\n%\n box_display ( m, n, @(x,y)x+y<=-1, @(x,y)log2(max(2*x,1))+log2(max(y,1))<=log2(8.1), title_string );\n filename = 'degree48_smolyak.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Created \"%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/box_display/box_display_test06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450968, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7376295007782163}} {"text": "function b = isPointOnLine3d(point, line, varargin)\n%ISPOINTONLINE3D Test if a 3D point belongs to a 3D line.\n%\n% B = isPointOnLine3d(POINT, LINE)\n% with POINT being [xp yp zp], and LINE being [x0 y0 z0 dx dy dz].\n% Returns 1 if point lies on the line, 0 otherwise.\n%\n% If POINT is an N-by-3 array of points, B is a N-by-1 array of booleans.\n%\n% If LINE is a N-by-6 array of lines, B is a N-by-1 array of booleans.\n%\n% B = isPointOnLine3d(POINT, LINE, TOL)\n% Specifies the tolerance used for testing location on 3D line.\n%\n% See also \n% lines3d, distancePointLine3d, linePosition3d, isPointOnLine\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inra.fr\n% Created: 2003-10-31\n% Copyright 2003-2022 INRA - TPV URPOI - BIA IMASTE\n\n% extract computation tolerance\ntol = 1e-14;\nif ~isempty(varargin)\n tol = varargin{1};\nend\n\n% size of inputs\nnp = size(point,1);\nnl = size(line, 1);\n\nif np == 1 || nl == 1 || np == nl\n % test if lines are colinear, using norm of the cross product\n b = bsxfun(@rdivide, vectorNorm3d( ...\n crossProduct3d(bsxfun(@minus, line(:,1:3), point), line(:,4:6))), ...\n vectorNorm3d(line(:,4:6))) < tol;\nelse\n % same test, but after reshaping arrays to manage difference of\n % dimensionality\n point = reshape(point, [np 1 3]);\n line = reshape(line, [1 nl 6]);\n b = bsxfun(@rdivide, vectorNorm3d( ...\n cross(bsxfun(@minus, line(:,:,1:3), point), line(ones(1,np),:,4:6), 3)), ...\n vectorNorm3d(line(:,:,4:6))) < tol;\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/isPointOnLine3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.843895100591521, "lm_q1q2_score": 0.7376294879897066}} {"text": "function geometry_test011 ( )\n\n%*****************************************************************************80\n%\n%% TEST011 tests CIRCLE_DIA2IMP_2D.\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 dim_num = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST011\\n' );\n fprintf ( 1, ' CIRCLE_DIA2IMP_2D converts a diameter to an\\n' );\n fprintf ( 1, ' implicit circle in 2D.\\n' );\n\n theta = 2.0;\n\n p1(1,1) = 2.0 + 5.0 * cos ( theta );\n p1(2,1) = 3.0 + 5.0 * sin ( theta );\n\n p2(1,1) = 2.0 - 5.0 * cos ( theta );\n p2(2,1) = 3.0 - 5.0 * sin ( theta );\n\n r8vec_print ( dim_num, p1, ' P1:' )\n r8vec_print ( dim_num, p2, ' P2:' )\n\n [ r, center ] = circle_dia2imp_2d ( p1, p2 );\n\n circle_imp_print_2d ( r, center, ' The implicit circle:' );\n\n return\nend\n", "meta": {"author": "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_test011.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606238, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7375244559318264}} {"text": "function [cc] = chaincode(b,unwrap)\n% Freeman Chain Code\n%\n% Description: Give Freeman chain code 8-connected representation of a\n% boundary\n% Author.....: Alessandro Mannini \n% Date.......: 2010, september\n%\n% usage:\n% --------------------------------------------------------\n% [cc] = chaincode(b,u)\n%\n% INPUT:\n% --------------------------------------------------------\n% b - boundary as np-by-2 array; \n% np is the number of pixels and each element is a pair (y,x) of\n% pixel coordinates\n% unwrap - (optional, default=false) unwrap code;\n% if enable phase inversions are eliminated\n% \n%\n% OUTPUT:\n% --------------------------------------------------------\n% cc is structure with the following fields:\n%\n% cc.code - 8-connected Freeman chain code as 1-by-np array (or\n% 1-by-(np-1) if the boundary isn't close)\n% cc.x0,cc.y0 - respectively the abscissa and ordinate of start point\n% cc.ucode - unwrapped 8-connected Freeman chain code (if required)\n%\n\n%\n%\n% used direction-to-code convention is: 3 2 1\n% \\ | /\n% 4 -- P -- 0\n% / | \\\n% 5 6 7\n% \n% and in terms of deltax,deltay if next pixel compared to the current:\n% --------------------------\n% | deltax | deltay | code |\n% |------------------------|\n% | 0 | +1 | 2 |\n% | 0 | -1 | 6 |\n% | -1 | +1 | 3 |\n% | -1 | -1 | 5 |\n% | +1 | +1 | 1 |\n% | +1 | -1 | 7 |\n% | -1 | 0 | 4 |\n% | +1 | 0 | 0 |\n% --------------------------\n%\n\n% check input arguments\nif nargin>2 \n error('Too many arguments');\nelseif nargin==0\n error('Too few arguments');\nelseif nargin==1\n unwrap=false;\nend \n% compute dx,dy by a circular shift on coords arrays by 1 element\nsb=circshift(b,[-1 0]);\ndelta=sb-b;\n% check if boundary is close, if not cut last element\nif abs(delta(end,1))>1 || abs(delta(end,2))>1\n delta=delta(1:(end-1),:);\nend\n% check if boundary is 8-connected\nn8c=find(abs(delta(:,1))>1 | abs(delta(:,2))>1);\nif size(n8c,1)>0 \n s='';\n for i=1:size(n8c,1)\n s=[s sprintf(' idx -> %d \\n',n8c(i))];\n end\n error('Curve isn''t 8-connected in elements: \\n%s',s);\nend\n\n\n% convert dy,dx pairs to scalar indexes thinking to them (+1) as base-3 numbers\n% according to: idx=3*(dy+1)+(dx+1)=3dy+dx+4 (adding 1 to have idx starting\n% from 1)\n% Then use a mapping array cm\n% --------------------------------------\n% | deltax | deltay | code | (base-3)+1 |\n% |-------------------------------------|\n% | 0 | +1 | 2 | 8 | \n% | 0 | -1 | 6 | 2 | \n% | -1 | +1 | 3 | 7 | \n% | -1 | -1 | 5 | 1 | \n% | +1 | +1 | 1 | 9 | \n% | +1 | -1 | 7 | 3 | \n% | -1 | 0 | 4 | 4 | \n% | +1 | 0 | 0 | 6 | \n% ---------------------------------------\n\nidx=3*delta(:,1)+delta(:,2)+5;\ncm([1 2 3 4 6 7 8 9])=[5 6 7 4 0 3 2 1];\n\n% finally the chain code array and the starting point\ncc.x0=b(1,2);\ncc.y0=b(1,1);\ncc.code=(cm(idx))';\n\n% If unwrapping is required, use the following algorithm\n%\n% if a(k), k=1..n is the original code and u(k) the unwrapped:\n%\n% - u(1)=a(1)\n% - u(k)=g(k), \n% g(k) in Z | (g(k)-a(k)) mod 8=0 and |g(k)-u(k-1)| is minimized \n%\nif (unwrap) \n a=cc.code;\n u(1)=a(1);\n la=size(a,1);\n for i=2:la\n n=round((u(i-1)-a(i))/8);\n u(i)=a(i)+n*8;\n end\n cc.ucode=u';\nend \n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29518-freeman-chain-code/chaincode.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7375244538173112}} {"text": "% this script represents the evolution of the covariance of an OU process in terms of the dispersion ellipsoid\n% see A. Meucci (2009) \n% \"Review of Statistical Arbitrage, Cointegration, and Multivariate Ornstein-Uhlenbeck\"\n% available at ssrn.com\n\n% Code by A. Meucci, April 2009\n% Most recent version available at www.symmys.com > Teaching > MATLAB\n\nclear; clc; close all\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% input parameters of multivariate OU process\nK=1;\nJ=1;\n\nx0=rand(K+2*J,1);\n\nMu=rand(K+2*J,1);\n\nA=rand(K+2*J,K+2*J)-.5;\nls=rand(K,1)-.5;\ngs=rand(J,1)-.5;\nos=rand(J,1)-.5;\n\nS=rand(K+2*J,K+2*J)-.5;\n\nts=.01*[0:10:100];\nNumSimul=10000;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% process inputs\nGamma=diag(ls);\nfor j=1:J\n G=[gs(j) os(j)\n -os(j) gs(j)];\n Gamma=blkdiag(Gamma,G);\nend\nTheta=A*Gamma*inv(A);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% one-step exact simulation\nSigma=S*S';\nX_0=repmat(x0',NumSimul,1);\n[X_t1, MuHat_t1, SigmaHat_t1]=OUstep(X_0,ts(end),Mu,Theta,Sigma);\n\n% multi-step simulation: exact and Euler approximation\nX_t=repmat(x0',NumSimul,1);\nX_tE=X_t;\nfor s=1:length(ts)\n Dt=ts(1);\n if s>1\n Dt=ts(s)-ts(s-1);\n end\n [X_t,MuHat_t,SigmaHat_t]=OUstep(X_t,Dt,Mu,Theta,Sigma);\n %[X_tE,MuHat_tE,SigmaHat_tE]=OUstepEuler(X_tE,Dt,Mu,Theta,Sigma);\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% plots \nPick=[K+2*J-1 K+2*J];\n\n% horizon simulations\nhold on\nh5=plot(X_t1(:,Pick(1)),X_t1(:,Pick(2)),'.');\nset(h5,'color','r','markersize',4)\n\n% horizon location\nhold on\nh4=plot(MuHat_t1(Pick(1)),MuHat_t1(Pick(2)),'.');\nset(h4,'color','k','markersize',5)\n\n% horizon dispersion ellipsoid \nhold on\nh3=TwoDimEllipsoid(MuHat_t1(Pick),SigmaHat_t1(Pick,Pick),2,0,0);\nset(h3,'color','k','linewidth',2);\n\n% starting point\nhold on\nh2=plot(x0(Pick(1)),x0(Pick(2)),'.');\nset(h2,'color','b','markersize',5)\n\n% starting generating dispersion ellipsoid\nhold on\nh1=TwoDimEllipsoid(x0(Pick),Sigma(Pick,Pick),2,0,0);\nset(h1,'color','b','linewidth',2);\n\nlegend([h1 h3],'generator','horizon');", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24120-review-of-statistical-arbitrage-cointegration-and-multivariate-ornstein-uhlenbeck/MultivariateOUnCointegration/Theory/S_CovarianceEvolution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7375244497234567}} {"text": "function fx = p15_fun ( option, nvar, x )\n\n%*****************************************************************************80\n%\n%% P15_FUN evaluates the function for problem 15.\n%\n% Title:\n%\n% The Trigger Circuit.\n%\n% Description:\n%\n% The current flow of a trigger circuit with an operational amplifier\n% is modeled. The variables are voltages, with X(6) the output\n% voltage and X(7) the input voltage.\n%\n% The function has the form\n%\n% F(X) = A * X + PHI ( X )\n%\n% where A is a 6 by 7 matrix, and PHI is a nonlinear term, that is,\n%\n% F(I) = SUM ( 1 <= J <= 7 ) A(I,J) * X(J) + PHI ( X )\n%\n% Options:\n%\n% Melhem lists the following limit points in X(7):\n%\n% ( 0.04936 0.54735 0.04944 0.04944 0.12920 1.16602 0.60185 )\n% ( 0.23577 0.66296 0.23759 0.23760 0.62083 9.60913 0.32286 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 August 20008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Rami Melhem, Werner Rheinboldt,\n% A Comparison of Methods for Determining Turning Points of Nonlinear Equations,\n% Computing,\n% Volume 29, Number 3, September 1982, pages 201-226.\n%\n% Gerd Poenisch, Hubert Schwetlick,\n% Computing Turning Points of Curves Implicitly Defined by Nonlinear\n% Equations Depending on a Parameter,\n% Computing,\n% Volume 26, Number 2, June 1981, pages 107-121.\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 function.\n%\n% Output, real FX(NVAR-1), the value of the function at X.\n%\n\n%\n% Get the linear coefficients.\n%\n array = p15_gx ( );\n%\n% Compute the linear portion of the function.\n%\n fx(1:nvar-1) = 0.0;\n\n for i = 1 : nvar - 1\n for j = 1 : nvar\n fx(i) = fx(i) + array(i,j) * x(j);\n end\n end\n%\n% Add the nonlinear terms.\n%\n fx(2) = fx(2) + 5.6D-08 * ( exp ( 25.0 * x(2) ) - 1.0 );\n fx(5) = fx(5) + 5.6D-08 * ( exp ( 25.0 * x(5) ) - 1.0 );\n fx(6) = fx(6) - 7.65 * atan ( 1962.0 * ( x(3) - x(1) ) ) / 0.201;\n\n return\nend\n", "meta": {"author": "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/p15_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.737500505563026}} {"text": "function out=prox_l1_squared(x,alpha)\n%PROX_L1_SQUARED computes the proximal operator of the function alpha*(norm(x(:),1)^2)\n%\n% Usage: \n% out = PROX_L1_SQUARED(x,alpha)\n% ===========================================\n% INPUT:\n% x - point to be projected (vector/matrix)\n% alpha - positive scalar\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 < 2)\n error ('usage: prox_l1_squared(x,alpha)') ;\nend\n\nif (alpha < 0)\n error('usage: prox_l1_squared(x,alpha) - alpha should be positive')\nend\n\n%setting eps to defalut value : 1e-10\neps = 1e-10 ;\n\nif (norm(x) < eps)\n out = x;\n return ;\nend\n\n%defining f on mu - to be used by the bisetion\nf=@(mu) sum(sum( max(sqrt(alpha) *abs(x)/sqrt(mu) - 2*alpha,0))) - 1 ;\n\nmu_min = 0 ;\nmu_max = 1 ;\nwhile(f(mu_max)> 0)\n mu_max = mu_max * 2 ;\nend\n\nfinal_mu = bisection(f,mu_min,mu_max,eps) ;\nlam = max(sqrt(alpha) * abs(x)/sqrt(final_mu) - 2 *alpha,0) ;\n\nout = (lam .* x) ./ (lam + 2 * 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_l1_squared.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7375005015019789}} {"text": "% MAIN - chain integrator\n%\n% Problem statement:\n%\n% Find the minimum-snap trajectory that moves a system between two boundary\n% points. Note that snap is the 4th derivative of position. Since the\n% dynamics are in first-order form, we need to include position, velocity,\n% acceleration, jerk in our state vector. We then set the control to be the\n% snap of the trajectory.\n%\n\nclc; clear;\naddpath ../../..\n\n%%%% Boundary-value problem:\n\nt0 = 0; %initial time\nx0 = [1;0]; %initial position\ndx0 = [0;0]; %initial velocity\nddx0 = [0;0]; %initial acceleration\ndddx0 = [0;0]; %initial jerk (derivative of acceleration)\nz0 = [x0;dx0;ddx0;dddx0]; %Full initial state\n\ntF = 1; %final time\nxF = [0;1]; %final position\ndxF = [0;0]; %final velocity\nddxF = [0;0]; %final acceleration\ndddxF = [0;0]; %final jerk (derivative of acceleration)\nzF = [xF;dxF;ddxF;dddxF]; %full final state\n\n\n%%%% Construct bounds struct, given problem specifications\n\nproblem.bounds.initialTime.low = t0;\nproblem.bounds.initialTime.upp = t0;\nproblem.bounds.finalTime.low = tF;\nproblem.bounds.finalTime.upp = tF;\n\nproblem.bounds.initialState.low = z0;\nproblem.bounds.initialState.upp = z0;\nproblem.bounds.finalState.low = zF;\nproblem.bounds.finalState.upp = zF;\n\n\n%%%% Construct a simple initial guess (linear between boundary)\nproblem.guess.time = [t0, tF];\nproblem.guess.state = [z0, zF];\nproblem.guess.control = [zeros(size(x0)), zeros(size(xF))];\n\n\n%%%% Define dynamics and objective functions:\n\n% Enforce the chain integrator dynamics:\nproblem.func.dynamics = @(t,z,u)( dynamics(z,u) );\n\n% Minimize the integral of the snap-squared along the trajectory.\n% Sum along each dimension of the state space. \nproblem.func.pathObj = @(t,z,u)( sum(u.^2,1) ); \n\n\n%%%% Select the method of choice:\n\n% problem.options.method = 'trapezoid';\n% problem.options.method = 'hermiteSimpson';\nproblem.options.method = 'chebyshev';\n% problem.options.method = 'rungeKutta';\n% problem.options.method = 'gpops'; % requires license for GPOPS-II\n\n\n%%%% Solve!\nsoln = optimTraj(problem);\n\n\n%%%% Unpack the solution\n\ntGrid = soln.grid.time;\nxGrid = soln.grid.state(1:2, :);\ndxGrid = soln.grid.state(3:4, :);\nddxGrid = soln.grid.state(5:6, :);\ndddxGrid = soln.grid.state(7:8, :);\nddddxGrid = soln.grid.control;\n\nt = linspace(tGrid(1), tGrid(end), 100);\nz = soln.interp.state(t);\nx = z(1:2,:);\ndx = z(3:4,:);\nddx = z(5:6,:);\ndddx = z(7:8,:);\nddddx = soln.interp.control(t);\n\n%%%% Plot the trajectory against time\nfigure(1); clf;\n\nsubplot(5,1,1); hold on;\nplot(t,x)\nplot(tGrid,xGrid,'ko','MarkerSize',8,'LineWidth',2);\n\nsubplot(5,1,2); hold on;\nplot(t,dx)\nplot(tGrid,dxGrid,'ko','MarkerSize',8,'LineWidth',2);\n\nsubplot(5,1,3); hold on;\nplot(t,ddx)\nplot(tGrid,ddxGrid,'ko','MarkerSize',8,'LineWidth',2);\n\nsubplot(5,1,4); hold on;\nplot(t,dddx)\nplot(tGrid,dddxGrid,'ko','MarkerSize',8,'LineWidth',2);\n\nsubplot(5,1,5); hold on;\nplot(t,ddddx)\nplot(tGrid,ddddxGrid,'ko','MarkerSize',8,'LineWidth',2);\n\n\n", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/minimumSnap/chainIntegrator/MAIN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7374604515159999}} {"text": "% Example of use for function 'power_flow_solver'.\n% Written by Dr. Yoash Levron, October 2012.\n%\n% All documentation may be obtained by typing:\n% 'HELP power_flow_solver' at the matlab command prompt.\n%\n% This script defines a simple power network\n% and uses the 'power_flow_solver' function to\n% compute the power flow in it.\n%\n% Associated file: 'power_flow_solver.m'\n\n\n%%%%%%% Define the network %%%%%%%\n% The network composes three buses.\n% bus 1 - (slack bus) a voltage source, E=1.0\n% bus 2 - a generator and a load.\n% bus 3 - a load.\n%\n% Define the line impedances:\nz12 = 0.05 + j*0.1; % impedance (inductive) connecting bus 1 to 2.\nz13 = 0.02 + j*0.05; % impedance (inductive) connecting bus 1 to 3.\nz23 = j*0.05; % impedance (inductive) connecting bus 2 to 3.\nz11 = -j*100; % shunt impedance (capacitive) at bus 1\nz22 = inf; % no shunt impedance at bus 2\nz33 = -j*40; % shunt impedance (capacitive) at bus 3\n\n% A matrix of the network impedances\nZmat = [z11 z12 z13;\n z12 z22 z23;\n z13 z23 z33];\n\n% compute the admittance matrix (admittamce = 1/impedance):\nYmat = 1./Zmat;\n\n% Define voltage at bus 1\nE1_phase = 0; % degree (reference phase angle).\nE1_mag = 1.0; % voltage magnitude\nE1 = E1_mag*exp(j*E1_phase*(pi/180));\n\n% Define generators and loads.\n% Pg&Qg - generators. Pl&Ql - loads.\nPg1=0; Qg1=0; Pl1=0; Ql1=0; % no power source on the slack bus.\nPg2=2; Qg2=0; Pl2=1; Ql2=1; % bus 2. generator and load.\nPg3=0; Qg3=0; Pl3=3; Ql3=0.5; % bus 3. a load.\n\n% sum generators and load to form united power sources.\n% (generators taken positive, loads taken negative).\nP1 = Pg1 - Pl1;\nP2 = Pg2 - Pl2;\nP3 = Pg3 - Pl3;\nQ1 = Qg1 - Ql1;\nQ2 = Qg2 - Ql2;\nQ3 = Qg3 - Ql3;\n\n% Define power vectors:\nPbus = [P1 P2 P3];\nQbus = [Q1 Q2 Q3];\n\n% run function to solve the power flow\n[Ebus, Ibus, Imat, iter] = ...\n power_flow_solver(Ymat, Pbus, Qbus, E1);\n\n% display results\nclc;\ndisp('--- SUMMARY OF RESULTS ---');\ndisp('number of iterations until convergence:');\ndisp(iter);\ndisp('voltage magnitudes');\ndisp(abs(Ebus.'));\ndisp('voltage phase angles (degree)');\ndisp(phase(Ebus.')*180/pi);\ndisp('current supplied by each source (amplitude)');\ndisp(abs(Ibus.'));\ndisp('Active power supplied by each source');\ndisp(real(Ebus.*conj(Ibus)));\ndisp('Reactive power supplied by each source');\ndisp(imag(Ebus.*conj(Ibus)));\ndisp('current in bus 1 --> bus 2');\ndisp(Imat(1,2));\ndisp('current in bus 1 --> bus 3');\ndisp(Imat(1,3));\ndisp('current in bus 2 --> bus 3');\ndisp(Imat(2,3));\ndisp('shunt currents in each bus (magnitude)');\ndisp(abs(diag(Imat).'));\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/38504-power-flow-solver-for-power-systems-analysis/test_flow_solver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7374604451654648}} {"text": "clear all; close all; clc\n\nn=100; L=4;\nx=linspace(0,L,n);\nf=(x.^2).'; % parabola with 100 data points\n\nM=21; % polynomial degree\nfor j=1:M\n phi(:,j)=(x.').^(j-1); % build matrix A\nend\n\ntrials=[2 10 100];\nfor j=1:3 \n for jj=1:trials(j)\n f=(x.^2+0.2*randn(1,n)).';\n a1=pinv(phi)*f; f1=phi*a1; E1(jj)=norm(f-f1)/norm(f);\n a2=phi\\f; f2=phi*a2; E2(jj)=norm(f-f2)/norm(f);\n [a3,stats]=lasso(phi,f,'Lambda',0.1); f3=phi*a3; E3(jj)=norm(f-f3)/norm(f);\n A1(:,jj)=a1; A2(:,jj)=a2; A3(:,jj)=a3;\n end\n A1m=mean(A1.'); A2m=mean(A2.'); A3m=mean(A3.');\n Err=[E1; E2; E3];\n \n subplot(3,3,j), bar(A1m), axis([0 21 -1 1.2])\n subplot(3,3,3+j), bar(A2m), axis([0 21 -1 1.2])\n subplot(3,3,6+j), bar(A3m), axis([0 21 -1 1.2]) \nend\n\n\n%subplot(3,3,j), bar(A1m,'FaceColor',[.6 .6 .6],'EdgeColor','k'), axis([0 21 -1 1.2])\n%subplot(3,3,3+j), bar(A2m,'FaceColor',[.6 .6 .6],'EdgeColor','k'), axis([0 21 -1 1.2])\n%subplot(3,3,6+j), bar(A3m,'FaceColor',[.6 .6 .6],'EdgeColor','k'), axis([0 21 -1 1.2])\n\n\n\n\n\n\n\n\n\n%%\nfigure(2)\n\nAtot=[A1m; A2m; A3m]; % average loadings of three methods\nAtot2=(Atot>0.2).*Atot; % threshold\nAtot3=[Atot; Atot2]; % combine both thresholded and not\n\nfigure(3), bar3(Atot.'), axis([0 4 0 20 0 1]), view(-70,38), set(gca,'Xtick',[],'Fontsize',[18])\nfigure(4), bar3(Atot2.'), axis([0 4 0 20 0 1]), view(-70,38), set(gca,'Xtick',[],'Fontsize',[18])\n\nn=200; L=8;\nx=linspace(0,L,n);\nx1=x(1:100); % train (interpolation)\nx2=x(101:200); % test (extrapolation)\n\nftrain=(x1.^2).'; % interpolated parabola x=[0,4]\nftest=(x2.^2).'; % extrapolated parbola x=[4,5]\n\nfor j=1:M\n phi_i(:,j)=(x1.').^(j-1); % interpolation key\n phi_e(:,j)=(x2.').^(j-1); % extrapolation key\nend\n\nfor jj=1:6 % compute inter/extra-polation scores\n ani=Atot3(jj,:).';\n fnai=phi_i*ani;\n Eni(jj)=norm(ftrain-fnai)/norm(ftrain);\n fnae=phi_e*ani;\n Ene(jj)=norm(ftest-fnae)/norm(ftest);\nend\n\nfigure(5)\nsubplot(3,2,1), bar(Eni)\nsubplot(3,2,2), bar(Ene)\n\nsubplot(3,2,3), bar(Eni), axis([0 7 0 0.01])\nsubplot(3,2,4), bar(Ene), axis([0 7 0 0.1])\n\nfigure(3)\nlegend('','','','Location','NorthEast')\nlegend boxoff\n\n%% Dendrograms\n\n\n\n\n", "meta": {"author": "dynamicslab", "repo": "databook_matlab", "sha": "d390d39d18489a4804ee87a143ae8db8a1f3010b", "save_path": "github-repos/MATLAB/dynamicslab-databook_matlab", "path": "github-repos/MATLAB/dynamicslab-databook_matlab/databook_matlab-d390d39d18489a4804ee87a143ae8db8a1f3010b/CH04/CH04_SEC06_1_kFoldValidation_production.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7374604374503649}} {"text": "function t = dec2twos(x, nbits)\n\n% DEC2TWOS Convert decimal integer to binary string two's complement.\n% \n% Usage: T = DEC2TWOS(X, NBITS)\n% \n% Converts the signed decimal integer given by X (either a scalar, vector,\n% or matrix) to the two's complement representation as a string. If X is a\n% vector or matrix, T(i, :) is the representation for X(i) (the shape of X\n% is not preserved).\n% \n% Example:\n% >> dec2twos([23 3 -23 -3])\n% \n% ans =\n% \n% 010111\n% 000011\n% 101001\n% 111101\n% \n% Inputs:\n% -X: decimal integers to convert to two's complement.\n% -NBITS: number of bits in the representation (optional, default is the\n% fewest number of bits necessary).\n% \n% Outputs:\n% -T: two's complement representation of X as a string.\n% \n% See also: TWOS2DEC, DEC2FIX, FIX2DEC, DEC2BIN, DEC2HEX, DEC2BASE.\n\nerror(nargchk(1, 2, nargin));\nx = x(:);\nmaxx = max(abs(x));\nnbits_min = nextpow2(maxx + (any(x == maxx))) + 1;\n\n% Default number of bits.\nif nargin == 1 || isempty(nbits)\n nbits = nbits_min;\nelseif nbits < nbits_min\n warning('dec2twos:nbitsTooSmall', ['Minimum number of bits to ' ...\n 'represent maximum input x is %i, which is greater than ' ...\n 'input nbits = %i. Setting nbits = %i.'], ...\n nbits_min, nbits, nbits_min)\n nbits = nbits_min;\nend\n\nt = repmat('0', numel(x), nbits); % Initialize output: Case for x = 0\nif any(x > 0)\n t(x > 0, :) = dec2bin(x(x > 0), nbits); % Case for x > 0\nend\nif any(x < 0)\n t(x < 0, :) = dec2bin(2^nbits + x(x < 0), nbits); % Case for x < 0\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/38889-twos-complement-binary-strings/dec2twos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7373921478289085}} {"text": "function p = predictOneVsAll(all_theta, X)\n%PREDICT Predict the label for a trained one-vs-all classifier. The labels \n%are in the range 1..K, where K = size(all_theta, 1). \n% p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions\n% for each example in the matrix X. Note that X contains the examples in\n% rows. all_theta is a matrix where the i-th row is a trained logistic\n% regression theta vector for the i-th class. You should set p to a vector\n% of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2\n% for 4 examples) \n\nm = size(X, 1);\nnum_labels = size(all_theta, 1);\n\n% You need to return the following variables correctly \np = zeros(size(X, 1), 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters (one-vs-all).\n% You should set p to a vector of predictions (from 1 to\n% num_labels).\n%\n% Hint: This code can be done all vectorized using the max function.\n% In particular, the max function can also return the index of the \n% max element, for more information see 'help max'. If your examples \n% are in rows, then, you can use max(A, [], 2) to obtain the max \n% for each row.\n% \n\n\n% x * all_theta' : 5000 * 10,每一行的每一个列值代表图像是1,2...10的可能性\n% use max(),M = max(A,[],dim) 沿着维度 dim 返回最大元素。例如,如果 A 为矩阵,则 max(A,[],2) 是包含每一行的最大值的列向量。\n% probaitilty代表每一行最大的值,p代表索引\n[probability, p] = max(sigmoid(X * all_theta'), [], 2);\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "xjwhhh", "repo": "AndrewNgMachineLearning", "sha": "d9d8491b315755ea3726bc366d72ba069712c363", "save_path": "github-repos/MATLAB/xjwhhh-AndrewNgMachineLearning", "path": "github-repos/MATLAB/xjwhhh-AndrewNgMachineLearning/AndrewNgMachineLearning-d9d8491b315755ea3726bc366d72ba069712c363/code/machine-learning-ex3/ex3/predictOneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768094082276, "lm_q2_score": 0.8596637505099168, "lm_q1q2_score": 0.7373921368265125}} {"text": "function [J,J_od,J_id,J_bl] = jdegree(CIJ)\n%JDEGREE Joint degree distribution\n%\n% [J,J_od,J_id,J_bl] = jdegree(CIJ);\n%\n% This function returns a matrix in which the value of each element (u,v)\n% corresponds to the number of nodes that have u outgoing connections \n% and v incoming connections.\n%\n% Input: CIJ, directed (weighted/binary) connection matrix\n%\n% Outputs: J, joint degree distribution matrix (shifted by one)\n% J_od, number of vertices with od>id.\n% J_id, number of vertices with id>od.\n% J_bl, number of vertices with id=od.\n%\n% Note: Weights are discarded.\n%\n%\n% Olaf Sporns, Indiana University, 2002/2006/2008\n\n\n% ensure CIJ is binary...\nCIJ = double(CIJ~=0);\n\nN = size(CIJ,1);\n\nid = sum(CIJ,1); % indegree = column sum of CIJ\nod = sum(CIJ,2)'; % outdegree = row sum of CIJ\n\n% Create the joint degree distribution matrix\n% Note: the matrix is shifted by one, to accomodate zero id and od in the first row/column.\n% Upper triangular part of the matrix has vertices with an excess of \n% outgoing edges (od>id)\n% Lower triangular part of the matrix has vertices with an excess of\n% outgoing edges (id>od)\n% Main diagonal has units with id=od\n\nszJ = max(max(id,od))+1;\nJ = zeros(szJ);\n\nfor i=1:N\n J(id(i)+1,od(i)+1) = J(id(i)+1,od(i)+1) + 1;\nend;\n\nJ_od = sum(sum(triu(J,1)));\nJ_id = sum(sum(tril(J,-1)));\nJ_bl = sum(diag(J));\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/jdegree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.8175744717487329, "lm_q1q2_score": 0.7373873120513901}} {"text": "function zList=genAllNestedZParenth(n,algorithm)\n%%GENALLNESTEDZPARENTH0 Generate all nested sets of n parenthesis pairs,\n% recording only the indices of the left parantheses.\n%\n%INPUTS: n The number of nested paranthesis pairs; n>=0. Passing zero will\n% result in an empty matrix being returned.\n% algorithm An optional parameter specifying the algorithm that should be\n% used to generate the parenthesis pairs. Possible values are:\n% 0 (The default if omitted or an empty matrix is passed) Use\n% the algorithm of Problem 2 of Section 7.2.1.6 of [1].\n% 1 Use algorithm N of Section 7.2.1.6 of [1].\n%\n%OUTPUTS: zList The nXnumPairs list of indices where the left parenthesis\n% goes.\n%\n%There is a total of CatalanNumber(n) possible arrangements of nested\n%parentheses.\n%\n%EXAMPLE:\n%To recreate the values in Table I of Section 7.2.1.6 of [1],\n%one can run\n% zList=genAllNestedZParenth(4)\n%\n%REFERENCES:\n%[1] D. E. Knuth, The Art of Computer Programming. Vol. 4A: Combinatorial\n% Algorithms, Part I, Boston: Addison-Wesley, 2011.\n%\n%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(algorithm))\n algorithm=0;\nend\n\nif(n==0)\n zList=[];\n return;\nend\n\nswitch(algorithm)\n case 0\n zList=genAllNestedZParenth0(n);\n case 1\n zList=genAllNestedZParenth1(n);\n otherwise\n error('Unknown algorithm specified.')\nend\n\nend\n\nfunction zList=genAllNestedZParenth0(n)\n%%GENALLNESTEDZPARENTH0 Generate all nested sets of n parenthesis pairs,\n% recording only the indices of the left parantheses using the\n% algorithm in Problem 2 of Section 7.2.1.6 of [1].\n%\n%REFERENCES\n%[1] D. E. Knuth, The Art of Computer Programming. Vol. 4A: Combinatorial\n% Algorithms, Part I, Boston: Addison-Wesley, 2011.\n%\n%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nif(n==1)\n zList=1;\n return;\nend\n\nnumBinTrees=CatalanNumber(n);\n%Allocate space.\nzList=zeros(n,numBinTrees);\n\n%Step T1 Initialize\nz=2*(0:n).'-1;\n\nfor curTree=1:numBinTrees\n %Step T2\n zList(:,curTree)=z(2:(n+1));\n \n %Step T3\n if(z(n-1+1)\n%\n% input: \n% pt: 3D points defined in a standard Cartesian system where a unitary\n% z-vector is (0,0,1), 3 columns for x, y and z \n% v1: the unitary z-vector for the target coordinate system\n% u1: the unitary z-vector for the source coordinate system, if ignored,\n% u1=(0,0,1) \n% p0: offset of the new coordinate system, if ignored, p0=(0,0,0)\n%\n% output:\n% newpt: the transformed 3D points\n%\n% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)\n%\n\nif(nargin<2)\n error('you must give at least pt and v1');\nend\nif(nargin==2)\n u1=[0,0,1];\nend\nif(nargin<=3)\n p0=[0,0,0];\nend\n\nu1=u1/norm(u1);\nv1=v1/norm(v1);\n\n[R,s]=rotmat2vec(u1,v1);\nnewpt=(R*pt'*s)';\n\nif(nargin>3)\n p0=p0(:)';\n newpt=newpt+repmat(p0,size(newpt,1),1);\nend", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/iso2mesh/rotatevec3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440397949314, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7371447108845302}} {"text": "function [out1, out2] = gpS00(X, P);\n%%function [out1, out2] = gpS00(X, {input, target, test});\n\n% gpS00: Gaussian process regression with \"squared negative exponential\"\n% covariance function and independent Gaussian noise model. Two modes are\n% possible: training and prediction: if no test data are given, the function\n% returns minus the log likelihood and its partial derivatives with respect to\n% the hyperparameters; this mode is used to fit the hyperparameters. If test\n% data are given, then (marginal) Gaussian predictions are computed, whose mean\n% and (noise free) variance are returned.\n%\n% usage: [fX dfX] = gpS00(X, input, target)\n% or: [mu S2] = gpS00(X, input, target, test)\n%\n% where:\n%\n% X is a (column) vector (of size D+2) of hyperparameters\n% input is a n by D matrix of training inputs\n% target is a (column) vector (of size n) of targets\n% test is a nn by D matrix of test inputs\n% fX is the returned value of minus log likelihood\n% dfX is a (column) vector (of size D+2) of partial derivatives\n% of minus the log likelihood wrt each of the hyperparameters\n% mu is a (column) vector (of size nn) of prediced means\n% S2 is a (column) vector (of size nn) of predicted variances\n%\n% where D is the dimension of the input. The form of the covariance function is\n%\n% C(x^p,x^q) = v^2 * exp[-(x^p - x^q)'*inv(P)*(x^p - x^q)/2]\n% + u^2 * delta_{p,q}\n%\n% where the first term is the squared negative exponential and the second term\n% with the kronecker delta is the noise contribution. The P matrix is diagonal\n% with \"Automatic Relevance Determination\" (ARD) or \"input length scale\"\n% parameters w_1^2,...,w_D^2; The hyperparameter v is the \"signal std dev\" and\n% u is the \"noise std dev\". All hyperparameters are collected in the vector X\n% as follows:\n%\n% X = [ log(w_1)\n% log(w_2) \n% .\n% log(w_D)\n% log(v)\n% log(u) ]\n%\n% Note: the reason why the log of the parameters are used in X is that this\n% often leads to a better conditioned (and unconstrained) optimization problem\n% than using the raw hyperparameters themselves.\n%\n% This function can conveniently be used with the \"minimize\" function to train\n% a Gaussian process:\n%\n% [X, fX, i] = minimize(X, 'gpS00', length, input, target)\n%\n% See also: minimize, hybrid\n% \n% (C) Copyright 1999 - 2003, Carl Edward Rasmussen (2003-08-08).\n\ninput=P{1};\ntarget=P{2};\nif length(P) == 3\n\ttest=P{3};\n\ttestmode=1;\nelse\n\ttestmode=0;\nend\n\n[n, D] = size(input); % number of examples and dimension of input space\ninput = input ./ repmat(exp(X(1:D))',n,1);\n\n% first, we write out the covariance matrix Q\n\nwarning off;\n\nQ = zeros(n,n);\nfor d = 1:D\n Q = Q + (repmat(input(:,d),1,n)-repmat(input(:,d)',n,1)).^2;\nend\nQ = exp(2*X(D+1))*exp(-0.5*Q);\n\nif ~testmode % if no test cases, we compute the negative log likelihood ...\n\n W = (Q+exp(2*X(D+2))*eye(n))\\eye(n); % W is inv (Q plus noise term)\n invQt = W*target; % don't compute determinant..\n [C,flag]=chol(Q+exp(2*X(D+2))*eye(n));\n logdetQ = 2*sum(log(diag(C))); % ..directly\n out1 = 0.5*logdetQ + 0.5*target'*invQt + 0.5*n*log(2*pi);\n\n % ... and its partial derivatives\n\n out2 = zeros(D+2,1); % set the size of the derivative vector\n W = W-invQt*invQt';\n Q = W.*Q;\n for d = 1:D\n out2(d) = ...\n sum(sum(Q.*(repmat(input(:,d),1,n)-repmat(input(:,d)',n,1)).^2))/2;\n end \n out2(D+1) = sum(sum(Q));\n out2(D+2) = trace(W)*exp(2*X(D+2));\n\nelse % ... otherwise compute (marginal) test predictions ...\n\n [nn, D] = size(test); % number of test cases and dimension of input space\n test = test ./ repmat(exp(X(1:D))',nn,1);\n\n a = zeros(n, nn); % compute the covariance between training and test cases\n for d = 1:D\n a = a + (repmat(input(:,d),1,nn)-repmat(test(:,d)',n,1)).^2;\n end\n a = exp(2*X(D+1))*exp(-0.5*a);\n\n % ... write out the desired terms\n\n if nargout == 1\n out1 = a'*((Q+exp(2*X(D+2))*eye(n))\\target); % predicted means\n else\n invQ = inv(Q+exp(2*X(D+2))*eye(n));\n out1 = a'*(invQ*target); % predicted means\n out2 = exp(2*X(D+1)) - sum(a.*(invQ*a),1)'; % predicted noise-free variance\n 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/External/spider/functions/gpS00.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7371326069463309}} {"text": "clear all; close all; clc\n\nn=100; L=4;\nx=linspace(0,L,n);\nf=(x.^2).'; % parabola with 100 data points\n\nM=20; % polynomical degree\nfor j=1:M\n phi(:,j)=(x.').^(j-1); % build matrix A\nend\n\nfor j=1:4\n fn=(x.^2+0.1*randn(1,n)).';\n an=pinv(phi)*fn; fna=phi*an; % least-square fit\n En=norm(f-fna)/norm(f);\n subplot(4,2,4+j),bar(an,'FaceColor',[.6 .6 .6],'EdgeColor','k')\nend\n\nsubplot(2,1,1), plot(x,f,'k'), hold on\n\n%% different regressions\nsubplot(2,1,1)\nlambda=0.1; phi2=phi(:,2:end);\nfor jj=1:100\n f=(x.^2+0.2*randn(1,n)).';\n a1=pinv(phi)*f; f1=phi*a1; E1(jj)=norm(f-f1)/norm(f);\n a2=phi\\f; f2=phi*a2; E2(jj)=norm(f-f2)/norm(f);\n [a3,stats]=lasso(phi,f,'Lambda',lambda); f3=phi*a3; E3(jj)=norm(f-f3)/norm(f);\n [a4,stats]=lasso(phi,f,'Lambda',lambda,'Alpha',0.8); f4=phi*a4; E4(jj)=norm(f-f4)/norm(f);\na5=robustfit(phi2,f);f5=phi*a5;E5(jj)=norm(f-f5)/norm(f);\na6=ridge(f,phi2,0.5,0);f6=phi*a6;E6(jj)=norm(f-f6)/norm(f);\n \n A1(:,jj)=a1;A2(:,jj)=a2;A3(:,jj)=a3;A4(:,jj)=a4;A5(:,jj)=a5;A6(:,jj)=a6;\n plot(x,f), hold on\nend\nErr=[E1; E2; E3; E4; E5; E6];\nErr2=[E1; E2; E3; E4; E5];\n\nfigure(2)\nsubplot(3,2,1), boxplot(A1.'), set(gca,'Xtick',1:20,'Xticklabel',{'1','','','','5','','','','','10','','','','','15','','','','','20'})\nsubplot(3,2,2), boxplot(A2.'), set(gca,'Xtick',1:20,'Xticklabel',{'1','','','','5','','','','','10','','','','','15','','','','','20'})\nsubplot(3,2,3), boxplot(A3.'), set(gca,'Xtick',1:20,'Xticklabel',{'1','','','','5','','','','','10','','','','','15','','','','','20'})\nsubplot(3,2,4), boxplot(A4.'), set(gca,'Xtick',1:20,'Xticklabel',{'1','','','','5','','','','','10','','','','','15','','','','','20'})\nsubplot(3,2,5), boxplot(A5.'), set(gca,'Xtick',1:20,'Xticklabel',{'1','','','','5','','','','','10','','','','','15','','','','','20'})\nsubplot(3,2,6), boxplot(A6.'), set(gca,'Xtick',1:20,'Xticklabel',{'1','','','','5','','','','','10','','','','','15','','','','','20'})\n\nfigure(3)\nsubplot(3,3,1), boxplot(Err.'), axis([0 7 0.02 0.07])\n\n%%\nclear phi\nM=10;\nEn=zeros(100,M);\nfor jj=1:M\n for j=1:jj\n phi(:,j)=(x.').^(j-1);\n end\n f=(x.^2).';\n for j=1:100\n fn=(x.^2+0.1*randn(1,n)).';\n an=pinv(phi)*fn; fna=phi*an;\n En(j,jj)=norm(f-fna)/norm(f);\n end\nend\n\nfigure(3)\nsubplot(3,3,2)\nboxplot(En)\n\nsubplot(3,3,3)\nboxplot(En), axis([0.5 10.5 0 0.008])\n", "meta": {"author": "dynamicslab", "repo": "databook_matlab", "sha": "d390d39d18489a4804ee87a143ae8db8a1f3010b", "save_path": "github-repos/MATLAB/dynamicslab-databook_matlab", "path": "github-repos/MATLAB/dynamicslab-databook_matlab/databook_matlab-d390d39d18489a4804ee87a143ae8db8a1f3010b/CH04/CH04_SEC04_1_CompareRegression_production.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7371326015276867}} {"text": "function tetrahedron_unit_monomial_test ( degree_max )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_UNIT_MONOMIAL_TEST tests TETRAHEDRON_UNIT_MONOMIAL.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 16 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DEGREE_MAX, the maximum total degree of the\n% monomials to check.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TETRAHEDRON_UNIT_MONOMIAL_TEST\\n' );\n fprintf ( 1, ' For the unit tetrahedron,\\n' );\n fprintf ( 1, ' TETRAHEDRON_UNIT_MONOMIAL returns the exact value of the\\n' );\n fprintf ( 1, ' integral of X^ALPHA Y^BETA Z^GAMMA\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Volume = %f\\n', tetrahedron_unit_volume ( ) );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ALPHA BETA GAMMA INTEGRAL\\n' );\n fprintf ( 1, '\\n' );\n\n for alpha = 0 : degree_max\n expon(1) = alpha;\n for beta = 0 : degree_max - alpha\n expon(2) = beta;\n for gamma = 0 : degree_max - alpha - beta\n expon(3) = gamma;\n value = tetrahedron_unit_monomial ( expon );\n fprintf ( 1, ' %8d %8d %8d %14.6e\\n', expon(1:3), value );\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/tetrahedron_felippa_rule/tetrahedron_unit_monomial_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.737130083859663}} {"text": "function C = ProdKL(A,B,K,L)\n%PRODKL Matrix product in approximately K-fold precision stored in L results\n%\n% C = ProdKL(A,B,K,L)\n%\n% Input A or B or both may be cell arrays, 1 <= L <= K. \n% Output C is cell array iff L>1, default is L=1.\n% Simple application of SumKL. All input must be real.\n% Relative error of the result is of order eps^L + eps^K cond(product) , see\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 02/17/08 S.M. Rump\n% modified 05/09/09 S.M. Rump rounding to nearest, default L=1\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==3\n L = 1;\n end\n \n if iscell(A) % input A cell array\n n = size(A{1},1);\n lenA = length(A);\n AA = zeros(n,lenA*n);\n for i=1:lenA\n AA(:,(i-1)*n+1:i*n) = A{i};\n end\n if iscell(B) % both A and B cell arrays\n lenB = length(B);\n m = lenA*n;\n AAA = zeros(n,lenB*m);\n BBB = zeros(lenB*m,n);\n for i=1:lenB\n AAA(:,(i-1)*m+1:i*m) = AA;\n BBB((i-1)*m+1:i*m,:) = repmat(B{i},lenA,1);\n end\n A = AAA;\n B = BBB;\n else\n A = AA;\n B = repmat(B,lenA,1);\n end\n else\n n = size(A,1);\n end\n if iscell(B) % input B cell array\n lenB = length(B);\n A = repmat(A,1,lenB);\n BB = zeros(lenB*n,n);\n for i=1:lenB\n BB((i-1)*n+1:i*n,:) = B{i};\n end\n B = BB;\n end\n if L==1\n C = zeros(n);\n else\n for i=1:L\n C{i} = zeros(n);\n end\n end\n for i=1:n\n for j=1:n\n [x,y] = TwoProduct(A(i,:),B(:,j)');\n res = SumKL([x y],K,L);\n if L==1\n C(i,j) = res;\n else\n for k=1:L\n C{k}(i,j) = res(k);\n end\n end\n end\n end\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/ProdKL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.737130083545456}} {"text": "function A = umADEIGSwhole(Ncell,p)\n\nDhat = zeros(p+1);\nfor n=0:p\n for m=n+1:2:p\n Dhat(n+1,m+1) = (2*n+1);\n end\nend\n\n% M = int_{-1}^{1} L_n(x)*L_m(x) dx (note dx=1 assumed)\nM = diag(2./(2*(0:p)+1));\n\n% D_nm = int_{-1}^{1} L_n(x)*L_m(x)*dx\nD = M*Dhat;\n\n% F_nm = L_n(-1)*L_m(-1)\nF = (-1).^[0:p]'*(-1).^[0:p];\n\n% G_nm = -L_n(-1)*L_m(1)\nG = -(-1).^[0:p]'*ones(1,p+1);\n\n% build entire matrix\nNtotal = Ncell*(p+1);\nA = zeros(Ntotal);\n\nfor cell = 1:Ncell\n id1 = ((cell-1)*(p+1)+1):cell*(p+1);\n A(id1,id1) = (1/2)*M\\(D+F);\n \n if(cell~=1)\n id2 = id1-(p+1);\n else\n id2 = id1+(Ncell-1)*(p+1);\n end\n \n A(id1, id2) = (1/2)*M\\G;\nend \n\neA = eig(A);\n\nplot(-real(eA), -imag(eA), 'bo'); \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/Legendre/umADEIGSwhole.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947070591979, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7370891671167729}} {"text": "function [rf, vf] = twobody2 (mu, tau, ri, vi)\n\n% solve the two body initial value problem\n\n% Shepperd's method\n\n% input\n\n% mu = gravitational constant (km**3/sec**2)\n% tau = propagation time interval (seconds)\n% ri = initial eci position vector (kilometers)\n% vi = initial eci velocity vector (kilometers/second)\n\n% output\n\n% rf = final eci position vector (kilometers)\n% vf = final eci velocity vector (kilometers/second)\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ntolerance = 1.0d-12;\n\nu = 0;\n\nimax = 20;\n\numax = +realmax;\n\numin = -realmax;\n\norbits = 0;\n\ntdesired = tau;\n\nthreshold = tolerance * abs (tdesired);\n\nr0 = norm(ri);\n\nn0 = dot(ri, vi);\n\nbeta = 2 * (mu / r0) - dot(vi, vi);\n\nif (beta ~= 0)\n umax = +1 / sqrt(abs(beta));\n \n umin = -1 / sqrt(abs(beta));\nend\n\nif (beta > 0)\n orbits = beta * tau - 2 * n0;\n \n orbits = 1 + (orbits * sqrt(beta)) / (pi * mu);\n \n orbits = floor (orbits / 2);\nend\n\nfor i = 1:1:imax\n\n q = beta * u * u;\n \n q = q / (1 + q);\n\n n = 0;\n \n r = 1;\n \n l = 1;\n \n s = 1;\n \n d = 3;\n \n gcf = 1;\n \n k = -5;\n \n gold = 0;\n\n while (gcf ~= gold)\n\n k = -k;\n \n l = l + 2;\n \n d = d + 4 * l;\n \n n = n + (1 + k) * l;\n \n r = d / (d - n * r * q);\n \n s = (r - 1) * s;\n\n gold = gcf;\n \n gcf = gold + s;\n\n end\n\n h0 = 1 - 2 * q;\n \n h1 = 2 * u * (1 - q);\n\n u0 = 2 * h0 * h0 - 1;\n \n u1 = 2 * h0 * h1;\n \n u2 = 2 * h1 * h1;\n \n u3 = 2 * h1 * u2 * gcf / 3;\n\n if (orbits ~= 0)\n u3 = u3 + 2 * pi * orbits / (beta * sqrt(beta));\n end\n\n r1 = r0 * u0 + n0 * u1 + mu * u2;\n \n dt = r0 * u1 + n0 * u2 + mu * u3;\n \n slope = 4 * r1 / (1 + beta * u * u);\n \n terror = tdesired - dt;\n\n if (abs (terror) < threshold)\n break;\n end;\n \n if ((i > 1) && (u == uold) )\n break;\n end\n \n if ((i > 1) && (dt == dtold) )\n break;\n end\n\n uold = u;\n \n dtold = dt;\n \n ustep = terror / slope;\n\n if (ustep > 0)\n umin = u;\n \n u = u + ustep;\n \n if (u > umax)\n u = (umin + umax) / 2;\n end\n else\n umax = u;\n \n u = u + ustep;\n \n if (u < umin)\n u = (umin + umax) / 2;\n end\n end\n\n if (i == imax)\n fprintf('\\n\\nmax iterations in twobody2 function');\n end\n\nend\n\nusaved = u;\n\nf = 1.0 - (mu / r0) * u2;\n\ngg = 1.0 - (mu / r1) * u2;\n\ng = r0 * u1 + n0 * u2;\n\nff = -mu * u1 / (r0 * r1);\n\n% final position and velocity vectors\n\nfor i = 1:1:3\n rf(i) = f * ri(i) + g * vi(i);\n\n vf(i) = ff * ri(i) + gg * vi(i);\nend\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/39178-circular-orbit-plane-change/twobody2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7370891634924919}} {"text": "function value = p27_exact ( dim_num )\n\n%*****************************************************************************80\n%\n%% P27_EXACT returns the exact integral for problem 27.\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 spatial dimension.\n%\n% Output, real VALUE, the exact value of the integral.\n%\n r = 0.0;\n r = p27_r8 ( 'G', 'R', r );\n\n c = [];\n c = p27_r8vec ( 'G', 'C', dim_num, c );\n\n value = 2.0^dim_num * ...\n cos ( 2.0 * pi * r + 0.5 * sum ( c(1:dim_num) ) ) * ...\n prod ( sin ( 0.5 * c(1:dim_num) ) ./ c(1:dim_num ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrature_test/p27_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7370736574681686}} {"text": "function [G,H] = mass_spring_gradient_hessian(V,E,k,U)\n\n % Compute the gradient and hessian of a mass-spring system defined for (V,E)\n % with the stiffness k and displacement U\n % Inputs:\n % V #V by 2 list of rest curve vertex positions\n % E #E by 2 list of edge indices\n % k scalar spring stiffness parameter\n % U #V by 2 list of deformed curve vertex displacements from the rest pose\n % Outputs:\n % G #V*2 list of gradient vectors per vertex defined at the current deformed position\n % H #V*2 by #V*2 hessian matrix defined at the current deformed position\n\n assert(size(E,2) == 2);\n U = reshape(U,size(V));\n \n % rest edge lengths\n LV = edge_lengths(V,E);\n LU = edge_lengths(U,E);\n f = k*0.5*sum((LV-LU).^2);\n\n if nargout==0\n return;\n end\n\n I = E(:,2);\n J = E(:,1);\n T0 = U(I,:) - U(J,:);\n t1 = normrow(T0);\n\n GI = ((t1-LV)./t1).*T0;\n GJ = -GI;\n\n dim = size(V,2);\n G = k*full(sparse([repmat(I,1,dim) repmat(J,1,dim)],repmat(1:dim,size(E,1),2),[GI GJ],size(V,1),dim));\n G = G(:); % to match the dimension: not sure if correct\n\n if nargout==1\n return;\n end\n\n % Outer product\n vec = @(X) X(:);\n T2 = T0(:,vec(repmat(1:dim,dim,1))').*T0(:,vec(repmat(1:dim,1,dim))');\n t3 = t1 - LV;\n\n HIJ = (t3./(t1.^3) - 1./(t1.^2)).*T2 - t3./t1.*(vec(eye(dim))');\n HII = -HIJ;\n HJJ = -HIJ;\n HJI = HIJ;\n n = size(V,1);\n H = sparse(n*dim,n*dim);\n for ii = 1:dim\n for jj = 1:dim\n oi = (ii-1)*dim+jj;\n Hiijj = sparse( ...\n [I I J J],[I J I J],[HII(:,oi) HIJ(:,oi) HJI(:,oi) HJJ(:,oi)],n,n);\n H(((ii-1)*n)+(1:n),((jj-1)*n)+(1:n)) = Hiijj;\n end\n end\n H = k*H;\n\nend\n", "meta": {"author": "odedstein", "repo": "sgi-introduction-course", "sha": "52278fc3b3dab52febb110a1a09d770f46b5e417", "save_path": "github-repos/MATLAB/odedstein-sgi-introduction-course", "path": "github-repos/MATLAB/odedstein-sgi-introduction-course/sgi-introduction-course-52278fc3b3dab52febb110a1a09d770f46b5e417/105_mass_spring/exercise/mass_spring_gradient_hessian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7370736537295107}} {"text": "function net = glm(nin, nout, outfunc, prior, beta)\n%GLM\tCreate a generalized linear model.\n%\n%\tDescription\n%\n%\tNET = GLM(NIN, NOUT, FUNC) takes the number of inputs and outputs for\n%\ta generalized linear model, together with a string FUNC which\n%\tspecifies the output unit activation function, and returns a data\n%\tstructure NET. The weights are drawn from a zero mean, isotropic\n%\tGaussian, with variance scaled by the fan-in of the output units.\n%\tThis makes use of the Matlab function RANDN and so the seed for the\n%\trandom weight initialization can be set using RANDN('STATE', S)\n%\twhere S is the seed value. The optional argument ALPHA sets the\n%\tinverse variance for the weight initialization.\n%\n%\tThe fields in NET are\n%\t type = 'glm'\n%\t nin = number of inputs\n%\t nout = number of outputs\n%\t nwts = total number of weights and biases\n%\t actfn = string describing the output unit activation function:\n%\t 'linear'\n%\t 'logistic'\n%\t 'softmax'\n%\t w1 = first-layer weight matrix\n%\t b1 = first-layer bias vector\n%\n%\tNET = GLM(NIN, NOUT, FUNC, PRIOR), in which PRIOR is a scalar, allows\n%\tthe field NET.ALPHA in the data structure NET to be set,\n%\tcorresponding to a zero-mean isotropic Gaussian prior with inverse\n%\tvariance with value PRIOR. Alternatively, PRIOR can consist of a data\n%\tstructure with fields ALPHA and INDEX, allowing individual Gaussian\n%\tpriors to be set over groups of weights in the network. Here ALPHA is\n%\ta column vector in which each element corresponds to a separate\n%\tgroup of weights, which need not be mutually exclusive. The\n%\tmembership of the groups is defined by the matrix INDEX in which the\n%\tcolumns correspond to the elements of ALPHA. Each column has one\n%\telement for each weight in the matrix, in the order defined by the\n%\tfunction GLMPAK, and each element is 1 or 0 according to whether the\n%\tweight is a member of the corresponding group or not.\n%\n%\tNET = GLM(NIN, NOUT, FUNC, PRIOR, BETA) also sets the additional\n%\tfield NET.BETA in the data structure NET, where beta corresponds to\n%\tthe inverse noise variance.\n%\n%\tSee also\n%\tGLMPAK, GLMUNPAK, GLMFWD, GLMERR, GLMGRAD, GLMTRAIN\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\nnet.type = 'glm';\nnet.nin = nin;\nnet.nout = nout;\nnet.nwts = (nin + 1)*nout;\n\nouttfns = {'linear', 'logistic', 'softmax'};\n\nif sum(strcmp(outfunc, outtfns)) == 0\n error('Undefined activation function. Exiting.');\nelse\n net.outfn = outfunc;\nend\n\nif nargin > 3\n if isstruct(prior)\n net.alpha = prior.alpha;\n net.index = prior.index;\n elseif size(prior) == [1 1]\n net.alpha = prior;\n else\n error('prior must be a scalar or structure');\n end\nend\n \nnet.w1 = randn(nin, nout)/sqrt(nin + 1);\nnet.b1 = randn(1, nout)/sqrt(nin + 1);\n\nif nargin == 5\n net.beta = beta;\nend\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/glm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7370210696221657}} {"text": "% Nonnegative Matrix Factorization with Quadratic Programming\n% The function iptrnr(Y,X,no_iter,lambdaA,rho,eta,epsil_A) returns\n% the matrix A for the constrained system of linear equations: AX = Y\n\nfunction A = iptrnr(Y,X,no_iter,lambdaA,rho,eta,epsil_A)\n\n% INPUTS:\n% > Y: observation matrix [I by K] of mixed signals (images) \n% > X: source component matrix [J by K]\n% > no_iter: number of inner iterations\n% > lambdaA: Tikhonov regularization parameter\n% > rho: auxiliary parameter for defining the log barrier parameter\n% > eta: parameter in stopping rule for iterations\n% > epsil_A: threshold for active-set variables\n\n% OUTPUT:\n% > A: mixing matrix [I by J]\n\n[J,K] = size(X); [I,Ky] = size(Y); M = I*J;\n\n% Initialization\nA = ones(I,J);\nQ_bar = spalloc(M,M,M*J); Q_tilde = spalloc(M,M,M*J);\n\nB = X*X'; C_bar = X*Y';\nQ_bar = kron(speye(I),B); % Hessian of D(Y||AX) with respect to A\nGo = (C_bar - B*A'); % Gradient of D(Y||AX) with respect to A^T\nAt = A';\ntheta = -(rho/(M))*abs(Go(:)'*At(:)); % initialization for \n %log barrier parameter\nl = 0;\nwhile l < no_iter % inner iterations\n \n l = l + 1; \n a = At(:);\n active = find(a < epsil_A); % active set\n inactive = find(a >= epsil_A); % inactive set\n \n if ~isempty(active)\n a_tilde = a; a_tilde(active) = [];\n N = length(a_tilde);\n c_tilde = C_bar(:); c_tilde(active) = [];\n c_tilde = 2*theta*1./a_tilde - c_tilde;\n Q_tilde = Q_bar;\n Q_tilde(:,active) = []; Q_tilde(active,:) = [];\n Q_tilde = Q_tilde - theta*spdiags(1./a_tilde.^2,0,N,N);\n else\n a_tilde = a;\n Q_tilde = Q_bar - theta*spdiags(1./a.^2,0,M,M) + lambdaA*speye(M);\n c_tilde = 2*theta*(1./a) - C_bar(:);\n end\n \n [Q,R] = qr(Q_tilde,-c_tilde); % Q-less QR factorization\n z_tilde = R\\Q; % Gaussian elimination\n h_tilde = z_tilde - a_tilde;\n beta = min(1, 0.9995*min(a_tilde./abs(h_tilde)));\n a_tilde = a_tilde + beta*h_tilde;\n \n theta_tilde = theta*(2*(1./a_tilde) - (1./a_tilde.^2).*z_tilde);\n theta = ( theta_tilde'*a_tilde);\n \n if ~isempty(active)\n an = zeros(M,1); an(inactive) = a_tilde; a = an;\n else\n a = a_tilde; \n end\n \n if abs(theta) < eta*norm(a) % stopping rule\n break\n end\n theta = (rho/sqrt(M))*theta;\n At = reshape(a,J,I);\n \nend\nA = At';\n\n\n\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/NMFLABSP_ver1.2/iptrnr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7370210641405185}} {"text": "function f = dtlz4a(x)\n\nalpha = 10;\n\n%% g function\nsum = 0;\nfor i = 3:8\nsum = sum + (x(:,i)-0.5)^2;\nend\ng = sum;\n\n%% cost functions\nf(:,1) = (1+g)*cos(((x(:,1)^alpha)*pi)/2)*cos(((x(:,2)^alpha)*pi)/2);\nf(:,2) = (1+g)*cos(((x(:,1)^alpha)*pi)/2)*sin(((x(:,2)^alpha)*pi)/2);\nf(:,3) = (1+g)*sin(((x(:,1)^alpha)*pi)/2);\nend\n", "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/dtlz4a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9688561676667173, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.7369610657723726}} {"text": "function PQ = paddedsize(AB,CD,PARAM)\n%PADDEDSIZE Computes padded sizes useful for FFT-based filtering. \n% PQ = PADDEDSIZE(AB), where AB is a two-element vector, computes the\n% two-element vector PQ = 2*AB.\n%\n% PQ = PADDEDSIZE(AB,'PWR2') computes the vector PQ such that PQ(1) =\n% PQ(2) = 2^nextpow2(2*m), where m is MAX(AB).\n%\n% PQ = PADDEDSIZE(AB,CD), where AB and CD are two-element size vectors,\n% computes the two-element size vector PQ. The elements of PQ are the\n% smallest even integers greater than or equal to AB + CD - 1.\n%\n% PQ = PADDEDSIZE(AB,CD,'PWR2') computes the vector PQ such that PQ(1)\n% = PQ(2) = 2^nextpow2(2*m), where m is MAX([AB,CD]).\n%\n% Copyright 2002-2020 Gatesmark\n%\n% This function, and other functions in the DIPUM Toolbox, are based \n% on the theoretical and practical foundations established in the \n% book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark \n% Press, 2020.\n%\n% Book website: http://www.imageprocessingplace.com\n% License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt\n\nif nargin == 1\n PQ = 2*AB;\nelseif nargin == 2 && ~ischar(CD)\n PQ = AB + CD - 1;\n PQ = 2*ceil(PQ/2);\nelseif nargin == 2\n m = max(AB); % Maximum dimension.\n \n % Find power-of-2 at least twice m.\n P = 2^nextpow2(2*m);\n PQ = [P,P];\nelseif (nargin == 3) && strcmpi(PARAM,'pwr2')\n m = max([AB,CD]); % Maximum dimension.\n P = 2^nextpow2(2*m);\n PQ = [P,P];\nelse \n error('Wrong number of inputs.')\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/paddedsize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7368470697756302}} {"text": "function [weight] = anticor_expert(data, weight_o, w)\n% This program generates portfolio for a specified parameter setting.\n% Anticor expert\n% while the original version is based on loop, which is slow in matlab,\n% I replace the code using matrix operations\n% Most previous experiments run based on the commented version, at the end\n% of the file.\n%\n% function [weight] = anticor_expert(data, weight_o, w)\n%\n% weight: experts portfolio, used for next rebalance/combination\n%\n% data: market sequence vectors\n% weight_o: last portfolio, also can be last price relative adjusted.\n% w: window size for the experts\n%\n% Example: [weight] = anticor_expert(data, weight_o, 30)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This file is part of OLPS: http://OLPS.stevenhoi.org/\n% Original authors: Bin LI, Steven C.H. Hoi \n% Contributors:\n% Change log: \n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[T, N]=size(data);\nweight = weight_o;\n\n% 1. Return the current portfolio if t < 2w\nif (T >= 2*w),\n % 2. Compute LX1, LX2\n LX1 = log(data((T-2*w+1):(T-w),:));\n LX2 = log(data((T-w+1):T,:));\n \n % 2. Compute averages of LX1 and LX2\n mu1 = mean(LX1); \n mu2 = mean(LX2);\n \n % M_cor = corr(LX1, LX2);\n M_cov = zeros(N, N); \n M_cor = zeros(N, N);\n \n % I replace the following loop using matrix operations\n n_LX1 = LX1(:, :) - repmat(mu1, [w, 1]);\n n_LX2 = LX2(:, :) - repmat(mu2, [w, 1]);\n \n Std1 = diag(n_LX1'*n_LX1)/(w-1);\n Std2 = diag(n_LX2'*n_LX2)/(w-1);\n Std12 = Std1*Std2';\n M_cov = n_LX1'*n_LX2/(w-1);\n \n M_cor(Std12==0) = 0;\n M_cor(Std12~=0) = M_cov(Std12~=0)./sqrt(Std12(Std12~=0));\n\n % claim varialbe, matrixization \n claim = zeros(N);\n w_mu2 = repmat(mu2', [1, N]);\n w_mu1 = repmat(mu2, [N, 1]);\n s_12 = (w_mu2 >= w_mu1) & (M_cor > 0);\n claim(s_12) = claim(s_12) + M_cor(s_12);\n \n diag_M_cor = diag(M_cor);\n cor1 = max(0, repmat(-diag_M_cor, [1, N]));\n cor2 = max(0, repmat(-diag_M_cor', [N, 1]));\n claim(s_12) = claim(s_12) + cor1(s_12) + cor2(s_12);\n \n transfer = zeros(N);\n sum_claim = repmat(sum(claim, 2), [1, N]);\n s_1 = abs(sum_claim) > 0;\n w_weight_o = repmat(weight_o, [1, N]);\n transfer(s_1) = w_weight_o(s_1).*claim(s_1)./sum_claim(s_1);\n\n % Use matrix operations, replacing the following loop\n transfer_ij = transfer'-transfer;\n weight = weight - sum(transfer_ij)';\nend\nend\n\n% for i=1:N,\n% for j = 1:N,\n% M_cov(i, j) = (LX1(:, i)-mu1(:, i))'*(LX2(:, j) - mu2(:, j))/(w-1);\n% \n% % Std1 = Std(LX1(:, i)\n% Std1 = (LX1(:, i) - mu1(:, i))'*(LX1(:, i) - mu1(:, i))/(w-1);\n% Std2 = (LX2(:, j) - mu2(:, j))'*(LX2(:, j) - mu2(:, j))/(w-1);\n% \n% if (Std12(i, j) == 0),\n% M_cor(i, j) = 0;\n% else\n% M_cor(i, j) = M_cov(i, j) / sqrt(Std1(i, 1)*Std2(j, 1));\n% end\n% end\n% end\n\n% \n% for i = 1:N,\n% for j = 1:N,\n% if ((mu2(i) >= mu2(j)) && (M_cor(i, j) > 0)),\n% claim(i, j) = claim(i, j) + M_cor(i, j);\n% % claim(i, j) = claim(i, j) + max(0, -M_cor(i, i));\n% % claim(i, j) = claim(i, j) + max(0, -M_cor(j, j));\n% end\n% end\n% end \n% for i = 1:N,\n% sum_claim_i = sum(claim(i, :));\n% if (abs(sum_claim_i) > 0)\n% for j = 1:N,\n% transfer(i, j) = weight_o(i)*claim(i, j)/sum_claim_i;\n% end\n% end\n% end\n% for i = 1:N,\n% for j = 1:N,\n% weight(i) = weight(i) - transfer(i, j) + transfer(j, i);\n% end\n% end\n", "meta": {"author": "OLPS", "repo": "OLPS", "sha": "9120783cd59a7966b0f78e2b5668030a4378b8af", "save_path": "github-repos/MATLAB/OLPS-OLPS", "path": "github-repos/MATLAB/OLPS-OLPS/OLPS-9120783cd59a7966b0f78e2b5668030a4378b8af/Strategy/anticor_expert.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7367576584988771}} {"text": "function y = vl_sigmoid(x)\n% VL_SIGMOID Sigmoid function\n% Y = VL_SIGMOID(X) returns\n%\n% Y = 1 ./ (1 + EXP(X)) ;\n%\n% Remark::\n% Useful properties of the sigmoid function are:\n%\n% - 1 - VL_SIGMOID(X) = VL_SIGMOID(-X)\n% - Centered sigmoid: 2 * VL_SIGMOID(X) - 1 ;\n% - VL_SIGMOID(X) = (EXP(X/2) - EXP(X/2)) / (EXP(X/2) + EXP(X/2))\n%\n% See also: VL_DSIGMOID(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\ny = 1 ./ (1 + exp(-x)) ;\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/special/vl_sigmoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391685381604, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7367576574473178}} {"text": "function [xi,yi] = snakeinterp(x,y,dmax,dmin)\n%----------This function is used for interpolating the snake adaptively\n\n% dmax: the maximum distance between two snake points\n% dmin: the maximum distance between two snake points\n% d(i,i+1)>dmax, then a new point is added between i and i+1\n% d(i,i+1)dmax);\n\nz = snakeindex(IDX);\n\np = 1:N+1;\n\nxi = interp1(p,[x;x(1)],z');\nyi = interp1(p,[y;y(1)],z');\n\nN = length(xi);\nd = abs(xi([2:N 1])- xi(:)) + abs(yi([2:N 1])- yi(:));\n\nwhile (max(d)>dmax),\n\n IDX = (d>dmax);\n z = snakeindex(IDX);\n\n p = 1:N+1;\n\n xi = interp1(p,[xi;xi(1)],z');\n yi = interp1(p,[yi;yi(1)],z');\n\n N = length(xi);\n d = abs(xi([2:N 1])- xi(:)) + abs(yi([2:N 1])- yi(:));\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/分割算法/Segmentation-of-Ultrasound-Images-master/Code/snakeinterp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723468, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.7367576541801428}} {"text": "function F=dwt_fuse(I1,I2,zt)\n% DWT\n% Input:\n% I1 - input image A\n% I2 - input image B\n% zt - maximum decomposition level\n% Output:\n% F - fused image \n%\n% The code is edited by Yu Liu, 01-09-2014.\n\n%-------------------------------------------------------------------------%\n% DWT\n%-------------------------------------------------------------------------%\nI1=double(I1);\nI2=double(I2);\ntempA=I1;\ntempB=I2;\n \nX=cell(zt,4); \nY=cell(zt,4); \nZ=cell(zt,4); \nfor i=1:zt\n [X{i,1},X{i,2},X{i,3},X{i,4}]=dwt2(tempA,'db1','mode','per'); \n tempA=X{i,1};\n [Y{i,1},Y{i,2},Y{i,3},Y{i,4}]=dwt2(tempB,'db1','mode','per'); \n tempB=Y{i,1};\nend\n\n%-------------------------------------------------------------------------%\n% low-pass fusion\n%-------------------------------------------------------------------------%\nZ{zt,1}=(X{zt,1}+Y{zt,1})/2;\n\n%-------------------------------------------------------------------------%\n% high-pass fusion\n%-------------------------------------------------------------------------% \nfor i=zt:-1:1 \n for j=2:4\n Z{i,j}=selc(X{i,j},Y{i,j},3); \n end\nend\n\n%-------------------------------------------------------------------------%\n% IDWT\n%-------------------------------------------------------------------------%\nfor i=zt:-1:1\n if i>1\n Z{i-1,1}=idwt2(Z{i,1},Z{i,2},Z{i,3},Z{i,4},'db1','mode','per');\n else\n F=idwt2(Z{i,1},Z{i,2},Z{i,3},Z{i,4},'db1','mode','per');\n end\nend\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/NSCT_SR/dwt_fuse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7367534601978862}} {"text": "function op = prox_Sl1( lambda )\n%PROX_SL1 Sorted/Ordered L1 norm.\n% OP = PROX_L1( lambda ) implements the nonsmooth function\n% OP(X) = sum(lambda.*sort(abs(X),'descend'))\n% where lambda is strictly positive and sorted in decreasing order,\n% in which case this function is a norm (and hence convex).\n% If lambda is a scalar, it will be expanded to all elements, but in this\n% case it is equivalent to the (scaled) usual l1 norm.\n% \n% Notice: this function uses mex files. Some pre-compiled binaries\n% for common systems are included; if these do not work for you,\n% then please install yourself. In the mexFiles/ subdirectory,\n% run the file \"makeMex.m\"\n% Reference:\n% http://www-stat.stanford.edu/~candes/OrderedL1/\n% \"Statistical Estimation and Testing via the Ordered L1 Norm\"\n% by M. Bogdan, E. van den Berg, W. Su, and E. J. Candès\n% 2013\n%\n% See also prox_l1.m, makeMex.m\n\nif nargin == 0,\n\tlambda = 1;\nelseif ~isnumeric( lambda ) || ~isreal( lambda ) || any( lambda(:) <= 0 ) \n\terror( 'Argument lambda must have all positive entries.' );\nend\nif ~issorted(flipud(lambda(:)))\n error( 'Argument lambda must be sorted in decreasing order.');\nend\nif numel(lambda)==1\n warning('TFOCS:prox_SL1','When lambda is a scalar, we recommend prox_l1.m instead pf prox_SL1.m');\nend\n\n\n% The mex file is in the child directory mexFiles/\n% Check for its existence. First, add the right paths\naddpath(fullfile(tfocs_where,'mexFiles'));\nif 3 ~= exist('proxAdaptiveL1Mex','file')\n makeMex;\n % check that it worked\n if 3 ~= exist('proxAdaptiveL1Mex','file')\n disp('Compilation of mex files for prox_SL1.m failed; please report this error');\n end\nend\n\nf = @(x) sum( lambda(:) .* sort(abs(x(:)), 'descend') );\nprox_f = @(x,t) proxOrderedL1(x,t.*lambda);\n\nop = tfocs_prox( f, prox_f , 'vector' ); % Allow vector stepsizes\n\n\nend\n\n% -- subroutines --\nfunction x = proxOrderedL1(y,lambda)\n % Normalization\n lambda = lambda(:);\n y = y(:);\n sgn = sign(y);\n [y,idx] = sort(abs(y),'descend');\n \n % Simplify the problem\n k = find(y > lambda,1,'last');\n \n % Compute solution and re-normalize\n n = numel(y);\n x = zeros(n,1);\n \n if (~isempty(k))\n v1 = y(1:k);\n if numel(lambda) > 1\n v2 = lambda(1:k);\n else\n v2 = lambda*ones(k,1); % if lambda is a scalar, implicity make it lambda*ones(size(y))\n end\n v = proxAdaptiveL1Mex(v1,v2);\n x(idx(1:k)) = v;\n end\n \n % Restore signs\n x = sgn .* x;\nend\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.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/prox_Sl1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7367534512094042}} {"text": "%% Machine Learning Online Class - Exercise 1: Linear Regression\n\n% Instructions\n% ------------\n% \n% This file contains code that helps you get started on the\n% linear exercise. You will need to complete the following functions \n% in this exericse:\n%\n% warmUpExercise.m\n% plotData.m\n% gradientDescent.m\n% computeCost.m\n% gradientDescentMulti.m\n% computeCostMulti.m\n% featureNormalize.m\n% normalEqn.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% x refers to the population size in 10,000s\n% y refers to the profit in $10,000s\n%\n\n%% Initialization\nclear ; close all; clc\n\n%% ==================== Part 1: Basic Function ====================\n% Complete warmUpExercise.m \nfprintf('Running warmUpExercise ... \\n');\nfprintf('5x5 Identity Matrix: \\n');\nwarmUpExercise()\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n\n%% ======================= Part 2: Plotting =======================\nfprintf('Plotting Data ...\\n')\ndata = load('ex1data1.txt');\nX = data(:, 1); y = data(:, 2);\nm = length(y); % number of training examples\n\n% Plot Data\n% Note: You have to complete the code in plotData.m\nplotData(X, y);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% =================== Part 3: Gradient descent ===================\nfprintf('Running Gradient Descent ...\\n')\n\nX = [ones(m, 1), data(:,1)]; % Add a column of ones to x\ntheta = zeros(2, 1); % initialize fitting parameters\n\n% Some gradient descent settings\niterations = 1500;\nalpha = 0.01;\n\n% compute and display initial cost\ncomputeCost(X, y, theta)\n\n% run gradient descent\ntheta = gradientDescent(X, y, theta, alpha, iterations);\n\n% print theta to screen\nfprintf('Theta found by gradient descent: ');\nfprintf('%f %f \\n', theta(1), theta(2));\n\n% Plot the linear fit\nhold on; % keep previous plot visible\nplot(X(:,2), X*theta, '-')\nlegend('Training data', 'Linear regression')\nhold off % don't overlay any more plots on this figure\n\n% Predict values for population sizes of 35,000 and 70,000\npredict1 = [1, 3.5] *theta;\nfprintf('For population = 35,000, we predict a profit of %f\\n',...\n predict1*10000);\npredict2 = [1, 7] * theta;\nfprintf('For population = 70,000, we predict a profit of %f\\n',...\n predict2*10000);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% ============= Part 4: Visualizing J(theta_0, theta_1) =============\nfprintf('Visualizing J(theta_0, theta_1) ...\\n')\n\n% Grid over which we will calculate J\ntheta0_vals = linspace(-10, 10, 100);\ntheta1_vals = linspace(-1, 4, 100);\n\n% initialize J_vals to a matrix of 0's\nJ_vals = zeros(length(theta0_vals), length(theta1_vals));\n\n% Fill out J_vals\nfor i = 1:length(theta0_vals)\n for j = 1:length(theta1_vals)\n\t t = [theta0_vals(i); theta1_vals(j)]; \n\t J_vals(i,j) = computeCost(X, y, t);\n end\nend\n\n\n% Because of the way meshgrids work in the surf command, we need to \n% transpose J_vals before calling surf, or else the axes will be flipped\nJ_vals = J_vals';\n% Surface plot\nfigure;\nsurf(theta0_vals, theta1_vals, J_vals)\nxlabel('\\theta_0'); ylabel('\\theta_1');\n\n% Contour plot\nfigure;\n% Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100\ncontour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))\nxlabel('\\theta_0'); ylabel('\\theta_1');\nhold on;\nplot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);\n", "meta": {"author": "AvaisP", "repo": "machine-learning-programming-assignments-coursera-andrew-ng", "sha": "45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf", "save_path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng", "path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng/machine-learning-programming-assignments-coursera-andrew-ng-45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf/machine-learning-ex1/ex1/ex1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7367266619256008}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: computes the angular displacements of a simple gravity pendulum\n%\n% PURPOSE: to illustrate no change in oscillatory amplitude under\n% variations in the radius of the pendulum bob.\n%\n% Author: N.A. Battista\n% Date: 12/13/2019\n% Institution: The College of New Jersey\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction simple_pendulum()\n\n%\n% Physical Parameters\n%\nm = 100; % Mass of Pendulum bob\ng=9.80665; % Gravitational Acceleration;\nL=0.2; % Length of Pendulum\n \n%\n% Vector of Radii\n%\nrVec = 100*[0.005 0.010 0.015 0.02 0.025];\n\n% \n% Temporal Parameters\n%\nt=0; % initial time\ntFinal = 8; % final-time\ndt = 1e-3; % time-step\nct=1; % counter\ntVec(ct)=t; % time vector storage\n\n%\n% Moment of Inertia\n% \nIVec = m*(0.5*rVec.^2+L^2); \n\n% \n% Initial Angular Displacement\n%\nang = -(pi/2-pi/5)*ones(1,5);\nphi = zeros( size( ang ) );\n\n\n%\n% Perform the time-stepping, e.g., solve the ODEs\n%\nwhile t<=tFinal\n \n % increment the storage counter\n ct = ct+1;\n\n % increment time\n t = t+dt;\n \n % save current time\n tVec(ct) = t;\n \n % solve 1st order ODE for angular displacement\n ang(ct,:) = ang(ct-1,:) + dt * ( phi(ct-1,:) );\n \n % solve 1st order ODE for angular velocity\n phi(ct,:) = phi(ct-1,:) + dt * ( -m*g*L ./IVec .* sin( ang(ct-1,:) ) );\n \nend\n\n\n%\n% Defining Colors for Plotting Data\n%\ncolor2 = [0.635 0.078 0.184]; % dark red\ncolor5 = [0.9 0.525 0.098]; % orange\ncolor6 = [0.929 0.840 0.1250]; % dark yellow\ncolor7 = [0.7 0.7 0]; % 'ugly' green\n\n%\n% Note discrepancy is a bit off due to small angle approximation: \n% sin(theta) ~ theta gives below period of oscillation\n%\nT1 = 2*pi*sqrt( IVec(1) / (m*g*L) );\n%\n% Actually computed value of period is:\nT1 = 1.93;\n\n%\n% Make Figure of Angular Displacement vs. Non-dimensional Time (# of oscillations of 'r' case)\n%\nlw=6;\nfs=18;\nplot(tVec/T1,ang(:,1),'k-','LineWidth',lw); hold on;\nplot(tVec/T1,ang(:,2),'b-','LineWidth',lw,'Color',color2); hold on;\nplot(tVec/T1,ang(:,3),'g-','LineWidth',lw,'Color',color5); hold on;\nplot(tVec/T1,ang(:,4),'r-','LineWidth',lw,'Color',color6); hold on;\nplot(tVec/T1,ang(:,5),'c-','LineWidth',lw,'Color',color7); hold on;\nxlabel('Non-Dimensional Time (# periods of r-case)');\nylabel('Angular Displacement (Radians)');\naxis([0 4*T1 -1 1.25]);\nleg=legend('r','2r','3r','4r','5r','Orientation','horizontal');\nset(gca,'FontSize',fs);\nset(leg,'FontSize',fs);\n", "meta": {"author": "nickabattista", "repo": "IB2d", "sha": "392d99c228cc801ff65766889c72e2e1492fe747", "save_path": "github-repos/MATLAB/nickabattista-IB2d", "path": "github-repos/MATLAB/nickabattista-IB2d/IB2d-392d99c228cc801ff65766889c72e2e1492fe747/matIB2d/Examples/Examples_Education/Pendulum/ODEs/simple_pendulum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7367266465221078}} {"text": "function point = intersectLines(line1, line2, varargin)\n%INTERSECTLINES Return all intersection points of N lines in 2D\n%\n% PT = intersectLines(L1, L2);\n% returns the intersection point of lines L1 and L2. L1 and L2 are 1-by-4\n% row arrays, containing parametric representation of each line (in the\n% form [x0 y0 dx dy], see 'createLine' for details).\n% \n% In case of colinear lines, returns [Inf Inf].\n% In case of parallel but not colinear lines, returns [NaN NaN].\n%\n% If each input is [N*4] array, the result is a [N*2] array containing\n% intersections of each couple of lines.\n% If one of the input has N rows and the other 1 row, the result is a\n% [N*2] array.\n%\n% PT = intersectLines(L1, L2, EPS);\n% Specifies the tolerance for detecting parallel lines. Default is 1e-14.\n%\n% Example\n% line1 = createLine([0 0], [10 10]);\n% line2 = createLine([0 10], [10 0]);\n% point = intersectLines(line1, line2)\n% point = \n% 5 5\n%\n% See also\n% lines2d, edges2d, intersectEdges, intersectLineEdge\n% intersectLineCircle\n%\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 31/10/2003.\n%\n\n% HISTORY\n% 2004-02-19 add support for multiple lines.\n% 2007-03-08 update doc\n% 2011-10-07 code cleanup\n\n\n%% Process input arguments\n\n% extract tolerance\ntol = 1e-14;\nif ~isempty(varargin)\n tol = varargin{1};\nend\n\n% check size of each input\nN1 = size(line1, 1);\nN2 = size(line2, 1);\nN = max(N1, N2);\nif N1 ~= N2 && N1*N2 ~= N\n error('matGeom:IntersectLines:IllegalArgument', ...\n 'The two input arguments must have same number of lines');\nend\n\n\n%% Check parallel and colinear lines\n\n% coordinate differences of origin points\ndx = bsxfun(@minus, line2(:,1), line1(:,1));\ndy = bsxfun(@minus, line2(:,2), line1(:,2));\n\n% indices of parallel lines\ndenom = line1(:,3) .* line2(:,4) - line2(:,3) .* line1(:,4);\npar = abs(denom) < tol;\n\n% indices of colinear lines\ncol = abs(dx .* line1(:,4) - dy .* line1(:,3)) < tol & par ;\n\n% initialize result array\nx0 = zeros(N, 1);\ny0 = zeros(N, 1);\n\n% initialize result for parallel lines\nx0(col) = Inf;\ny0(col) = Inf;\nx0(par & ~col) = NaN;\ny0(par & ~col) = NaN;\n\n% in case all line couples are parallel, return\nif all(par)\n point = [x0 y0];\n return;\nend\n\n\n%% Extract coordinates of itnersecting lines\n\n% indices of intersecting lines\ninds = ~par;\n\n% extract base coordinates of first lines\nif N1 > 1\n line1 = line1(inds,:);\nend\nx1 = line1(:,1);\ny1 = line1(:,2);\ndx1 = line1(:,3);\ndy1 = line1(:,4);\n\n% extract base coordinates of second lines\nif N2 > 1\n line2 = line2(inds,:);\nend\nx2 = line2(:,1);\ny2 = line2(:,2);\ndx2 = line2(:,3);\ndy2 = line2(:,4);\n\n% re-compute coordinate differences of origin points\ndx = bsxfun(@minus, line2(:,1), line1(:,1));\ndy = bsxfun(@minus, line2(:,2), line1(:,2));\n\n\n%% Compute intersection points\n\ndenom = denom(inds);\nx0(inds) = (x2 .* dy2 .* dx1 - dy .* dx1 .* dx2 - x1 .* dy1 .* dx2) ./ denom ;\ny0(inds) = (dx .* dy1 .* dy2 + y1 .* dx1 .* dy2 - y2 .* dx2 .* dy1) ./ denom ;\n\n% concatenate result\npoint = [x0 y0];\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom2d/intersectLines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7366916683469067}} {"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\nidx_1 = find(p >= 0.5);\nidx_0 = find(p < 0.5);\n\np(idx_1) = ones(size(idx_1));\np(idx_0) = zeros(size(idx_0));\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "1094401996", "repo": "machine-learning-coursera", "sha": "e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb", "save_path": "github-repos/MATLAB/1094401996-machine-learning-coursera", "path": "github-repos/MATLAB/1094401996-machine-learning-coursera/machine-learning-coursera-e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb/problem_sets/ex2_solution/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.8333245932423309, "lm_q1q2_score": 0.7366916646875279}} {"text": "function [ value, ifault ] = alogam ( x )\n\n%*****************************************************************************80\n%\n%% ALOGAM computes the logarithm of the Gamma function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 January 2008\n%\n% Author:\n%\n% Original FORTRAN77 version by Malcolm Pike, David Hill.\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Malcolm Pike, David Hill,\n% Algorithm 291:\n% Logarithm of Gamma Function,\n% Communications of the ACM,\n% Volume 9, Number 9, September 1966, page 684.\n%\n% Parameters:\n%\n% Input, real X, the argument of the Gamma function.\n% X should be greater than 0.\n%\n% Output, real ALOGAM, the logarithm of the Gamma\n% function of X.\n%\n% Output, integer IFAULT, error flag.\n% 0, no error.\n% 1, X <= 0.\n%\n if ( x <= 0.0 )\n ifault = 1;\n value = 0.0;\n return\n end\n\n ifault = 0;\n y = x;\n\n if ( x < 7.0 )\n\n f = 1.0;\n z = y;\n\n while ( z < 7.0 )\n f = f * z;\n z = z + 1.0;\n end\n\n y = z;\n f = - log ( f );\n\n else\n\n f = 0.0;\n\n end\n\n z = 1.0 / y / y;\n\n value = f + ( y - 0.5 ) * log ( y ) - y ...\n + 0.918938533204673 + ...\n ((( ...\n - 0.000595238095238 * z ...\n + 0.000793650793651 ) * z ...\n - 0.002777777777778 ) * z ...\n + 0.083333333333333 ) / y;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms179/alogam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7364995973536227}} {"text": "function ising_2d_simulation ( m, n, iterations, thresh, seed )\n\n%*****************************************************************************80\n%\n%% ISING_2D_SIMULATION carries out a 2D Ising simulation.\n%\n% Discussion:\n%\n% Note that, when all the cells are updated in a single cycle, there is\n% a mathematically stable checkerboard solution, in which all the reds\n% and blacks flip color repeatedly.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ISING_2D_SIMULATION\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Monte Carlo simulation of a 2D Ising model.\\n' );\n%\n% Arguments not supplied are set to default values.\n%\n if ( nargin < 1 )\n m = 10;\n else\n m = str2num ( m );\n end\n\n if ( nargin < 2 )\n n = 10;\n else\n n = str2num ( n );\n end\n\n if ( nargin < 3 )\n iterations = 15;\n else\n iterations = str2num ( iterations );\n end\n\n if ( nargin < 4 )\n thresh = 0.50;\n else\n thresh = str2num ( thresh );\n end\n\n if ( nargin < 5 )\n seed = 123456789;\n else\n seed = str2num ( seed );\n end\n%\n% Define the probability of flipping if you are in a neighborhood of\n% 1, 2, 3, 4, or 5 of the same sign.\n%\n% This should really be some kind of exponential dependent on \"temperature\".\n%\n prob = [ 0.98, 0.85, 0.50, 0.15, 0.02 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The row dimension M = %d\\n', m );\n fprintf ( 1, ' The column dimension N = %d\\n', n );\n fprintf ( 1, ' The number of iterations taken is ITERATIONS = %d\\n', iterations );\n fprintf ( 1, ' The threshhold THRESH = %f\\n', thresh );\n fprintf ( 1, ' The seed SEED = %d\\n', seed );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The transition probability table, based on the number of\\n' );\n fprintf ( 1, ' neighbors with the same charge.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' 1 2 3 4 5\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' %10.4f %10.4f %10.4f %10.4f %10.4f\\n', prob(1:5) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' An automatic pause of 2 seconds is imposed between \\n;' );\n fprintf ( 1, ' successive displays.\\n' );\n%\n% Initialize C1.\n%\n [ c1, seed ] = ising_2d_initialize ( m, n, thresh, seed );\n%\n% Do the simulation.\n%\n [ c1, seed ] = transition ( m, n, iterations, prob, seed, c1 );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ISING_2D_SIMULATION\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction i4mat_print ( m, n, a, title )\n\n%*****************************************************************************80\n%\n%% I4MAT_PRINT prints an I4MAT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 September 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns of the matrix.\n%\n% Input, integer A(M,N), an M by N matrix to be printed.\n%\n% Input, string TITLE, a title.\n%\n i4mat_print_some ( m, n, a, 1, 1, m, n, title );\n\n return\nend\nfunction i4mat_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )\n\n%*****************************************************************************80\n%\n%% I4MAT_PRINT_SOME prints out a portion of an I4MAT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns of the matrix.\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 if ( m <= 0 || n <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' (None)\\n' );\n return\n end\n\n for j2lo = max ( jlo, 1 ): incx : min ( jhi, n )\n\n j2hi = j2lo + incx - 1;\n j2hi = min ( j2hi, n );\n j2hi = min ( j2hi, jhi );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Col: ' );\n\n for j = j2lo : j2hi\n fprintf ( 1, '%7d ', j );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Row\\n' );\n fprintf ( 1, '\\n' );\n\n i2lo = max ( ilo, 1 );\n i2hi = min ( ihi, m );\n\n for i = i2lo : i2hi\n\n fprintf ( 1, '%5d: ', i );\n for j = j2lo : j2hi\n fprintf ( 1, '%7d ', a(i,j) );\n end\n\n fprintf ( 1, '\\n' );\n\n end\n\n end\n\n return\nend\nfunction [ c, seed ] = i4mat_uniform ( m, n, a, b, seed )\n\n%*****************************************************************************80\n%\n%% I4MAT_UNIFORM returns a scaled pseudorandom I4MAT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2006\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% Pierre L'Ecuyer,\n% Random Number Generation,\n% in Handbook of Simulation,\n% edited by Jerry Banks,\n% Wiley Interscience, page 95, 1998.\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 row and column dimensions of the matrix.\n%\n% Input, integer A, B, the minimum and maximum acceptable values.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, integer C(M,N), the randomly chosen integer vector.\n%\n% Output, integer SEED, the updated seed.\n%\n if ( seed == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_UNIFORM - Fatal error!\\n' );\n fprintf ( 1, ' Input SEED = 0!\\n' );\n error ( 'I4MAT_UNIFORM - Fatal error!' );\n end\n\n seed = floor ( seed );\n a = round ( a );\n b = round ( b );\n\n for j = 1 : n\n\n for i = 1 : m\n\n seed = mod ( seed, 2147483647 );\n\n if ( seed < 0 ) \n seed = seed + 2147483647;\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 + 2147483647;\n end\n\n r = seed * 4.656612875E-10;\n%\n% Scale R to lie between A-0.5 and B+0.5.\n%\n r = ( 1.0 - r ) * ( min ( a, b ) - 0.5 ) ...\n + r * ( max ( a, b ) + 0.5 );\n%\n% Use rounding to convert R to an integer between A and B.\n%\n value = round ( r );\n\n value = max ( value, min ( a, b ) );\n value = min ( value, max ( a, b ) );\n\n c(i,j) = value;\n\n end\n end\n\n return\nend\nfunction c5 = ising_2d_agree ( m, n, c1 )\n\n%*****************************************************************************80\n%\n%% ISING_2D_AGREE returns the number of neighbors agreeing with each cell.\n%\n% Discussion:\n%\n% The count includes the cell itself, so it is between 1 and 5.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of cells in each spatial dimension.\n%\n% Input, integer C1(M,N), an array of 1's and -1's.\n%\n% Output, integer C5(M,N), the number of neighbors that agree.\n% 1, 2, 3, 4, or 5.\n%\n c5 = c1 ...\n + circshift ( c1, [ -1, 0 ] ) ...\n + circshift ( c1, [ +1, 0 ] ) ...\n + circshift ( c1, [ 0, -1 ] ) ...\n + circshift ( c1, [ 0, +1 ] );\n\n i = find ( 0 < c1 );\n c5(i) = ( 5 + c5(i) ) / 2;\n\n i = find ( c1 < 0 );\n c5(i) = ( 5 - c5(i) ) / 2;\n\n return\nend\nfunction ising_2d_display ( step, m, n, c1 )\n\n%*****************************************************************************80\n%\n%% ISING_2D_DISPLAY displays the current Ising status.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer STEP, the step number.\n%\n% Input, integer M, N, the number of rows and columnss.\n%\n% Input, integer C1(M,N), the status of each cell:\n% -1, display as a shade of red.\n% +1, display as a shade of blue.\n%\n figure ( 1 )\n%\n% Clear the graphics frame.\n%\n clf\n%\n% Determine the plot range.\n%\n margin = 0.05;\n\n x_axes_min = 1.0 - 0.5 - margin;\n x_axes_max = m + 0.5 + margin;\n y_axes_min = 1.0 - 0.5 - margin;\n y_axes_max = n + 0.5 + margin;\n%\n% Fill in the background with black.\n%\n x1 = x_axes_min;\n x2 = x_axes_max;\n y1 = y_axes_min;\n y2 = y_axes_max;\n\n rgb = [ 0.5, 0.5, 0.5 ];\n\n fill ( [ x1, x2, x2, x1 ], [ y1, y1, y2, y2 ], rgb );\n hold on\n%\n% Draw a square, representing the bed,\n% with most of the length and width, centered at (I,J).\n%\n for i = 1 : m\n for j = 1 : n\n\n x1 = j - 0.47;\n x2 = j + 0.47;\n y1 = ( m + 1 - i ) - 0.47;\n y2 = ( m + 1 - i ) + 0.47;\n\n if ( c1(i,j) == - 1 )\n rgb = [ 1.0, 0.0, 0.0 ];\n elseif ( c1(i,j) == + 1 )\n rgb = [ 0.0, 0.0, 1.0 ];\n end\n\n fill ( [ x1, x2, x2, x1 ], [ y1, y1, y2, y2 ], rgb );\n hold on\n\n end\n end\n%\n% Make a title.\n%\n title_string = sprintf ( 'Ising charges +1/-1 on step %d', step );\n\n title ( title_string )\n%\n% Choose the aspect ratio and other plot details.\n%\n axis ( [ x_axes_min, x_axes_max, y_axes_min, y_axes_max] );\n axis equal\n axis tight\n axis off\n\n hold off\n\n pause ( 2 )\n\n return\nend\nfunction [ c1, seed ] = ising_2d_initialize ( m, n, thresh, seed )\n\n%*****************************************************************************80\n%\n%% ISING_2D_INITIALIZE initializes the Ising array.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 November 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 THRESH, the threshhold value, between 0 and 1.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, integer C1(M,N), an array of 1's and -1's.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n c1 = ones ( m, n );\n\n [ r, seed ] = r8mat_uniform_01 ( m, n, seed );\n \n i = find ( r <= thresh );\n\n c1(i) = -1;\n\n return\nend\nfunction ising_2d_stats ( step, m, n, c1 )\n\n%*****************************************************************************80\n%\n%% ISING_2D_STATS prints information about the current step.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer STEP, the step number.\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, integer C1(M,N), the current state of the system.\n%\n if ( step == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Step Positives Negatives\\n' );\n fprintf ( 1, ' # %% # %%\\n' );\n fprintf ( 1, '\\n' );\n end\n\n pos_count = sum ( sum ( 0 < c1 ) );\n neg_count = m * n - pos_count;\n pos_percent = ( 100 * pos_count ) / ( m * n );\n neg_percent = ( 100 * neg_count ) / ( m * n );\n\n fprintf ( 1, ' %4d %6d %6.2f %6d %6.2f\\n', ...\n step, pos_count, pos_percent, neg_count, neg_percent );\n\n return\nend\nfunction neighbor_2d_display ( step, m, n, c1, c5 )\n\n%*****************************************************************************80\n%\n%% NEIGHBOR_2D_DISPLAY displays the current Ising neighbor status.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer STEP, the step number.\n%\n% Input, integer M, N, the number of rows and columnss.\n%\n% Input, integer C1(M,N), the status of each cell:\n%\n% Input, integer C5(M,N), the number of agreeable neighbors.\n%\n figure ( 2 )\n%\n% Clear the graphics frame.\n%\n clf\n%\n% Determine the plot range.\n%\n margin = 0.05;\n\n x_axes_min = 1.0 - 0.5 - margin;\n x_axes_max = m + 0.5 + margin;\n y_axes_min = 1.0 - 0.5 - margin;\n y_axes_max = n + 0.5 + margin;\n%\n% Fill in the background with black.\n%\n x1 = x_axes_min;\n x2 = x_axes_max;\n y1 = y_axes_min;\n y2 = y_axes_max;\n\n rgb = [ 0.5, 0.5, 0.5 ];\n\n fill ( [ x1, x2, x2, x1 ], [ y1, y1, y2, y2 ], rgb );\n hold on\n%\n% Draw a square, representing the bed,\n% with most of the length and width, centered at (I,J).\n%\n for i = 1 : m\n for j = 1 : n\n\n x1 = j - 0.47;\n x2 = j + 0.47;\n y1 = ( m + 1 - i ) - 0.47;\n y2 = ( m + 1 - i ) + 0.47;\n\n c = c1(i,j) * c5(i,j);\n\n if ( c == - 5 )\n rgb = [ 1.0, 0.0, 0.0 ];\n elseif ( c == - 4 )\n rgb = [ 1.0, 0.2, 0.2 ];\n elseif ( c == - 3 )\n rgb = [ 1.0, 0.4, 0.4 ];\n elseif ( c == - 2 )\n rgb = [ 1.0, 0.7, 0.7 ];\n elseif ( c == - 1 )\n rgb = [ 1.0, 0.8, 0.8 ];\n elseif ( c == 0 )\n rgb = [ 1.0, 1.0, 1.0 ];\n elseif ( c == + 1 )\n rgb = [ 0.7, 0.7, 1.0 ];\n elseif ( c == + 2 )\n rgb = [ 0.6, 0.6, 1.0 ];\n elseif ( c == + 3 )\n rgb = [ 0.4, 0.4, 1.0 ];\n elseif ( c == + 4 )\n rgb = [ 0.2, 0.2, 1.0 ];\n elseif ( c == + 5 )\n rgb = [ 0.0, 0.0, 1.0 ];\n end\n\n fill ( [ x1, x2, x2, x1 ], [ y1, y1, y2, y2 ], rgb );\n hold on\n\n end\n end\n%\n% Make a title.\n%\n title_string = sprintf ( 'Ising neighborhoods -5 to +5, step %d to step %d', step-1, step );\n\n title ( title_string )\n%\n% Choose the aspect ratio and other plot details.\n%\n axis ( [ x_axes_min, x_axes_max, y_axes_min, y_axes_max] );\n axis equal\n axis tight\n axis off\n\n hold off\n\n pause ( 2 )\n\n return\nend\nfunction neighbor_2d_stats ( step, m, n, c1, c5 )\n\n%*****************************************************************************80\n%\n%% NEIGHBOR_2D_STATS prints neighbor statistics about the current step.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer STEP, the step number.\n%\n% Input, integer M, N, the number of rows and columns.\n%\n% Input, integer C1(M,N), the current state of the system.\n%\n% Input, integer C5(M,N), the number of agreeable neighbors.\n%\n if ( step == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Step Neighborhood Charge:\\n' );\n fprintf ( 1, ...\n ' -5 -4 -3 -2 -1 +1 +2 +3 +4 +5\\n' );\n fprintf ( 1, '\\n' );\n end\n\n fprintf ( 1, ' %4d', step );\n\n for n = -5 : 5\n if ( n ~= 0 )\n c = sum ( sum ( c1 .* c5 == n ) );\n fprintf ( 1, ' %4d', c );\n end\n end\n fprintf ( 1, '\\n' );\n \n return\nend\nfunction [ r, seed ] = r8mat_uniform_01 ( m, n, seed )\n\n%*****************************************************************************80\n%\n%% R8MAT_UNIFORM_01 returns a unit pseudorandom R8MAT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 September 2006\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 the array.\n%\n% Input, integer SEED, the integer \"seed\" used to generate\n% the output random number.\n%\n% Output, real R(M,N), an array of random values between 0 and 1.\n%\n% Output, integer SEED, the updated seed. This would\n% normally be used as the input seed on the next call.\n%\n r = zeros ( m, n );\n\n if ( seed == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_UNIFORM_01 - Fatal error!\\n' );\n fprintf ( 1, ' Input SEED = 0!\\n' );\n error ( 'R8MAT_UNIFORM_01 - Fatal error!' );\n end\n\n for j = 1 : n\n for i = 1 : m\n\n seed = floor ( seed );\n\n seed = mod ( seed, 2147483647 );\n\n if ( seed < 0 ) \n seed = seed + 2147483647;\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 + 2147483647;\n end\n\n r(i,j) = seed * 4.656612875E-10;\n\n end\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\nfunction [ c1, seed ] = transition ( m, n, iterations, prob, seed, c1 )\n\n%*****************************************************************************80\n%\n%% TRANSITION carries out a Monte Carlo simulation of a 2D Ising model.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of cells in each spatial\n% dimension.\n%\n% Input, integer ITERATIONS, the number of iterations to carry out.\n%\n% Input, real PROB(1:5). PROB(I) represents the probability\n% that the spin of a given cell will be reversed, given that it has I immediate\n% neighbors (including itself) with spin the same as its own.\n%\n% Input/output, integer SEED, a seed for the random number generator.\n%\n% Input/output, integer C1(M,N). On input, the current state of the\n% system. On output, the state of the system after the iterations.\n%\n step = 0;\n ising_2d_stats ( step, m, n, c1 );\n ising_2d_display ( step, m, n, c1 );\n\n for step = 1 : iterations\n%\n% C5 contains 1 through 5, the number of cells that agree with the center cell.\n%\n c5 = ising_2d_agree ( m, n, c1 );\n\n if ( 0 )\n neighbor_2d_stats ( step, m, n, c1, c5 );\n end\n\n if ( 0 )\n neighbor_2d_display ( step, m, n, c1, c5 );\n end\n%\n% Determine the chances of flipping cell (I,J).\n%\n threshhold = zeros ( m, n );\n\n for j = 1 : 5\n i = find ( c5 == j );\n threshhold(i) = prob(j);\n end\n\n [ r, seed ] = r8mat_uniform_01 ( m, n, seed );\n\n i = find ( r < threshhold );\n\n c1(i) = - c1(i);\n\n ising_2d_stats ( step, m, n, c1 );\n ising_2d_display ( step, m, n, c1 );\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/ising_2d_simulation/ising_2d_simulation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7364995894976065}} {"text": "function value = i4_characteristic ( q )\n\n%*****************************************************************************80\n%\n%% I4_CHARACTERISTIC gives the characteristic for an integer.\n%\n% Discussion:\n%\n% For any positive integer Q, the characteristic is:\n%\n% Q, if Q is a prime;\n% P, if Q = P^N for some prime P and some integer N;\n% 0, otherwise, that is, if Q is negative, 0, 1, or the product\n% of more than one distinct prime.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2005\n%\n% Author:\n%\n% FORTRAN77 original version by Bratley, Fox, Niederreiter.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Paul Bratley, Bennett Fox, Harald Niederreiter,\n% Algorithm 738:\n% Programs to Generate Niederreiter's Low-Discrepancy Sequences,\n% ACM Transactions on Mathematical Software,\n% Volume 20, Number 4, pages 494-495, 1994.\n%\n% Parameters:\n%\n% Input, integer Q, the value to be tested.\n%\n% Output, integer VALUE, the characteristic of Q.\n%\n if ( q <= 1 )\n value = 0;\n return\n end\n%\n% If Q is not prime, then there is at least one prime factor\n% of Q no greater than SQRT(Q)+1.\n%\n% A faster code would only consider prime values of I,\n% but that entails storing a table of primes and limiting the\n% size of Q. Simplicity and flexibility for now!\n%\n i_max = floor ( sqrt ( q ) ) + 1;\n\n for i = 2 : i_max\n\n if ( mod ( q, i ) == 0 )\n\n while ( mod ( q, i ) == 0 )\n q = q / i;\n end\n\n if ( q == 1 )\n value = i;\n else\n value = 0;\n end\n\n return\n\n end\n\n end\n%\n% If no factor was found, then Q is prime.\n%\n value = q;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/i4lib/i4_characteristic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.736475169471068}} {"text": "function [A1, B1, C1, A2, B2, C2] = sss(a, b, c)\n%SSS gives both solutions to the side-side-side problem, in radians.\n%\n% SSS(a, b, c) results in NaNs for those indices where the existence \n% condition |pi - a| - |pi - b| <= |pi - c| <= |pi - a| + |pi -b| is not\n% met. \n%\n% See also SSSD.\n\n% Rody P.S. Oldenhuis\n% Delft University of Technology\n% oldenhuis@gmail.com\n%\n% Created : 23/Feb/2009\n% Last edited: 30/Nov/2012\n\n % first solution\n A1 = acos2( (cos(a) - cos(b).*cos(c))./(sin(b).*sin(c)), a);\n B1 = acos2( (cos(b) - cos(a).*cos(c))./(sin(a).*sin(c)), b);\n C1 = acos2( (cos(c) - cos(a).*cos(b))./(sin(a).*sin(b)), c);\n \n % second solution\n A2 = 2*pi - A1;\n B2 = 2*pi - B1;\n C2 = 2*pi - C1;\n \n % check constraints\n indices = ( ...\n (abs(pi-a) - abs(pi-b)) > abs(pi-c) | ...\n abs(pi-c) > (abs(pi-a) + abs(pi-b)) );\n A1(indices) = NaN; B1(indices) = NaN; C1(indices) = NaN;\n A2(indices) = NaN; B2(indices) = NaN; C2(indices) = NaN;\n \nend", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SphericalTrigToolbox/sss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768620069626, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.7364512586070452}} {"text": "function proj2d = projection(data3d,param, angle_rad)\n\nproj2d = zeros(param.nu,param.nv,'single');\n\n[uu,vv] = meshgrid(param.us,param.vs);\n\n[xx,yy] = meshgrid(param.xs,param.ys);\n\nrx = xx.*cos(angle_rad) - yy.*sin(angle_rad);\nry = xx.*sin(angle_rad) + yy.*cos(angle_rad);\n\nfor iz = 1:param.nz \n \n data3d(:,:,iz) = interp2(xx,yy ,data3d(:,:,iz),rx,ry,'linear');\n \nend\n\ndata3d(isnan(data3d))=0;\n\ndata3d = permute(data3d,[1 3 2]);\n\n[xx,zz] = meshgrid(param.xs,param.zs);\n\nfor iy = 1:param.ny\n \n Ratio = (param.ys(iy)+param.DSO)/(param.DSD);\n \n pu = uu*Ratio;\n pv = vv*Ratio; \n \n pu = (pu - xx(1,1))/(param.dx)+1; \n pv = (pv - zz(1,1))/(param.dz)+1; \n \n tmp = interp2(data3d(:,:,iy),pv,pu,'linear');\n \n tmp(isnan(tmp))=0;\n \n proj2d = proj2d + tmp';\nend\n\ndist = sqrt((param.DSD)^2 + uu.^2 + vv.^2)./(param.DSD)*param.dy;\n\nproj2d = proj2d .* dist';\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/35548-3d-cone-beam-ct-cbct-projection-backprojection-fdk-mlem-reconstruction-matlab-codes-for-students/CBCT_FDK_MLEM_April_2013/projection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7364512428236126}} {"text": "function value = scnrm2 ( n, x, incx )\n\n%*****************************************************************************80\n%\n%% SCNRM2 returns the euclidean norm of a complex vector.\n%\n% Discussion:\n%\n% SCNRM2 := sqrt ( sum ( conjg ( x(1:n) ) * x(1:n) ) )\n% = sqrt ( dot_product ( x(1:n), x(1:n) ) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 April 2006\n%\n% Author:\n%\n% MATLAB version by 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% LC: QA214.L56.\n%\n% Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,\n% Basic Linear Algebra Subprograms for FORTRAN usage,\n% ACM Transactions on Mathematical Software,\n% Volume 5, Number 3, pages 308-323, 1979.\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vector.\n%\n% Input, complex X(*), the vector.\n%\n% Input, integer INCX, the increment between successive entries of X.\n%\n% Output, real VALUE, the norm of the vector.\n%\n value = sqrt ( sum ( ( real ( x(1:incx:1+(n-1)*incx) ) ).^2 ) ...\n + sum ( ( imag ( x(1:incx:1+(n-1)*incx) ) ).^2 ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linpack_c/scnrm2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7364495194098749}} {"text": "classdef hessenberg\n% Functions to work with Hessenberg forms\n\nmethods(Static)\n\n\nfunction [Q, R] = qr(A)\n % Givens method for computing the QR factorization A = QR of a Hessenberg matrix.\n % A is modified in the algorithm\n % GVL4: algorithm 5.2.5\n import spx.la.givens.rotation;\n [n,n] = size(A);\n % Space for saving the Q factor\n Q = eye(n, n);\n % iterate over each column from first to last but one.\n for j=1:n-1\n % We need to process only one pair of rows\n % The diagonal element and immediate sub-diagonal element.\n a = A(j,j);\n b = A(j+1,j);\n % Compute the needed rotation for making b 0.\n [c,s] = rotation(a,b);\n % Form the givens rotation matrix.\n G = [c s;-s c];\n % Rotate the two consecutive rows based submatrix\n A(j:j+1,j:n) = G'*A(j:j+1,j:n);\n % Rotate corresponding columns n Q matrix\n % by postmultiplication with G\n Q(:,j:j+1) = Q(:,j:j+1)*G;\n end\n % Return the triangular form\n R = A;\nend % function\n\n\n\nfunction [H, cs, ss] = qr_rq(H)\n % Takes a Hessenberg matrix H = QR and returns RQ\n % GVL4: algorithm 7.4.1\n import spx.la.givens.rotation;\n [n,n] = size(H);\n % Space for storing the c and s values\n cs = zeros(1, n);\n ss = zeros(1, n);\n % first the QR factorization\n % iterate over each column from first to last but one.\n for k=1:n-1\n % We need to process only one pair of rows\n % The diagonal element and immediate sub-diagonal element.\n a = H(k,k);\n b = H(k+1,k);\n % Compute the needed rotation for making b 0.\n [c,s] = rotation(a,b);\n % Store the rotation\n cs(k) = c;\n ss(k) = s;\n % Form the givens rotation matrix.\n G = [c s;-s c];\n % Rotate the two consecutive rows based submatrix\n H(k:k+1,k:n) = G'*H(k:k+1,k:n);\n end\n % Now the RQ formation\n for k=1:n-1\n G = [cs(k) ss(k); -ss(k) cs(k)];\n H(1:k+1,k:k+1) = H(1:k+1,k:k+1) * G;\n end\n % The product of these Givens rotations is also upper Hessenberg.\n % Product of two Hessenberg matrices is Hessenberg.\nend % function\n\n\nfunction [H, U0] = hess(A)\n % Reduction of a square matrix A into Hessenberg form \n % using Householder reflections\n % GVL4: algorithm 7.4.2\n [n,n] = size(A);\n import spx.la.house;\n % Iterate over columns of A\n for k=1:n-2\n % Compute the householder reflector for k-th column\n % covering only sub-diagonal elements\n [v,beta] = house.gen(A(k+1:n,k));\n % Update the submatrix of A by premultiplication with the Projector\n A(k+1:n,k:n) = A(k+1:n,k:n) - (beta*v)*(v'*A(k+1:n,k:n));\n % Postmultiply with the same projector without affecting\n % the 0's in the k-th column\n A(:,k+1:n) = A(:,k+1:n) - (A(:,k+1:n)*v)*(beta*v)';\n % Store the householder reflection vector \n A(k+2:n,k) = v(2:n-k);\n end\n % Extract the Hessenberg form\n H = triu(A,-1);\n if nargout > 1\n % Extract the orthogonal matrix U_0 such that\n % A = U_0 H U_0^T\n U0 = eye(n,n);\n U0(2:n,2:n) = house.q_back_accum_full(A(2:n,1:n-1));\n end\nend % function\n\n\nfunction [H, i1, i2] = backsearch(H, z)\n % Searches for a subdiagonal entry in H which is\n % negligible. From last row to first row.\n if nargin < 2\n z = size(H, 2);\n end\n i1 = z;\n i2 = z;\n % Compute the Frobenius norm of H\n h_norm = norm(H, 'fro');\n % The threshold for negligible entries\n thr = eps * h_norm\n % iterate over diagonal entries backwards\n while i1 >1\n % check for negligible subdiagonal entry.\n fprintf('%d, %d, %e\\n', i1, i1-1, H(i1, i1-1));\n if (abs(H(i1, i1-1)) < thr )\n % Make this entry zero\n H(i1, i1-1) = 0;\n if (i1 == i2)\n i2 = i1 - 1;\n i1 = i1 - 1;\n else\n return;\n end\n else\n i1 = i1 - 1;\n end\n\n end\nend\n\n\nend % methods \n\nend % classdef\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/library/+spx/+la/hessenberg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7364156412078564}} {"text": "function y=rdct(x,n,a,b)\n%RDCT Discrete cosine transform of real data Y=(X,N,A,B)\n% Data is truncated/padded to length N.\n%\n% This routine is equivalent to multiplying by the matrix\n%\n% rdct(eye(n)) = diag([sqrt(2)*B/A repmat(2/A,1,n-1)]) * cos((0:n-1)'*(0.5:n)*pi/n)\n%\n% Default values of the scaling factors are A=sqrt(2N) and B=1 which\n% results in an orthogonal matrix. Other common values are A=1 or N and/or B=1 or sqrt(2). \n% If b~=1 then the columns are no longer orthogonal.\n%\n% see IRDCT for the inverse transform\n\n% BUG: in line 51 we should do chopping after transform and not before\n\n\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: rdct.m,v 1.6 2007/05/04 07:01:39 dmb Exp $\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\nfl=size(x,1)==1;\nif fl x=x(:); end\n[m,k]=size(x);\nif nargin<2 n=m;\nend\nif nargin<4 b=1; \n if nargin<3 a=sqrt(2*n);\n end\n end\nif n>m x=[x; zeros(n-m,k)];\nelseif n0\n rat_na_lt(n_index) = (log(1+P) - sqrt(1-(1+P)^(-2))./sqrt(nn(n_index)) + 0.5*log(nn(n_index))./nn(n_index))/log(2); \nend\n \n\n\nR_st = C - sqrt(V./nn)*qfuncinv(error);\nC_lt=log(1+P/(1-error)); \n\nindex_large_n = find(nn>n_min);\n\nfor ii=index_large_n\n n=nn(ii);\n for R_star = R_st(ii):0.0001:C_lt\n omega = P: 0.00001:P*1.2; %note that larger endpoing for omega (P*1.2) gives a better estimate for rate_na;\n \n q_arg=sqrt(n)*(log(1+omega)-R_star)./sqrt(1-(1+omega).^(-2)) ;\n \n error_temp = min( 1-P./omega + P.*qfunc( q_arg)./omega);\n if error_temp> error\n rate_na_lt(ii)= (R_star +0.5*log(n)./n)./log(2) ;\n break\n end\n end\nend\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/long-term-power-constraint/awgn/awgn_na_lt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7363208325590677}} {"text": "function value = p16_exact ( dim_num )\n\n%*****************************************************************************80\n%\n%% P16_EXACT returns the exact integral for problem 16.\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 spatial dimension.\n%\n% Output, real VALUE, the exact value of the integral.\n%\n\n%\n% Get the limits of integration.\n%\n [ a, b ] = p16_lim ( dim_num );\n%\n% Get the location of Z.\n%\n z = [];\n z = p16_r8vec ( 'G', 'Z', dim_num, z );\n%\n% The value of the DIM_NUM dimensional integral can be broken down\n% into the weighted sum of 1 dimensional integrals.\n%\n value = 0.0;\n\n volume = prod ( b(1:dim_num) - a(1:dim_num) );\n\n for i = 1 : dim_num\n%\n% Z < A < B\n%\n if ( z(i) < a(i) )\n\n integral = 0.5 * ( b(i) - a(i) ) * ( b(i) + a(i) - 2.0 * z(i) );\n%\n% A < Z < B\n%\n elseif ( z(i) < b(i) )\n\n integral = 0.5 * ( ( b(i) - z(i) )^2 + ( z(i) - a(i) )^2 );\n%\n% A < B < Z\n%\n else\n\n integral = 0.5 * ( b(i) - a(i) ) * ( 2.0 * z(i) - a(i) - b(i) );\n\n end\n\n value = value + volume * integral / ( b(i) - a(i) );\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/quadrature_test/p16_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7362501641793358}} {"text": "function f = goldstein_price_xy ( x, y )\n\n%*****************************************************************************80\n%\n%% GOLDSTEIN_PRICE_XY evaluates the Goldstein-Price polynomial.\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% Zbigniew Michalewicz,\n% Genetic Algorithms + Data Structures = Evolution Programs,\n% Third Edition,\n% Springer Verlag, 1996,\n% ISBN: 3-540-60676-9,\n% LC: QA76.618.M53.\n%\n% Parameters:\n%\n% Input, real X, Y, the arguments of the function.\n%\n% Output, real F, the value of the function at X.\n%\n a = x + y + 1.0;\n\n b = 19.0 - 14.0 * x + 3.0 * x * x - 14.0 * y ...\n + 6.0 * x * y + 3.0 * y * y;\n\n c = 2.0 * x - 3.0 * y;\n\n d = 18.0 - 32.0 * x + 12.0 * x * x + 48.0 * y ...\n - 36.0 * x * y + 27.0 * y * y;\n\n f = ( 1.0 + a * a * b ) * ( 30.0 + c * c * 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/levels/goldstein_price_xy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7362501621779486}} {"text": "function v = fdm_2d_vector(n0,f_str)\n%\n% Generates a vector v which contains the values of a function f(x,y) \n% on an equidistant grid in the interior of the unit square. The grid\n% points are numbered consistently with those used in the function\n% 'fdm_2d_matrix'.\n%\n% This function is just used as an easy way to generate test problems\n% rather than to solve PDEs.\n%\n% Calling sequence:\n% \n% v = fdm_2d_vector( n0, f_str)\n%\n% Input:\n% \n% n0 number of inner grid points in each dimension;\n% f_str string describing the function f in the space variables 'x'\n% and 'y', e.g., f_str = 'sin(x+2*y)+3'. \n%\n% Output:\n%\n% v vector of order n = n0^2 containing the values of f(x,y).\n%\n%\n% LYAPACK 1.0 (Thilo Penzl, May 1999)\n\n% Input data not completely checked!\n\nna = nargin;\n\nif na~=2\n error('Wrong number of input parameters.');\nend\n\nh = 1.0/(n0+1); \n\nn2 = n0*n0;\n\nv = zeros(n2,1);\n\ni = 0;\n\nfor iy = 1:n0\n y = iy*h;\n for ix = 1:n0\n x = ix*h;\n i = i+1;\n v(i) = eval(f_str);\n end\nend \n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21-lyapack/lyapack/examples/fdm_2d_vector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7362501601765613}} {"text": "function an=euler2axan(phi,theta,psi,M)\n% From Euler angles (phi,theta,psi) to axis angle (x y z alpha)/(gamma,delta):\n\n% v=[(cos(al-gm)+1)*(1-cos(bt));\n% sin(al-gm)*(1-cos(bt));\n% sin(bt)*(sin(al)+sin(gm))]\n\ncost=cos(theta);\nsint=cos(theta);\nomcost=(1-cost);\nif sint==0\n x=0;\n y=0;\n z=1;\nelse\n x = (cos(phi-psi)+1)*omcost;\n y = sin(phi-psi)*omcost;\n z = sint*(sin(phi)+sin(psi));\nend\n\nif (x==0)&&(y==0)&&(z==0)\n x=1;\n y=0;\n z=0;\nelse\n vn=sqrt(x^2+y^2+z^2);\n x=x/vn;\n y=y/vn;\n z=z/vn;\nend\n\nv=[x y z]';\n\n%[THETA,PHI,R] = cart2sph(X,Y,Z)\n\n[gamma,delta,tmp] = cart2sph(x,y,z);\n\ncppp=cos(phi+psi);\nTr=cppp+cppp*cost+cost;\nalpha=atan2(-(M(1,2)*v(3)+M(2,3)*v(1)+M(3,1)*v(2)-M(1,3)*v(2)-M(3,2)*v(1)-M(2,1)*v(3)),Tr-1);\n% if (-(M(1,2)*v(3)+M(2,3)*v(1)+M(3,1)*v(2)-M(1,3)*v(2)-M(3,2)*v(1)-M(2,1)*v(3)))>=0\n% alpha=acos((Tr-1)/2);\n% else\n% alpha=-acos((Tr-1)/2);\n% end\n\nan={{gamma,delta,alpha},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/24067-eular-angles-gui/euler_files/euler2axan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7362390965190387}} {"text": "function [Y,T]=derivs(x,dim)\n%Syntax: [Y,T]=derivs(x,dim) \n%____________________________ \n%\n% The phase space reconstruction of a time series x whith the derivatives approach,\n% in embedding dimension m.\n% \n% Y is the trajectory matrix in the reconstructed phase space.\n% T is the phase space length.\n% x is the time series. \n% dim is the embedding dimension.\n%\n%\n% Reference:\n%\n% Packard N H, Cruchfield J P, Farmer J D, Shaw R S (1980): Geometry from a Time\n% Series. Physical Review Letters 45: 712-715\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% 11 Mar 2001.\n\nif nargin<1 | isempty(x)==1\n error('You should provide a time series.');\nelse\n % x must be a vector\n if min(size(x))>1\n error('Invalid time series.');\n end\n x=x(:);\n % N is the time series length\n N=length(x);\nend\n\nif nargin<2 | isempty(dim)==1\n dim=2;\nelse\n % dim must be scalar\n if sum(size(dim))>2\n error('dim must be scalar.');\n end\n % dim must be an integer\n if dim-round(dim)~=0\n error('dim must be an integer.');\n end\n % dim must be positive\n if dim<=0\n error('dim must be positive.');\n end\nend\n\n\n% Initialize the phase space\nY=zeros(N,dim);\n\n% Phase space reconstruction with the derivatives approach\nY(:,1)=x;\nfor i=2:dim\n Y(:,i)=[diff(Y(:,i-1));0];\nend\n\n% Total points on phase space \nT=N-(dim-1);\n\n% Remove the meaningless points\nY(T+1: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/1597-chaotic-systems-toolbox/derivs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7361696935571364}} {"text": "function bvec2 = bvec_complement2 ( n, bvec1 )\n\n%*****************************************************************************80\n%\n%% BVEC_COMPLEMENT2 computes the two's complement of a binary vector.\n%\n% Discussion:\n%\n% A BVEC is an integer vector of binary digits, intended to\n% represent an integer. BVEC(1) is the units digit, BVEC(N-1)\n% is the coefficient of 2^(N-2), and BVEC(N) contains sign\n% information. It is 0 if the number is positive, and 1 if\n% the number is negative.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 November 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the length of the vectors.\n%\n% Input, integer BVEC1(N), the vector to be complemented.\n%\n% Output, integer BVEC2(N), the two's complemented vector.\n%\n base = 2;\n\n bvec3(1:n) = ( base - 1 ) - bvec1(1:n);\n\n bvec4(1) = 1;\n bvec4(2:n) = 0;\n\n bvec2 = bvec_add ( n, bvec3, bvec4 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/bvec/bvec_complement2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7361696867073889}} {"text": "function fd1d_heat_implicit_test03 ( )\n\n%*****************************************************************************80\n%\n%% FD1D_HEAT_IMPLICIT_TEST03 does a simple test problem.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 30 January 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD1D_HEAT_IMPLICIT_TEST03:\\n' );\n fprintf ( 1, ' Compute an approximate solution to the time-dependent\\n' );\n fprintf ( 1, ' one dimensional heat equation:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' dH/dt - K * d2H/dx2 = f(x,t)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Run a simple test case.\\n' );\n%\n% Heat coefficient.\n%\n k = k_test03 ( );\n%\n% X_NUM is the number of equally spaced nodes to use between 0 and 1.\n%\n x_num = 21;\n x_min = -5.0;\n x_max = +5.0;\n dx = ( x_max - x_min ) / ( x_num - 1 );\n x = linspace ( x_min, x_max, x_num );\n%\n% T_NUM is the number of equally spaced time points between 0 and 10.0.\n%\n t_num = 81;\n t_min = 0.0;\n t_max = 4.0;\n dt = ( t_max - t_min ) / ( t_num - 1 );\n t = linspace ( t_min, t_max, t_num );\n%\n% Get the CFL coefficient.\n%\n cfl = fd1d_heat_implicit_cfl ( k, t_num, t_min, t_max, x_num, x_min, x_max );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of X nodes = %d\\n', x_num );\n fprintf ( 1, ' X interval is [%f,%f]\\n', x_min, x_max );\n fprintf ( 1, ' X spacing is %f\\n', dx );\n fprintf ( 1, ' Number of T values = %d\\n', t_num );\n fprintf ( 1, ' T interval is [%f,%f]\\n', t_min, t_max );\n fprintf ( 1, ' T spacing is %f\\n', dt );\n fprintf ( 1, ' Constant K = %g\\n', k );\n fprintf ( 1, ' CFL coefficient = %g\\n', cfl );\n%\n% Get the system matrix.\n%\n a = fd1d_heat_implicit_matrix ( x_num, cfl );\n\n hmat = zeros ( x_num, t_num );\n\n for j = 1 : t_num\n if ( j == 1 )\n h = ic_test03 ( x_num, x, t(j) );\n h = bc_test03 ( x_num, x, t(j), h );\n else\n h = fd1d_heat_implicit ( a, x_num, x, t(j-1), dt, cfl, @rhs_test03, @bc_test03, h );\n end\n hmat(1:x_num,j) = h(1:x_num);\n end\n%\n% Plot the data.\n%\n figure ( 3 )\n [ tmat, xmat ] = meshgrid ( t, x );\n mesh ( tmat, xmat, hmat );\n title ( 'H(X,T) for TEST03 computed by FD1D\\_HEAT\\_IMPLICIT' );\n xlabel ( '<-- Time -->' );\n ylabel ( '<-- X -->' );\n zlabel ( '<-- H(X,T) -->' );\n%\n% Write the data to files.\n%\n r8mat_write ( 'h_test03.txt', x_num, t_num, hmat );\n r8vec_write ( 't_test03.txt', t_num, t );\n r8vec_write ( 'x_test03.txt', x_num, x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' H(X,T) written to \"h_test03.txt\"\\n' );\n fprintf ( 1, ' T values written to \"t_test03.txt\"\\n' );\n fprintf ( 1, ' X values written to \"x_test3.txt\"\\n' );\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fd1d_heat_implicit/fd1d_heat_implicit_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7361696845309766}} {"text": "function jacobi_eigenvalue_test02 ( )\n\n%*****************************************************************************80\n%\n%% JACOBI_EIGENVALUE_TEST02 uses a 4x4 test matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 14 July 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_EIGENVALUE_TEST02\\n' );\n fprintf ( 1, ' For a symmetric matrix A,\\n' );\n fprintf ( 1, ' JACOBI_EIGENVALUE computes the eigenvalues D\\n' );\n fprintf ( 1, ' and eigenvectors V so that A * V = D * V.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' As a \"sanity check\", input a diagonal matrix.\\n' );\n \n n = 4;\n\n a = [ ...\n 4.0, 0.0, 0.0, 0.0;\n 0.0, 1.0, 0.0, 0.0;\n 0.0, 0.0, 3.0, 0.0;\n 0.0, 0.0, 0.0, 2.0 ];\n\n r8mat_print ( n, n, a, ' Input matrix A:' );\n\n it_max = 100;\n\n [ v, d, it_num, rot_num ] = jacobi_eigenvalue ( n, a, it_max );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of iterations = %d\\n', it_num );\n fprintf ( 1, ' Number of rotations = %d\\n', rot_num );\n\n r8vec_print ( n, d, ' Eigenvalues D:' );\n\n r8mat_print ( n, n, v, ' Eigenvector matrix V:' );\n%\n% Compute eigentest.\n%\n error_frobenius = r8mat_is_eigen_right ( n, n, a, v, d );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Frobenius norm error in eigensystem A*V-D*V = %g\\n', ...\n error_frobenius );\n\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/jacobi_eigenvalue/jacobi_eigenvalue_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.736169683282515}} {"text": "function f_lim = sphArrayNoiseThreshold(R, Nmic, maxG_db, maxN, arrayType, dirCoeff)\n%SPHARRAYNOISETHRESHOLD Returns freq.limits for noise amplification in an SMA\n%\n% SPHARRAYNOISETHRESHOLD returns the frequencies that the noise in the \n% output channels of a SMA, after performing the SHT and equalization of \n% the output signals, reaches a certain user-defined threshold maxG_db.\n% The frequencies are computed only at the lower range of each order, \n% where its response decays rapidly, ignoring for example the nulls of an \n% open array at the higher frequencies. The estimation of the limits are\n% based on a linear approximation of the log-log response found e.g. in \n%\n% Sector-based Parametric Sound Field Reproduction in the Spherical Harmonic Domain\n% A Politis, J Vilkamo, V Pulkki\n% IEEE Journal of Selected Topics in Signal Processing 9 (5), 852 - 866\n%\n% Inputs:\n% R: array radius\n% Nmic: number of microphones\n% maxG_db: max allowed amplification for the noise level, \n% maxG_db = 20*log10(maxG)\n% maxN: maximum order that the array supports\n% arrayType: 'open', 'rigid' or 'directional' for an open or rigid spherical \n% array of omnidirectional microphones, or for an array of\n% first-order directional microphones\n% dirCoeff: (optional) if arrayType=='directional', then dirCoeff \n% expresses the first-order directivity of microphones\n% from 0-1 (1:omni, 0.5:cardioid, 0:dipole)\n% \n% f_lim: frequency points that the threhsold is reached, \n% for orders 1:maxN\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% SPHARRAYNOISETHRESHOLD.M - 11/7/2013\n% Archontis Politis, archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin<6\n dirCoeff = [];\nend\n\nc = 343;\nf_lim = zeros(1,maxN);\nfor n=1:maxN\n bn = sphModalCoeffs(n, 1, arrayType, dirCoeff)/(4*pi);\n bn = bn(end);\n maxG = 10^(maxG_db/10);\n kR_lim = (maxG*Nmic*abs(bn).^2)^(-10*log10(2)/(6*n));\n f_lim(n) = kR_lim*c/(2*pi*R);\nend\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/sphArrayNoiseThreshold.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7361667169441892}} {"text": "function q = mat2quat(mat,varargin)\n% converts direction cosine matrix to quaternion\n%\n% Syntax\n% q = mat2quat(mat)\n%\n% Input\n% mat - vector of matrixes\n%\n% Output\n% q - @quaternion\n%\n% See also\n%\n% quaternion_matrix Euler axis2quat hr2quat\n%\n% Description\n% Wertz says to the algo similar to this with largest divisor\n% q4 = 1/2*sqrt((1+mat(1,1)+mat(2,2)+mat(3,3))); \n% Eqn 12-14a - c\n% Quat(1) = (mat(2,3)-mat(3,2))/q4/4;\n% Quat(2) = (mat(3,1)-mat(1,3))/q4/4;\n% Quat(3) = (mat(1,2)-mat(2,1))/q4/4;\n% Quat(4) = q4\n\nQuat=zeros(4,1);\n \n%Compute absolute values of the four quaternions from diags of Eqn 12-13\n%absQ=0.5*sqrt([1 -1 -1;-1 1 -1;-1 -1 1;1 1 1]*diag(mat)+1);\n\nabsQ(1,:) = 0.5 * sqrt(1+mat(1,1,:)+mat(2,2,:)+mat(3,3,:));\nabsQ(2,:) = 0.5 * sqrt(1-mat(1,1,:)-mat(2,2,:)+mat(3,3,:));\nabsQ(3,:) = 0.5 * sqrt(1+mat(1,1,:)-mat(2,2,:)-mat(3,3,:));\nabsQ(4,:) = 0.5 * sqrt(1-mat(1,1,:)+mat(2,2,:)-mat(3,3,:));\n\n[~,ind]=max(absQ); % Select biggest for best accuracy\n\nqind = ind == 1;\nif any(qind)\n Quat(1,qind)=absQ(1,qind);\n Quat(2,qind)=squeeze((mat(2,3,qind)-mat(3,2,qind))).'.*0.25./absQ(1,qind);\n Quat(3,qind)=squeeze((mat(3,1,qind)-mat(1,3,qind))).'.*0.25./absQ(1,qind);\n Quat(4,qind)=squeeze((mat(1,2,qind)-mat(2,1,qind))).'.*0.25./absQ(1,qind);\nend\n\nqind = ind == 2;\nif any(qind)\n Quat(1,qind)=squeeze(mat(1,2,qind)-mat(2,1,qind)).'.*0.25./absQ(2,qind);\n Quat(2,qind)=squeeze(mat(3,1,qind)+mat(1,3,qind)).'.*0.25./absQ(2,qind);\n Quat(3,qind)=squeeze(mat(3,2,qind)+mat(2,3,qind)).'.*0.25./absQ(2,qind);\n Quat(4,qind)=absQ(2,qind);\nend\n\nqind = ind == 3;\nif any(qind)\n Quat(1,qind)=squeeze(mat(2,3,qind)-mat(3,2,qind)).'.*0.25./absQ(3,qind);\n Quat(2,qind)=absQ(3,qind);\n Quat(3,qind)=squeeze(mat(1,2,qind)+mat(2,1,qind)).'.*0.25./absQ(3,qind);\n Quat(4,qind)=squeeze(mat(3,1,qind)+mat(1,3,qind)).'.*0.25./absQ(3,qind);\nend\n \nqind = ind == 4;\nif any(qind)\n Quat(1,qind)=squeeze(mat(3,1,qind)-mat(1,3,qind)).'.*0.25./absQ(4,qind);\n Quat(2,qind)=squeeze(mat(1,2,qind)+mat(2,1,qind)).'.*0.25./absQ(4,qind);\n Quat(3,qind)=absQ(4,qind);\n Quat(4,qind)=squeeze(mat(2,3,qind)+mat(3,2,qind)).'.*0.25./absQ(4,qind);\nend\n\nq = quaternion(real(Quat));\nq = q./norm(q);\nq = inv(q).';\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/mat2quat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229961215457, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7361667153037736}} {"text": "%% DEMO_volumetric_SED_eval\n% This demo was developed as part of the paper:\n% Moerman et al. \"Novel Hyperelastic Models for Large Volumetric\n% Deformations\". \n% \n% The demo features: \n% * Implementations of hyperelastic volumetric strain energy density\n% functions (SEDs)\n% * Visualizations of the SED, hydrostatic stress, and tangent as a\n% function of the volume ratio.\n\n%% Keywords\n%\n% * Strain energy density\n% * Volumetric\n% * Visualization\n\n%%\n\nclear; close all; clc;\n\n%% Plot settings\nfontSize=20;\nfontSizeInner=fontSize+15;\nfontSizeLabel=fontSize+30;\nplotColors=gjet(4);\nplotColors=plotColors([1 2 4],:);\n\nlineWidth=3;\ngridAlpha=0.3;\nLineWidthAxis=2;\nlegendHeight=0.05;\nnumXTicks=5;\n\n%% Control parameters\n\nformulationCases=1:12; %Choose formulation 1:12\nk=1; %Default bulk modulus (except for hyperfoam)\n\nJ_max=2;\nnumPoints=2000; %Number of points for plotting\nJ=linspace(0.1,J_max,numPoints)'; %The volume ratios\nxtickRange=linspace(0,max(J),numXTicks); %X-axis tick range\n\n%% Get or set formulation specific data and parameters\n\nfor formulationCase=formulationCases\n \n switch formulationCase\n case 1 %Hencky\n formulationName='Hencky';\n parSet(1)=k; %Bulk modulus\n case 2 %Simo\n formulationName='Simo';\n parSet(1)=k; %Bulk modulus\n case 3 %Bischoff\n formulationName='Bischoff';\n b=2; %Beta\n parSet(1)=k; %Bulk modulus\n parSet(2)=b; %Beta\n case 4 %Modified Ogden\n formulationName='Modified Ogden';\n b=2;%Beta\n parSet(1)=k; %Bulk modulus\n parSet(2)=b; %Beta\n case 5 %Hyperfoam\n formulationName='Hyperfoam';\n mu=1;\n a=2; %Alpha\n b=2; %Beta\n parSet(1)=mu; %Mu\n parSet(2)=a; %Alpha\n parSet(3)=b; %Beta\n case 6 %Doll and Schweizerhoff\n formulationName='Doll and Schweizerhoff';\n a=3; %Alpha\n b=2; %Beta\n parSet(1)=k; %Bulk modulus\n parSet(2)=a; %Alpha\n parSet(3)=b; %Beta\n case 7 %Montella et al.\n formulationName='Montella et al.';\n k1=1;\n beta1=1/8;\n k2=1;\n beta2=1/8;\n m=4;\n parSet(1)=k; %Bulk modulus\n parSet(2)=beta1; \n parSet(3)=k2; \n parSet(4)=beta2; \n parSet(5)=m; \n case 8 %Moerman 1\n formulationName='Moerman 1';\n b1=3;\n b2=2;\n parSet(1)=k; %Bulk modulus\n parSet(2)=b1; %Alpha\n parSet(3)=b2; %Beta\n case 9 %Moerman 1A\n formulationName='Moerman 1A';\n b1=3;\n b2=2;\n q=0.5;\n parSet(1)=k; %Bulk modulus\n parSet(2)=b1; %Alpha\n parSet(3)=b2; %Beta\n parSet(4)=q; %Weigthing factor\n case 10 %Moerman 1B\n formulationName='Moerman 1B';\n b1=3;\n b2=2;\n parSet(1)=k; %Bulk modulus\n parSet(2)=b1; %Alpha\n parSet(3)=b2; %Beta\n case 11 %Moerman 2\n formulationName='Moerman 2';\n J1=max(J)+0.1;\n J2=0;\n parSet(1)=k; %Bulk modulus\n parSet(2)=J1; %J1\n parSet(3)=J2; %J2\n case 12 %Moerman 2A\n formulationName='Moerman 2A';\n b1=3;\n b2=2;\n parSet(1)=k; %Bulk modulus\n parSet(2)=b1; %Alpha\n parSet(3)=b2; %Beta\n case 13 %Moerman 3\n formulationName='Moerman 3';\n J1=max(J)+0.1;\n J2=0;\n s1=0.15;\n s2=0.15;\n q1=0.9;\n q2=0.9;\n parSet(1)=k; %Bulk modulus\n parSet(2)=J1; %J1\n parSet(3)=J2; %J2\n parSet(4)=s1; %s1\n parSet(5)=s2; %s2\n parSet(6)=q2; %q1\n parSet(7)=q2; %q2\n end\n \n %% Calculate SED\n \n %Get normalized SED\n [W,S,T]=SED_eval(formulationCase,parSet,J);\n \n %% Visualize data\n \n hf=cFigure;\n ht=subtitle(formulationName);\n ht.FontSize=fontSizeLabel;\n ht.Interpreter='latex';\n \n subplot(1,3,1); hold on;\n set(gca,'FontSize',fontSize,'LineWidth',LineWidthAxis,'GridAlpha',gridAlpha);\n xlabel('$J$','FontSize',fontSizeLabel,'Interpreter','latex');\n ylabel('$\\Psi/\\kappa$','FontSize',fontSizeLabel,'Interpreter','latex');\n \n hp1=plot(J,W,'k-','LineWidth',lineWidth);\n hp1.Color=plotColors(1,:);\n \n grid on; axis tight; axis square; box on;\n xlim([0 max(J(:))]);\n set(gca,'XTick',xtickRange);\n \n subplot(1,3,2); hold on;\n set(gca,'FontSize',fontSize,'LineWidth',LineWidthAxis,'GridAlpha',gridAlpha);\n xlabel('$J$','FontSize',fontSizeLabel,'Interpreter','Latex');\n ylabel('$\\sigma_{h}/\\kappa$','FontSize',fontSizeLabel,'Interpreter','Latex');\n grid on; axis tight; axis square; box on;\n \n hp2=plot(J,S,'k-','LineWidth',lineWidth);\n hp2.Color=plotColors(2,:);\n \n grid on; axis tight; axis square; box on;\n xlim([0 max(J(:))]);\n set(gca,'XTick',xtickRange);\n \n subplot(1,3,3); hold on;\n set(gca,'FontSize',fontSize,'LineWidth',LineWidthAxis,'GridAlpha',gridAlpha);\n xlabel('$J$','FontSize',fontSizeLabel,'Interpreter','latex');\n ylabel('$\\frac{\\partial^2 \\Psi}{\\partial J^2} /\\kappa$','FontSize',fontSizeLabel,'Interpreter','Latex');\n \n hp3=plot(J,T,'k-','LineWidth',lineWidth);\n hp3.Color=plotColors(3,:);\n \n grid on; axis tight; axis square; box on;\n xlim([0 max(J(:))]);\n ylim([0 max(T(:))]);\n set(gca,'XTick',xtickRange);\n \n drawnow;\n \nend\n\n%% Evaluate SED\n\nfunction [W,S,T]=SED_eval(formulationCase,parSet,J)\n\nswitch formulationCase\n case 1 %Hencky\n k=parSet(1);\n W=k/2*log(J).^2;\n S=k*log(J)./J;\n T=(k-k*log(J))./J.^2;\n case 2 %Simo\n k=parSet(1);\n W=(k/2).*(J-1).^2;\n S=(k/2).*(2*J-2);\n T=k*ones(size(J));\n case 3 %Bischoff\n k=parSet(1);\n b=parSet(2);\n W=(k./b.^2).*(cosh(b*(J-1))-1);\n S=(k./b) .* sinh(b*(J-1));\n T=k .* cosh(b*(J-1));\n case 4 %Modified Ogden\n k=parSet(1);\n b=parSet(2);\n W=(k./b.^2).*(J.^-b - 1 + b.*log(J));\n S=(k./b) .*(1./J - J.^(-b-1));\n T=(k./b) .*(-1./J.^2 + (b+1).*J.^(-b-2));\n case 5 %Hyperfoam\n mu=parSet(1);\n a=parSet(2);\n b=parSet(3);\n k=mu.*(b+1/3);\n W=(2*mu./(a.^2)).*( 3*(J.^(a/3)-1)...\n +(1./b.*( (J.^(-a.*b))-1 )) );\n S=(1./J).*(2*mu./a).*(J.^(a/3)...\n -J.^(-a.*b) );\n T=(1./(J.^2)).*(2*mu/a).*((a./3-1).*J.^(a./3) +...\n (a.*b+1).*J.^(-a*b) );\n case 6 %Doll and Schweizerhoff\n k=parSet(1);\n a=parSet(2);\n b=parSet(3);\n W=( (k/(a+b)).*( ((1/(a+1)).*(J.^(a+1))) + ((1/(b-1)).*(J.^(-b+1)))) )...\n -(k.*(1/(a+1)).*(1/(b-1)));\n S=(k/(a+b)).*(J.^a-J.^(-b));\n T=(k/(a+b)).*(a*J.^(a-1)+b*J.^(-b-1));\n case 7\n k=parSet(1);\n beta1=parSet(2);\n k2=parSet(3);\n beta2=parSet(4);\n m=parSet(5);\n \n %SED\n W1=k./(2.*beta1).*exp(beta1.* (log(J).^2))-(k/(2*beta1));\n W2=k2./(m.*beta2).*exp(beta2.*abs(log(J).^m))-(k2/(m*beta2));\n W=W1+W2;\n \n %Stress\n S1=(k./J).*(exp(beta1.* log(J).^2) .* log(J));\n S2=(k2./J).*(exp(beta2.*abs(log(J)).^m).*(abs(log(J)).^(m-1)).*sign(log(J)));\n S=S1+S2;\n \n %Tangent\n T1=(k./J.^2) .* exp(beta1.* log(J) .^2).*(beta1.*2.* log(J) .^2 - log(J) + 1);\n T2=(k2./J.^2) .* exp(beta2.*abs(log(J)).^m).*(beta2.*m.*abs(log(J)).^m - log(J) + m -1).*abs(log(J)).^(m-2);\n T=T1+T2;\n\n case 8 %Moerman 1\n k=parSet(1);\n b1=parSet(2);\n b2=parSet(3);\n W=(k/4) .*( (1/b1^2).*((J.^ b1)-1).^2 + ...\n (1/b2^2).*((J.^-b2)-1).^2 );\n S=(k/2)./J .*( (1/b1 ).*(J.^( 2*b1) - J.^b1 ) - ...\n (1/b2 ).*(J.^(-2*b2) - J.^-b2) );\n T=(k/2)./J.^2.*( ((2-1/b1)*J.^( 2*b1)-(1-1/b1)*J.^b1) + ...\n ((2+1/b2)*J.^(-2*b2)-(1+1/b2)*J.^-b2) );\n case 9 %Moerman 1A\n k=parSet(1);\n b1=parSet(2);\n b2=parSet(3);\n q=parSet(4);\n \n W1=(k/(2*b1^2)).*( q).*((J.^ b1)-1).^2;\n W2=(k/(2*b2^2)).*(1-q).*((J.^-b2)-1).^2;\n W=W1+W2;\n \n S1= (k/b1)./J.*( q).*(J.^( 2*b1)-J.^b1 );\n S2=-(k/b2)./J.*(1-q).*(J.^(-2*b2)-J.^-b2);\n S=S1+S2;\n \n T1=(k./J.^2).*( q).*((2-1/b1)*J.^( 2*b1)-(1-1/b1)*J.^b1 );\n T2=(k./J.^2).*(1-q).*((2+1/b2)*J.^(-2*b2)-(1+1/b2)*J.^-b2);\n T=T1+T2;\n case 10 %Moerman 1B\n k=parSet(1);\n b1=parSet(2);\n b2=parSet(3);\n \n L1=(J>=1);\n L2=(J<1);\n \n W=zeros(size(J));\n W(L1)=(k/(2*b1^2)).*((J(L1).^ b1)-1).^2;\n W(L2)=(k/(2*b2^2)).*((J(L2).^-b2)-1).^2;\n \n S=zeros(size(J));\n S(L1)= (k/b1).*(J(L1).^( 2*b1-1)-J(L1).^( b1-1));\n S(L2)=-(k/b2).*(J(L2).^(-2*b2-1)-J(L2).^(-b2-1));\n \n T=zeros(size(J));\n T(L1)=(k/b1).*((2*b1-1)*J(L1).^( 2*b1-2)-(b1-1)*J(L1).^( b1-2));\n T(L2)=(k/b2).*((2*b2+1)*J(L2).^(-2*b2-2)-(b2+1)*J(L2).^(-b2-2));\n case 11 %Moerman 2\n k=parSet(1);\n J1=parSet(2);\n J2=parSet(3);\n \n a1=(2/pi)*(J1-1);\n a2=(2/pi)*(J2-1);\n \n W1=(-k*a1.^2)*log(cos((J-1)/a1));\n W2=(-k*a2.^2)*log(cos((J-1)/a2));\n \n W=zeros(size(W1));\n W(J>=1)=W1(J>=1);\n W(J<1)=W2(J<1);\n W=real(W);\n W(J>=J1)=inf;\n W(J<=J2)=inf;\n \n S1=(k.*a1).*tan((J-1)/a1);\n S2=(k.*a2).*tan((J-1)/a2);\n S=zeros(size(S1));\n S(J>=1)=S1(J>=1);\n S(J<1)=S2(J<1);\n S(J>=J1)=inf;\n S(J<=J2)=-inf;\n \n T1=k*sec((J-1)/a1).^2;\n T2=k*sec((J-1)/a2).^2;\n T=zeros(size(T1));\n T(J>=1)=T1(J>=1);\n T(J<1)=T2(J<1);\n T(J>=J1)=inf;\n T(J<=J2)=inf;\n case 12 %Moerman 2A\n k=parSet(1);\n b1=parSet(2);\n b2=parSet(3);\n \n W1=(k./b1.^2).*(cosh(b1*(J-1))-1);\n S1=(k./b1) .* sinh(b1*(J-1));\n T1=k .* cosh(b1*(J-1));\n \n W2=(k./b2.^2).*(cosh(b2*(J-1))-1);\n S2=(k./b2) .* sinh(b2*(J-1));\n T2=k .* cosh(b2*(J-1));\n \n W3=k.*(-4/pi^2) .*log(cos(pi/2*(1-J)));\n S3=k.*(-2/pi) .*tan(pi/2*(1-J));\n T3=k .*sec(pi/2*(1-J)).^2;\n \n W=W1;\n S=S1;\n T=T1;\n \n W(J<1)=W2(J<1)/2+W3(J<1)/2;\n S(J<1)=S2(J<1)/2+S3(J<1)/2;\n T(J<1)=T2(J<1)/2+T3(J<1)/2;\n case 13 %Moerman 3\n k=parSet(1);\n J1=parSet(2);\n J2=parSet(3);\n s_1=parSet(4);\n s_2=parSet(5);\n q1=parSet(6);\n q2=parSet(7);\n \n L=J<1;\n \n % PART 1\n a1=(pi/2)*(1/(J1-1));\n a2=(pi/2)*(1/(J2-1));\n \n %SED\n W11=(-1/a1.^2)*log(cos((J-1).*a1));\n W21=(-1/a2.^2)*log(cos((J-1).*a2));\n W1=zeros(size(J));\n W1(~L)=W11(~L);\n W1(L)=W21(L);\n W1=real(W1);\n W1(J>J1)=inf;\n W1(JJ1)=inf;\n S1(JJ1)=inf;\n T1(J=J1)=inf;\n W(J<=J2)=inf;\n \n S(J>=J1)=inf;\n S(J<=J2)=-inf;\n \n T(J>=J1)=inf;\n T(J<=J2)=inf;\n \nend\n\n%Normalise based on bulk-modulus\nW=W/k; S=S/k; T=T/k;\n\nend\n\n%%\n%\n% <>\n%\n% _*GIBBON*_\n% \n%\n% _Kevin Mattheus Moerman_, \n\n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/DEMO_volumetric_SED_eval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7361667126241039}} {"text": "% Bezier parameters\n% Copyright by Nguyen Quoc Duan - EMMC11\n\n% Purpose : to compute the parameter terms in Bezier curves\n% n : the polynomial degree of Bezier curve\n\nfunction B_para=B_para(i,n,t)\nB_para=(1-t)^(n-i)*t^i;\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/12414-bezier-curve/Bezier_circle/B_para.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7361667077028565}} {"text": "function [Au, PHIu, Av, PHIv, w, TWOCIR]=ep2ap(SEMA, ECC, INC, PHA, plot_demo)\n%\n% Convert tidal ellipse parameters into amplitude and phase lag parameters.\n% Its inverse is app2ep.m. Please refer to app2ep for the meaning of the \n% inputs and outputs.\n%\n% Zhigang Xu\n% Oct. 20, 2000\n%\n% Document: tidal_ellipse.ps\n% \nif nargin < 5\n plot_demo=0; % by default, no plot for the ellipse\nend\n\n Wp = (1+ECC)/2 .*SEMA;\n Wm = (1-ECC)/2 .*SEMA;\n THETAp = INC-PHA;\n THETAm = INC+PHA;\n\n %convert degrees into radians\n THETAp = THETAp/180*pi;\n THETAm = THETAm/180*pi;\n\n %Calculate wp and wm.\n wp = Wp.*exp(i*THETAp);\n wm = Wm.*exp(i*THETAm);\n \n if nargout >= 5\n ndot=36;\n dot = 2*pi/ndot;\n ot = [0:dot:2*pi-dot];\n w = wp(:)*exp(i*ot)+wm(:)*exp(-i*ot);\n w=reshape(w, [size(wp) ndot]);\n end\n\n % Calculate cAu, cAv --- complex amplitude of u and v\n cAu = wp+conj(wm);\n cAv = -i*(wp-conj(wm));\n Au = abs(cAu);\n Av = abs(cAv); \n PHIu = -angle(cAu)*180/pi;\n PHIv = -angle(cAv)*180/pi;\n \n % flip angles in the range of [-180 0) to the range of [180 360).\n id = PHIu < 0; PHIu(id) = PHIu(id) + 360;\n id = PHIv < 0; PHIv(id) = PHIv(id) + 360;\n\n if any(plot_demo) \n plot_ell(SEMA,ECC,INC,PHA,plot_demo);\n end\n\n if nargout == 6\n TWOCIR=struct('Wp', Wp, 'THETAp', THETAp, 'wp', ... \n wp, 'Wm', Wm, 'THETAm', THETAm, 'wm', wm, 'ot', ot, 'dot', dot);\n end\n \n%Authorship Copyright:\n%\n% The author of this program retains the copyright of this program, while\n% you are welcome to use and distribute this program as long as you credit \n% the author properly and respect the program name itself. Particularly, \n% you are expected to retain the original author's name in this original \n% version of the program or any of its modified version that you might make.\n% You are also expected not to essentially change the name of the programs \n% except for adding possible extension for your own version you might create, \n% e.g. app2ep_xx is acceptable. Any suggestions are welcome and enjoy my \n% program(s)!\n%\n%\n%Author Info:\n%_______________________________________________________________________\n% Zhigang Xu, Ph.D. \n% (pronounced as Tsi Gahng Hsu)\n% Research Scientist\n% Coastal Circulation \n% Bedford Institute of Oceanography \n% 1 Challenge Dr.\n% P.O. Box 1006 Phone (902) 426-2307 (o) \n% Dartmouth, Nova Scotia Fax (902) 426-7827 \n% CANADA B2Y 4A2 email xuz@dfo-mpo.gc.ca \n%_______________________________________________________________________\n%\n%Release Date: Nov. 2000\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/347-tidalellipse/ep2ap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7360872189957806}} {"text": "function x = gendatav(pc,R0,nobs)\n%function x = gendatav(pc,R0,nobs)\n%\n% Simulates nobs observations of a vector AR-process\n% with partial correlations pc and covariance matrix R0.\n%\n% See also FILTERV, RANDN.\n\n% S. de Waele, FEB 2001.\n\nif ~isstatv(pc), error('Partial correlations non-stationairy!'), end\norder = kingsize(pc,3)-1;\ndim = size(pc,1);\nI = eye(dim);\n[rc,rcb] = pc2rcv(pc,R0);\n[Pf,Pb] = pc2resv(pc,R0);\npar = zeros(dim,dim,order+1);\nparb = zeros(dim,dim,order+1);\n\nx = zeros(dim,1,nobs); %The signal in matrix notation\n%First observation\ninnovation = randncov(Pf(:,:,1));\nx(:,:,1) = innovation;\n\npar(:,:,1) = I; \nparb(:,:,1)= I; \nif order,\n\tpar(:,:,2) = rc(:,:,2);\n\tparb(:,:,2)= rcb(:,:,2);\n\tpar_o = par;\n\tparb_o = parb;\nend \n\n%observation 2 to order\nfor obs = 2:order,\n innovation = randncov(Pf(:,:,obs));\n prediction = -prodsumv(flipdim(par(:,:,2:obs),3),x(:,:,1:obs-1));\n x(:,:,obs) = prediction+innovation;\n \n p=obs; %The next observations requires the AR(obs)-model\n %par(:,:,2:p) = par_o(:,:,2:p) +flipdim(filterv(rc(:,:,p+1),1,parb_o(:,:,2:p)),3);\n par(:,:,2:p) = par_o(:,:,2:p) +flipdim(armafilterv(parb_o(:,:,2:p),1,rc(:,:,p+1)),3);\n par(:,:,p+1)= rc(:,:,p+1);\n parb(:,:,2:p) = parb_o(:,:,2:p) +flipdim(armafilterv(par_o(:,:,2:p),1,rcb(:,:,p+1)),3);\n parb(:,:,p+1)= rcb(:,:,p+1);\n \n par_o = par;\n parb_o = parb;\n \nend %for obs = 2:order,\n\n%observations order+1 to nobs\ninnovation = zeros(dim,1,nobs-order);\nfor i = 1:nobs-order,\n innovation(:,:,i) = randncov(Pf(:,:,order+1));\nend\nx(:,:,order+1:end) = armafilterv(innovation,par,I,x(:,:,1:order));\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/gendatav.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676518712608, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7360872116592775}} {"text": "% SOSDEMO6 --- MAX CUT\n% Section 3.6 of SOSTOOLS User's Manual\n% \n\nclear; echo on;\nsyms x1 x2 x3 x4 x5;\nvartable = [x1; x2; x3; x4; x5];\n\n% Number of cuts\nf = 2.5 - 0.5*x1*x2 - 0.5*x2*x3 - 0.5*x3*x4 - 0.5*x4*x5 - 0.5*x5*x1;\n\n% Boolean constraints\nbc{1} = x1^2 - 1 ;\nbc{2} = x2^2 - 1 ;\nbc{3} = x3^2 - 1 ;\nbc{4} = x4^2 - 1 ;\nbc{5} = x5^2 - 1 ;\n\n% =============================================\n% First, initialize the sum of squares program\nprog = sosprogram(vartable);\n\n% =============================================\n% Then define SOSP variables\n\n% -- p1(x) -- : sum of squares\n% Monomial vector: 5 independent variables, degree <= 1\nZ = monomials(vartable,[0 1]); \n[prog,p{1}] = sossosvar(prog,Z);\n\n% -- p2(x) ... p6(x) : polynomials\n% Monomial vector: 5 independent variables, degree <= 2\nZ = monomials(vartable,0:2);\nfor i = 1:5\n [prog,p{1+i}] = sospolyvar(prog,Z);\nend;\n\n% =============================================\n% Next, define SOSP constraints\n\n% Constraint : p1(x)*(gamma - f(x)) + p2(x)*bc1(x)\n% + ... + p6(x)*bc5(x) - (gamma-f(x))^2 >= 0\ngamma = 4;\n\nexpr = p{1}*(gamma-f);\nfor i = 2:6\n expr = expr + p{i}*bc{i-1};\nend;\nexpr = expr - (gamma-f)^2;\n\nprog = sosineq(prog,expr);\n\n% =============================================\n% And call solver\nprog = sossolve(prog);\n\n% =============================================\n% Program is feasible, thus 4 is an upper bound for the cut.\necho off", "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/SOSTOOLS.300/SOSTOOLS.300/demos/sosdemo6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7360872055017219}} {"text": "function ppwd = pwd_imp_circexp(pm,Npw)\n%PWD_IMP_CIRCEXP converts a circular basis expansion of a sound field to its\n%two-dimensional plane wave decomposition\n%\n% Usage: ppwd = pwd_imp_circexp(pm,[Npw])\n%\n% Input parameters:\n% pm - circular basis expansion [N x (M+1)]\n% Npw - number of equi-angular distributed plane waves, optional, \n% default: 2*M+1\n%\n% Output parameters:\n% ppwd - plane wave decomposition [N x Npw]\n%\n% See also: driving_function_imp_localwfs_sbl_ps,\n% driving_function_imp_localwfs_sbl_pw\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 = 2;\nnarginchk(nargmin,nargmax);\nisargmatrix(pm);\nM = size(pm,2)-1;\nif nargin == nargmin\n Npw = 2*M+1;\nelse\n isargpositivescalar(Npw);\nend\n\n\n%% ===== Computation ====================================================\n% Implementation of\n% ___\n% _ \\\n% p(phipw, t) = /__ p (t) i^m e^(-i m phipw)\n% m=-M..M m\n% with\n%\n% phipw = n * 2*pi/Npw\n\npm = [conj(pm(:,end:-1:2)), pm]; % append coefficients for negative m\nppwd = inverse_cht(bsxfun(@times,pm,1i.^(-M:M)),Npw);\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_time_domain/pwd_imp/pwd_imp_circexp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7360143896550831}} {"text": "function [ vX, mX ] = SolveLsL1ComplexCd( mA, vB, lambdaFctr, numIterations )\n% ----------------------------------------------------------------------------------------------- %\n%[ vX, mX ] = SolveLsL1ComplexPgm( mA, vB, lambdaFctr, numIterations )\n% Solves the 0.5 * || A x - b ||_2 + \\lambda || x ||_1 problem using\n% Coordinate Descent Method. The model allows A, b and x to be Complex.\n% Input:\n% - mA - Model Matrix.\n% The model matrix.\n% Structure: Matrix (m X n).\n% Type: 'Single' / 'Double' (Complex).\n% Range: (-inf, inf).\n% - vB - Input Vector.\n% The model known data.\n% Structure: Vector (m X 1).\n% Type: 'Single' / 'Double' (Complex).\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 Coordinate Descent Method - https://en.wikipedia.org/wiki/Coordinate_descent.\n% Remarks:\n% 1. Coordienat Descent is basically Steepest Descnt in L1 Norm.\n% Known Issues:\n% 1. A\n% TODO:\n% 1. B\n% Release Notes:\n% - 1.0.000 07/11/2016\n% * First realease version.\n% ----------------------------------------------------------------------------------------------- %\n\nvANorm = sum(mA .* conj(mA), 1);\nnumElements = size(mA, 2); % Keep Phase, Soft Threshold the\n% Modulus\n\n% vXAbs = abs(vX);\n% vXPhase = angle(vX);\n% \n% vX = max(vXAbs - lambdaFactor, 0) .* exp(1i * vXPhase);\n\nvXAbs = abs(vX);\n\nvX = (vX ./ vXAbs) .* max((vXAbs - lambdaFactor), 0);\nvX(vXAbs == 0) = 0;\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/Mathematics/Q1344369/SolveLsL1ComplexCd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7358658275424846}} {"text": "function M = compute_compressed_sensing_matrix(p,n, type, options)\n\n% compute_compressed_sensing_matrix - compute a CS matrix\n%\n% M = compute_compressed_sensing_matrix(p,n, type, options);\n%\n% M is a (p,n) matrix.\n% type can be\n% 'gaussian': gaussian entries\n% 'randnormed': random unit norm columns\n% 'bernouilli': random +-1/sqrt(p)\n% 'orthoproj': random projector M'*M=Id\n% 'fourier': random Fourier rows\n% 'sincos': random cosine/sine rows\n%\n% Copyright (c) 2008 Gabriel Peyre\n\nif nargin<3\n type = 'gaussian';\nend\n\noptions.null = 0;\nswitch lower(type)\n case 'gaussian'\n \tM = randn(p,n) / sqrt(p);\n case {'randnormed' 'rand'}\n M = randn(p,n);\n M = M ./ repmat( sqrt(sum(M.^2)), [p 1] );\n case 'bernouilli'\n M = sign(randn(p,n)) / sqrt(p);\n case {'orthoproj' 'randproj'}\n M = randn(p,n);\n [M,R] = qr(M'); M = M(:,1:p)'; \n case 'fourier'\n [X,Y] = meshgrid(0:n-1:0:n-1);\n M = exp( 2i*pi/n * X.*Y ) / sqrt(p);\n sel = randperm(n); sel = sel(1:p);\n M = M(sel,:);\n case 'sincos'\n [X,Y] = meshgrid(0:n-1,0:n/2);\n M = cos( 2*pi/n * X.*Y );\n [X,Y] = meshgrid(0:n-1,1:n/2-1);\n M = [M; sin( 2*pi/n * X.*Y )];\n M = M ./ repmat( sqrt(sum(M.^2,2)), [1 n] );\n sel = randperm(n); sel = sel(1:p);\n M = M(sel,:) * sqrt( n/p );\n case 'projoptim'\n niter = getoptions(options, 'niter_projoptim', 40);\n M = randn(p,n);\n for i=1:niter\n % unit normed\n M = M ./ repmat( sqrt(sum(M.^2)), [p 1] );\n % projector\n [U,S,V] = svd(M, 'econ');\n S = diag(diag(S)*0+1);\n M = U*S*V'; \n end\n otherwise \n error('Unknown matrice type');\nend\n\nreturn;\n%% old code\n\nif nargin<4\n normtype = 'normalize';\nend\n\nswitch lower(type)\n case 'random'\n M = randn(n,m);\n case 'bumps' \n normtype = 'none';\n % m bumps\n sigma = 0.05;\n x = linspace(0,1,m+1)'; x(end) = []; % bump centers\n M = zeros(n,m);\n t = linspace(0,1,n+1)'; t(end) = [];\n for i=1:m\n u = t-x(i); u(u>1/2) = 1-u(u>1/2);\n M(:,i) = exp( -u.^2 / (2*sigma^2) );\n end\nend\n\nswitch lower(normtype)\n case 'normalize'\n % lines should be of unit norm\n d = sqrt( sum(M.^2,1) );\n M = M ./ repmat( d, [size(M,1) 1] );\n case 'orthogonalize'\n % M*M' = Id\n M = orth(M')';\n case 'none'\n otherwise\n error('Unknown normalization');\nend", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_sparsity/compute_compressed_sensing_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.7358658152661626}} {"text": "function [xi,w]=fifthOrder2DCubPoints()\n%%FIFTHORDER2DCUBPOINTS Generate fifth-order cubature points\n% for integration over a 2-dimensional cube with bounds of \n% (-1,-1), (-1,1), (1,1), and (1,-1).\n%\n%INPUTS: None\n%\n%OUTPUTS: xi This is a 2XnumCubPoints set of points for the standard\n% square.\n% w A 1XnumCubPoints set of cubature weights. This sums to the\n% volume of the standard square (4).\n%\n%This function implements the points given in [1] (8 points).\n%\n%EXAMPLE:\n%We compare a 4th-order moment computed using these cubature points\n%to one computed using monomialIntCube (a 5th order moment would have just\n%been 0). The results are the same within typical finite precision limits.\n% [xi,w]=fifthOrder2DCubPoints();\n% alpha=[2;2];\n% theMoment=findMomentFromSamp(alpha,xi,w);\n% intVal=monomialIntCube(alpha);\n% RelErr=(theMoment-intVal)/intVal\n%\n%REFERENCES:\n%[1] 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\nM=[0.68313005106397322554806924536807013272, 0, 0.8163265306122448979591836734693877551;\n 0, 0.68313005106397322554806924536807013272, 0.8163265306122448979591836734693877551;\n-0.68313005106397322554806924536807013272, 0, 0.8163265306122448979591836734693877551;\n 0, -0.68313005106397322554806924536807013272, 0.8163265306122448979591836734693877551;\n 0.8819171036881968635005385845464201419, 0.8819171036881968635005385845464201419, 0.1836734693877551020408163265306122449;\n 0.8819171036881968635005385845464201419, -0.8819171036881968635005385845464201419, 0.1836734693877551020408163265306122449;\n -0.8819171036881968635005385845464201419, 0.8819171036881968635005385845464201419, 0.1836734693877551020408163265306122449;\n -0.8819171036881968635005385845464201419, -0.8819171036881968635005385845464201419, 0.1836734693877551020408163265306122449];\nw=M(:,3);\nxi=M(:,1:2)';\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/Numerical_Integration/Cubature_Points/Cube_Space/Square/fifthOrder2DCubPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7358206349477763}} {"text": "%% Data Structure: Boundary Conditions\n%\n% We use |bdFlag(1:NT,1:3)| to record the type of three edges of each\n% triangle. Similarly in 3-D, we use |bdFlag(1:NT,1:4)| to record the type\n% of four faces of each tetrahedron. The value is the type of boundary\n% condition.\n%\n% * 0: non-boundary, i.e., an interior edge or face.\n% * 1: first type, i.e., a Dirichlet boundary edge or face. \n% * 2: second type, i.e., a Neumann boundary edge or face. \n% * 3: third type, i.e., a Robin boundary edge or face.\n\n%% Local labeling of edges and faces\n% We label three edges of a triangle such that |bdFlag(t,i)| is the edge\n% opposite to the i-th vertex. Similarly |bdFlag(t,i)| is the face opposite\n% to the i-th vertex.\n\nnode = [1,0; 1,1; 0,0];\nelem = [1 2 3];\nedge = [2 3; 1 3; 1 2];\nshowmesh(node,elem);\nfindnode(node);\nfindedge(node,edge);\n\n%% Set up boundary conditions\n%\n% The function |setboundary| is to set up the bdFlag matrix for a 2-D\n% triangulation and |setboundary3| for a 3-D triangulation. \n%\nhelp setboundary\n\n%% \n% Note that if the i-th edge of t is on the boundary but |bdFlag(t,i)=0|,\n% it is equivalent to use homogenous Neumann boundary condition (zero\n% flux).\n\n\n%% Example: Crack Domain\nnode = [1,0; 0,1; -1,0; 0,-1; 0,0; 1,0]; % nodes\nelem = [5,1,2; 5,2,3; 5,3,4; 5,4,6]; % elements\nelem = label(node,elem); % label the mesh\nfigure;\nshowmesh(node,elem); % plot mesh\nfindelem(node,elem); % plot element indices\nfindnode(node,2:6); % plot node indices\ntext(node(6,1),node(6,2)+0.075,int2str(1),'FontSize',16,'FontWeight','bold');\nhold on;\nplot([node(1,1),node(5,1)], [node(1,2),node(5,2)],'r-', 'LineWidth',3);\nbdFlag = setboundary(node,elem,'Dirichlet'); % Dirichlet boundary condition\ndisplay(elem)\ndisplay(bdFlag)\n%% \n% node 1 and node 6 are the same point (1,0)\n\n%%\nbdFlag = setboundary(node,elem,'Dirichlet','abs(x) + abs(y) == 1','Neumann','y==0');\ndisplay(bdFlag)\n\n%% Example: Prism Domain\nnode = [-1,-1,-1; 1,-1,-1; 1,1,-1; -1,1,-1; -1,-1,1; 1,-1,1; 1,1,1; -1,1,1]; \nelem = [1,2,3,7; 1,6,2,7; 1,5,6,7];\nelem = label3(node,elem);\nfigure;\nshowmesh3(node,elem);\nview([-53,8]);\nfindnode3(node,[1 2 3 5 6 7]);\nfindelem3(node,elem);\nbdFlag = setboundary3(node,elem,'Dirichlet','(z==1) | (z==-1)');\ndisplay(elem)\ndisplay(bdFlag)\n\n%%\n% The top and bottom of the prism is set as Dirichlet boundary condition\n% and other faces are zero flux boundary condition.\n\n%% Remark\n% It would save storage if we record boundary edges or faces only. The\n% current data structure is convenient for the local refinement and\n% coarsening since the boundary can be easily update along with the change\n% of elements. The matrix |bdFlag| is sparse but we use a dense matrix to\n% store it. We do not save |bdFlag| as a sparse matrix since updating\n% sparse matrix is time consuming. We set up the type of |bdFlag| or\n% |bdFlag| to |uint8| to minimize the waste of spaces.\n\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/doc/bddoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.87407724336544, "lm_q1q2_score": 0.7358206342067153}} {"text": "function [ x, odata, opts ] = solver_TraceLS( A, b, lambda, x0, opts )\n% SOLVER_TRACELS Unconstrained form of trace-regularized least-squares problem.\n% [ x, odata, opts ] = solver_TraceLS( A, b, lambda, x0, opts )\n% Solves the trace-regularized least squares problem\n% minimize (1/2)*norm( A * X - b )^2 + lambda * trace( X )\n% with the constraint that X is positive semi-definite.\n% A must be a matrix or a linear operator, b must be a vector, \n% and lambda must be a real positive scalar. \n% The initial point x0 and option structure opts are\n% both optional.\n%\n% If \"A\" is a sparse matrix, and nnz(Z) = length(b), then it is assumed\n% that the nonzero entries correspond to samples, and then the\n% corresponding sampling operator is used.\n%\n% If opts.largescale = true, then uses an iterative method\n% to compute the eigenvalue decomposition used with prox_trace.\n%\n% See also solver_L1RLS (aka The Lasso)\n\n\n% Added Feb 7, 2011\nerror(nargchk(3,5,nargin));\nif nargin < 4, x0 = []; end\nif nargin < 5, opts = []; end\nif ~isfield( opts, 'restart' ), \n opts.restart = 100; \nend\nif issparse(A) && nnz(A) == length(b)\n A = linop_subsample(A);\nend\nif isfield( opts,'largescale')\n prx = prox_trace( lambda, opts.largescale );\n opts = rmfield(opts,'largescale');\nelse\n prx = prox_trace( lambda );\nend\n% Note: the proximity operator of trace is really a combination\n% of the proximity operator of trace and the indicator\n% set of positive semi-definite matrices.\n% So we do not need to *explicitly* include the positive semi-definite constraint.\n\n[x,odata,opts] = tfocs( smooth_quad, { A, -b }, prx, x0, opts );\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_TraceLS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7358206339207108}} {"text": "function result = sphere_monomial_int_nd ( n, r, e )\n\n%*****************************************************************************80\n%\n%% SPHERE_MONOMIAL_INT_ND integrates a monomial on a sphere in ND.\n%\n% Discussion:\n%\n% The sphere may have nonunit radius, but it must be centered at 0.\n%\n% The integration region is\n%\n% sum ( x(i)**2 ) = R**2.\n%\n% The monomial is F(X) = X(1)**E(1) * X(2)**E(2) * ... * X(N)**E(N).\n%\n% This routine is useful for testing the accuracy of quadrature\n% rules on the sphere.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 18 January 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Philip Davis, Philip Rabinowitz,\n% Methods of Numerical Integration,\n% Second Edition,\n% Academic Press, 1984, page 263.\n%\n% Parameters:\n%\n% Input, integer N, the dimension of the space.\n%\n% Input, real R, the radius of the sphere.\n%\n% Input, integer E(N), the exponents of X, Y and Z in the monomial.\n% Each exponent must be nonnegative.\n%\n% Output, real RESULT, the integral.\n%\n if ( any ( e(1:n) < 0 ) )\n result = -r8_huge ( result );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPHERE_MONOMIAL_INT_ND - Fatal error!\\n' );\n fprintf ( 1, ' All exponents must be nonnegative.\\n' );\n error ( 'SPHERE_MONOMIAL_INT_ND - Fatal error!' );\n end\n\n if ( all ( e(1:n) == 0 ) )\n\n result = 2.0 * sqrt ( pi^n ) / gamma ( 0.5 * n );\n\n elseif ( any ( mod ( e(1:n), 2 ) == 1 ) )\n\n result = 0.0;\n\n else\n\n result = 2.0;\n\n for i = 1 : n\n result = result * gamma ( 0.5 * ( e(i) + 1 ) );\n end\n\n result = result / gamma ( 0.5 * ( sum ( e(1:n) + 1 ) ) );\n\n end\n\n result = result * r^( sum ( e(1:n) ) + 2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stroud/sphere_monomial_int_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7358206325062103}} {"text": "function degree = r8poly_degree ( na, a )\n\n%*****************************************************************************80\n%\n%% R8POLY_DEGREE returns the degree of a polynomial in power sum form.\n%\n% Discussion:\n%\n% The power sum form of a polynomial is:\n%\n% p(x) = a(0) + a(1) * x + ... + a(n-1) * x**(n-1) + a(n) * x**(n)\n%\n% The degree of a polynomial is the index of the highest power\n% of X with a nonzero coefficient.\n%\n% The degree of a constant polynomial is 0. The degree of the\n% zero polynomial is debatable, but this routine returns the\n% degree as 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 30 June 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NA, the dimension of A.\n%\n% Input, real A(1:NA+1), the coefficients of the polynomials.\n%\n% Output, integer DEGREE, the degree of A.\n%\n degree = na;\n\n while ( 0 < degree )\n\n if ( a(degree+1) ~= 0.0 )\n return\n end\n\n degree = degree - 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/r8poly_degree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.7358206286839537}} {"text": "function fem2d_pack_test17 ( )\n\n%*****************************************************************************80\n%\n%% TEST17 demonstrates S_L2NORM.\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 element_num = 40;\n psi_num = element_num + 1;\n quad_num = 5;\n\n x_max = 1.0;\n x_min = 0.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST17\\n' );\n fprintf ( 1, ' S_L2NORM computes the L2 norm of a scalar function\\n' );\n fprintf ( 1, ' S(X) over a region (of any dimension), assuming:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' * that there is a set of finite element basis\\n' );\n fprintf ( 1, ' functions PSI;\\n' );\n fprintf ( 1, ' * that the region is decomposed into a number of\\n' );\n fprintf ( 1, ' elements whose areas are known;\\n' );\n fprintf ( 1, ' * that the integral is to be computed by a quadrature\\n' );\n fprintf ( 1, ' rule applied in the same way to each element;\\n' );\n fprintf ( 1, ' * that the value of the basis functions is given\\n' );\n fprintf ( 1, ' at every quadrature node in every element;\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Our example will have one spatial dimension.\\n' );\n fprintf ( 1, ' XMIN = %f\\n', x_min );\n fprintf ( 1, ' XMAX = %f\\n', x_max );\n fprintf ( 1, ' The number of intervals will be %d\\n', element_num );\n fprintf ( 1, ' The number of basis functions is %d\\n', psi_num );\n fprintf ( 1, ' The number of quadrature points is %d\\n', quad_num );\n%\n% Set the nodes.\n%\n for i = 1 : psi_num\n node_x(i) = ( ( psi_num - i ) * x_min ...\n + ( i - 1 ) * x_max ) ...\n / ( psi_num - 1 );\n end\n%\n% Set the element \"areas\".\n%\n for i = 1 : element_num\n element_area(i) = node_x(i+1) - node_x(i);\n end\n%\n% Set the quadrature weights and abscissas.\n%\n quad_weight(1) = 0.236926885056189087514264040720;\n quad_weight(2) = 0.478628670499366468041291514836;\n quad_weight(3) = 0.568888888888888888888888888889;\n quad_weight(4) = 0.478628670499366468041291514836;\n quad_weight(5) = 0.236926885056189087514264040720;\n\n quad_weight(1:5) = quad_weight(1:5) / 2.0;\n\n quad_x(1) = - 0.906179845938663992797626878299;\n quad_x(2) = - 0.538469310105683091036314420700;\n quad_x(3) = 0.0;\n quad_x(4) = 0.538469310105683091036314420700;\n quad_x(5) = 0.906179845938663992797626878299;\n%\n% Set the finite element coefficients of S. In our formulation,\n% these finite element coefficients are simply the function values\n% at the nodes.\n%\n for i = 1 : psi_num\n s_coef(i) = sin ( node_x(i) );\n end\n%\n% For each basis function I,\n% for each element J,\n% for each quadrature point K,\n%\n% ...evaluate the basis function in the element at the quadrature point.\n%\n psi_quad(1:psi_num,1:element_num,1:quad_num) = 0.0;\n\n for psi = 1 : psi_num\n\n for element = 1 : element_num\n\n if ( element < psi - 1 )\n\n continue\n\n elseif ( element == psi - 1 )\n\n xl = node_x(element);\n xr = node_x(element+1);\n\n for quad = 1 : quad_num\n\n x = ( ( 1.0 - quad_x(quad) ) * xl ...\n + ( 1.0 + quad_x(quad) ) * xr ) ...\n / 2.0;\n\n psi_quad(psi,element,quad) = ( x - xl ) / ( xr - xl );\n\n end\n\n elseif ( element == psi )\n\n xl = node_x(element);\n xr = node_x(element+1);\n\n for quad = 1 : quad_num\n\n x = ( ( 1.0 - quad_x(quad) ) * xl ...\n + ( 1.0 + quad_x(quad) ) * xr ) ...\n / 2.0;\n\n psi_quad(psi,element,quad) = ( xr - x ) / ( xr - xl );\n\n end\n\n elseif ( psi < element )\n continue\n end\n\n end\n\n end\n%\n% Ask S_L2NORM to compute the integral of L2 norm of S.\n%\n l2norm = s_l2norm ( psi_num, element_num, quad_num, element_area, ...\n quad_weight, psi_quad, s_coef );\n\n fprintf ( 1, '\\n');\n fprintf ( 1, ' The computed L2 norm is %f\\n', l2norm );\n%\n% The integral of (sin(x))**2 is x/2 - sin(2x)/4\n%\n exact = sqrt ( ...\n ( 0.5 * x_max - 0.25 * sin ( 2.0 * x_max ) ) ...\n - ( 0.5 * x_min - 0.25 * sin ( 2.0 * x_min ) ) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The exact value is %f\\n', exact );\n\n return\nend\n", "meta": {"author": "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/fem2d_pack_test17.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7358206259563829}} {"text": "% Duffing_Bif - Bifurcation diagram for the Duffing equation.\n% Copyright Springer 2013 Stephen Lynch.\n% Make sure Duffing is in your directory.\nclear\nglobal Gamma;\nMax=120;step=0.001;interval=Max*step;a=1;b=0;\n% Ramp the amplitude up.\nfor n=1:Max\n Gamma=step*n;\n [t,x]=ode45('Duffing',0:(2*pi/1.25):(4*pi/1.25),[a,b]);\n a=x(2,1);\n b=x(2,2);\n rup(n)=sqrt((x(2,1))^2+(x(2,2))^2);\nend\n% Ramp the amplitude down.\nfor n=1:Max\n Gamma=interval-step*n;\n [t,x]=ode45('Duffing',0:(2*pi/1.25):(4*pi/1.25),[a,b]);\n a=x(2,1);\n b=x(2,2);\n rdown(n)=sqrt((x(2,1))^2+(x(2,2))^2);\nend\nhold on\nrr=step:step:interval;\nplot(rr,rup)\nplot(interval-rr,rdown)\nhold off\nfsize=15;\naxis([0 .12 0 2])\nxlabel('\\Gamma','FontSize',fsize)\nylabel('r','FontSize',fsize)\ntitle('Bifurcation Diagram of the Duffing System. Bistable Region.')\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/32919-applications-of-chaos-and-nonlinear-dynamics-in-engineering-vol-1/Duffing_Bif.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7357952331122456}} {"text": "function value = i4_modp ( i, j )\n\n%*****************************************************************************80\n%\n%% I4_MODP returns the nonnegative remainder of I4 division.\n%\n% Discussion:\n%\n% If\n% NREM = I4_MODP ( I, J )\n% NMULT = ( I - NREM ) / J\n% then\n% I = J * NMULT + NREM\n% where NREM is always nonnegative.\n%\n% The MOD function computes a result with the same sign as the\n% quantity being divided. Thus, suppose you had an angle A,\n% and you wanted to ensure that it was between 0 and 360.\n% Then mod(A,360) would do, if A was positive, but if A\n% was negative, your result would be between -360 and 0.\n%\n% On the other hand, I4_MODP(A,360) is between 0 and 360, always.\n%\n% Example:\n%\n% I J MOD I4_MODP Factorization\n%\n% 107 50 7 7 107 = 2 * 50 + 7\n% 107 -50 7 7 107 = -2 * -50 + 7\n% -107 50 -7 43 -107 = -3 * 50 + 43\n% -107 -50 -7 43 -107 = 3 * -50 + 43\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% Parameters:\n%\n% Input, integer I, the number to be divided.\n%\n% Input, integer J, the number that divides I.\n%\n% Output, integer VALUE, the nonnegative remainder when I is\n% divided by J.\n%\n if ( j == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_MODP - Fatal error!\\n' );\n fprintf ( 1, ' Illegal divisor J = %d\\n', j );\n error ( 'I4_MODP - Fatal error!' );\n end\n\n value = mod ( i, j );\n\n if ( value < 0 )\n value = value + abs ( 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/sparse_grid_cc/i4_modp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.7357442003914194}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Q = T2quaternion(T)\n% Returns the quaternion corresponding to an homogeneous transformation \n% matrix T. Only the 3x3 rotation matrix in T is used.\n%\n% See also QPROD, QUATERNION2T.\n%\n% Author: Arturo Gil. Universidad Miguel Hern�ndez de Elche. email:\n% arturo.gil@umh.es date: 21/04/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 Q = T2quaternion(T)\n% use only the orientation\nR = T(1:3, 1:3);\n\nQ = zeros(1,4);\nQ(1) = sqrt(trace(R))/2;\nQ(1) = real(Q(1));\n\nLx = R(3,2) - R(2,3);\t\nLy = R(1,3) - R(3,1);\t\nLz = R(2,1) - R(1,2);\t\n\nif (R(1,1) >= R(2,2)) && (R(1,1) >= R(3,3))\n Lx1 = R(1,1) - R(2,2) - R(3,3) + 1;\t\n Ly1 = R(2,1) + R(1,2);\t\t\t\n Lz1 = R(3,1) + R(1,3);\nelseif (R(2,2) >= R(3,3))\n Lx1 = R(2,1) + R(1,2);\t\t\t\n Ly1 = R(2,2) - R(1,1) - R(3,3) + 1;\t\n Lz1 = R(3,2) + R(2,3);\t\t\nelse\n Lx1 = R(3,1) + R(1,3);\t\t\t\n Ly1 = R(3,2) + R(2,3);\t\t\t\n Lz1 = R(3,3) - R(1,1) - R(2,2) + 1;\t\nend\n\nif (Lx >= 0) || (Ly >= 0) || (Lz >= 0)\n Lx = Lx + Lx1;\n Ly = Ly + Ly1;\n Lz = Lz + Lz1;\nelse\n Lx = Lx - Lx1;\n Ly = Ly - Ly1;\n Lz = Lz - Lz1;\nend\n\nif norm([Lx Ly Lz]) == 0\n Q = [1 0 0 0];\nelse\n s = sqrt(1-Q(1)^2)/norm([Lx Ly Lz]);\n Q(2:4) = s*[Lx Ly Lz];\nend\n\n\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/T2quaternion_back.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7356861757992987}} {"text": "function [ bin, bin_limit ] = r8vec_bin ( n, x, bin_num, bin_min, bin_max )\n\n%*****************************************************************************80\n%\n%% R8VEC_BIN computes bins based on a given R8VEC.\n%\n% Discussion:\n%\n% The user specifies minimum and maximum bin values, BIN_MIN and\n% BIN_MAX, and the number of bins, BIN_NUM. This determines a\n% \"bin width\":\n%\n% H = ( BIN_MAX - BIN_MIN ) / BIN_NUM\n%\n% so that bin I will count all entries X(J) such that\n%\n% BIN_LIMIT(I-1) <= X(J) < BIN_LIMIT(I).\n%\n% The array X does NOT have to be sorted.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries of X.\n%\n% Input, real X(N), an (unsorted) array to be binned.\n%\n% Input, integer BIN_NUM, the number of bins. Two extra bins,\n% #1 and #BIN_NUM+2, count extreme values.\n%\n% Input, real BIN_MIN, BIN_MAX, define the range and size\n% of the bins. BIN_MIN and BIN_MAX must be distinct.\n% Normally, BIN_MIN < BIN_MAX, and the documentation will assume\n% this, but proper results will be computed if BIN_MIN > BIN_MAX.\n%\n% Output, integer BIN(1:BIN_NUM+2).\n% BIN(1) counts entries of X less than BIN_MIN.\n% BIN(BIN_NUM+2) counts entries greater than or equal to BIN_MAX.\n% For 2 <= I <= BIN_NUM+1, BIN(I) counts the entries X(J) such that\n% BIN_LIMIT(I-1) <= X(J) < BIN_LIMIT(I).\n% where H is the bin spacing.\n%\n% Output, real BIN_LIMIT(1:BIN_NUM+1), the \"limits\" of the bins.\n% BIN(I) counts the number of entries X(J) such that\n% BIN_LIMIT(I-1) <= X(J) < BIN_LIMIT(I).\n%\n if ( bin_max == bin_min )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8VEC_BIN - Fatal error!\\n' );\n fprintf ( 1, ' BIN_MIN = BIN_MAX.\\n' );\n error ( 'R8VEC_BIN - Fatal error!' )\n end\n\n bin(1:bin_num+2) = 0;\n\n for i = 1 : n\n\n t = ( x(i) - bin_min ) / ( bin_max - bin_min );\n\n if ( t < 0.0 )\n j = 0;\n elseif ( 1.0 <= t )\n j = bin_num + 1;\n else\n j = 1 + floor ( bin_num * t );\n end\n\n bin(j+1) = bin(j+1) + 1;\n\n end\n%\n% Compute the bin limits.\n%\n for i = 0 : bin_num\n bin_limit(i+1) = ( ( bin_num - i ) * bin_min ...\n + ( i ) * bin_max ) ...\n / ( bin_num );\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_bin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7356784670569145}} {"text": "function spline_test001 ( )\n\n%*****************************************************************************80\n%\n%% TEST001 tests PARABOLA_VAL2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 February 2009\n%\n% Author\n%\n% John Burkardt\n%\n ndim = 1;\n ndata = 5;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST001\\n' );\n fprintf ( 1, ' PARABOLA_VAL2 evaluates parabolas through\\n' );\n fprintf ( 1, ' 3 points in a table\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Our data tables will actually be parabolas:\\n' );\n fprintf ( 1, ' A: 2*x**2 + 3 * x + 1.\\n' );\n fprintf ( 1, ' B: 4*x**2 - 2 * x + 5.\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : ndata\n\n xval = 2.0 * i;\n xdata(i) = xval;\n ydata(1,i) = 2.0 * xval * xval + 3.0 * xval + 1.0;\n zdata(i) = 4.0 * xval * xval - 2.0 * xval + 5.0;\n\n fprintf ( 1, '%6d %10f %10f %10f\\n', i, xdata(i), ydata(1,i), zdata(i) );\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Interpolated data:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEFT, X, Y1, Y2\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : 5\n\n xval = 2 * i - 1;\n left = i;\n\n if ( ndata - 2 < left )\n left = ndata - 2;\n end\n\n if ( left < 1 )\n left = 1;\n end\n\n yval = parabola_val2 ( ndim, ndata, xdata, ydata, left, xval );\n\n zval = parabola_val2 ( ndim, ndata, xdata, zdata, left, xval );\n\n fprintf ( 1, '%6d %10f %10f %10f\\n', left, xval, yval(1), zval(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/spline/spline_test001.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7356784498586459}} {"text": "function divdif_test03 ( )\n\n%*****************************************************************************80\n%\n%% DIVDIF_TEST03 tests DIF_BASIS.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 June 2013\n%\n% Author:\n%\n% John Burkardt\n%\n ntab = 5;\n nstep = 9;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DIVDIF_TEST03\\n' );\n fprintf ( 1, ' DIF_BASIS computes Lagrange basis polynomials\\n' );\n fprintf ( 1, ' in difference form.\\n' );\n fprintf ( 1, '\\n' );\n%\n% Set the base points.\n%\n xtab = r8vec_indicator ( ntab );\n\n r8vec_print ( ntab, xtab, ' The base points:' );\n%\n% Get the difference tables for the basis polynomials and print them.\n%\n diftab = dif_basis ( ntab, xtab );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The table of difference vectors defining the basis\\n' );\n fprintf ( 1, ' polynomials. Each column represents a polynomial.\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : ntab\n fprintf ( 1, ' ' );\n for j = 1 : ntab\n fprintf ( 1, '%14f', diftab(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n%\n% Evaluate basis polynomial 3 at a set of points.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Evaluate basis polynomial #3 at a set of points.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X Y\\n' );\n fprintf ( 1, '\\n' );\n xhi = ntab;\n xlo = 1.0;\n\n for i = 1 : nstep\n\n xval = ( ( nstep - i ) * xlo ...\n + ( i - 1 ) * xhi ) ...\n / ( nstep - 1 );\n\n yval = dif_val ( ntab, xtab, diftab(1:ntab,3), xval );\n\n fprintf ( 1, ' %14f %14f\\n', xval, yval );\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/divdif/divdif_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7355688942025218}} {"text": "function par_est\n% parameter estimation with derivatives Holzbecher September 2005\n% for exponential fit of exponent lambda for c(0)=c0\nglobal tfit cfit c0 \n\n% specify fitting data\ntfit = [0.25 1 2 4 8]; \ncfit = [0.7716 0.5791 0.4002 0.1860 0.1019]; \nc0 = .8;\n\nlambda = fzero(@myfun,0.11); \nnormc = norm(cfit - c0*exp(-lambda*tfit));\ndisplay (['Best fit for lambda = ' num2str(lambda)]);\ndisplay (['Norm of residuals =' num2str(normc)]);\ntmax = tfit(size(tfit,2));\nt = [0:0.01*tmax:tmax];\nfigure; plot (tfit,cfit,'or',t,c0*exp(-lambda*t),'-');\nlegend ('given','modelled');\ntext(0.5*tmax,c0*0.7,['\\lambda: ' num2str(lambda)]); \ntext(0.5*tmax,c0*0.6,['norm of residuals: ' num2str(normc)]);\nxlabel ('time'); ylabel ('concentration')\n\nfunction f = myfun(lambda)\nglobal tfit cfit c0 \n\nt = tfit;\nc = c0*exp(-lambda*t); % solve linear decay equation for c with c(0)=c0 \nclambda = -c.*t; % equation for dc/dlambda\nf = (cfit-c)*clambda'; % specify function f to vanish\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_est.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.7931059487389966, "lm_q1q2_score": 0.735497341643124}} {"text": "function mean = burr_mean ( a, b, c, d )\n\n%*****************************************************************************80\n%\n%% BURR_MEAN returns the mean of the Burr PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, C, D, the parameters of the PDF.\n% 0 < B,\n% 0 < C.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n mean = a + b * gamma ( 1.0 - 1.0 / c ) * gamma ( d + 1.0 / c ) / gamma ( 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/prob/burr_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.7354973407263091}} {"text": "function dist = polygon_point_dist ( n, v, p )\n\n%*****************************************************************************80\n%\n%% POLYGON_POINT_DIST: distance ( polygon, point ).\n%\n% Discussion:\n%\n% Thanks to Stefano Zappacosta for pointing out that the arguments\n% passed to SEGMENT_POINT_DIST_2D needed to be transposed,\n% 27 June 2006.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 June 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of vertices.\n%\n% Input, real V(2,N), the vertices of the polygon.\n%\n% Input, real P(2,1), the point to be checked.\n%\n% Output, real DIST, the distance from the point to the polygon.\n%\n\n%\n% Find the distance to each of the line segments.\n%\n dist = inf;\n\n for j = 1 : n\n\n jp1 = j + 1;\n if ( n < jp1 ) then\n jp1 = jp1 - n;\n end\n\n dist2 = segment_point_dist ( v(1:2,j), v(1:2,jp1), p );\n\n if ( dist2 < dist )\n dist = dist2;\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/polygon_properties/polygon_point_dist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7354383174579763}} {"text": "function determ = ortega_determinant ( n, u, v, d )\n\n%*****************************************************************************80\n%\n%% ORTEGA_DETERMINANT returns the determinant of the ORTEGA matrix.\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% Reference:\n%\n% James Ortega,\n% Generation of Test Matrices by Similarity Transformations,\n% Communications of the ACM,\n% Volume 7, 1964, pages 377-378.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% 2 <= N.\n%\n% Input, real U(N), V(N), vectors which define the matrix.\n% U'V must not equal -1.0. If, in fact, U'V = 0, and U, V and D are\n% integers, then the matrix, inverse, eigenvalues, and eigenvectors \n% will be integers.\n%\n% Input, real D(N), the desired eigenvalues.\n%\n% Output, real DETERM, the determinant.\n%\n determ = prod ( d(1:n) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/ortega_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7354280942897581}} {"text": "function MS = createMesh1D(varargin)\n% MeshStructure = createMesh1D(Nx, Width)\n% MeshStructure = createMesh1D(facelocationX)\n% creates a uniform 1D mesh:\n% Nx is the number of cells in x (horizontal) direction\n% Width is the domain length in x direction\n%\n% SYNOPSIS:\n% MeshStructure = createMesh1D(Nx, Width)\n%\n% PARAMETERS:\n% Nx: number of cells in the domain\n% Width: domain length\n%\n% RETURNS:\n% MeshStructure.\n% dimensions=1 (1D problem)\n% numbering: shows the indexes of cellsn from left to right\n% dx: cell size (=Width/Nx)\n% cellcenters.x: location of each cell in the x direction\n% facecenters.x: location of interface between cells in the\n% x direction\n% numberofcells: Nx\n%\n%\n% EXAMPLE:\n% L = 1.0; % length of the domain\n% Nx = 10; % number of cells in the domain\n% m = createMesh1D(Nx, L);\n% plot(m.cellcenters.x, ones(size(m.cellcenters.x)), 'o', ...\n% m.facecenters.x, ones(size(m.facecenters.x)), '-+');\n% legend('cell centers', 'face centers');\n%\n% SEE ALSO:\n% createMesh2D, createMesh3D, createMeshCylindrical1D, ...\n% createMeshCylindrical2D, createCellVariable, createFaceVariable\n\n% Written by Ali A. Eftekhari\n% See the license file\n\nif nargin==2\n % uniform 1D mesh\n Nx=varargin{1};\n Width=varargin{2};\n % cell size is dx\n dx = Width/Nx;\n CellSize.x= dx*ones(Nx+2,1);\n CellSize.y= [0.0];\n CellSize.z= [0.0];\n CellLocation.x= [1:Nx]'*dx-dx/2;\n CellLocation.y= [0.0];\n CellLocation.z= [0.0];\n FaceLocation.x= [0:Nx]'*dx;\n FaceLocation.y= [0.0];\n FaceLocation.z= [0.0];\nelseif nargin==1\n % nonuniform 1D mesh\n facelocationX=varargin{1};\n n=size(facelocationX);\n if n(1)==1\n facelocationX=facelocationX';\n end\n Nx = length(facelocationX)-1;\n CellSize.x= [facelocationX(2)-facelocationX(1); ...\n facelocationX(2:end)-facelocationX(1:end-1); ...\n facelocationX(end)-facelocationX(end-1)];\n CellSize.y= [0.0];\n CellSize.z= [0.0];\n CellLocation.x= 0.5*(facelocationX(2:end)+facelocationX(1:end-1));\n CellLocation.y= [0.0];\n CellLocation.z= [0.0];\n FaceLocation.x= facelocationX;\n FaceLocation.y= [0.0];\n FaceLocation.z= [0.0];\nend\n\nMS=MeshStructure(1, ...\n [Nx,1], ...\n CellSize, ...\n CellLocation, ...\n FaceLocation, ...\n [1], ...\n [1]);\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/MeshGeneration/createMesh1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7354280917432544}} {"text": "function [dists, neighInds] = nndist(points)\n%NNDIST Nearest-neighbor distances of each point in a set\n%\n% DISTS = nndist(POINTS)\n% Returns the distance to the nearest neighbor of each point in an array\n% of points.\n% POINTS is an array of points, NP-by-ND.\n% DISTS is a NP-by-1 array containing the distances to the nearest\n% neighbor.\n%\n% This functions first computes the Delaunay triangulation of the set of\n% points, then search for nearest distance in the set of each vertex\n% neighbors. This reduces the overall complexity, but difference was\n% noticed only for large sets (>10000 points)\n%\n% Example\n% % Display Stienen diagram of a set of random points in unit square\n% pts = rand(100, 2);\n% [dists, inds] = nndist(pts);\n% figure; drawPoint(pts, 'k.');\n% hold on; drawCircle([pts dists/2], 'b');\n% axis equal; axis([-.1 1.1 -.1 1.1]);\n% % also display edges\n% drawEdge([pts pts(inds, :)], 'b');\n%\n% See also\n% points2d, distancePoints, minDistancePoints, findPoint\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@nantes.inra.fr\n% Created: 2011-12-01, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n% number of points\nn = size(points, 1);\n\n% allocate memory\ndists = zeros(n, 1);\nneighInds = zeros(n, 1);\n\n% in case of few points, use direct computation\nif n < 3\n inds = 1:n;\n for i = 1:n\n % compute minimal distance\n [dists(i), indN] = minDistancePoints(points(i,:), points(inds~=i, :));\n if indN >= i\n neighInds(i) = inds(indN) + 1;\n else\n neighInds(i) = inds(indN);\n end\n end\n return;\nend\n\n% use Delaunay Triangulation to facilitate computations\nDT = delaunayTriangulation(points);\n\n% compute distance to nearest neighbor of each point in the pattern\nfor i = 1:n\n % find indices of neighbor vertices in Delaunay Triangulation.\n % this set contains the nearest neighbor\n inds = unique(DT.ConnectivityList(sum(DT.ConnectivityList == i, 2) > 0, :));\n inds = inds(inds~=i);\n \n % compute minimal distance \n [dists(i), indN] = min(distancePoints(points(i,:), points(inds, :)));\n neighInds(i) = inds(indN);\nend\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom2d/nndist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7354280808535176}} {"text": "function [varargout]=quiver3Dpatch(x,y,z,ux,uy,uz,c,a)\n\n% function [F,V,C]=quiver3Dpatch(x,y,z,ux,uy,uz,c,a)\n% ------------------------------------------------------------------------\n%\n% This function allows plotting of colored 3D arrows by generating patch\n% data (faces F, vertices V and color data C). The patch data which\n% allows plotting of 3D quiver arrows with specified (e.g. colormap driven)\n% color. To save memory n arrows are created using only n*6 faces and n*7\n% vertices. The vector \"a\" defines arrow length scaling where a(1) is the\n% smallest arrow length and a(2) the largest. Use the PATCH command to plot\n% the arrows: \n%\n% [F,V,C]=quiver3Dpatch(x,y,z,ux,uy,uz,a)\n% patch('Faces',F,'Vertices',V,'CData',C,'FaceColor','flat'); \n%\n% Below is an example illustrating color specifications for (combined)\n% patch data. \n%\n%%% EXAMPLE\n% % Simulating 3D volume and vector data\n% n=25;\n% [X,Y,Z]=meshgrid(linspace(-4.77,4.77,n));\n% phi=(1+sqrt(5))/2;\n% M=2 - (cos(X + phi*Y) + cos(X - phi*Y) + cos(Y + phi*Z) + cos(Y - phi*Z) + cos(Z - phi*X) + cos(Z + phi*X));\n% \n% % Simulating vector data \n% %Vector data here based on the gradient of the image\n% [u,v,w] = gradient(M); \n% G=hypot(hypot(u,v),w); %Vector lenghts\n% \n% a=[min(G(:)) max(G(:))]; %Arrow length scaling\n% L=G>0.7; %Logic indices for arrows to make a selection if required\n% [Fv,Vv,Cv]=quiver3Dpatch(X(L),Y(L),Z(L),u(L),v(L),w(L),G(L),a);\n% \n% figure; \n% xlabel('X','FontSize',10);ylabel('Y','FontSize',10);zlabel('Z','FontSize',10);\n% title('Colormap driven vectors','FontSize',15);\n% patch('Faces',Fv,'Vertices',Vv,'EdgeColor','none', 'CData',Cv,'FaceColor','flat','FaceAlpha',1); \n% \n% colormap jet; colorbar; \n% % caxis([min(Cv(:)) max(Cv(:))]);\n% view(3); grid on; axis equal; axis vis3d; \n% set(gca,'FontSize',10);\n% camlight headlight; lighting flat;\n% drawnow;\n%\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n%\n% 2014/01/13 Updated example in help\n% 2014/11/11 Updated to allow for RGB color input data (e.g. C is an nx3 array)\n% 2016/06/30 Added handling of empty \"a\" parameter. Reverts to default\n% normal length range. \n%------------------------------------------------------------------------\n\n%% \n\n%Convert to columns\nx=x(:); y=y(:); z=z(:); \nux=ux(:); uy=uy(:); uz=uz(:); \n\n%Spherical coordinates\n[THETA_vec,PHI_vec,R_vec] = cart2sph(ux,uy,uz);\n \n%% Setting arrow size properties\n\nif isempty(a)\n a=[min(R_vec(:)) max(R_vec(:))];\nend\n\n%Arrow length\nif min(R_vec(:))==max(R_vec(:)) %If all radii are equal, or if just 1 vector is used\n arrow_length=a(2)*ones(size(R_vec)); %All arrow lengths become a(2)\nelse\n %Scale arrow lengths between a(1) and a(2)\n arrow_length=R_vec-min(R_vec(:));\n arrow_length=a(1)+((arrow_length./max(arrow_length(:))).*(a(2)-a(1)));\nend\n\n%Other arrow dimensions as functions of arrow length and phi (golden ratio)\nphi=(1+sqrt(5))/2;\nhead_size=arrow_length./(phi);\nhead_width=head_size./(2.*phi);\nstick_width=head_width./(2.*phi);\nif numel(a)==3\n head_width=a(3)*head_width;\n stick_width=a(3)*stick_width;\nend\nh=sin((2/3).*pi).*stick_width;\nha=sin((2/3).*pi).*head_width;\n\n%% Creating arrow triangle vertices coordinates\n\nX_tri=[zeros(size(x)) zeros(size(x)) zeros(size(x))...\n head_size.*ones(size(x)) head_size.*ones(size(x)) head_size.*ones(size(x))...\n arrow_length];\nY_tri=[-(0.5.*stick_width).*ones(size(x)) (0.5.*stick_width).*ones(size(x)) zeros(size(x))...\n -(0.5.*head_width).*ones(size(x)) (0.5.*head_width).*ones(size(x)) zeros(size(x))...\n zeros(size(x))];\nZ_tri=[-(0.5.*stick_width.*tan(pi/6)).*ones(size(x))...\n -(0.5.*stick_width.*tan(pi/6)).*ones(size(x))...\n (h-(0.5.*stick_width.*tan(pi/6))).*ones(size(x))...\n -(0.5.*head_width.*tan(pi/6)).*ones(size(x))...\n -(0.5.*head_width.*tan(pi/6)).*ones(size(x))...\n (ha-(0.5.*head_width.*tan(pi/6))).*ones(size(x))...\n zeros(size(x))];\n\n% Rotating vertices\n[THETA_ar,PHI_ar,R_vec_ar] = cart2sph(X_tri,zeros(size(Y_tri)),Z_tri);\nPHI_ar=PHI_ar+PHI_vec*ones(1,size(THETA_ar,2));\n[X_arg,Y_arg,Z_arg] = sph2cart(THETA_ar,PHI_ar,R_vec_ar);\nY_arg=Y_arg+Y_tri;\n[THETA_ar,PHI_ar,R_vec_ar] = cart2sph(X_arg,Y_arg,Z_arg);\nTHETA_ar=THETA_ar+THETA_vec*ones(1,size(THETA_ar,2));\n[X_arg,Y_arg,Z_arg] = sph2cart(THETA_ar,PHI_ar,R_vec_ar);\n\nX_arg=X_arg+x*ones(1,size(THETA_ar,2)); X_arg=X_arg';\nY_arg=Y_arg+y*ones(1,size(THETA_ar,2)); Y_arg=Y_arg';\nZ_arg=Z_arg+z*ones(1,size(THETA_ar,2)); Z_arg=Z_arg';\n\nV=[X_arg(:) Y_arg(:) Z_arg(:)];\n\n%% Creating faces matrix\n\n%Standard vertex order for 6 face arrow style\nF_order=[1 2 7; 2 3 7; 3 1 7; 4 5 7; 5 6 7; 6 4 7;];\nno_nodes=size(X_tri,2);\nb=(no_nodes.*((1:1:numel(x))'-1))*ones(1,3);\n\n%Loops size(F_order,1) times\nF=zeros(numel(x)*size(F_order,1),3); %Allocating faces matrix\nfor f=1:1:size(F_order,1)\n Fi=ones(size(x))*F_order(f,:)+b;\n F(1+(f-1)*numel(x):f*numel(x),:)=Fi;\nend\n\n% %Alternative without for loop, not faster for some tested problems\n% F_order=(ones(numel(x),1)*[1 2 7 2 3 7 3 1 7 4 5 7 5 6 7 6 4 7])';\n% F_order1=ones(numel(x),1)*(1:6);\n% F_order2=ones(numel(x),1)*[2 3 1 5 6 4];\n% F_order=[F_order1(:) F_order2(:)];\n% F_order(:,3)=7;\n% b=repmat(((no_nodes.*(0:1:numel(x)-1)')*ones(1,3)),[6,1]);\n% F=F_order+b;\n\n%% Collect face and vertex output\nvarargout{1}=F;\nvarargout{2}=V;\n\n%% Add color specification if requested\n\nif nargout==3\n if isempty(c) %If empty specify vector magnitudes as colormap driven color\n C=repmat(R_vec,[size(F_order,1),1]);\n else %If user specified color replicate to match # of added faces for arrow\n %c my be an nx3 array to allow for RGB type color data\n C=repmat(c,[size(F_order,1),1]);\n end\n varargout{3}=C;\nend\n\nend\n\n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/lib/quiver3Dpatch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7354197938132844}} {"text": "function [gd,relres,iter]=gabfirdual(Ldual,g,a,M,varargin)\n%GABFIRDUAL Compute FIR dual window\n% Usage: gd=gabfirdual(Ldual,g,a,M);\n% gd=gabfirdual(Ldual,g,a,M, varagin);\n%\n% Input parameters:\n% Ldual : Length of dual window\n% g : Window function\n% a : Time shift\n% M : Number of Channels\n% alpha1 : Weight of $l^1$-norm in the time domain\n% alpha2 : Weight of $l^1$-norm in the freq. domain\n%\n% Output parameters:\n% gd : Dual window\n%\n% `gabfirdual(Ldual,g,a,M)` computes an FIR window *gd* which is an\n% approximate dual window of the Gabor system defined by *g*, *a* and\n% *M*. The FIR dual window will be supported on *Ldual* samples.\n%\n% This function solve a convex optimization problem that can be written\n% as:\n%\n% .. gd = argmin_x || alpha x||_1 + || beta Fx||_1 \n%\n% .. + || omega (x -g_l) ||_2^2 + delta || x ||_S0\n%\n% .. + gamma || nabla F x ||_2^2 + mu || nabla x ||_2^2\n%\n% .. such that x is a dual windows of g\n%\n% .. math:: \\begin{split} \\text{gd} = & \\text{arg} \\min_x \\| \\alpha x \\|_1 + \\| \\beta \\mathcal{F}x\\|_1 \\\\ & + \\| \\omega (x - g_l) \\|_2^2 \\\\ & \\delta \\| x \\|_{S0}+ \\mu \\| \\nabla x \\|_2^2 +\\gamma \\| \\nabla \\mathcal{F} x \\|_2^2 \\\\ & \\text{such that } x \\text{ is a dual window of }g \\end{split}\n%\n% **Note**: This function require the unlocbox. You can download it at\n% ``_\n% \n% The function uses an iterative algorithm to compute the approximate\n% FIR dual. The algorithm can be controlled by the following flags:\n%\n% 'alpha',alpha Weight in time. If it is a scalar, it represent the\n% weights of the entire L1 function in time. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L1 norm (length: Ldual).\n% Default value is $\\alpha=0$.\n% **Warning**: this value should not be too big in order to\n% avoid the the L1 norm proximal operator kill the signal.\n% No L1-time constraint: $\\alpha=0$\n%\n% 'beta',beta Weight in frequency. If it is a scalar, it represent the\n% weights of the entire L1 function in frequency. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L1 norm in frequency. (length: Ldual).\n% Default value is $\\beta=0$.\n% **Warning**: this value should not be too big in order to\n% avoid the the L1 norm proximal operator kill the signal.\n% No L1-frequency constraint: $\\beta=0$\n%\n% 'omega',omega Weight in time of the L2-norm. If it is a scalar, it represent the\n% weights of the entire L2 function in time. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L2 norm (length: Ldual).\n% Default value is $\\omega=0$.\n% No L2-time constraint: $\\omega=0$\n%\n% 'glike',g_l $g_l$ is a windows in time. The algorithm try to shape\n% the dual window like $g_l$. Normalization of $g_l$ is done\n% automatically. To use option omega should be different\n% from 0. By default $g_d=0$.\n%\n% 'mu',mu Weight of the smooth constraint Default value is 1. \n% No smooth constraint: $\\mu=0$\n% \n% 'gamma',gamma Weight of the smooth constraint in frequency. Default value is 1. \n% No smooth constraint: $\\gamma=0$\n% \n% 'delta',delta Weight of the S0-norm. Default value is 0. \n% No S0-norm: $\\delta=0$\n%\n% 'dual' Look for a dual windows (default)\n%\n% 'painless' Construct a starting guess using a painless-case\n% approximation. This is the default\n%\n% 'zero' Choose a starting guess of zero.\n%\n% 'rand' Choose a random starting phase.\n%\n% 'tol',t Stop if relative residual error is less than the \n% specified tolerance. \n%\n% 'maxit',n Do at most n iterations. default 200\n%\n% 'print' Display the progress.\n%\n% 'debug' Display all the progresses.\n%\n% 'quiet' Don't print anything, this is the default.\n%\n% 'fast' Fast algorithm, this is the default.\n%\n% 'slow' Safer algorithm, you can try this if the fast algorithm\n% is not working. Before using this, try to iterate more.\n%\n% 'printstep',p If 'print' is specified, then print every p'th\n% iteration. Default value is p=10;\n%\n% 'hardconstraint' Force the projection at the end (default)\n%\n% 'softconstaint' Do not force the projection at the end\n%\n% See also: gaboptdual, gabdual, gabtight, gabfirtight, gaboptdual\n \n\n\n% Author: Nathanael Perraudin\n% Date : 18 Feb 2014\n\n\nif nargin<4\n error('%s: Too few input parameters.',upper(mfilename));\nend;\n\n% l=length(varargin);\n% varargin(l+1)=cellstr('support');\n% varargin(l+2)=num2cell(Ldual);\n\n[gd,relres,iter]=gabconvexopt(g,a,M,varargin{:}, 'support',Ldual);\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/gabor/gabfirdual.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.7354197934158322}} {"text": "function dc = diffusivity_2d_elman ( a, cl, dc0, m_1d, omega, n1, n2, x, y )\n\n%*****************************************************************************80\n%\n%% DIFFUSIVITY_2D_ELMAN evaluates a 2D stochastic diffusivity function.\n%\n% Discussion:\n%\n% The 2D diffusion equation has the form\n%\n% - Del ( DC(X,Y) Del U(X,Y) ) = F(X,Y)\n%\n% where DC(X,Y) is a function called the diffusivity.\n%\n% In the stochastic version of the problem, the diffusivity function\n% includes the influence of stochastic parameters:\n%\n% - Del ( DC(X,Y;OMEGA) Del U(X,Y;OMEGA) ) = F(X,Y).\n%\n% In this function, the domain is assumed to be the square [-A,+A]x[-A,+A].\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 December 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Howard Elman, Darran Furnaval,\n% Solving the stochastic steady-state diffusion problem using multigrid,\n% IMA Journal on Numerical Analysis,\n% Volume 27, Number 4, 2007, pages 675-688.\n%\n% Roger Ghanem, Pol Spanos,\n% Stochastic Finite Elements: A Spectral Approach,\n% Revised Edition,\n% Dover, 2003,\n% ISBN: 0486428184,\n% LC: TA347.F5.G56.\n%\n% Parameters:\n%\n% Input, real A, the \"radius\" of the square region. The region\n% is assumed to be [-A,+A]x[-A,+A].\n% 0 < A.\n%\n% Input, real CL, the correlation length.\n% 0 < CL.\n%\n% Input, real DC0, the constant term in the expansion of the \n% diffusion coefficient. Take DC0 = 10.\n%\n% Input, integr M_1D, the first and second dimensions of the stochastic\n% parameter array.\n%\n% Input, real OMEGA(M_1D*M_1D), the stochastic parameters.\n%\n% Input, integer N1, N2, the dimensions of the X and Y arrays.\n%\n% Input, real X(N1,N2), Y(N1,N2), the points where the diffusion coefficient is to \n% be evaluated.\n%\n% Output, real DC(N1,N2), the value of the diffusion coefficient at X.\n%\n\n%\n% Compute THETA.\n%\n theta_1d = theta_solve ( a, cl, m_1d );\n%\n% m = m_1d * m_1d;\n% theta_1d = theta_solve ( a, cl, m );\n%\n% Compute LAMBDA_1D.\n%\n lambda_1d(1:m_1d) = 2.0 * cl ./ ( 1.0 + cl^2 * theta_1d(1:m_1d).^2 );\n%\n% Compute C_1DX(1:M1D) and C_1DY(1:M1D) at (X,Y).\n%\n c_1dx = zeros ( m_1d, n1, n2 );\n c_1dy = zeros ( m_1d, n1, n2 );\n\n k = 0;\n\n while ( 1 )\n\n if ( m_1d <= k )\n break\n end\n\n k = k + 1;\n c_1dx(k,1:n1,1:n2) = cos ( theta_1d(k) * a * x(1:n1,1:n2) ) ...\n / sqrt ( a + sin ( 2.0 * theta_1d(k) * a ) / ( 2.0 * theta_1d(k) ) );\n c_1dy(k,1:n1,1:n2) = cos ( theta_1d(k) * a * y(1:n1,1:n2) ) ...\n / sqrt ( a + sin ( 2.0 * theta_1d(k) * a ) / ( 2.0 * theta_1d(k) ) );\n\n if ( m_1d <= k )\n break\n end\n\n k = k + 1;\n c_1dx(k,1:n1,1:n2) = sin ( theta_1d(k) * a * x(1:n1,1:n2) ) ...\n / sqrt ( a - sin ( 2.0 * theta_1d(k) * a ) / ( 2.0 * theta_1d(k) ) );\n c_1dy(k,1:n1,1:n2) = sin ( theta_1d(k) * a * y(1:n1,1:n2) ) ...\n / sqrt ( a - sin ( 2.0 * theta_1d(k) * a ) / ( 2.0 * theta_1d(k) ) );\n\n end\n%\n% Evaluate the diffusion coefficient DC at (X,Y).\n% This nonsense of fussy array shapes really frustrates me!\n%\n k = 0;\n dc = dc0 * ones ( 1, n1, n2 );\n for j = 1 : m_1d\n for i = 1 : m_1d\n k = k + 1;\n dc(1,1:n1,1:n2) = dc(1,1:n1,1:n2) + sqrt ( lambda_1d(i) * lambda_1d(j) ) ...\n * c_1dx(i,1:n1,1:n2) .* c_1dy(j,1:n1,1:n2) * omega(k);\n end\n end\n\n dc = reshape ( dc, n1, n2 );\n\n return\nend\nfunction theta = theta_solve ( a, cl, m )\n\n%*****************************************************************************80\n%\n%% THETA_SOLVE solves a pair of transcendental equations.\n%\n% Discussion:\n%\n% The vector THETA returned by this function is needed in order to define\n% the terms in a Karhunen-Loeve expansion of a diffusion coefficient.\n%\n% The two equations are:\n%\n% 1/CL - THETA * TAN ( A * THETA ) = 0\n% THETA - 1/CL * TAN ( A * THETA ) = 0\n%\n% A and CL are taken to be positive. Over each open interval \n%\n% ( n - 1/2 pi, n + 1/2 pi ) / A, for N = 0, 1, ...\n%\n% the function TAN ( A * THETA ) monotonically rises from -oo to +00; \n% therefore, it can be shown that there is one root of each equation \n% in every interval of this form. Moreover, because of the positivity\n% of A and CL, we can restrict our search to the interval \n%\n% [ n pi, n + 1/2 pi ) / A, for N = 0, 1, ...\n%\n% This function computes K such roots, starting in the first interval,\n% finding those two roots, moving to the next interval, and so on, until\n% the requested number of roots have been found. Odd index roots will\n% correspond to the first equation, and even index roots to the second.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 July 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Howard Elman, Darran Furnival,\n% Solving the Stochastic Steady-State Diffusion Problem Using Multigrid,\n% University of Maryland Department of Computer Science,\n% Technical Report TR-4786.\n%\n% Parameters:\n%\n% Input, real A, the \"radius\" of the domain, D = (-A,A)x(-A,A).\n% 0 < A.\n%\n% Input, real CL, the correlation length.\n% 0 < CL.\n%\n% Input, integer M, the number of values to compute.\n%\n% Output, real THETA(M), the values of Theta.\n%\n k = 0;\n theta = zeros(m,1);\n%\n% [ XA_INIT, XB_INIT] = [ n * pi, n+1/2 pi ] / a, n = 0, 1, 2, ...\n%\n xa_init = 0.0;\n xb_init = ( pi / 2 ) / a;\n\n while ( 1 )\n%\n% Seek root of equation 1 in interval.\n%\n if ( m <= k )\n break\n end\n\n k = k + 1;\n xa = xa_init;\n fa = 1.0 / cl - xa * tan ( a * xa );\n ftol = eps * ( abs ( fa ) + 1.0 );\n xb = xb_init;\n fb = - fa;\n fc = fa;\n bmatol = 100.0 * eps * ( abs ( xa ) + abs ( xb ) );\n\n while ( bmatol < xb - xa )\n\n xc = ( xa + xb ) / 2;\n fc = 1.0 / cl - xc * tan ( a * xc );\n\n if ( abs ( fc ) <= ftol )\n break\n elseif ( 0 < fc )\n xa = xc;\n else\n xb = xc;\n end\n\n end\n\n theta(k) = xc;\n%\n% Seek root of equation 2 in interval.\n%\n if ( m <= k )\n break\n end\n\n k = k + 1;\n%\n% In the first interval, we need to skip the zero root of equation 2.\n%\n if ( k == 2 )\n\n k = k - 1;\n\n else\n\n xa = xa_init;\n fa = xa - tan ( a * xa ) / cl;\n ftol = eps * ( abs ( fa ) + 1.0 );\n xb = xb_init;\n fb = - fa;\n\n while ( bmatol < xb - xa )\n\n xc = ( xa + xb ) / 2;\n fc = xc - tan ( a * xc ) / cl;\n\n if ( abs ( fc ) <= ftol )\n break\n elseif ( 0 < fc )\n xa = xc;\n else\n xb = xc;\n end\n\n end\n\n theta(k) = xc;\n\n end\n%\n% Advance the interval.\n%\n xa_init = xa_init + pi / a;\n xb_init = xb_init + pi / a;\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/stochastic_diffusion/diffusivity_2d_elman.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7354197902399118}} {"text": "function [Geometry,Geom_res] =fbkp_grid(theta,N,interp)\n\n% theta are imput as angles in degrees\n% Define the x & y axes for the reconstructed image so that the origin\n% (center) is in the spot which RADON would choose.\n\n% N is a scalar that specifies the number of rows and columns in the \n% reconstructed image. N is determined from the length of the projections: !!!!\n%\n% N = 2*floor(size(P,1)/(2*sqrt(2)))\n%\ntheta = pi*theta/180;\n\nxax = (1:N)-ceil(N/2);\nx = repmat(xax,N,1) ; \n% x coordinates, the y coordinates are rot90(x)\ny = rot90(x);\ncostheta = cos(theta);\nsintheta = sin(theta);\n\n% Backprojection - vectorized in (x,y), looping over theta\nsa=size(x,1); sb=size(x,2); sc=length(theta);\n\n\nif strcmp(interp, 'nearest neighbor')\n Geometry=repmat(int16(0),[sa,sb,sc]);\n Geom_res=[];\n for i=1:length(theta)\n t=[];\n t = round( x*costheta(i) + y*sintheta(i) );\n Geometry(:,:,i)=t;\n end\n \nelseif strcmp(interp, 'linear')\n Geometry=repmat(int16(0),[sa,sb,sc]); % parte intera\n Geom_res=repmat(uint8(0),[sa,sb,sc]); % parte decimale\n \n for i=1:length(theta) \n t = x.*costheta(i) + y.*sintheta(i); \n a = floor(t); \n % img = img + (t-a).*proj(a+1+ctrIdx) + (a+1-t).*proj(a+ctrIdx);\n Geometry(:,:,i)=a ; % floor\n Geom_res(:,:,i)=uint8( abs(t-a)*100) ; % decimal i.e. double - floor\n\n end\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/schena/fbkp_grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7354197801141241}} {"text": "function [C, dA] = mcml_grad(x, X, P)\n%MCML_GRAD Computes MCML cost function and gradient \n%\n% [C, dA] = mcml_grad(x, X, P)\n%\n% Computes MCML cost function and gradient.\n%\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n\n % Decode solution\n [n, d] = size(X);\n A = reshape(x, [d d]);\n \n % Compute conditional probabilities for current solution\n D = zeros(n, n);\n for i=1:n\n diffX = bsxfun(@minus, X(i,:), X(i + 1:end,:));\n dist = sum((diffX * A) .* diffX, 2);\n D(i + 1:end, i) = dist;\n D(i, i + 1:end) = dist';\n end\n Q = exp(-D);\n Q(1:n+1:end) = 0;\n Q = bsxfun(@rdivide, Q, sum(Q, 2));\n Q = max(Q, realmin);\n \n % Compute cost function\n C = sum(P(:) .* log(P(:) ./ Q(:)));\n\n % Compute gradient with respect to A\n if nargin > 1\n dA = zeros(d, d);\n PQ = P - Q;\n for i=1:n\n diffX = bsxfun(@minus, X(i,:), X);\n dA = dA + bsxfun(@times, PQ(i,:), diffX') * diffX;\n end\n end\n dA = dA(:);\n ", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/mcml_grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7354197789217678}} {"text": "function psnr = PSNR(img_ref, img_dist, comparison_domain, max_value, mask)\n%\n%\n% psnr = PSNR(img_ref, img_dist, comparison_domain, max_value, mask)\n%\n%\n% Input:\n% -img_ref: input reference image\n% -img_dist: input distorted image\n% -comparison_domain: the domain where to compare images\n% 'lin': linear\n% 'log2': log base 2\n% 'log': natural logarithm\n% 'log10': log base 10\n% 'pu': perceptual uniform encoding\n% -max_value: maximum value (in the linear domain) of the images domain\n% -mask: a binary image for masked computations.\n%\n% Output:\n% -psnr: classic PSNR in dB; i.e., higher values means better quality.\n% \n% Copyright (C) 2016-18 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\n%check if images have same size and type\n[img_ref, img_dist, domain, mxt] = checkDomains(img_ref, img_dist);\ncheckNegative(img_ref);\ncheckNegative(img_dist);\n\n%determine the maximum value\nif(~exist('max_value', 'var'))\n max_value = -1000;\nend\n\nif(~exist('comparison_domain', 'var'))\n comparison_domain = 'lin';\nend\n\nif(~exist('mask', 'var'))\n mask = [];\nend\n\nbFlag = strcmp(domain, 'uint8') | strcmp(domain, 'uint16');\n\nif(bFlag && strcmp(comparison_domain, 'pu'))\n error('PU encoding does not make sense for uint8 or uint16 values. Physical values are required!');\nend\n\nif(bFlag && contains(comparison_domain, 'log'))\n error('logarithmic encoding does not make sense for uint8 or uint16 values. Please use linear domain!');\nend\n\nif(max_value < 0.0)\n max_value = mxt;\nend\n\n[img_ref, ~] = changeComparisonDomain(img_ref, comparison_domain);\n[img_dist, ~] = changeComparisonDomain(img_dist, comparison_domain);\n[max_value, bNeg] = changeComparisonDomain(max_value, comparison_domain);\ncomparison_domain = '';\n\nif(max_value < 0.0)\n max_value = -max_value;\nend\n\n%compute MSE\nmse = MSE(img_ref, img_dist, bNeg, comparison_domain, mask);\n\nif(mse > 0.0)\n %compute PSNR\n psnr = 20 * log10(max_value / sqrt(mse));\nelse\n disp('PSNR: the images are the same!');\n psnr = 1000;\nend\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/Metrics/PSNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7353608458455883}} {"text": "function [I,x,W,F] = sphericalradial(f,m,P,param)\n% SPHERICALRADIAL - ND scaled spherical-radial cubature rule\n%\n% Syntax:\n% [I,x,W,F] = sphericalradial(f,m,P[,param])\n%\n% In:\n% f - Function f(x,param) as inline, name or reference\n% m - Mean of the d-dimensional Gaussian distribution\n% P - Covariance of the Gaussian distribution\n% param - Parameters for the function (optional)\n%\n% Out:\n% I - The integral\n% x - Evaluation points\n% W - Weights\n% F - Function values\n%\n% Description:\n% Apply the spherical-radial cubature rule to integrals of form:\n% int f(x) N(x | m,P) dx\n\n% History:\n% Aug 5, 2010 - Renamed from 'cubature' to 'sphericalradial' (asolin)\n\n% Copyright (c) 2010 Arno Solin\n%\n% This software is distributed under the GNU General Public \n% Licence (version 2 or later); please refer to the file \n% Licence.txt, included with the software, for details.\n\n%% Spherical-radial cubature rule\n\n % The dimension of m is\n n = size(m,1);\n \n % Evaluation points (nx2n)\n x = [eye(n) -eye(n)];\n \n % Scaling\n x = sqrt(n)*x;\n x = chol(P)'*x + repmat(m,1,2*n);\n\n % Evaluate the function at the points\n if ischar(f) || strcmp(class(f),'function_handle')\n if nargin < 4\n F = feval(f,x);\n else\n F = feval(f,x,param);\n end\n elseif isnumeric(f)\n F = f*x;\n else\n if nargin < 4\n F = f(x);\n else\n F = f(x,param);\n end\n end\n \n % The weights are\n W = 1/(2*n);\n \n % Return integral value\n I = W*sum(F,2);\n \n % Return weights\n W = W*ones(1,2*n);\n \n ", "meta": {"author": "EEA-sensors", "repo": "ekfukf", "sha": "d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8", "save_path": "github-repos/MATLAB/EEA-sensors-ekfukf", "path": "github-repos/MATLAB/EEA-sensors-ekfukf/ekfukf-d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8/sphericalradial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7353574150198829}} {"text": "function [M_est,U_est,V_est,L1_error] = RobustApproximation_M_UV_TraceNormReg(M,W,r,lambda,rho,maxIterIN,signM)\n%% Robust low-rank matrix approximation with missing data and outliers\n% min |W.*(M-E)|_1 + lambda*|V|_*\n% s.t., E = UV, U'*U = I\n%\n%Input: \n% M: m*n data matrix\n% W: m*n indicator matrix, with '1' means 'observed', and '0' 'missing'.\n% r: the rank of r\n% lambda: the weighting factor of the trace-norm regularization, 1e-3 in default.\n% rho: increasing ratio of the penalty parameter mu, usually 1.05.\n% maxInterIN: maximum iteration number of inner loop, usually 100.\n% signM: if M>= 0, then signM = 1, otherwise, signM = 0;\n%Output:\n% M_est: m*n full matrix, such that M_est = U_est*V_est\n% U_est: m*r matrix\n% V_est: r*n matrix\n% L1_error: the L1-norm error of observed data only.\n%% Normalization\nscale = max(max(abs(M)));\nM = M/scale;\n\n%% In-default parameters\n[m n] = size(M); %matrix dimension\nif nargin < 6\n maxIterIN = 100;\nend\nif nargin < 5\n rho = 1.05;\nend\nif nargin < 4\n lambda = 1e-3;\nend\nif nargin < 3\n disp('Please input the data matrix M, the indicator W and the rank r, and try again.');\nend\n\nmaxIterOUT = 5000;\nmax_mu = 1e20;\nmu = 1e-6;\nM_norm = norm(M,'fro');\ntol = 1e-8*M_norm;\n\ncW = ones(size(W)) - W; %the complement of W.\ndisplay = 1; %display progress\n%% Initializing optimization variables as zeros\nE = zeros(m,n);\nU = zeros(m,r);\nV = zeros(r,n);\nY = zeros(m,n); %lagrange multiplier\n%% Start main outer loop\niter_OUT = 0;\nobjs=[];\nwhile iter_OUT < maxIterOUT\n iter_OUT = iter_OUT + 1;\n \n itr_IN = 0;\n obj_pre = 1e20;\n %start inner loop\n while itr_IN < maxIterIN \n %update U\n temp = (E + Y/mu)*V';\n \n [Us,sigma,Ud] = svd(temp,'econ'); % stable\n %[Us,sigma,Ud] = svdecon(temp); % fastest\n \n U = Us*Ud';\n\n %update V\n temp = U'*(E + Y/mu);\n \n [Vs,sigma,Vd] = svd(temp,'econ'); % stable\n %[Vs,sigma,Vd] = svdecon(temp); % fastest\n \n sigma = diag(sigma);\n svp = length(find(sigma > lambda/mu));\n if svp >= 1\n sigma = sigma(1:svp) - lambda/mu;\n else\n svp = 1;\n sigma = 0;\n end\n V = Vs(:,1:svp)*diag(sigma)*Vd(:,1:svp)';\n sigma0 = sigma;\n\n UV = U*V;\n \n %update E\n temp1 = UV - Y/mu;\n temp = M-temp1;\n E = max(0,temp - 1/mu) + min(0,temp + 1/mu); \n E = (M-E).*W + temp1.*cW;\n \n if signM > 0\n E(E<0) = 0;\n end\n \n %evaluate current objective\n obj_cur = sum(sum(abs(W.*(M-E)))) + lambda*sum(sigma0) + sum(sum(Y.*(E-UV))) + mu/2*norm(E-UV,'fro')^2;\n\n %check convergence of inner loop\n if abs(obj_cur - obj_pre) <= 1e-8*abs(obj_pre)\n break;\n else\n obj_pre = obj_cur;\n itr_IN = itr_IN + 1;\n end\n end\n\n leq = E - UV;\n stopC = norm(leq,'fro');\n if display\n obj = sum(sum(abs(W.*(M-UV)))) + lambda*sum(sigma0);\n objs = [objs,obj];\n end\n if display && (iter_OUT==1 || mod(iter_OUT,50)==0 || stopC tol)\n%\n% Iteration becoming unbounded?\n%\n if(abs(x) > 1.d9)\n disp(' iterate too large');\n if nargout == 2\n histmp(itc+1,:)=[itc,abs(fc)];\n hist=histmp(1:itc,:);\n end\n return\n end\n%\n% Check for small relative derivatives.\n%\n if(abs(fp) <= small*abs(fc))\n disp(' small derivative error');\n return;\n end\n s=-fc/fp;\n xt=x+s;\n ft=feval(f,xt);\n x=xt;\n itc=itc+1;\n%\n% Too many iterations?\n%\n if(itc > maxit)\n disp(' maxit reached');\n if nargout == 2\n histmp(itc+1,:)=[itc,abs(fc)];\n hist=histmp(1:itc,:);\n end\n return\n end\n%\n fc=feval(f,x);\n if nargout == 2\n histmp(itc+1,:)=[itc,abs(fc)];\n end\n end\n if nargout == 2\n hist=histmp(1:itc+1,:);\n end\n%\n% A simple forward difference in MATLAB.\n%\nfunction fp = fordiff(f,x,fc)\n h=1.d-7;\n%\n% Notice how f is evaluated using the feval command.\n%\n fright=feval(f,x+h);\n fp=(fright-fc)/h;\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/Chapter1/chordsol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.8824278664544912, "lm_q1q2_score": 0.7353488520106582}} {"text": "function line_integrals_test01 ( )\n\n%*****************************************************************************80\n%\n%% LINE_INTEGRALS_TEST01 compares exact and estimated monomial integrals.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n m = 1;\n n = 4192;\n test_num = 11;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LINE_INTEGRALS_TEST01\\n' );\n fprintf ( 1, ' Use LINE01_SAMPLE to estimate integrals\\n' );\n fprintf ( 1, ' along the length of the unit line in 1D.\\n' );\n%\n% Get sample points.\n%\n seed = 123456789;\n [ x, seed ] = line01_sample ( n, seed );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of sample points used is %d\\n', n );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' E MC-Estimate Exact Error\\n' );\n fprintf ( 1, '\\n' );\n\n for test = 1 : test_num\n\n e = test - 1;\n\n value = monomial_value_1d ( n, e, x );\n\n result = line01_length ( ) * sum ( value(1:n) ) / n;\n exact = line01_monomial_integral ( e );\n error = abs ( result - exact );\n\n fprintf ( 1, ' %2d %14.6g %14.6g %10.2e\\n', ...\n e, result, exact, 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/line_integrals/line_integrals_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8333245932423309, "lm_q1q2_score": 0.7353488480320974}} {"text": "function [y] = favar_transx(x,tcode)\n%% Transform x\n% Stock & Watson (2016)\n% Return Series with same dimension and corresponding dates\n% Missing values where not calculated\n% -- Tcodes:\n% 1 Level\n% 2 First Difference\n% 3 Second Difference\n% 4 Log-Level\n% 5 Log-First-Difference\n% 6 Log-Second-Difference\n% \t\t 7 First difference of percent change: (x(t)/x(t-1)-1)-(x(t-1)/x(t-2)-1), FRED-MD data (McCracken & Ng)\n% \n\nsmall=1.0e-06;\n\nn=size(x,1);\ny=NaN*zeros(n,1);\n\n if tcode==1\n y=x;\n\n elseif tcode==2\n y(2:n)=x(2:n)-x(1:n-1);\n\n elseif tcode==3\n y(3:n)=x(3:n)-2*x(2:n-1)+x(1:n-2);\n\n elseif tcode==4\n if min(x) < small\n y=NaN;\n else\n x=log(x);\n y=x;\n end\n \n elseif tcode==5\n if min(x) < small\n y = NaN;\n else\n x=log(x);\n y(2:n)=x(2:n)-x(1:n-1);\n end\n \n elseif tcode==6\n if min(x) < small\n y = NaN;\n else\n x=log(x);\n y(3:n)=x(3:n)-2*x(2:n-1)+x(1:n-2);\n end\n \n elseif tcode==7\n if min(x) < small\n y = NaN;\n else\n y1(2:n)=(x(2:n)-x(1:n-1))./x(1:n-1);\n y(3:n)=y1(3:n)-y1(2:n-1);\n end\n else\n y = NaN;\n end", "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/favar_transx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7353009201953207}} {"text": "function xhat = kalman(z, A, C, R, Q)\n% Simple Kalman Filter (linear) with optimal gain, no control signal\n%\n% z Measurement signal m observations X # of observations\n% A State transition model n X n, n = # of state values\n% C Observation model m X n\n% R Covariance of observation noise m X m\n% Q Covariance of process noise n X n\n%\n% Based on http://en.wikipedia.org/wiki/Kalman_filter, but matrices named\n% A, C, G instead of F, H, K.\n%\n% See http://home.wlu.edu/~levys/kalman_tutorial for background\n%\n% Copyright (C) 2014 Simon D. Levy\n%\n% This code is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as\n% published by the Free Software Foundation, either version 3 of the\n% License, or (at your option) any later version.\n%\n% This code 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 Lesser General Public License\n% along with this code. If not, see .\n\n% Initializtion =====================================================\n\n% Number of sensors\nm = size(C, 1);\n\n% Number of state values\nn = size(C, 2);\n\n% Number of observations\nnumobs = size(z, 2);\n\n% Use linear least squares to estimate initial state from initial\n% observation\nxhat = zeros(n, numobs);\nxhat(:,1) = C \\ z(:,1);\n\n% Initialize P, I\nP = ones(size(A));\nI = eye(size(A));\n\n% Kalman Filter =====================================================\n\nfor k = 2:numobs\n \n % Predict\n xhat(:,k) = A * xhat(:,k-1);\n P = A * P * A' + Q;\n \n % Update\n G = P * C' / (C * P * C' + R);\n P = (I - G * C) * P;\n xhat(:,k) = xhat(:,k) + G * (z(:,k) - C * xhat(:,k));\n \nend\n", "meta": {"author": "simondlevy", "repo": "SensorFusion", "sha": "b83451beb18c61d7ee30cbf5e5371a1c6669f9e3", "save_path": "github-repos/MATLAB/simondlevy-SensorFusion", "path": "github-repos/MATLAB/simondlevy-SensorFusion/SensorFusion-b83451beb18c61d7ee30cbf5e5371a1c6669f9e3/kalman.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.7353009174472671}} {"text": "function b = bernsteincop(x,g)\n%BERNSTEINCOP Bernstrein Empirical copula based on sample X.\n% B = BERNSTEINCOP(X,G) returns bivariate bernstein empirical copula\n% for GxG points grid. Extension to n dimensional bernstein empirical\n% 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\nc = ecopula(x);\n\n[m n] = size(c);\n\nb=zeros(g);\n\nfor i=1:g\n for j=1:g\n b(i,j)=sum(sum( bernstein(i/g,1:m,m)'*(bernstein(j/g,1:m,m)).*c ));\n end\nend\n\n%------------------------------------------------------------\nfunction y = bernstein(u,i,n)\n% BERNSTEIN calculates values of Bernstein polynomials.\n\ny = factorial(n)./factorial(i)./factorial(n-i).*u.^i.*(1-u).^(n-i);", "meta": {"author": "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/bernsteincop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7353009113070534}} {"text": "% Demonstration of the degree elevation algorithm. \n% \n \ncrv = nrbtestcrv; \n \n% plot the control points \nplot(crv.coefs(1,:),crv.coefs(2,:),'bo') \ntitle('Degree elevation of test curve by 1'); \nhold on; \nplot(crv.coefs(1,:),crv.coefs(2,:),'b--'); \n \n% draw nurbs curve \nnrbplot(crv,48); \n \n% degree elevate the curve by 1 \nicrv = nrbdegelev(crv, 1); \n \n% insert new knots and plot new control points \nplot(icrv.coefs(1,:),icrv.coefs(2,:),'ro') \nplot(icrv.coefs(1,:),icrv.coefs(2,:),'r--'); \n \nhold off; \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/26390-nurbs-toolbox-by-d-m-spink/nurbs_toolbox/demodegelev.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7352750405992259}} {"text": "% Jason Joseph Rebello\n% Carnegie Mellon University (Jan 2012 - May 2013) \n% MS in Electrical & Computer Engineering\n% Principal Component Analysis\n\n% This program uses Principal Component Analysis to reduce the number\n% of features used in face recognition. This program allows you to set K\n% if you know the number of Principal components needed or calculates K \n% based on how much variance you would like to preserve in the images.\n% Note: K has been commented out since I am calculating K based on\n% variance.\n\nclear all;\nclc;\nclose all;\n\nfprintf('Principal Component Analysis used for Face Recognition\\n\\n');\nt = cputime;\n\n%% Initializing Variable\n\nfprintf('Initializing Variables');\n%K = 100; % Number of reduced features (principal components)\ndispFaces = 12; % How many faces to display\nvariance = 90; % Enter a number between 1 and 99 both inclusive based on\n % how much variance to preserve.\ntopeig = 12; % Used to display the top 10 eigen vectors found\nfprintf('...done\\n\\n'); \n\n%% Loading and Visualizing data\n\nfprintf('Loading and Visualizing data');\nload('faces.mat');\ndisplayData(X(1:dispFaces, :)); % function taken from Machine Learning course \ntitle('Original faces') % by Prof Andrew Ng.\nfprintf('...done\\n\\n');\npause(1);\n\n%% Normalizing features\n\nfprintf('Normalizing features');\n[X mu stddev] = normalizeFeatures(X);\nfprintf('...done\\n\\n');\n\n%% Perform PCA to get eigen vectors and eigen values\n\nfprintf('Performing PCA & displaying top %d eigen vectors found', topeig);\n[U,S] = performPCA(X);\ndisplayData(U(:, 1:topeig)');\ntitle('Top Eigen Vecotrs found');\nfprintf('...done\\n\\n');\npause(2);\n\n%% Calculate K based on variance\n\nfprintf('Find best value of K based on Variance');\nK = findK(S, variance);\nfprintf('...done\\n\\n');\n\n%% Get data with reduced features\n\nfprintf('Displaying data with reduced features');\nreducedData = reducedFeatures(X, U, K);\nfprintf('...done\\n\\n');\n\n%% Recover Original Data\n\nfprintf('Recovering Original Data from reduced features');\nXRecovered = recoverData(reducedData, U, K);\nfprintf('...done\\n\\n');\n\n%% Display Original and Recovered Data\n\nfprintf('Displaying Original and Recovered Data');\nshow(X, XRecovered, dispFaces);\nfprintf('...done\\n\\n');\n\nfprintf('Program executed in %f seconds or %f minutes\\n\\n', cputime-t, ...\n (cputime-t)/60);\npause(1);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/42847-principal-component-analysis-pca/PCA/pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7352750256796126}} {"text": "function theVec=vech(H,offDiagScalFact,omitDiagonal)\n%%VECH The vector half operator. Given a square 2D matrix H, this returns\n% the entries that are on or below the main diagonal of H, listed\n% column-by-column, unless omitDiagonal=true, in which case the main\n% diagonal is omitted too.\n%\n%INPUTS: H An nXn matrix. It can be real or complex.\n% offDiagScalFact An optional scalar factor by which the off-diagonal\n% elements are scaled. If this parameter is omitted or an empty\n% matrix is passed, then the default value of 1 is used.\n% omitDiagonal An optional parameter indicating whether the elements on the\n% main diagonal should be omitted. The default if omitted or an\n% empty matrix is passed is false.\n%\n%OUTPUTS: theVec A (n*(n+1)/2)X1 matrix holding the lower-triangular part\n% of the matrix, listed column-by-column. If omitDiagonal is\n% true, then this is a (n*(n+1)/2-n)X1 vector, as the\n% elements on the main diagonal were omitted.\n%\n%The opposite of this function is vech2Mat.\n%\n%December 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(omitDiagonal))\n omitDiagonal=false;\nend\n\nif(nargin<2||isempty(offDiagScalFact))\n offDiagScalFact=1;\nend\n\nn=size(H,1);\n\nif(omitDiagonal)\n numEls=n*(n+1)/2-n;\n theVec=zeros(numEls,1);\n if(numEls==0)\n return;\n end\n curStart=1;\n for curCol=1:n\n %Off-diagonal elements\n span=(curStart):(curStart+n-curCol-1);\n theVec(span)=H((curCol+1):end,curCol)*offDiagScalFact;\n\n curStart=curStart+n-curCol;\n end\nelse\n theVec=zeros(n*(n+1)/2,1);\n\n curStart=1;\n for curCol=1:n\n %The diagonal element\n theVec(curStart)=H(curCol,curCol);\n\n %Off-diagonal elements\n span=(curStart+1):(curStart+n-curCol);\n theVec(span)=H((curCol+1):end,curCol)*offDiagScalFact;\n\n curStart=curStart+n-curCol+1;\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/Basic_Matrix_Operations/vech.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.9019206673024666, "lm_q1q2_score": 0.7352750227054213}} {"text": "function [mappedX, mapping] = npe(X, no_dims, k, eig_impl)\n%NPE Perform the Neighborhood Preserving Embedding algorithm\n%\n% [mappedX, mapping] = npe(X, no_dims, k)\n% [mappedX, mapping] = npe(X, no_dims, k, eig_impl)\n% \n% Runs the Neighborhood Preserving Embedding algorithm on dataset X to \n% reduce it to dimensionality no_dims. The number of neighbors that is used\n% by LPP is specified by k (default = 12).\n%\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n\n if size(X, 2) > size(X, 1)\n error('Number of samples should be higher than number of dimensions.');\n end\n if ~exist('no_dims', 'var')\n no_dims = 2; \n end\n if ~exist('k', 'var')\n k = 12;\n end\n if ~exist('eig_impl', 'var')\n eig_impl = 'Matlab';\n end\n \n % Get dimensionality and number of dimensions\n [n, d] = size(X);\n mapping.mean = mean(X, 1);\n\n % Compute pairwise distances and find nearest neighbours (vectorized implementation)\n disp('Finding nearest neighbors...'); \n [distance, neighborhood] = find_nn(X, k);\n max_k = size(neighborhood, 2);\n if nargout > 1\n mapping.nbhd = distance;\n end\n X = X';\n neighborhood = neighborhood';\n \n % Find reconstruction weights for all points by solving the MSE problem \n % of reconstructing a point from each neighbours. A used constraint is \n % that the sum of the reconstruction weights for a point should be 1.\n disp('Compute reconstruction weights...');\n if k > d \n tol = 1e-5;\n else\n tol = 0;\n end\n\n % Construct reconstruction weight matrix\n W = zeros(max_k, n);\n for i=1:n\n nbhd = neighborhood(:,i);\n if ischar(k)\n nbhd = nbhd(nbhd ~= 0);\n end\n kt = numel(nbhd);\n z = X(:,nbhd) - repmat(X(:,i), 1, kt); % Shift point to origin\n C = z' * z;\t\t\t\t\t\t\t\t\t\t\t\t% Compute local covariance\n C = C + eye(kt, kt) * tol * trace(C);\t\t\t\t\t% Regularization of covariance (if K > D)\n wi = C \\ ones(kt, 1); % Solve linear system\n wi = wi / sum(wi); % Make sure that sum is 1\n W(:,i) = [wi; nan(max_k - kt, 1)];\n end\n\n % Now that we have the reconstruction weights matrix, we define the \n % sparse cost matrix M = (I-W)'*(I-W).\n M = sparse(1:n, 1:n, ones(1, n), n, n, 4 * max_k * n);\n for i=1:n\n w = W(:,i);\n w(isnan(w)) = 0;\n j = neighborhood(:,i);\n w = w(j ~= 0);\n j = j(j ~= 0);\n M(i, j) = M(i, j) - w';\n M(j, i) = M(j, i) - w;\n M(j, j) = M(j, j) + w * w';\n end\n\t\n\t% For sparse datasets, we might end up with NaNs or Infs in M. We just set them to zero for now...\n\tM(isnan(M)) = 0;\n\tM(isinf(M)) = 0;\n\n % Compute XWX and XX and make sure these are symmetric\n X = X';\n WP = X' * M * X;\n DP = X' * X;\n DP = (DP + DP') / 2;\n WP = (WP + WP') / 2;\n\n % Solve generalized eigenproblem\n if size(X, 1) > 1500 && no_dims < (size(X, 1) / 10)\n if strcmp(eig_impl, 'JDQR')\n options.Disp = 0;\n options.LSolver = 'bicgstab';\n [eigvector, eigvalue] = jdqz(WP, DP, no_dims, 'SA', options);\n else\n options.disp = 0;\n options.issym = 1;\n options.isreal = 0;\n [eigvector, eigvalue] = eigs(WP, DP, no_dims, 'SA', options);\n end\n else\n [eigvector, eigvalue] = eig(WP, DP);\n end\n \n % Sort eigenvalues in descending order and get smallest eigenvectors\n [eigvalue, ind] = sort(diag(eigvalue), 'ascend');\n eigvector = eigvector(:,ind(1:no_dims));\n \n % Compute final linear basis and map data\n mappedX = X * eigvector;\n mapping.M = eigvector;\n", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/npe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7352660147555498}} {"text": "function [Q,w,S] = quadrature_points(V,F,k)\n % QUADRATURE_POINTS Sample quadrature points on a triangle or tetrahedron.\n %\n % Q = quadrature_points(V,F)\n %\n % Inputs:\n % V #V by dim list of vertex positions\n % F #F by simplex-size list of indices into V\n % k number of quadrature points {1,3,6}\n % Outputs:\n % Q #F by dim by k list of quadrature points\n % w #k list of weights\n % S #F*k by #V sparse matrix so that Q ~= S*V (~= means after\n % reordering)\n %\n % Example:\n % Q = quadrature_points(V,F);\n % QQ = reshape(permute(Q,[1 3 2]),[],3);\n % QQQ = permute(reshape(QQ,permute(size(Q),[1 3 2])),[1 3 2]);\n % max(abs(Q-QQQ))\n % \n % See also: barycenter\n %\n\n % Compute element quadrature points\n % \"A SET OF SYMMETRIC QUADRATURE RULES ON TRIANGLES AND TETRAHEDRA\", Table 2.2\n dim = size(V,2);\n ss = size(F,2);\n switch ss\n case 3\n switch k\n case 1\n lambda = [1/3 1/3 1/3];\n case 3\n %a = 0.5;\n a = 0.15;\n lambda = unique(perms([a a 1-2*a]),'rows');\n case 6\n a = 0.05;\n b = 0.1;\n lambda = unique(perms([a b 1-a-b]),'rows');\n otherwise\n error(sprintf('Unsupported number of quadratures %d',k));\n end\n % uniform weights\n w = ones(size(lambda,1),1)/size(lambda,1);\n QQ = cat(4,V(F(:,1),:),V(F(:,2),:),V(F(:,3),:));\n otherwise\n error(sprintf('Unsupported simplex-size %d',ss));\n end\n \n % #F by #lambda matrix of indices of all of the new points\n I = ((1:size(F,1))') + (0:size(lambda,1)-1)*size(F,1);\n S = sparse( ...\n repmat(I,size(F,2),1), ...\n repmat(F(:),1,size(lambda,1)), ...\n reshape(permute(repmat(lambda,[1 1 size(F,1)]),[3 2 1]),numel(F),size(lambda,1)), ...\n size(F,1)*size(lambda,1), ...\n size(V,1));\n % Q2 = S*V;\n \n lambda = permute(lambda,[3 4 1 2]);\n Q = sum(bsxfun(@times,QQ,lambda),4);\n \n % The Q ordering is silly. S*V ~= Q after gnarly reordering\n assert(max(max(max(abs(Q-permute(reshape(S*V,[size(Q,1) size(Q,3) size(Q,2)]),[1 3 2])))))<1e-12)\n \nend", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/mesh/quadrature_points.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7352642515907524}} {"text": "function [L_b,lambda_b,h_b,v_eb_n,C_b_n] = ECEF_to_NED(r_eb_e,v_eb_e,C_b_e)\n%ECEF_to_NED - Converts Cartesian to curvilinear position, velocity\n%resolving axes from ECEF to NED and attitude from ECEF- to NED-referenced\n%\n% Software for use with \"Principles of GNSS, Inertial, and Multisensor\n% Integrated Navigation Systems,\" Second Edition.\n%\n% This function created 2/4/2012 by Paul Groves\n%\n% Inputs:\n% r_eb_e Cartesian position of body frame w.r.t. ECEF frame, resolved\n% along ECEF-frame axes (m)\n% v_eb_e velocity of body frame w.r.t. ECEF frame, resolved along\n% ECEF-frame axes (m/s)\n% C_b_e body-to-ECEF-frame coordinate transformation matrix\n%\n% Outputs:\n% L_b latitude (rad)\n% lambda_b longitude (rad)\n% h_b height (m)\n% v_eb_n velocity of body frame w.r.t. ECEF frame, resolved along\n% north, east, and down (m/s)\n% C_b_n body-to-NED coordinate transformation matrix\n\n% Parameters\nR_0 = 6378137; %WGS84 Equatorial radius in meters\n% e = 0.0818191908425; %WGS84 eccentricity\n\necc2=0.006694380022900;\n\n% Copyright 2012, Paul Groves\n% License: BSD; see license.txt for details\n\n% Begins\n\n% Convert position using Borkowski closed-form exact solution\n% From (2.113)\nlambda_b = atan2(r_eb_e(2),r_eb_e(1));\n\n% From (C.29) and (C.30)\nk1 = sqrt(1 - ecc2) * abs (r_eb_e(3));\nk2 = ecc2 * R_0;\nbeta = sqrt(r_eb_e(1)^2 + r_eb_e(2)^2);\nE = (k1 - k2) / beta;\nF = (k1 + k2) / beta;\n\n% From (C.31)\nP = 4/3 * (E*F + 1);\n\n% From (C.32)\nQ = 2 * (E^2 - F^2);\n\n% From (C.33)\nD = P^3 + Q^2;\n\n% From (C.34)\nV = (sqrt(D) - Q)^(1/3) - (sqrt(D) + Q)^(1/3);\n\n% From (C.35)\nG = 0.5 * (sqrt(E^2 + V) + E);\n\n% From (C.36)\nT = sqrt(G^2 + (F - V * G) / (2 * G - E)) - G;\n\n% From (C.37)\nL_b = sign(r_eb_e(3)) * atan((1 - T^2) / (2 * T * sqrt (1 - ecc2)));\n\n% From (C.38)\nh_b = (beta - R_0 * T) * cos(L_b) +...\n (r_eb_e(3) - sign(r_eb_e(3)) * R_0 * sqrt(1 - ecc2)) * sin (L_b);\n \n% Calculate ECEF to NED coordinate transformation matrix using (2.150)\ncos_lat = cos(L_b);\nsin_lat = sin(L_b);\ncos_long = cos(lambda_b);\nsin_long = sin(lambda_b);\nC_e_n = [-sin_lat * cos_long, -sin_lat * sin_long, cos_lat;...\n -sin_long, cos_long, 0;...\n -cos_lat * cos_long, -cos_lat * sin_long, -sin_lat];\n \n% Transform velocity using (2.73)\nv_eb_n = C_e_n * v_eb_e;\n\n% Transform attitude using (2.15)\nC_b_n = C_e_n * C_b_e;\n\n% Ends", "meta": {"author": "benzenemo", "repo": "TightlyCoupledINSGNSS", "sha": "136225ef063709abfce681dd1e3e29234a187626", "save_path": "github-repos/MATLAB/benzenemo-TightlyCoupledINSGNSS", "path": "github-repos/MATLAB/benzenemo-TightlyCoupledINSGNSS/TightlyCoupledINSGNSS-136225ef063709abfce681dd1e3e29234a187626/CalculateTCRes/ECEF_to_NED.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067195846919, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.735148554538013}} {"text": "function [cg, psg] = crandn(rgau,m)\n% Generate correlated Gaussian sequences by Fourier synthesis.\n%\n% Input parameters:\n% rgau = correlation function - length n/2\n% m = number of realisations\n%\n% Output:\n% cg = m x n matrix containing m sequences of n correlated variates from\n% a zero mean, unit variance normal distribution\n% psg = input power spectrum (Fourier transform of correlation function)\n%\n% Note: Since this uses the fast Fourier transform, it will be fastest if\n% n is a power of 2.\n%\n% S Bocquet 12 August 2008 Tested with MATLAB Version 7.6.0.324 (R2008a)\n%\nif ~isvector(rgau)\n error('crandn:vector','Correlation function must be a vector')\nend\nif ((rgau(1) ~= 1) || (max(abs(rgau)) > 1))\n error('crandn:cfnorm','Correlation function not properly normalised');\nend\nif abs(rgau(end)) > 0.01\n warning('crandn:cfdecay','Correlation function does not go to zero')\nend\nn = 2*length(rgau);\nrgau2 = [rgau(1:end),0,rgau(end:-1:2)]; % two sided correlation function\npsg = abs(fft(rgau2)); % Fourier transform of correlation function\nnrm = mean(psg)/n; % normalisation\nh = sqrt(psg/nrm); % normalised filter function\ncg = zeros(n,m);\nfor i=1:m\n if mod(i,2)==1\n g = complex(randn(1,n),randn(1,n));\n cg2 = ifft(g.*h); % correlated Gaussian process\n cg(:,i) = real(cg2);\n else\n cg(:,i) = imag(cg2);\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/21325-crandn/crandn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7350986886324687}} {"text": "function [x,f,info]=convexQuadProgSOCP(G,a,C,b,numEqConst,params)\n%%CONVEXQUADPROGSOCP Perform quadratic programming on a convex problem.\n% Specifically, this algorithm solves the optimization\n% problem \n% minimize_x a'*x+(1/2)*x'*G*x\n% such that C(:,1:numEqConst)'*x=b\n% and C(:,(numEqConst+1):end)'*x>=b\n% Convexity means that G is positive (semi)definite. This\n% reformulates the problem as a second order cone problem\n% and then uses splittingConicSolver to solve the problem.\n% Unlike the active set method of [2], this formulation\n% tends to converge slowly on large problems (large being,\n% for example, 81 dimensions). \n%\n%INPUTS: G An nXn real, positive definite symmetric matrix (n>0).\n% a An nX1 real vector.\n% C An nXm real matrix (m>=0). The first numEqConst constraints (the\n% equality constraints) must be linearly independent or the\n% algorithm will identify the problem as infeasible.\n% b An mX1 vector.\n% numEqConst The number of constraints in C that are equality constraints\n% (numEqConst<=m). If this parameter is omitted or an empty matrix\n% is passed, the default numEqConst=0 is used.\n% params Parameters that affect how the function splittingConicSolver,\n% which is used by this function, works. See the comments to\n% splittingConicSolver for more information.\n%\n%OUTPUTS: x The nX1 solution to the optimization problem or an empty matrix\n% if the problem is infeasible or unbounded.\n% f The value of the objective function at x, or an empty matrix\n% if the problem is infeasible or unbounded.\n% info The problem is formulated as a second-order cone optimization\n% problem. This is the information regarding the termination\n% state returned by the splittingConicSolver function.\n%\n%As shown in [1], the equivalent second order cone optimization problem is\n%minimize t\n%subject to norm(SG*x+SG\\a)<=t\n% and C(:,1:numEqConst)'*x=b(1:numEqConst)\n% and C(:,(numEqConst+1):end)'*x>=b((numEqConst+1):end)\n% where SG=sqrtm(G)\n%The function splittingConicSolver is used to solve the problem.\n%\n%EXAMPLE 1:\n%This is the example worked out step-by-step in [2]:\n% G=[4, -2;-2, 4];\n% b=[0;0;2];\n% a=[6;0];\n% C=[1,0,1;\n% 0,1,1]; \n% [x,f,info]=convexQuadProgSOCP(G,a,C,b)\n%The optimal solution can be seen to be x=[0.5;1.5] and f=6.5;\n%\n%EXAMPLE 3:\n%This is an example of a problem having both inequality and equality\n%constraints:\n% G=[4, -2;-2, 4];\n% b=[2;1.6];\n% a=[6;0];\n% C=[1,0;\n% 1,1];\n% numEqConst=1;%One equality constraint.\n% [x,f,exitCode]=convexQuadProgSOCP(G,a,C,b,numEqConst)\n%The optimal solution is x=[0.4;1.6] and f=6.56.\n%\n%REFERENCES:\n%[1] S. Lobo, Miguel, L. Vandenberg, S. Boyd, and H. Lebret, \"Applications\n% of second-order cone programming,\" Linear Algebra and its\n% Applications, vol. 284, no. 1, pp. 193-228, 1998.\n%[2] D.Goldfarb and A. Idnani, \"A numerically stable dual method for\n% solving strictly convex quadratic programs,\" Mathematical Programming,\n% vol. 27, no. 1, pp. 1-33, Sep. 1983.\n%\n%February 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<5||isempty(numEqConst))\n numEqConst=0; \nend\n\nif(nargin<6)\n params=[]; \nend\n\nif(numEqConst>size(C,1))\n error('numEqConst is larger than the number of constraints in C')\nend\n\nP0=G;\n%The real command can help deal with finite precision issues.\nP0Root=real(sqrtm(P0));\nq0=a;\nAeq=C(:,1:numEqConst)';\nbeq=b(1:numEqConst);\nALeq=-C(:,(numEqConst+1):end)';\nbLeq=-b((numEqConst+1):end);\n\nnumIneqConst=length(bLeq);\n\n%The extra variable t is appended to the end.\nnumDim=length(a);\nc=zeros(numDim+1,1);\nc(end)=1;\n\n%Allocate space.\nnumVar=numEqConst+numIneqConst+numDim+1;\nF=zeros(numVar,numDim+1);\ng=zeros(numVar,1);\n\n%First, the equality constraints.\nF(1:numEqConst,1:numDim)=Aeq;\ng(1:numEqConst)=beq;\ncurRow=numEqConst+1;\ncone=[];\ncone.f=numEqConst;\n\n%Next, the inequality constraints\nsel=curRow:(curRow+numIneqConst-1);\nF(sel,1:numDim)=ALeq;\ng(sel)=bLeq;\ncone.l=numIneqConst;\ncurRow=curRow+numIneqConst;\n\n%Finally, the quadratic constraint.\nF(curRow,:)=-c';\ng(curRow)=0;\ncurRow=curRow+1;\n\nsel=curRow:(curRow+numDim-1);\nF(sel,1:numDim)=-P0Root;\n%g(sel)=P0Root\\q0;\ng(sel)=pinv(P0Root)*q0;\ncone.q=numDim+1;\n\n[x,~,~,info]=splittingConicSolver(F,g,c,cone,params);\n\nif(~isempty(x))\n x=x(1:numDim);%Get rid of the auxiliary variable.\n f=a'*x+(1/2)*x'*G*x;\nelse\n f=[];\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/Continuous_Optimization/Quadratic_Programming/convexQuadProgSOCP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7350986850594673}} {"text": "function[varargout]=ecconv(varargin)\n%ECCONV Converts between eccentricity measures.\n% \n% Y=ECCONV(X,STR) converts the eccentricity measure X into eccentricity\n% measure Y as specified by the string STR. \n% \n% STR is of the form 'in2out' where the names 'in' and 'out' may be\n% chosen from the following table.\n%\n% STR Name Definition \n% ----------------------------------------------------------------\n% 'ecc' Eccentricity sgn(b)*sqrt(1-b^2/a^2)\n% 'ell' Ellipticity b/a\n% 'lin' Linearity sgn(b)*(a^2-b^2)/(a^2+b^2)\n% 'circ' Circularity 2ab/(a^2+b^2) \n% 'nu' Eccentricity angle asin(b/sqrt(a^2 + b^2))\n% 'rot' Rotary ratio sgn(b)*(a-abs(b))/(a+abs(b))\n% \n% where \"a\" and \"b\" are the semi-major and semi-minor axes respective. \n% For example, ECC=ECCONV(L,'lin2ecc') converts the ellipse linearity L\n% into eccentricity ECC. \n%\n% All quantities are positive for mathematically positive rotation\n% and negative for mathematically negative rotation. Note the linearity\n% is undefined for the case of purely circular rotation a=abs(b);\n%\n% For further details, see Lilly and Gascard (2006).\n% ____________________________________________________________________\n% \n% Cell array input/output\n%\n% If ECCONV is given cell array input, it returns cell array output.\n%\n% Thus X may be a cell arrays of numerical arrays, and the output Y will\n% also be a cell array having an identical size as X.\n% ____________________________________________________________________\n%\n% See also ELLCONV, ELLDIFF, TRANSCONV. \n%\n% Usage: lin=ecconv(b./a,'ell2lin');\n% ecc=ecconv(lin,'lin2ecc');\n%\n% 'ecconv --t' runs a test.\n% 'ecconv --f' generates a sample figure.\n% _________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2005--2015 J.M. Lilly --- type 'help jlab_license' for details \n \n \nif strcmpi(varargin{1}, '--t')\n ecconv_test,return\nend\nif strcmpi(varargin{1}, '--f')\n type makefigs_ecconv\n makefigs_ecconv;\n return\nend\n \n%if nargin==2\n\nx=varargin{1};\nstr=varargin{2};\necconv_checkstr(str);\n\nif ~iscell(x)\n y=ecconv_one(x,str);\n y(isinf(x))=inf;\nelse\n for i=1:length(x)\n y{i,1}=ecconv_one(x{i},str);\n y{i}(isinf(x{i}))=inf;\n end\nend\n\nvarargout{1}=y;\n\n\nfunction[y]=ecconv_one(x,str)\n\nsizex=size(x);\nx=x(:);\n\n\nstr1=str(1:strfind(str,'2')-1);\nstr2=str(strfind(str,'2')+1:end);\nif aresame(str1,'circ')&&~aresame(str2,'circ')\n lin=sign(x).*sqrt(1-x.^2);\n eval(['y=lin2' str2 '(x);'])\nelseif ~aresame(str1,'circ')&&aresame(str2,'circ')\n eval(['lin=' str1 '2lin(x);'])\n y=sign(lin).*sqrt(1-lin.^2);\nelse\n eval(['y=' str '(x);'])\nend\ny=reshape(y,sizex);\n \n \n% elseif nargin==3\n% x1=varargin{1};\n% x2=varargin{2};\n% str=varargin{3};\n% ecconv_checkstr(str);\n% eval(['[y1,y2]=' str '(x1,x2);'])\n% varargout{1}=y1;\n% varargout{2}=y2;\n% end\n\nfunction[]=ecconv_checkstr(str)\nii=strfind(str,'2');\nif isempty(ii)\n error('STR should be of the form ''ecc2lin''.')\nend\nstr1=str(1:ii-1);\nstr2=str(ii+1:end);\n\nif ~aresame(str1,'nu') && ~aresame(str1,'ecc') && ~aresame(str1,'lin') && ~ ...\n aresame(str1,'rot') && ~aresame(str1,'ell') && ~aresame(str1,'circ')\n error(['Input parameter name ' str1 ' is not supported.'])\nend\nif ~aresame(str2,'nu') && ~aresame(str2,'ecc') && ~aresame(str2,'lin') && ~ ...\n aresame(str2,'rot') && ~aresame(str2,'ell') &&~aresame(str2,'circ')\n error(['Output parameter name ' str2 ' is not supported.'])\nend\n\nfunction[nu]=ell2nu(ell)\nnu=atan(ell);\nfunction[ell]=nu2ell(nu)\nell=tan(nu);\nfunction[ecc]=ell2ecc(ell)\necc=nu2ecc(ell2nu(ell));\nfunction[ell]=ecc2ell(ecc)\nell=nu2ell(ecc2nu(ecc));\nfunction[rot]=ell2rot(ell)\nrot=nu2rot(ell2nu(ell));\nfunction[ell]=rot2ell(rot)\nell=nu2ell(rot2nu(rot));\nfunction[lin]=ell2lin(ell)\nlin=nu2lin(ell2nu(ell));\nfunction[ell]=lin2ell(lin)\nell=nu2ell(lin2nu(lin));\n\nfunction[ecc]=nu2ecc(nu)\necc=sign(nu).*sqrt(1-squared(tan(nu)));\nvindexinto(ecc,1,find(nu==0),1);\nvindexinto(ecc,0,find(abs(nu)==pi/4),1);\n\nfunction[nu]=ecc2nu(ecc)\nnu=sign(ecc).*atan(sqrt(1-squared(ecc)));\nvindexinto(nu,pi/4,find(ecc==0),1);\n\nfunction[lambda]=nu2lin(nu)\nlambda=sign(nu).*cos(2*nu);\nvindexinto(lambda,1,find(nu==0),1);\nvindexinto(lambda,0,find(abs(nu)==pi/4),1);\n\nfunction[nu]=lin2nu(lambda)\nnu=sign(lambda).*atan(sqrt(frac(1-abs(lambda),1+abs(lambda))));\nvindexinto(nu,pi/4,find(lambda==0),1);\n\nfunction[alpha]=nu2rot(nu)\nalpha=sign(nu).*frac(1-abs(tan(nu)),1+abs(tan(nu)));\nvindexinto(alpha,1,find(nu==0),1);\nvindexinto(alpha,0,find(abs(nu)==pi/4),1);\n\nfunction[nu]=rot2nu(alpha)\nnu=sign(alpha).*atan(frac(1-abs(alpha),1+abs(alpha)));\nvindexinto(nu,pi/4,find(alpha==0),1);\n\nfunction[ecc]=lin2ecc(lambda)\necc=sign(lambda).*sqrt(frac(2*abs(lambda),1+abs(lambda)));\nvindexinto(ecc,0,find(lambda==0),1);\n\nfunction[lambda]=ecc2lin(ecc)\nlambda=sign(ecc).*frac(squared(ecc),2-squared(ecc));\nvindexinto(lambda,0,find(ecc==0),1);\n\nfunction[alpha]=lin2rot(lambda)\nalpha=nu2rot(lin2nu(lambda));\nvindexinto(alpha,0,find(lambda==0),1);\n\nfunction[lambda]=rot2lin(alpha)\nlambda=nu2lin(rot2nu(alpha));\nvindexinto(lambda,0,find(alpha==0),1);\n\nfunction[alpha]=ecc2rot(ecc)\nalpha=nu2rot(ecc2nu(ecc));\nvindexinto(alpha,0,find(ecc==0),1);\n\nfunction[ecc]=rot2ecc(alpha)\necc=nu2ecc(rot2nu(alpha));\nvindexinto(ecc,0,find(alpha==0),1);\n \nfunction[x]=rot2rot(x)\nfunction[x]=nu2nu(x)\nfunction[x]=ecc2ecc(x)\nfunction[x]=lin2lin(x)\nfunction[x]=ell2ell(x)\nfunction[x]=circ2circ(x)\n\n \n%/********************************************************\nfunction[]=ecconv_test\nstr{1}='nu';\nstr{2}='ecc';\nstr{3}='lin';\nstr{4}='rot';\nstr{5}='ell';\n\nx=rand(100,1)*2-1;\nx(end+1,1)=1; %Add an exact one\nx(end+1,1)=0; %Add an exact zero\n\nclear y z x2 bool\n\n%Turn lambda into all others\nfor i=1:length(str)\n y(:,i)=ecconv(x,['lin2' str{i}]);\nend\n\n%Turn all others into everything else\nfor i=1:length(str)\n for j=1:length(str)\n z(:,i,j)=ecconv(y(:,i),[str{i} '2' str{j}]);\n end\nend\n\n%Turn everything back into lambda\nfor i=1:length(str)\n for j=1:length(str)\n x2(:,i,j)=ecconv(z(:,i,j),[str{j} '2lin']);\n end\nend\n\nfor i=1:size(x2,2)\n for j=1:size(x2,2)\n bool(i,j)=aresame(squeeze(x2(:,i,j)),x,1e-14);\n end\nend\n\nreporttest('ECCONV', allall(bool))\n%\\********************************************************\n\n\n% %Not currently used\n% figure\n% lambda=(0:.001:1)';\n% \n% ecc=ecconv(lambda,'lin2ecc');\n% alpha=ecconv(lambda,'lin2rot');\n% ecc1=sqrt(2)*sqrt(lambda);\n% alpha1=lambda/2;\n% \n% plot(lambda,[ecc,alpha,ecc1,alpha1]);\n% linestyle k 2k k-- 2k--\n% axis([0 1 0 1]),axis square \n% text(0.4,0.7,'\\epsilon')\n% text(0.7,0.5,'\\alpha')\n% title('Eccentricity measures')\n% xlabel('Ellipse parameter \\lambda')\n% ylabel('Eccentricity \\epsilon or rotary ratio \\alpha')\n% set(gcf,'paperposition', [2 2 3.5 3.5])\n% xtick(.1),ytick(.1),fixlabels(-1)\n% fontsize 14 14 14 14\n\n% function[kappa,nu]=ab2kn(a,b)\n% kappa=frac(1,sqrt(2))*sqrt(squared(a)+squared(b));\n% nu=atan(frac(b,a));\n% \n% function[a,b]=kn2ab(kappa,nu)\n% a=cos(nu).*kappa*sqrt(2);\n% b=sin(nu).*kappa*sqrt(2);\n% \n% function[nu]=ab2nu(a,b)\n% nu=atan(frac(b,a));\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/ecconv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7350986826376976}} {"text": "function [tx, ty] = rectToPolygon(rect)\n%RECTTOPOLYGON Convert a rectangle into a polygon (set of vertices)\n%\n% POLY = rectToPolygon(RECT);\n% Converts rectangle given as [X0 Y0 W H] or [X0 Y0 W H THETA] into a\n% 4-by-2 array double, containing coordinate of rectangle vertices.\n% X0 and Y0 are the coordinates of the \"lower left\" vertex (before\n% applying rotation), W and H are the width and the height of the\n% rectangle, and THETA is the rotation angle around the first vertex, in\n% degrees.\n%\n% See also:\n% orientedBoxToPolygon, ellipseToPolygon, drawRect, drawPolygon\n%\n%\n\n% ---------\n% Author: David Legland\n% e-mail: david.legland@nantes.inra.fr\n% INRA - TPV URPOI - BIA IMASTE\n% created the 06/04/2005.\n%\n\n% HISTORY\n\n% extract rectangle parameters\ntheta = 0;\nx0 = rect(1);\ny0 = rect(2);\nw = rect(3);\nh = rect(4);\nif length(rect) > 4\n theta = rect(5);\nend\n\n% precompute angular quantities\ncot = cosd(theta);\nsit = sind(theta);\n\n% compute vertex coordinates\ntx = zeros(4, 1);\nty = zeros(4, 1);\ntx(1) = x0;\nty(1) = y0;\ntx(2) = x0 + w * cot;\nty(2) = y0 + w * sit;\ntx(3) = x0 + w * cot - h * sit;\nty(3) = y0 + w * sit + h * cot;\ntx(4) = x0 - h * sit;\nty(4) = y0 + h * cot;\n\n% format output\nif nargout <= 1\n tx = [tx ty];\nend\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom2d/rectToPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7350986802159276}} {"text": "function gbasis=groebner(polyset,ord,varnames,tol)\n% GROEBNER - calculate the reduced Groebner basis of a set of polynomials\n% usage: gbasis = groebner(polyset,ord)\n% gbasis = groebner(polyset,ord,varnames)\n% gbasis = groebner(polyset,ord,varnames,tol)\n%\n% INPUTS: polyset, ord, varnames, tol\n% polyset is a cell array of multivariate polynomial coefficients\n% the cell elements can be all strings or all arrays.\n% If the polynomials are specified with arrays, each row of the array\n% represents a single term. The first element is the coefficient and\n% the others are the degrees of each unknown in the term.\n% e.g. [-1,2,1;1,0,1] represents -x1^2*x2+x2\n% If the polynomials are specified as strings, they must use variable\n% names 'x1','x2',... (unless varnames is provided) and be valid inputs\n% for petschel.str2poly.m\n% ord is a string specifying the monomial ordering:\n% 'lex': lexicographical, order by highest power of most significant\n% indeterminate, e.g. x1>x2^2, x1*x2>x1.\n% 'grlex': graded lex, order by total degree then lex,\n% e.g. x1^2*x2 > x1*x2^2 > x1^2\n% 'grevlex': graded reverse lex, order by total degree then by lowest\n% power of least significant indeterminate, e.g. x1*x2^2 > x1*x2*x3\n% (for all cases have x1>x2>...>xn)\n% note: revlex is not a well-ordering because 1>x1>x1^2>...\n% varnames (optional) is a cell array of variable names if polyset is a\n% cell array of strings and the variable names are not 'x1', 'x2', etc.\n% If specified, there must always be at least 2 variables.\n% tol (optional) is the zero tolerance for coefficients, otherwise\n% catastrophic cancellation may occur. Default value is 0\n%\n% OUTPUTS: gbasis\n% gbasis is the reduced Groebner basis of the set of polynomials, in the\n% same format (strings or matrices) as polyset{1}.\n%\n% ALGORITHM:\n% A modified Buchberger's algorithm is used. In Buchberger's algorithm,\n% at each step calculate Sij = (Lij/ai)*Pi - (Lij/aj)*Pj, for all pairs of\n% polynomials Pi, Pj, where ai and aj are the leading terms of Pi and Pj,\n% and Lij is the least common multiple of ai and aj; then reduce Sij with\n% respect to the polynomials and add it to the set (note that Sij always\n% reduces to zero if ai and aj have no variables in common). The\n% algorithm terminates when no new polynomials can be added to the set.\n% This function reduces the polynomials at each step in order to find the\n% reduced Groebner basis.\n%\n% EXAMPLE: simplify equations x^2+2xy^2=0, xy+2y^3=1\n% A1=[1,2,0;2,1,2]; % 1*x^2*y^0 + 2*x^1*y^2\n% A2=[-1,0,0;1,1,1;2,0,3]; % -1*x^0*y^0 + 1*x^1*y^1 + 2*x^0*y^3\n% y=groebner({A1,A2},'lex');\n% petschel.poly2str(y) % returns {'x2^3-0.5', 'x1'}\n%\n% EXAMPLE: same, but with equations specified as strings:\n% groebner({'x^2+2*x*y^2','x*y+2*y^3-1'},'lex',{'x','y'})\n% % returns {'y^3-0.5','x'}\n%\n% EXAMPLE: show that a set of equations is inconsistent\n% groebner({'x + y', 'x^2 - 1', 'y^2 - 2*x'}, 'lex', {'x', 'y'})\n% % returns {'1'}\n%\n%\n% KNOWN ISSUES\n%\n% 0. GENERAL: while a significant effort has been made to ensure that the\n% program works as described, unidentified bugs may remain and the results\n% should be regarded with caution. In particular, the suite of tests\n% performed was by no means comprehensive.\n%\n% 1. ACCURACY: the algorithm by default works in floating-point which\n% ultimately cannot perform exact arithmetic, so unexpected silent errors may\n% occur even when the coefficients are specified as integers. A workaround\n% is to use other data types but this has its own issues (see below).\n%\n% 1a. EXAMPLE (roundoff - linearly independent polynomials)\n% eps % returns 2.2204e-16 (32-bit PC windows machine epsilon)\n% groebner({'x1+x2','x1+1.000000000000001*x2'},'lex') % ok, returns {'x2','x1'}\n% groebner({'x1+x2','x1+1.0000000000000001*x2'},'lex') % not ok, returns {'x2+x1'}\n%\n% 1b. EXAMPLE (roundoff - linearly dependent polynomials)\n% 2/sqrt(2)-sqrt(2) % expect 0, returns -2.2204e-016\n% petschel.poly2str(groebner({[1,1,0;sqrt(2),0,1],[1/sqrt(2),1,0;1,0,1]},'lex')) % ok, returns {'1.41421*x2+x1'}\n% petschel.poly2str(groebner({[1,1,0;sqrt(2),0,1],[sqrt(2),1,0;2,0,1]},'lex')) % not ok, returns {'x2','x1'}\n% petschel.poly2str(groebner({[1,1,0;sqrt(2),0,1],[sqrt(2),1,0;2,0,1]},'lex',{},1e-14)) % ok, returns {'1.41421*x2+x1'}\n%\n% 1c. EXAMPLE (courtesy of Christophe Lauwerys - catastrophic cancellation & tolerance bug)\n% groebner({'t^3+x+y','t^2+0.5*x^2-x-z^2','t^2+y-z^2'},'lex',{'t','x','y','z'}) % ans{1} contains Inf\n%\n% 1d. EXAMPLE (from Mathematica documentation - catastrophic cancellation because of large intermediate coefficients)\n% % expect 3 polynomials returns, one of degree 8 in z; instead can get '1'\n% groebner({'x^2 + y^2 + z^2 - 1', 'x*y - z + 2', 'z^2 - 2*x + 3*y'}, 'lex', {'x', 'y','z'})\n%\n% 2. NON-DOUBLE INPUTS: use of non-double coefficients is not supported. While\n% it may be tempting to introduce symbolic coefficients, it is not clear how\n% they should be consistently treated - for example 'A*x' could reduce to '0'\n% or 'x' or both, depending upon the assumptions on the coefficient A.\n%\n% 3. EFFICIENCY: The reduction algorithms aren't terribly efficient. One of\n% the major bottlenecks at present is the calculation of the leading term,\n% which currently involves a call to sortrows each time. It could be more\n% efficient to maintain an ordered list or even a priority queue (e.g.\n% implemented as a heap). Also lattice reduction algorithms such as LLL\n% might speed things up.\n%\n%\n% SEE ALSO:\n% petschel.poly2str, petschel.str2poly, petschel.polynsolve\n\n% Author: Ben Petschel 19/6/2009\n%\n% Change history:\n% 19/6/2009 - first release (ord='grlex' and ord='grevlex' not\n% implemented yet)\n% 22/6/2009 - implemented ord='grlex' and ord='grevlex'\n% reduction algorithm now reduces lower-order terms as well\n% 23/6/2009 - removed ord='revlex' because it is not a well-ordering\n% 17/7/2009 - fixed bug in handling polynomials with >=3 variables\n% 20/3/2010 - changed polynomial representation from multidimensional\n% arrays to 2d arrays (more memory efficient with large number of vars)\n% 11/10/2010 - bugfix for handling error tolerance\n\nif (numel(polyset)>0) && ischar(polyset{1})\n \n charout = true;\n \n if nargin<3\n \n polyset = petschel.str2poly(polyset);\n \n else\n \n polyset = petschel.str2poly(polyset,varnames);\n \n end\n \nelse\n \n charout = false;\n \nend\n\nif nargin<4\n \n tol = 0;\n \nend\n\n% determine the number of degrees\nnd=max(cellfun(@(x)size(x,2)-1,polyset)); % error if = 0\n\nif nd == 0\n \n error('number of variables must be >= 1');\n \nend\n\ngbasis = fullreduce(polyset,ord,tol,nd);\n\noldgbasis = {};\n\nwhile ~isequal(oldgbasis,gbasis)\n \n oldgbasis = gbasis;\n \n Qset = SPoly(gbasis,ord,tol,nd);\n \n gbasis = fullreduce([gbasis,Qset],ord,tol,nd);\n \nend\n\nif charout\n \n if nargin<3\n \n gbasis = petschel.poly2str(gbasis);\n \n else\n \n gbasis = petschel.poly2str(gbasis,varnames);\n \n end\n \nend\n\nend % main function groebner(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Qset = SPoly(Pset,ord,tol,nd)\n% calculates all reduced S-polynomials of Pset (Pset must be reduced)\n% Sij = (Lij/ai)*Pi - (Lij/aj)*Pj,\n% for all pairs of polynomials Pi, Pj, where ai and aj are the leading\n% terms of Pi and Pj, and Lij is the least common multiple of ai and aj\n% then reduces Sij wrt Pset\n\nQset = {};\n\nfor i=1:numel(Pset)-1\n \n for j=i+1:numel(Pset)\n \n [c1,d1] = leadterm(Pset{i},ord,tol,nd); %#ok<*ASGLU>\n \n [c2,d2] = leadterm(Pset{j},ord,tol,nd);\n \n if any(and(d1>0,d2>0))\n % leading terms have a variable in common, so S-poly is nontrivial\n L = max(d1,d2); % LCM of leading terms\n \n S = addpolys(multiplyterm(Pset{i},L-d1),multconst(multiplyterm(Pset{j},L-d2),-1));\n \n S = reduceset(S,Pset,ord,tol,nd);\n \n %if any(S(:)~=0),\n if abs(leadterm(S,ord,tol,nd))>tol\n \n Qset{end+1}=S; % add S to the list\n \n end\n \n end\n \n end\n \nend\n\nend % helper function SPoly(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Qset = fullreduce(Pset,ord,tol,nd)\n% reduces all polynomials wrt each other\nQset = Pset;\n\noldQset = {};\n\nwhile ~isequal(oldQset,Qset)\n \n oldQset = Qset;\n \n for i=1:numel(Qset)-1\n \n for j=i+1:numel(Qset)\n \n Qset{i}=reduce(Qset{i},Qset{j},ord,tol,nd);\n \n Qset{j}=reduce(Qset{j},Qset{i},ord,tol,nd);\n \n end\n \n end\n \nend\n\n% keep only the nonzero results (to within zero tolerance tol)\nQset = Qset(cellfun(@(x)abs(leadterm(x,ord,tol,nd))>tol,Qset));\n\nif numel(Qset)==1\n \n % special case, a single equation can slip through without being reduced\n c = leadterm(Qset{1},ord,tol,nd);\n \n % coefficients occupy first column of the array\n Qset{1} = multconst(Qset{1},1/c); % know c~=0 because have already removed zero eqns\n \nend\n\nend % helper function fullreduce(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Q = reduceset(P,Pset,ord,tol,nd)\n% reduces P wrt all polynomials in Pset\nQ = P;\n\noldQ = [];\n\nwhile ~isequal(oldQ,Q)\n \n oldQ = Q;\n \n for i=1:numel(Pset)\n \n Q=reduce(Q,Pset{i},ord,tol,nd);\n \n end\n \nend\n\nend % helper function reduceset(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Q1=reduce(P1,P2,ord,tol,nd)\n% reduces a polynomial P1 by subtracting multiples of P2 so that leading\n% term coefficient is 1 and leading term of P2 does not divide that of P1\n\nQ2=P2;\n\n[c2,d2] = leadterm(Q2,ord,tol,nd);\n\nif abs(c2)<=tol\n \n % ignore terms less than tol\n keepgoing = false;\n \n Q1 = P1;\n \nelse\n \n keepgoing = true;\n \n Q2 = multconst(Q2,1/c2);\n \n Q1 = 0; % will successively add terms to Q\n % remove the leading terms, in order to reduce wrt lower terms\n remain = P1;\n \nend\n\n\nwhile keepgoing\n \n [c1,d1] = leadterm(remain,ord,tol,nd);\n \n if abs(c1)<=tol\n \n % ignore terms less than tol\n keepgoing = false;\n \n else\n %reduce remain by Q2, if possible, or remove leading term\n if d1>=d2\n % can reduce Q1 by Q2, so subtract a multiple of Q2 from Q1\n remain = addpolys(remain,multconst(multiplyterm(Q2,d1-d2),-c1));\n \n else\n % cannot reduce any further wrt leading term, but try lower terms\n lead = multiplyterm(c1,d1);\n \n remain = addpolys(remain,multconst(lead,-1));\n \n Q1 = addpolys(Q1,lead); % add irreducible terms to Q1\n \n end\n \n end\n \nend\n\n% reduce leading coefficient, if possible\nc1 = leadterm(Q1,ord,tol,nd);\n\nif abs(c1)>tol\n \n Q1 = multconst(Q1,1/c1);\n \nend\n\nend % helper function reduce(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Q=multconst(P,c)\n% returns c*P where c is a constant\n\nQ = P;\n\nQ(:,1)=Q(:,1)*c;\n\nend % helper function multconst(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Q=addpolys(P1,P2)\n% adds two polynomials\n\ns1 = size(P1,2);\n\ns2 = size(P2,2);\n\nif s1>s2\n \n Q = [P1;P2,zeros(size(P2,1),s1-s2)];\n \nelse\n \n Q = [P1,zeros(size(P1,1),s2-s1);P2];\n \nend\n\nQ = sortrows(Q,2:size(Q,2));\n\ni=1;\n\nwhile itol,1,'last');\n \n if isempty(ind)\n \n coeff = 0;\n \n deg = zeros(1,d-1);\n \n else\n \n coeff = P(ind,1);\n \n deg = P(ind,2:end);\n \n end\n \nend % if all(P(:)==0)\n\nif nd>d-1\n \n deg = [deg,zeros(1,nd-d+1)];\n \nend\n\nend % helper function leadterm(...)\n\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/ragnarok/third_party/+petschel/groebner.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7349920718402062}} {"text": "function y = winconv(x,varargin)\n%WINCONV Discrere time convolution of a sequence with a window.\n% y = WINCONV(X) convolves the sequence X with a rectangular window. The\n% length of the window is same as that of X.\n%\n% y = WINCONV(X,WINTYPE) convolves the sequence X with the window\n% specified by WINTYPE. WINTYPE can be either 'rect', or 'hamming', or\n% 'hanning', or 'bartlett', or 'blackman'. The length of the window is \n% same as that of X.\n%\n% y = WINCONV(X,WINTYPE,WINAMP) convolves the sequence X with the window\n% specified by WINTYPE. The amplitude of the window is set by WINAMP. So\n% WINAMP must be a real number/vector. The length of the window is same \n% as that of X. WINAMP could be a real constant or a vector with WINLEN \n% elements.\n% \n% y = WINCONV(X,WINTYPE,WINAMP,WINLEN) convolves the sequence X with the\n% window specified by WINTYPE having amplitude WINAMP and length WINLEN.\n%\n% See also CONV, FFT, RECTWIN, HAMMING, HANNING, BARTLETT, BLACKMAN.\n%\n% Author: Nabin Sharma\n% Date: 2009/03/15\n\nerror(nargchk(1,4,nargin,'struct'));\n\nlen = length(varargin);\nswitch len\n case 0\n wintype = 'rectwin';\n A = 1;\n L = length(x);\n case 1\n if ischar(varargin{1})\n wintype = lower(varargin{1});\n A = 1;\n L = length(x);\n end\n case 2\n if ischar(varargin{1}) && isreal(varargin{2})\n wintype = lower(varargin{1});\n A = varargin{2};\n L = length(x);\n end\n case 3\n if ischar(varargin{1}) && isreal(varargin{2}) &&...\n isreal(varargin{3})\n wintype = lower(varargin{1});\n A = varargin{2};\n L = varargin{3};\n end\nend\n\n% generate the window\nw1 = (window(str2func(wintype),L)).'; A = A(:).';\nw = A.*w1;\n\n% perform the convolution using FFT\nNFFT = 2^(nextpow2(length(x)+L));\nX = fft(x,NFFT); W = fft(w,NFFT);\nY = X.*W;\ny = ifft(Y,NFFT);\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/23571-short-time-energy-and-zero-crossing-rate/stezcr/winconv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7349774423770702}} {"text": "function G = filterDog2d( r, var, order, show )\n% Difference of Gaussian (Dog) Filter.\n%\n% Adapted from code by Serge Belongie. Takes a \"Difference of Gaussian\" -\n% all centered on the same point but with different values for sigma. Also\n% serves as an approximation to an Laplacian of Gaussian (LoG) filter (if\n% order==1).\n%\n% USAGE\n% G = filterDog2d( r, var, order, [show] )\n%\n% INPUTS\n% r - Final filter will be 2*r+1 on each side\n% var - variance of central Gaussian\n% order - should be either 1-LoG or 2-difference of 3 Gaussians\n% show - [0] figure to use for optional display\n%\n% OUTPUTS\n% G - filter\n%\n% EXAMPLE\n% G = filterDog2d( 40, 40, 1, 1 ); %order=1 (LoG)\n% G = filterDog2d( 40, 40, 2, 3 ); %order=2\n%\n% See also FILTERDOOG, FILTERGAUSS\n%\n% Piotr's Image&Video Toolbox Version 2.0\n% Copyright 2012 Piotr Dollar. [pdollar-at-caltech.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the Simplified BSD License [see external/bsd.txt]\n\nif( nargin<4 || isempty(show) ); show=0; end\n\n% create filter\nN = 2*r+1;\nif (order==1)\n Ga = filterGauss( [N N], [], .71*var );\n Gb = filterGauss( [N N], [], 1.14*var );\n a=1; b=-1; G = a*Ga + b*Gb;\n\nelseif (order==2)\n Ga = filterGauss( [N N], [], 0.62*var );\n Gb = filterGauss( [N N], [], var );\n Gc = filterGauss( [N N], [], 1.6*var );\n a=-1; b=2; c=-1; G = a*Ga + b*Gb + c*Gc;\n\nelse\n error('order must be 1 or 2');\nend\n\n% normalize\nG=G-mean(G(:));\nG=G/norm(G(:),1);\n\n% display\nif(show); filterVisualize( G, show, 'row' ); end\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SketchTokens-master/toolbox/filters/filterDog2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8688267643505194, "lm_q1q2_score": 0.7349774306335488}} {"text": "function y = nigpdf(x, alpha, beta, mu, delta)\n%NIGPDF Probability density function (pdf) for Normal-Inverse-Gaussian distribution.\n% Y = NIGPDF(X, ALPHA, BETA, MU, DELTA) returns the pdf of the \n% Normal-Inverse-Gaussian distribution with the parameter BETA which \n% determines the skewness, shape parameter ALPHA, location parameter MU \n% and scale parameter DELTA, evaluated at the values in X.\n% \n% ALPHA, BETA, MU, DELTA must be scalar values.\n% ALPHA and DELTA must be positive values.\n% ALPHA > |BETA| must hold.\n%\n% Default values for ALPHA = 1, BETA = 0; MU = 0; DELTA = 1.\n%\n% See also NIGCDF, NIGINV, NIGRND, NIGSTATS.\n%\n% References:\n% [1] Prause, K. (1999). The Generalized Hyperbolic Model\n\n% -------------------------------------------------------------------------\n% \n% Allianz, Group Risk Controlling\n% Risk Methodology\n% Koeniginstr. 28\n% D-80802 Muenchen\n% Germany\n% Internet: www.allianz.de\n% email: ralf.werner@allianz.de\n% \n% Implementation Date: 2006 - 05 - 01\n% Author: Dr. Ralf Werner\n%\n% -------------------------------------------------------------------------\n\n%% Default input values\nif nargin < 2\n alpha = 1;\nend\nif nargin < 3\n beta = 0;\nend\nif nargin < 4\n mu = 0;\nend\nif nargin < 5\n delta = 1;\nend\n\n%% Constraints for the parameters\nif alpha <= 0\n error('ALPHA must be positive.');\nend\nif delta <= 0\n error('DELTA must be positive.');\nend\nif abs(beta)>=alpha\n error('|BETA| must be smaller than ALPHA');\nend\n\n% transform input into column vector\n[nx, mx] = size(x);\nx = reshape(x, nx * mx, 1);\n\n% calculate leading factor\nq = (delta * alpha / pi) * exp(delta * sqrt(alpha^2 - beta^2));\nxbar = x - mu;\nz = sqrt(delta^2 + xbar .* xbar);\n\n% modified Bessel function of the third kind \nK = besselk(1, (alpha * z));\n\ny = q ./ z .* K .* exp(beta * (x - mu));\n\n% transform input vector back to input format\ny = reshape(y, nx, mx);\ny(isinf(x)) = 0;\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/10934-normal-inverse-gaussian-nig-distribution-updated-version/nigpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7349621527409651}} {"text": "function tauc = taucv(alfa,f,n)\n%TAUCV Upper percentage point of the tau distribution.\n% tauc=taucv(alfa,f,n) computes the critical value of tau distribution\n% for the Type I error--significance level (alfa), degree of freedom (f)\n% and the number of observations (n). It is used in Pope test for outliers.\n% \n% References:\n% [1] Koch KR,1999, Parameter estimation and hypothesis testing in linear models,\n% Springer Verlag, Berlin\n% [2] Pope AJ,1976, The statistics of residuals and the detection of outliers.\n% NOAA Technical Report NOS65 NGS1, US Department of Commerce, National Geodetic\n% Survey,Rockville, Maryland\n% -----------------------------------------------------------------------------\n% Written by Cuneyt AYDIN, 2003, Yildiz Technical University, Geodesy Division\n% e-mail:caydin@yildiz.edu.tr\n% ----------------------------------------------------------------------------- \n\nif nargin < 3, \n error('requires at least three input arguments; alfa,f and n'); \n end \n \nif f==1\n error('degree of freedom must be larger than 1 (f>1)')\n \nend\n\nfdist=finv((1-alfa/n),1,(f-1));\ntauc=sqrt((f*fdist)/(f-1+fdist));\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/3435-taucv/taucv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7349621487957598}} {"text": "function [a,r,f] = femq1_diff(xy,ev)\n%femq1_diff vectorized bilinear coefficient matrix generator\n% [A,Q,f] = femq1_diff(xy,ev);\n% input\n% xy vertex coordinate vector \n% ev element mapping matrix\n% output\n% A stiffness matrix\n% Q mass matrix \n% f rhs vector\n%\n% Natural boundary conditions apply. Dirichlet conditions\n% must be explicitly enforced by calling function nonzerobc.\n% IFISS function: DJS; 4 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \nx=xy(:,1); y=xy(:,2);\nnvtx=length(x);\nnel=length(ev(:,1));\nlx=max(x)-min(x); ly=max(y)-min(y);\nhx=max(diff(x)); hy=max(diff(y));\nfprintf('setting up Q1 diffusion matrices... ')\n%\n% initialise global matrices\n a = sparse(nvtx,nvtx);\n r = sparse(nvtx,nvtx);\n f = zeros(nvtx,1);\n%\n% set up 2x2 Gauss points\n gpt=1.0e0/sqrt(3.0e0);\n s(1) = -gpt; t(1) = -gpt;\n s(2) = gpt; t(2) = -gpt;\n s(3) = gpt; t(3) = gpt;\n s(4) = -gpt; t(4) = gpt;\n%\n% inner loop over elements \n for ivtx = 1:4\n xl_v(:,ivtx) = x(ev(:,ivtx));\n yl_v(:,ivtx) = y(ev(:,ivtx)); \n\t end\n ae = zeros(nel,4,4);\n re = zeros(nel,4,4);\n fe = zeros(nel,4); \n% loop over 2x2 Gauss points\n for igpt = 1:4\n sigpt=s(igpt);\n tigpt=t(igpt);\n% evaluate derivatives etc\n [jac,invjac,phi,dphidx,dphidy] = deriv(sigpt,tigpt,xl_v,yl_v);\n rhs = gauss_source(sigpt,tigpt,xl_v,yl_v);\n for j = 1:4\n for i = 1:4\n ae(:,i,j) = ae(:,i,j) + dphidx(:,i).*dphidx(:,j) .* invjac(:);\n ae(:,i,j) = ae(:,i,j) + dphidy(:,i).*dphidy(:,j) .* invjac(:);\n re(:,i,j) = re(:,i,j) + phi(:,i).*phi(:,j) .* jac(:);\n end\n fe(:,j) = fe(:,j) + rhs(:) .* phi(:,j) .* jac(:); \n\t end\n% end of Gauss point loop\n end\n% perform assembly of global matrix and source vector \n for krow=1:4\n\t nrow=ev(:,krow);\t \n for kcol=1:4\n\t\t ncol=ev(:,kcol);\t \n a = a + sparse(nrow,ncol,ae(:,krow,kcol),nvtx,nvtx);\n r = r + sparse(nrow,ncol,re(:,krow,kcol),nvtx,nvtx);\n end\n f(nrow,1) = f(nrow,1) + fe(:,krow);\n end\n%\nfprintf('done\\n')\nreturn\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/toms866/diffusion/femq1_diff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7349621465855438}} {"text": "function [u, v] = HS(im1, im2, alpha, ite, uInitial, vInitial, displayFlow, displayImg)\n% Horn-Schunck optical flow method \n% Horn, B.K.P., and Schunck, B.G., Determining Optical Flow, AI(17), No.\n% 1-3, August 1981, pp. 185-203 http://dspace.mit.edu/handle/1721.1/6337\n%\n% Usage:\n% [u, v] = HS(im1, im2, alpha, ite, uInitial, vInitial, displayFlow)\n% For an example, run this file from the menu Debug->Run or press (F5)\n%\n% -im1,im2 : two subsequent frames or images.\n% -alpha : a parameter that reflects the influence of the smoothness term.\n% -ite : number of iterations.\n% -uInitial, vInitial : initial values for the flow. If available, the\n% flow would converge faster and hence would need less iterations ; default is zero. \n% -displayFlow : 1 for display, 0 for no display ; default is 1.\n% -displayImg : specify the image on which the flow would appear ( use an\n% empty matrix \"[]\" for no image. )\n%\n% Author: Mohd Kharbat at Cranfield Defence and Security\n% mkharbat(at)ieee(dot)org , http://mohd.kharbat.com\n% Published under a Creative Commons Attribution-Non-Commercial-Share Alike\n% 3.0 Unported Licence http://creativecommons.org/licenses/by-nc-sa/3.0/\n%\n% October 2008\n% Rev: Jan 2009\n\n%% Default parameters\nif nargin<1 || nargin<2\n im1=imread('yos9.tif');\n im2=imread('yos10.tif');\nend\nif nargin<3\n alpha=1;\nend\nif nargin<4\n ite=100;\nend\nif nargin<5 || nargin<6\n uInitial = zeros(size(im1(:,:,1)));\n vInitial = zeros(size(im2(:,:,1)));\nelseif size(uInitial,1) ==0 || size(vInitial,1)==0\n uInitial = zeros(size(im1(:,:,1)));\n vInitial = zeros(size(im2(:,:,1)));\nend\nif nargin<7\n displayFlow=1;\nend\nif nargin<8\n displayImg=im1;\nend\n \n%% Convert images to grayscale\nif size(size(im1),2)==3\n im1=rgb2gray(im1);\nend\nif size(size(im2),2)==3\n im2=rgb2gray(im2);\nend\nim1=double(im1);\nim2=double(im2);\n\nim1=smoothImg(im1,1);\nim2=smoothImg(im2,1);\n\ntic;\n\n%%\n% Set initial value for the flow vectors\nu = uInitial;\nv = vInitial;\n\n% Estimate spatiotemporal derivatives\n[fx, fy, ft] = computeDerivatives(im1, im2);\n\n% Averaging kernel\nkernel_1=[1/12 1/6 1/12;1/6 0 1/6;1/12 1/6 1/12];\n\n% Iterations\nfor i=1:ite\n % Compute local averages of the flow vectors\n uAvg=conv2(u,kernel_1,'same');\n vAvg=conv2(v,kernel_1,'same');\n % Compute flow vectors constrained by its local average and the optical flow constraints\n u= uAvg - ( fx .* ( ( fx .* uAvg ) + ( fy .* vAvg ) + ft ) ) ./ ( alpha^2 + fx.^2 + fy.^2); \n v= vAvg - ( fy .* ( ( fx .* uAvg ) + ( fy .* vAvg ) + ft ) ) ./ ( alpha^2 + fx.^2 + fy.^2);\nend\n\nu(isnan(u))=0;\nv(isnan(v))=0;\n\n%% Plotting\nif displayFlow==1\n plotFlow(u, v, displayImg, 5, 5); \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/22756-horn-schunck-optical-flow-method/HS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7348305326797298}} {"text": "%% squircle\n% Below is a demonstration of the features of the |squircle| function\n\n%%\nclear; close all; clc;\n\n%% Syntax\n% |[V]=squircle(r,f,n);|\n\n%% Description \n% The squircle is a shape intermediate between a circle and a square. This\n% function outputs the coordinates V for a squircle using the input radius\n% r, the weighting parameter f, and the number of points n. \n%\n% See also: https://en.wikipedia.org/wiki/Squircle\n%\n% This implementation is based on: \n% https://arxiv.org/vc/arxiv/papers/1604/1604.02174v1.pdf\n\n%% Examples \n% \n\n%% Example 1: Constructing a squircle\nn=200; %Number of points on curve\nr=2; %Squircle radius\n\n%%\n\nf=0.5; \n[V]=squircle(r,f,n);\n\n%%\n\nt=linspace(0,2*pi,n)';\nVc=r*[cos(t) sin(t) zeros(size(t))]; %Circle coordinates\nVs=r*[-1 -1 0; 1 -1 0; 1 1 0; -1 1 0; -1 -1 0];\n\n%%\n% Visualization\n\ncFigure; hold on\nhp1=plotV(Vc,'r-' ,'LineWidth',2);\nhp2=plotV(Vs,'b-' ,'LineWidth',2);\nhp3=plotV(V ,'k.-','LineWidth',5);\n\naxis equal; axis tight; grid on; box on; \nset(gca,'FontSize',25);\naxis(r*[-1.25 1.25 -1.25 1.25]);\nlegend([hp1 hp2 hp3],{'Circle','Square',['Squircle ','f=',num2str(f)]},'Location','NorthEastOutSide')\ndrawnow; \n\n\n%% Example 2: Animate effect of varying f\n\nn=104; %Number of points on curve\nr=1; %Squircle radius\n\nnSteps=25; %Number of animation steps\nf=linspace(0,1,nSteps);\n\n%%\n\nhf=cFigure; hold on\nht=gtitle(['f=',sprintf('%.3f',f(1))],25);\nc=spectral(nSteps);\nfor q=1:1:nSteps \n [V]=squircle(r,f(q),n); \n hp1=plotV(V,'k-','LineWidth',2);\n hp1.Color=c(q,:); \nend\n\nhp2=plotV(V,'k.-','LineWidth',4,'MarkerSize',25);\naxis equal; axis tight; grid on; box on; \ncolormap(c); colorbar; caxis([0 1]);\nset(gca,'FontSize',25);\ndrawnow; \n\n%%\n%Populate the animation structure\n\n%Create the time vector\nanimStruct.Time=linspace(0,1,nSteps);\n\nfor q=1:1:nSteps \n [V]=squircle(r,f(q),n);\n \n %Set entries in animation structure\n animStruct.Handles{q}=[hp2 hp2 ht]; %Handles of objects to animate\n animStruct.Props{q}={'XData','YData','String'}; %Properties of objects to animate\n animStruct.Set{q}={V(:,1),V(:,2),['f=',sprintf('%.3f',f(q))]}; %Property values for to set in order to animate\nend\n\nanim8(hf,animStruct);\n\n%%\n% \n% <>\n% \n% _*GIBBON*_ \n% \n% \n% _Kevin Mattheus Moerman_, \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/HELP_squircle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7348305320798854}} {"text": "function [yi, ypi] = trigint(x, y, xi, c)\n\n% hRIGINT 1-D piecewise trigonometric interpolation\n% TRIGINT(X,Y,XI,C) interpolates to find YI, the values of the\n% underlying function Y at the points in the array XI, using\n% piecewise trigonometric interpolation. X and Y must be vectors \n% of length N.\n%\n% C specifies the number of data points to use in the\n% interpolation. The default is to use all points.\n%\n% [YI,YPI] = TRIGINT() also returns the interpolated derivative\n% of the underlying function Y at points XI.\n\n% Joe Henning - Fall 2012\n\n% On the Interpolation Trigonometric Polynomial with an Arbitrary Even Number of Nodes\n% Ernest Scheiber\n% 2011 13th International Symposium on Symbolic and Numeric Algorithms for Scientific Computing\n% 978-0-7695-4630-8/11 2011 IEEE\n% DOI 10.1109/SYNASC.2011.13\n\nif (nargin < 4)\n c = 0;\nend\n\nn = length(x);\n\nif (n < c)\n fprintf('??? Bad c input to trigint ==> c <= length(x)\\n');\n yi = [];\n ypi = [];\n return\nend\n\nfor i = 1:length(xi)\n % Find the right place in the table by means of a bisection.\n klo = 1;\n khi = n;\n while (khi-klo > 1)\n k = fix((khi+klo)/2.0);\n if (x(k) > xi(i))\n khi = k;\n else\n klo = k;\n end\n end\n \n h = x(khi) - x(klo);\n if (h == 0.0)\n fprintf('??? Bad x input to trigint ==> x values must be distinct\\n');\n yi(i) = NaN;\n ypi(i) = NaN;\n continue;\n end\n\n % Evaluate lagrange polynomial\n yi(i) = 0;\n ypi(i) = 0;\n if (c == 0)\n if (mod(n,2) == 0) % even\n for k = 1:n\n sumx = 0;\n for m = 1:n\n sumx = sumx + x(m);\n end\n term = y(k)*(cos(0.5*(xi(i)-x(k))) + sin(0.5*(xi(i)-x(k)))*cot(0.5*sumx));\n termp = 0;\n termp2 = y(k)*0.5*(-sin(0.5*(xi(i)-x(k))) + cos(0.5*(xi(i)-x(k)))*cot(0.5*sumx));\n for m = 1:n\n if (k ~= m)\n term = term*sin(0.5*(xi(i)-x(m)))/sin(0.5*(x(k)-x(m)));\n prod = 0.5*cos(0.5*(xi(i)-x(m)));\n for j = 1:n\n if ((k ~= j) && (m ~= j))\n prod = prod*sin(0.5*(xi(i)-x(j)))/sin(0.5*(x(k)-x(j)));\n end\n end\n termp = termp + y(k)*(cos(0.5*(xi(i)-x(k))) + sin(0.5*(xi(i)-x(k)))*cot(0.5*sumx))*prod/sin(0.5*(x(k)-x(m)));\n termp2 = termp2*sin(0.5*(xi(i)-x(m)))/sin(0.5*(x(k)-x(m)));\n end\n end\n yi(i) = yi(i) + term;\n ypi(i) = ypi(i) + termp + termp2;\n end\n else % odd\n for k = 1:n\n term = y(k);\n termp = 0;\n for m = 1:n\n if (k ~= m)\n term = term*sin(0.5*(xi(i)-x(m)))/sin(0.5*(x(k)-x(m)));\n prod = 0.5*cos(0.5*(xi(i)-x(m)));\n for j = 1:n\n if ((k ~= j) && (m ~= j))\n prod = prod*sin(0.5*(xi(i)-x(j)))/sin(0.5*(x(k)-x(j)));\n end\n end\n termp = termp + y(k)*prod/sin(0.5*(x(k)-x(m)));\n end\n end\n yi(i) = yi(i) + term;\n ypi(i) = ypi(i) + termp;\n end\n end\n else\n if (mod(c,2) == 0) % even\n c2 = c/2;\n if (klo < c2)\n klo = c2;\n end\n if (klo > n-c2)\n klo = n-c2;\n end\n khi = klo + 1;\n for k = klo-(c2-1):klo+c2\n sumx = 0;\n for m = klo-(c2-1):klo+c2\n sumx = sumx + x(m);\n end\n term = y(k)*(cos(0.5*(xi(i)-x(k))) + sin(0.5*(xi(i)-x(k)))*cot(0.5*sumx));\n termp = 0;\n termp2 = y(k)*0.5*(-sin(0.5*(xi(i)-x(k))) + cos(0.5*(xi(i)-x(k)))*cot(0.5*sumx));\n for m = klo-(c2-1):klo+c2\n if (k ~= m)\n term = term*sin(0.5*(xi(i)-x(m)))/sin(0.5*(x(k)-x(m)));\n prod = 0.5*cos(0.5*(xi(i)-x(m)));\n for j = 1:n\n if ((k ~= j) && (m ~= j))\n prod = prod*sin(0.5*(xi(i)-x(j)))/sin(0.5*(x(k)-x(j)));\n end\n end\n termp = termp + y(k)*(cos(0.5*(xi(i)-x(k))) + sin(0.5*(xi(i)-x(k)))*cot(0.5*sumx))*prod/sin(0.5*(x(k)-x(m)));\n termp2 = termp2*sin(0.5*(xi(i)-x(m)))/sin(0.5*(x(k)-x(m)));\n end\n end\n yi(i) = yi(i) + term;\n ypi(i) = ypi(i) + termp + termp2;\n end\n else % odd\n c2 = floor(c/2);\n if (klo < c2+1)\n klo = c2+1;\n end\n if (klo > n-c2)\n klo = n-c2;\n end\n khi = klo + 1;\n for k = klo-c2:klo+c2\n term = y(k);\n termp = 0;\n for m = klo-c2:klo+c2\n if (k ~= m)\n term = term*sin(0.5*(xi(i)-x(m)))/sin(0.5*(x(k)-x(m)));\n prod = 0.5*cos(0.5*(xi(i)-x(m)));\n for j = 1:n\n if ((k ~= j) && (m ~= j))\n prod = prod*sin(0.5*(xi(i)-x(j)))/sin(0.5*(x(k)-x(j)));\n end\n end\n termp = termp + y(k)*prod/sin(0.5*(x(k)-x(m)));\n end\n end\n yi(i) = yi(i) + term;\n ypi(i) = ypi(i) + termp;\n end\n end\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/36800-interpolation-utilities/trigint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7348305284355335}} {"text": "% \n% Sort the terms of a multivariate polynomial f according to \n% the lexicographical order, and combine the like terms \n% \n% Syntax: >> G = mvPolynSort(F) \n% >> G = mvPolynSort(F, tord) \n% >> [G,idg] = mvPolynSort(F) \n% >> [G,idg] = mvPolynSort(F, tord) \n% \n% Input: F -- (matrix) multivariate polynomial in coeff. matrix \n% tord -- (string, optional) 'lex' or 'grlex', term order type \n% The default is 'lex' if not provided \n%\n% Output: G --- (matrix) sorted coeff. matrix of the input polynomial \n% idg --- (vector) the indices of G terms \n% \n% Examples: \n% \n% >> F \n% \n% F = \n% \n% 0 0 4 3 3 0 \n% 0 0 1 0 0 1 \n% 0 0 1 0 0 2 \n% 8 7 -7 2 4 -5 \n% \n% >> [g,idg] = mvPolynSort(F) \n% \n% G = \n% \n% 0 3 4 0 \n% 0 0 1 1 \n% 0 0 1 2 \n% 15 6 -7 -5 \n% \n% idg = \n% \n% 1 4 20 26 \n% \n% >> [G,idg] = mvPolynSort(F,'grlex') \n% \n% G = \n% \n% 0 0 3 4 \n% 0 1 0 1 \n% 0 2 0 1 \n% 15 -5 6 -7 \n% \n% \n% idg = \n% \n% 1 12 20 80 \n% \n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/homotopy/mvPolynSort.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7348305238914149}} {"text": "function [ mH ] = GenerateToeplitzConvMatrix( vH, numElementsData, convShape )\n% ----------------------------------------------------------------------------------------------- %\n%[ mH ] = GenerateToeplitzConvMatrix( vH, numElementsData, convShape )\n% Generates matrix 'mH' such that mH * vX = conv(vX, vH, 'convShape').\n% Input:\n% - vH - Input Vector.\n% The coeeficients of the filter.\n% Structure: Vector (n X 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - numElementsData - Number of Elements of the Data.\n% Number of elements in the vector to convolve.\n% In the equation above it is 'length(vX)'.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, 3, ...}.\n% - convShape - Convolution Shape.\n% Sets the convolution type. Using same\n% definitions as in MATLAB 'conv()' function.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, 3}.\n% Output:\n% - mH - Toeplitz Convolution Matrix.\n% Structure: Matrix.\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References\n% 1. A\n% Remarks:\n% 1. B\n% Known Issues:\n% 1. C\n% TODO:\n% 1. D\n% Release Notes:\n% - 1.0.001 17/01/2020 Royi Avital\n% * Direct use of 'toeplitz()' to create the\n% 'CONVOLUTION_SHAPE_SAME' case.\n% - 1.0.000 11/01/2020 Royi Avital\n% * First realease version.\n% ----------------------------------------------------------------------------------------------- %\n\nCONVOLUTION_SHAPE_FULL = 1;\nCONVOLUTION_SHAPE_SAME = 2;\nCONVOLUTION_SHAPE_VALID = 3;\n\nnumTaps = length(vH);\n\nswitch(convShape)\n case(CONVOLUTION_SHAPE_FULL)\n vR = [vH(1); zeros(numElementsData - 1, 1)];\n vC = [vH(:); zeros(numElementsData - 1, 1)];\n case(CONVOLUTION_SHAPE_SAME)\n sepIdx = ceil((numTaps + 1) / 2);\n vC = zeros(numElementsData, 1);\n vR = zeros(numElementsData, 1);\n vC(1:numTaps - sepIdx + 1) = vH(sepIdx:numTaps);\n vR(1:sepIdx) = vH(sepIdx:-1:1);\n case(CONVOLUTION_SHAPE_VALID)\n vR = [flip(vH(:), 1); zeros(numElementsData - numTaps, 1)];\n vC = [vH(end); zeros(numElementsData - numTaps, 1)];\nend\n\nmH = toeplitz(vC, vR);\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/SignalProcessing/Q45879/GenerateToeplitzConvMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7347631012080904}} {"text": "function KG = kappa(I)\n% get curvature information of input image\n% input: 2D image I\n% output: curvature matrix KG\n\n% Copyright (c) 2009, \n% Yue Wu @ ECE Department, Tufts University\n% All Rights Reserved \n\nI = double(I);\n[m,n] = size(I);\nP = padarray(I,[1,1],1,'pre');\nP = padarray(P,[1,1],1,'post');\n\n% central difference\nfy = P(3:end,2:n+1)-P(1:m,2:n+1);\nfx = P(2:m+1,3:end)-P(2:m+1,1:n);\nfyy = P(3:end,2:n+1)+P(1:m,2:n+1)-2*I;\nfxx = P(2:m+1,3:end)+P(2:m+1,1:n)-2*I;\nfxy = 0.25.*(P(3:end,3:end)-P(1:m,3:end)+P(3:end,1:n)-P(1:m,1:n));\nG = (fx.^2+fy.^2).^(0.5);\nK = (fxx.*fy.^2-2*fxy.*fx.*fy+fyy.*fx.^2)./((fx.^2+fy.^2+eps).^(1.5));\nKG = K.*G;\nKG(1,:) = eps;\nKG(end,:) = eps;\nKG(:,1) = eps;\nKG(:,end) = eps;\nKG = KG./max(max(abs(KG)));\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/特征提取算法/DAPI_image_feature_extraction-master/chanvese/kappa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440397949314, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7347508185621568}} {"text": "function par_est\n% parameter estimation with derivatives Holzbecher September 2005\n% for exponential fit of exponent lambda for c(0)=c0\nglobal tfit cfit c0 \n\n% specify fitting data\ntfit = [0.25 1 2 4 8]; \ncfit = [0.7716 0.5791 0.4002 0.1860 0.1019]; \nc0 = .8;\n\nlambda = fzero(@myfun,0.11); \nnormc = norm(cfit - c0*exp(-lambda*tfit));\ndisplay (['Best fit for lambda = ' num2str(lambda)]);\ndisplay (['Norm of residuals =' num2str(normc)]);\ntmax = tfit(size(tfit,2));\nt = [0:0.01*tmax:tmax];\nfigure; plot (tfit,cfit,'or',t,c0*exp(-lambda*t),'-');\nlegend ('given','modelled');\ntext(0.5*tmax,c0*0.7,['\\lambda: ' num2str(lambda)]); \ntext(0.5*tmax,c0*0.6,['norm of residuals: ' num2str(normc)]);\nxlabel ('time'); ylabel ('concentration')\n\nfunction f = myfun(lambda); \nglobal tfit cfit c0 \n\nt = tfit;\nc = c0*exp(-lambda*t); % solve linear decay equation for c with c(0)=c0 \nclambda = -c.*t; % equation for dc/dlambda\nf = (cfit-c)*clambda'; % specify function f to vanish\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_est.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7347508163171221}} {"text": "function t = iseuclidean(D)\n%ISEUCLIDEAN Is a distance matrix Euclidean?\n% T = ISEUCLIDEAN(D) returns a logical indicating whether or not the\n% dissimilarity matrix D is a Euclidean distance matrix, i.e., whether\n% there exist n points in p-dimensional space (for some p < n) such that\n% their Euclidean distances are given by D. D may be specified as either\n% a full (square, symmetric) dissimilarity matrix, or as the lower\n% triangle (e.g., output by PDIST).\n%\n% This algorithm is essentially classical multidimensional scaling.\n%\n% See also CMDSCALE, PDIST, LINKAGE.\n%\n% References:\n% [1] Seber, G.A.F., Multivariate Observations, Wiley, 1984\n\n% Copyright 1993-2002 The MathWorks, Inc. \n% $Revision: 1.4 $ $Date: 2002/02/04 19:25:44 $\n\n[n m] = size(D);\ndel = 10*eps;\n\n% lower triangle form for D\nif n == 1\n % make sure it's a valid dissimilarity matrix\n n = (1+sqrt(1+8*m))/2;\n if n == fix(n) & all(D >= 0)\n D = squareform(D);\n else\n warning('Not a valid dissimilarity or distance matrix.')\n t = logical(0);\n return\n end\n \n% full matrix form, make sure it's valid dissimilarity matrix\nelseif n ~= m | any(any(D < 0 | abs(D - D') > del*max(max(D)))) | any(diag(D) > del)\n warning('Not a valid dissimilarity or distance matrix.')\n t = logical(0);\n return\nend\n\nP = eye(n) - repmat(1/n,n,n);\nB = P * (-.5 * D .* D) * P;\ng = eig((B+B')./2); % guard against spurious complex e-vals from roundoff\nt = all(-eps^(3/4)*max(abs(g)) <= g); % all non-negative eigenvals (within roundoff)?\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SpatialLayout_shrink/spatiallayoutcode/GeometricContext/geomContext_src_07_02_08/src/tools/weightedstats/private/iseuclidean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7347473872277571}} {"text": "function z=hyperg(a,b,c,x,n)\n% HYPERGEOMETRIC2F1 Computes the hypergeometric function \n% using a series expansion:\n%\n% f(a,b;c;x)=\n%\n% 1 + [ab/1!c]x + [a(a+1)b(b+1)/2!c(c+1)]x^2 +\n% [a(a+1)(a+2)b(b+1)(b+2)/3!c(c+1)(c+2)]x^3 + ...\n%\n% The series is expanded to n terms\n%\n% This function solves the Gaussian Hypergeometric Differential Equation:\n%\n% x(1-x)y'' + {c-(a+b+1)x}y' - aby = 0\n%\n% The Hypergeometric function converges only for:\n% |x| < 1\n% c != 0, -1, -2, -3, ...\n%\n%\n% Comments to:\n% Diego Garcia - d.garcia@ieee.org\n% Chuck Mongiovi - mongiovi@fast.net\n% June 14, 2002\n\nif nargin ~= 5\n error('Usage: hypergeometric2f1(a,b,c,x,n) --> Wrong number of arguments')\nend\n\nif (n <= 0 | n ~= floor(n))\n error('Usage: hypergeometric2f1(a,b,c,x,n) --> n has to be a positive integer')\nend\n\n% if (abs(x) > 1)\n% z=min(0.99,x);\n% return;\n% error('Usage: hypergeometric2f1(a,b,c,x,n) --> |x| has to be less than 1')\n% end\n\nif (c <= 0 & c == floor(c))\n error('Usage: hypergeometric2f1(a,b,c,x,n) --> c != 0, -1, -2, -3, ...')\nend\n\nz = 0;\nm = 0;\nwhile (m long-term trend\n% c: nx1 --> cycle as deviation from long-term trend (as %)\n% ------------------------------------------------------------\n% INPUT: z: nx1 --> short-term trend or s.a. time series\n% lambda: 1x1 --> balance between adjustment and smoothness\n% ------------------------------------------------------------\n% LIBRARY: dif\n% ------------------------------------------------------------\n\n% written by:\n% Enrique M. Quilis\n% Macroeconomic Research Department\n% Ministry of Economy and Competitiveness\n% \n\n% Version 2.0 [May 2009]\n\n% Size of the input data\n[n,m] = size(z);\n\n% Second difference matrix\nD = dif(2,n);\nD(1:2,:) = [];\n\n% Matrix form of the filter (non inverted)\nH = eye(n) + lambda*(D'*D);\n\n% Computing long-term trend\ny = H \\ z;\n\n% Computing cycle as deviation from long term trend\nc = 100 * (z - y) ./ y;\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39770-temporal-disaggregation-library/hp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561136, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7346569946460078}} {"text": "function output = perceptronTrain(input)\n%perceptronTrain Training of two-class perceptron.\n% OUTPUT = perceptronTrain(INPUT) training of two-class perceptron. The\n% input and output parameters of are structures defined as follows.\n%\n% Parameter input is a structure with the following fields:\n% \n% input.X A matrix of size n-by-np whose columns are\n% n-dimensional input pattern vectors, and np is\n% the number of such vectors. For example, for a\n% set of 100, 3-element patterns, matrix inputs.X\n% would be of size 3-by-100. The function augments\n% the patterns by appending a 1 at the end of all\n% pattern vectors.\n%\n% input.r Class membership vector of size 1-by-np whose \n% kth value is 1 if the pattern vector in the kth\n% column of X belongs to class c1; otherwise the\n% kth value of input.r is -1.\n%\n% input.Alpha Learning rate positive scalar that defaults to\n% 0.5.\n% \n% input.W0 Initial augmented weight vector of size \n% (n + 1)-by-1. Its components default to uniform\n% random numbers in the range [0,1].\n%\n% input.NumEpochs The number of training epochs. Defaults to 100. \n%\n%\n% Parameter output is a structure with the following fields.\n% \n% output.W (n + 1)-by-1 weight vector at completion of\n% training. This may or not be a solution that\n% separates the two classes, depending on the\n% number of epochs specified and whether the\n% classes are linearly separable.\n%\n% output.Convergence True (1) if training converged and false (0)\n% otherwise.\n%\n% output.ActualEpochs The actual number of epochs of training\n% executed.\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% AUGMENT THE PATTERN VECTORS.\n% Number of patterns.\nnp = size(input.X,2);\n% Augment the pattern vectors.\nX = cat(1,input.X,ones(1,np));\n\n% SET DEFAULTS.\nif ~isfield(input,'Alpha')\n input.Alpha = 0.5;\nend\nif ~isfield(input,'NumEpochs')\n input.NumEpochs = 100;\nend \nif ~isfield(input,'W0')\n rng('shuffle');\n input.W0 = rand(size(X,1),1);\nend\n\n% INITIALIZATION.\n% Make sure that input.W0 is a column vector.\ninput.W0 = input.W0(:);\n% Initial values for loop.\nw_last = input.W0;\nw = input.W0;\noutput.ActualEpochs = 0;\n\n% ITERATE.\nfor I = 1:input.NumEpochs\n output.ActualEpochs = output.ActualEpochs + 1;\n output.Convergence = true;\n for J = 1:np\n % An error has been committed for the Jth pattern if the sign of\n % w'*input.X(:,J) does not match the sign of input.r\n if sign(w'*X(:,J)) ~= input.r(J)\n w = w_last + input.r(J)*input.Alpha*X(:,J);\n output.Convergence = false;\n w_last = w;\n end\n end\n % Exit if convergence was not set to false for an entire epoch.\n if output.Convergence\n output.W = w_last;\n output.ActualEpochs = I;\n break\n end\nend\noutput.ActualEpochs = I;\noutput.W = w_last;\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/perceptronTrain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7345126616448562}} {"text": "function [ A, rhs ] = boundary ( nx, ny, x, y, A, rhs )\n\n%*****************************************************************************80\n%\n%% BOUNDARY sets up the matrix and right hand side at boundary nodes.\n%\n% Discussion:\n%\n% For this simple problem, the boundary conditions specify that the solution\n% is 10 on the left size, 100 on the right side, and 0 on the top and bottom.\n%\n% Nodes are assigned a single index K, which increases as:\n%\n% (NY-1)*NX+1 (NY-1)*NX+2 ... NY * NX\n% .... .... ... .....\n% NX+1 NX+2 ... 2 * NX\n% 1 2 ... NX\n%\n% The index K of a node on the lower boundary satisfies:\n% 1 <= K <= NX\n% The index K of a node on the upper boundary satisfies:\n% (NY-1)*NX+1 <= K <= NY * NX\n% The index K of a node on the left boundary satisfies:\n% mod ( K, NX ) = 1\n% The index K of a node on the right boundary satisfies:\n% mod ( K, NX ) = 0\n%\n% If we number rows from bottom I = 1 to top I = NY\n% and columns from left J = 1 to right J = NX, then the relationship\n% between the single index K and the row and column indices I and J is:\n% K = ( I - 1 ) * NX + J\n% and\n% J = 1 + mod ( K - 1, NX )\n% I = 1 + ( K - J ) / NX\n% \n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 July 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NX, NY, the number of grid points in X and Y.\n%\n% Input, real X(NX), Y(NY), the coordinates of grid lines.\n%\n% Input, real sparse A(N,N), the system matrix, with the entries for the\n% interior nodes filled in.\n%\n% Input, real RHS(N), the system right hand side, with the entries for the\n% interior nodes filled in.\n%\n% Output, real sparse A(N,N), the system matrix, with the entries for all \n% nodes filled in.\n%\n% Output, real RHS(N), the system right hand side, with the entries for \n% all nodes filled in.\n%\n\n%\n% Left boundary.\n%\n j = 1;\n for i = 1 : ny\n kc = ( i - 1 ) * nx + j;\n xc = x(j);\n yc = y(i);\n A(kc,kc) = 1.0;\n rhs(kc,1) = 10.0;\n end\n%\n% Right boundary.\n%\n j = nx;\n for i = 1 : ny\n kc = ( i - 1 ) * nx + j;\n xc = x(j);\n yc = y(i);\n A(kc,kc) = 1.0;\n rhs(kc,1) = 100.0;\n end\n%\n% Lower boundary.\n%\n i = 1;\n for j = 1 : nx\n kc = ( i - 1 ) * nx + j;\n xc = x(j);\n yc = y(i);\n A(kc,kc) = 1.0;\n rhs(kc,1) = 0.0;\n end\n%\n% Upper boundary.\n%\n i = ny;\n for j = 1 : nx\n kc = ( i - 1 ) * nx + j;\n xc = x(j);\n yc = y(i);\n A(kc,kc) = 1.0;\n rhs(kc,1) = 0.0;\n end\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/fd2d_heat_steady/boundary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7345126563538575}} {"text": "function s=phaseran(x,c)\n%Syntax: s=phaseran(x,c)\n%_______________________\n%\n% Makes c phase randomized surrogates of a time series x.\n%\n% s is the phase randomized time series.\n% x is the original time series.\n% c is the number of surrogates.\n%\n%\n% References:\n%\n% Theiler J, Galdrikian B, Longtin A, Eubank S, Farmer D J (1992): Using \n% Surrogate Data to Detect Nonlinearity in Time Series. In Nonlinear Modeling\n% and Forecasting, eds. Casdagli M & Eubank S. 163-188. Addison-Wesley\n%\n% Theiler J, Eubank S,Galdrikian B, Longtin A, Farmer D J (1992): Testing\n% for nonlinearity in time series: the method of surrogate data. Physica D\n% 58: 77-94\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% 12 Apr 2002\n\nif nargin<1 | isempty(x)==1\n error('You should provide a time series.');\nelse\n % x must be a vector\n if min(size(x))>1\n error('Invalid time series.');\n end\n x=x(:);\n % N is the time series length\n N=length(x);\nend\n\nif nargin<2 | isempty(c)==1\n c=1;\nelse\n % c must be scalar\n if sum(size(c))>2\n error('c must be scalar.');\n end\n % c must be greater or equal than 1\n if c<1\n error('c must be greater or equal than 1.');\n end\nend\n\n\n% FFT on x\ny=fft(x);\n% Magnitudes\nm=abs(y);\n% Angles\np=angle(y);\n% The imaginary unit\ni=sqrt(-1);\n% Half of the data points\nh=floor(N/2);\n\nfor j=1:c\n % Randomized phases\n if rem(N,2)==0\n p1=rand(h-1,1)*2*pi;\n p(2:N)=[p1' p(h+1) -flipud(p1)'];\n % Adjust the magnitudes\n m=[m(1:h+1);flipud(m(2:h))];\n else\n p1=rand(h,1)*2*pi;\n p(2:N)=[p1 -flipud(p1)];\n end\n % Back to the complex numbers\n s(:,j)=m.*exp(i*p);\n % Back to the time series (phase randomized surrogates)\n s(:,j)=real(ifft(s(:,j)));\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/1597-chaotic-systems-toolbox/phaseran.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7345126563538574}} {"text": "function [xx, yy] = chebpts2(nx, ny, D, kind)\n%CHEBPTS2 Chebyshev tensor product grid.\n% [XX YY] = CHEBPTS2(N) constructs an N by N grid of Chebyshev tensor points\n% on [-1,1]^2.\n%\n% [XX YY] = CHEBPTS2(NX,NY) constructs an NX by NY grid of Chebyshev tensor\n% points on [-1,1]^2.\n%\n% [XX YY] = CHEBPTS2(NX,NY,D) constructs an NX by NY grid of Chebyshev tensor\n% points on the rectangle [a,b] x [c,d], where D = [a b c d].\n%\n% [XX YY] = CHEBPTS2(NX,NY,D,KIND) constructs a Chebyshev tensor grid of\n% the kind KIND. KIND = 2 is the default. \n% \n% See also CHEBPTS.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif ( nargin > 2 ) \n % Third argument should be a domain. \n D = D(:).'; % make a row vector. \n if ( ~all( size( D ) == [1 4] ) )\n error('CHEBFUN:CHEBFUN2:chebpts2:domain', 'Unrecognised domain.');\n end\nelse % Default to the canoncial domain.\n D = [-1, 1, -1, 1];\nend\n\nif ( nargin == 1 ) \n % Make it a square Chebyshev grid if only one input. \n ny = nx; \nend\nif ( nargin < 4 )\n % default to Chebyshev point of the 2nd kind. \n kind = 2; \nend\n\n% Get points: \nx = chebpts(nx, D(1:2), kind); \ny = chebpts(ny, D(3:4), kind); \n\n% Tensor product. \n[xx, yy] = meshgrid(x, y); \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/@chebfun2/chebpts2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7345126402589723}} {"text": "function avgNEES = ANEES(trans_err, rot_err, err_sigma)\n\n stateErr = [rot_err;trans_err];\n stateVar = err_sigma.^2;\n avgNEES = 0;\n stepNum = size(stateErr, 2);\n for i = 1:stepNum\n avgNEES = avgNEES + (1/stepNum)*stateErr(:,i)'*inv(diag(stateVar(:,i)))*stateErr(:,i);\n end\nend", "meta": {"author": "yuzhou42", "repo": "MSCKF", "sha": "d95d90c85b24f27001bd0ecdce8739b6e602b6df", "save_path": "github-repos/MATLAB/yuzhou42-MSCKF", "path": "github-repos/MATLAB/yuzhou42-MSCKF/MSCKF-d95d90c85b24f27001bd0ecdce8739b6e602b6df/KITTI Trials/ANEES.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541626630937, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.734483556556134}} {"text": "function h = matrix_decomp\n\n%% Problem instance settings\n\nm = 20;\nn = 50;\nuse_cvx = 1; % set to 0 for larger instances\n\n%% Problem data\n\ns = RandStream.create('mt19937ar','seed',5489);\nRandStream.setDefaultStream(s);\n\nN = 3;\nr = 4;\n\nL = randn(m,r) * randn(r,n); % low rank\nS = sprandn(m,n,0.05); % sparse\nS(S ~= 0) = 20*binornd(1,0.5,nnz(S),1)-10;\nV = 0.01*randn(m,n); % noise\n\nA = S + L + V;\n\ng2_max = norm(A(:),inf);\ng3_max = norm(A);\ng2 = 0.15*g2_max;\ng3 = 0.15*g3_max;\n\n%% CVX\n\nif use_cvx\n tic;\n\n cvx_begin\n cvx_precision low\n variables X_1(m,n) X_2(m,n) X_3(m,n)\n minimize(0.5*square_pos(norm(X_1,'fro')) + g2*norm(X_2(:),1) + g3*norm_nuc(X_3))\n subject to\n X_1 + X_2 + X_3 == A;\n cvx_end\n\n h.cvx_toc = toc;\n h.p_cvx = cvx_optval;\n h.X1_cvx = X_1;\n h.X2_cvx = X_2;\n h.X3_cvx = X_3;\n\n X_2(abs(X_2) < 1e-4) = 0;\n rhat = sum(svd(X_3) > 1e-4);\n fprintf('CVX (vs true):\\n');\n fprintf('|V| = %.2f; |X_1| = %.2f\\n', norm(V, 'fro'), norm(X_1,'fro'));\n fprintf('nnz(S) = %d; nnz(X_2) = %d\\n', nnz(S), nnz(X_2));\n fprintf('rank(L) = %d; rank(X_3) = %d\\n', rank(L), rhat);\nend\n\n%% ADMM\n\nMAX_ITER = 100;\nABSTOL = 1e-4;\nRELTOL = 1e-2;\n\ntic;\n\nlambda = 1;\nrho = 1/lambda;\n\nX_1 = zeros(m,n);\nX_2 = zeros(m,n);\nX_3 = zeros(m,n);\nz = zeros(m,N*n);\nU = zeros(m,n);\n\nfprintf('\\n%3s\\t%10s\\t%10s\\t%10s\\t%10s\\t%10s\\n', 'iter', ...\n 'r norm', 'eps pri', 's norm', 'eps dual', 'objective');\n\nfor k = 1:MAX_ITER\n\n B = avg(X_1, X_2, X_3) - A./N + U;\n\n % x-update\n X_1 = (1/(1+lambda))*(X_1 - B);\n X_2 = prox_l1(X_2 - B, lambda*g2);\n X_3 = prox_matrix(X_3 - B, lambda*g3, @prox_l1);\n\n % (for termination checks only)\n x = [X_1 X_2 X_3];\n zold = z;\n z = x + repmat(-avg(X_1, X_2, X_3) + A./N, 1, N);\n\n % u-update\n U = B;\n\n % diagnostics, reporting, termination checks\n h.objval(k) = objective(X_1, g2, X_2, g3, X_3);\n h.r_norm(k) = norm(x - z,'fro');\n h.s_norm(k) = norm(-rho*(z - zold),'fro');\n h.eps_pri(k) = sqrt(m*n*N)*ABSTOL + RELTOL*max(norm(x,'fro'), norm(-z,'fro'));\n h.eps_dual(k) = sqrt(m*n*N)*ABSTOL + RELTOL*sqrt(N)*norm(rho*U,'fro');\n \n if k == 1 || mod(k,10) == 0\n fprintf('%4d\\t%10.4f\\t%10.4f\\t%10.4f\\t%10.4f\\t%10.2f\\n', k, ...\n h.r_norm(k), h.eps_pri(k), h.s_norm(k), h.eps_dual(k), h.objval(k));\n end\n\n if h.r_norm(k) < h.eps_pri(k) && h.s_norm(k) < h.eps_dual(k)\n break;\n end\n\nend\n\nh.admm_toc = toc;\nh.admm_iter = k;\nh.X1_admm = X_1;\nh.X2_admm = X_2;\nh.X3_admm = X_3;\n\nfprintf('\\nADMM (vs true):\\n');\nfprintf('|V| = %.2f; |X_1| = %.2f\\n', norm(V, 'fro'), norm(X_1,'fro'));\nfprintf('nnz(S) = %d; nnz(X_2) = %d\\n', nnz(S), nnz(X_2));\nfprintf('rank(L) = %d; rank(X_3) = %d\\n', rank(L), rank(X_3));\n\nif use_cvx\n fprintf('\\nADMM vs CVX solutions (in Frobenius norm):\\n');\n fprintf('X_1: %.2e; X_2: %.2e; X_3: %.2e\\n', ...\n norm(h.X1_cvx - X_1,'fro'), norm(h.X2_cvx - X_2,'fro'), norm(h.X3_cvx - X_3,'fro'));\nend\n\nend\n\nfunction x = avg(varargin)\n N = length(varargin);\n x = 0;\n for k = 1:N\n x = x + varargin{k};\n end\n x = x/N;\nend\n\nfunction p = objective(X_1, g_2, X_2, g_3, X_3)\n p = norm(X_1,'fro').^2 + g_2*norm(X_2(:),1) + g_3*norm(svd(X_3),1);\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/ttd/ADMM/matrix_decomp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7344692819048636}} {"text": "function [Z,W,P,T] = dosc(X,Y,nocomp,tol)\n% DOSC Direct Orthogonal Signal Correction\n%\n% [Z,W,P,T] = dosc(X,Y,nocomp,tol);\n%\n% Input\n% X Matrix of predictor variables (usually spectra) (I x J)\n% Y Predicted variables (e.g. concentration) (I x K)\n% nocomp number of DOSC components to calculate \n% tol tolerance used to calculate pseudinverse of X\n% a tolerance of 1E-3 worked well in two cases presented in paper [1] \n%\n%\n% Output\n% Z DOSC corrected matrix X (I x J)\n% W Weights used to determine DOSC components (J x nocomp)\n% P Loadings used to remove DOSC component from X (J x nocomp)\n% T DOSC components (I x nocomp)\n% \n% \n% Once the calibration is done, new (scaled) x-data can be corrected by \n% newx = x - x*W*P'; Or use mfile dosc_pred\n%\n% See Reference\n% Westerhuis JA, de Jong S and Smilde AK, Direct orthogonal signal correction, \n% Chemometrics and Intelligent Laboratory Systems, 56, (2001), 13-25.\n\n% Sijmen de Jong, Oct 99\n% Adjusted by Johan Westerhuis\n% ==========================================================================\n% Copyright 2005 Biosystems Data Analysis Group ; Universiteit van Amsterdam\n% ==========================================================================\n\n% project Y onto X (step 1)\nYhat = X*(pinv(X')'*Y);\n\n% deflate X wrt Yhat (step 2)\nAyX = X-Yhat*(pinv(Yhat)*X); \n\n% find major PCs of AyX\n[Ta,D] = eigs(AyX*AyX',nocomp);\n\n% Calculate pseudoinverse of X using tolerance (step 5a)\npinvX = pinv(X',tol)';\n\n% The tolerance can be changed to the number of PCR components (nc) used\n% to estimate the pseudo inverse.\n% [U,S,V] = svd(X,0);\n% Xcorr = U(:,1:nc)*S(1:nc,1:nc)*V(:,1:nc)';\n% pinvX = pinv(Xcorr);\n\nW = pinvX*Ta;\nT = X*W;\n\n% Calculate loadings to remove DOSC component (step 7a)\nP = X'*T*inv(T'*T);\n\n% deflate X wrt to DOSC components (step 6a)\nZ = X - T*P';", "meta": {"author": "FuSiry", "repo": "Spectral-preprocessing-algorithm", "sha": "f426ddd1b02175d7051566d433e6f21459b15237", "save_path": "github-repos/MATLAB/FuSiry-Spectral-preprocessing-algorithm", "path": "github-repos/MATLAB/FuSiry-Spectral-preprocessing-algorithm/Spectral-preprocessing-algorithm-f426ddd1b02175d7051566d433e6f21459b15237/Spectral-preprocessing-algorithm/matlab/dosc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545377452443, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7344247456242193}} {"text": "function [score,in,out]=clusterquality(f,S,partition)\n%function [score,in,out]=clusterquality(f,S,partition)\n%\n%PURPOSE\n%\n%To compute a simple quality (compactness) index for the given\n%clusters. The more dense and isolated a cluster is the bigger\n%value the index gets; however, if there is only one item in a\n%cluster the index is not computed (a NaN is returned for that\n%cluster) \n%\n%INPUT\n%\n% f (string) cluster score function: 'mean' or 'minmax'\n% S (NxN matrix) similarity matrix\n% partition (Nx1 vector) partition vector (see explanation for\n% 'partition vector' in function hcluster) \n%\n%OUTPUT\n%\n%score (Kx1 vector) score(k) contains the index value for\n% cluster k: score(k)=in(k)-out(k) \n%in (Kx1 vector) see above \n%out (Kx1 vector) see above\n%\n%DETAILS\n%\n%For f='mean' the average extra-cluster similarity is subtracted\n%from the mean intra-cluster similarity.\n%\n% Iq=avg(intra-cluster similarity) - avg(extra-cluster similarity)\n%\n%The index is described in publication Himberg et al. (2004),\n%\"Validating the independent components of neuroimaging time-series\n%via clustering and visualization\". NeuroImage, 22:3(1214-1222). It\n%is used by default in Icasso functions.\n%\n%(The intra-cluster similarities for cluster C mean the mutual\n%similarities between the estimates in C, and the extra-cluster\n%similarities for C are the similarities between the estimates in C\n%and the estimates not in C.) \n%\n%Note: if there is only one item in a cluster, index\n%value NaN is returned for that cluster.\n%\n%You can also specify a more conservative but less robust criteria\n%('minmax') where the maximum extra-cluster similarity is\n%subtracted from the minimum intra-cluster similarity: if\n%f='minmax' the maximum extra-cluster similarity is subtracted from\n%the minimum intra-cluster similarity. \n%\n%SEE ALSO\n% clusterstat\n% icassoStability\n\n%COPYRIGHT NOTICE\n%This function is a part of Icasso software library\n%Copyright (C) 2003-2005 Johan Himberg\n%\n%This program is free software; you can redistribute it and/or\n%modify it under the terms of the GNU General Public License\n%as published by the Free Software Foundation; either version 2\n%of the License, or any later version.\n%\n%This program is distributed in the hope that it will be useful,\n%but WITHOUT ANY WARRANTY; without even the implied warranty of\n%MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n%GNU General Public License for more details.\n%\n%You should have received a copy of the GNU General Public License\n%along with this program; if not, write to the Free Software\n%Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n% ver 1.2 100105\n\nNcluster=max(partition);\ns=clusterstat(S,partition);\n\n% Compute score\nswitch lower(f)\n case 'mean'\n in=s.internal.avg;\n out=s.external.avg;\n case 'minmax'\n in=s.internal.min;\n out=s.external.max;\n otherwise\n error('Unrecognized score function.');\nend\n\nscore=in-out;\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/icasso/clusterquality.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723468, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.734423594491911}} {"text": "classdef Kernel < handle\n %{\n Kernel function\n \n INPUT\n X data (n*d)\n Y data (m*d)\n\n OUTPUT\n K kernel matrix (n*m)\n \n ----------------------------------------------------------------------\n \n type -\n \n linear : k(x,y) = x'*y\n polynomial : k(x,y) = (γ*x'*y+c)^d\n gaussian : k(x,y) = exp(-γ*||x-y||^2)\n sigmoid : k(x,y) = tanh(γ*x'*y+c)\n laplacian : k(x,y) = exp(-γ*||x-y||)\n \n \n degree - d\n offset - c\n gamma - γ\n \n ----------------------------------------------------------------------\n \n Version 1.1, 11-MAY-2021\n Email: iqiukp@outlook.com\n ----------------------------------------------------------------------\n %}\n \n properties\n type = 'gaussian'\n offset = 0\n gamma = 0.1\n degree = 2\n end\n \n methods\n function obj = Kernel(varargin)\n inputValue = varargin;\n nParameter = size(inputValue, 2)/2;\n supportedKernelFunc = {'linear', 'gaussian', 'polynomial', 'sigmoid', 'laplacian'};\n for n = 1:nParameter\n parameter = inputValue{(n-1)*2+1};\n value = inputValue{(n-1)*2+2};\n if strcmp(parameter, 'type')\n if ~any(strcmp(value, supportedKernelFunc))\n errorText = sprintf([\n 'Unsupported kernel function.\\n',...\n 'Use one of these kernel functions:\\n', ...\n 'linear, gaussian, polynomial, sigmoid, laplacian.']); \n error(errorText)\n end\n end\n obj.(parameter) = value;\n end\n end\n \n function K = computeMatrix(obj, x, y)\n K = zeros(size(x, 1), size(y, 1));\n % compute the kernel matrix\n switch obj.type\n case 'linear' % linear kernel function\n K = x*y';\n \n case 'gaussian' % gaussian kernel function\n try\n K = exp(-obj.gamma*pdist2(x, y, 'squaredeuclidean'));\n catch\n sx = sum(x.^2, 2);\n sy = sum(y.^2, 2);\n xy = 2*x*y';\n K = exp((bsxfun(@minus, bsxfun(@minus, xy, sx), sy'))*obj.gamma);\n end\n \n case 'polynomial' % polynomial kernel function\n K = (obj.gamma*x*y'+obj.offset).^double(obj.degree);\n \n case 'sigmoid' % sigmoid kernel function\n K = tanh(obj.gamma*x*y'+obj.offset);\n \n case 'laplacian' % laplacian kernel function\n K = exp(-obj.gamma*pdist2(x, y, 'cityblock'));\n end\n end\n end\nend", "meta": {"author": "iqiukp", "repo": "KPCA-MATLAB", "sha": "16dd1567d7109f55a7c83d2fe3dcb558cf1a8fbf", "save_path": "github-repos/MATLAB/iqiukp-KPCA-MATLAB", "path": "github-repos/MATLAB/iqiukp-KPCA-MATLAB/KPCA-MATLAB-16dd1567d7109f55a7c83d2fe3dcb558cf1a8fbf/KernelPCA/Kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.734423578808903}} {"text": "function geometry_test174 ( )\n\n%*****************************************************************************80\n%\n%% TEST174 tests RADEC_TO_XYZ, XYZ_TO_RADEC.\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 = 6;\n\n ptest = [ ...\n 1.0, 0.0, 0.0; ...\n 0.0, 1.0, 0.0; ...\n 0.0, 0.0, 1.0; ...\n 1.0, 1.0, 1.0; ...\n 5.0, -2.0, -1.0; ...\n -2.0, -2.0, -2.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST174\\n' );\n fprintf ( 1, ' RADEC_TO_XYZ converts XYZ to RADEC coordinates.\\n' );\n fprintf ( 1, ' XYZ_TO_RADEC converts RADEC to XYZ coordinates.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' P1 RA DEC P2\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : ntest\n\n p1(1:3,1) = ptest(1:3,i);\n\n [ ra, dec ] = xyz_to_radec ( p1 );\n p2 = radec_to_xyz ( ra, dec );\n\n fprintf ( 1, ' %10f %10f %10f %10f %10f %10f %10f %10f\\n', ...\n p1(1:3,1), ra, dec, p2(1:3,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/geometry/geometry_test174.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7343643898549232}} {"text": "function [p,w] = nrbeval(nurbs,tt) \n% \n% Function Name: \n% \n% nrbeval - Evaluate a NURBS at parameteric points \n% \n% Calling Sequence: \n% \n% [p,w] = nrbeval(crv,ut) \n% [p,w] = nrbeval(srf,{ut,vt}) \n% \n% Parameters: \n% \n% crv\t\t: NURBS curve, see nrbmak. \n% \n% srf\t\t: NURBS surface, see nrbmak. \n% \n% ut\t\t: Parametric evaluation points along U direction. \n% \n% vt\t\t: Parametric evaluation points along V direction. \n% \n% p\t\t: Evaluated points on the NURBS curve or surface as cartesian \n% \t\tcoordinates (x,y,z). If w is included on the lhs argument list \n% \t\tthe points are returned as homogeneous coordinates (wx,wy,wz). \n% \n% w\t\t: Weights of the homogeneous coordinates of the evaluated \n% \t\tpoints. Note inclusion of this argument changes the type \n% \t\tof coordinates returned in p (see above). \n% \n% Description: \n% \n% Evaluation of NURBS curves or surfaces at parametric points along the \n% U and V directions. Either homogeneous coordinates are returned if the \n% weights are requested in the lhs arguments, or as cartesian coordinates. \n% This function utilises the 'C' interface bspeval. \n% \n% Examples: \n% \n% Evaluate the NURBS circle at twenty points from 0.0 to 1.0 \n% \n% nrb = nrbcirc; \n% ut = linspace(0.0,1.0,20); \n% p = nrbeval(nrb,ut); \n% \n% See: \n% \n% bspeval \n% \n \n% D.M. Spink \n% Copyright (c) 2000. \n \nif nargin < 2 \n error('Not enough input arguments'); \nend \n \nfoption = 1; % output format 3D cartesian coordinates \nif nargout == 2 \n foption = 0; % output format 4D homogenous coordinates \nend \n \nif ~isstruct(nurbs) \n error('NURBS representation is not structure!'); \nend \n \nif ~strcmp(nurbs.form,'B-NURBS') \n error('Not a recognised NURBS representation'); \nend \n \nif iscell(nurbs.knots) \n % NURBS structure represents a surface \n \n num1 = nurbs.number(1); \n num2 = nurbs.number(2); \n degree = nurbs.order-1; \n \n if iscell(tt) \n % Evaluate over a [u,v] grid \n % tt{1} represents the u direction \n % tt{2} represents the v direction \n \n nt1 = length(tt{1}); \n nt2 = length(tt{2}); \n \n % Evaluate along the v direction \n val = reshape(nurbs.coefs,4*num1,num2); \n val = bspeval(degree(2),val,nurbs.knots{2},tt{2}); \n val = reshape(val,[4 num1 nt2]); \n \n % Evaluate along the u direction \n val = permute(val,[1 3 2]); \n val = reshape(val,4*nt2,num1); \n val = bspeval(degree(1),val,nurbs.knots{1},tt{1}); \n val = reshape(val,[4 nt2 nt1]); \n val = permute(val,[1 3 2]); \n \n w = val(4,:,:); \n p = val(1:3,:,:); \n if foption \n p = p./repmat(w,[3 1 1]); \n end \n \n else \n \n % Evaluate at scattered points \n % tt(1,:) represents the u direction \n % tt(2,:) represents the v direction \n \n nt = size(tt,2); \n \n val = reshape(nurbs.coefs,4*num1,num2); \n val = bspeval(degree(2),val,nurbs.knots{2},tt(2,:)); \n val = reshape(val,[4 num1 nt]); \n \n \n % evaluate along the u direction \n pnts = zeros(4,nt); \n for v = 1:nt \n coefs = squeeze(val(:,:,v)); \n pnts(:,v) = bspeval(degree(1),coefs,nurbs.knots{1},tt(1,v)); \n end \n \n w = pnts(4,:); \n p = pnts(1:3,:); \n if foption \n p = p./w; \n end \n \n end \n \nelse \n \n % NURBS structure represents a curve \n % tt represent a vector of parametric points in the u direction \n \n val = bspeval(nurbs.order-1,nurbs.coefs,nurbs.knots,tt); \n \n w = val(4,:); \n p = val(1:3,:); \n if foption \n p = p./repmat(w,3,1); \n end \n \nend \n \n \n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26390-nurbs-toolbox-by-d-m-spink/nurbs_toolbox/nrbeval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898305367524, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7342856511935221}} {"text": "function [maskOut]=kGaussian_color_EM(imageFile,k)\n%% this function uses EM algorithm and gaussian distribution function to do\n% image segmentation on the color space\n% try: \n% img=imread('onion.png');\n% [maskOut]=kGaussian_color_EM(img,9); figure; imshow(maskOut)\n% written by Rongwen Lu on 12/11/2011; email: rongwen@uab.edu\nimg=double(imageFile);\n\n\n\n\n\n[M,N,P]=size(img);\nn=M*N;\nimgR=img(:,:,1); \nimgG=img(:,:,2);\nimgB=img(:,:,3);\n[cy,cx]=ind2sub([M,N],1:n);\n\n%normalize each vector; delete it if normalization is not needed; weights\n%are also assigned here;\n% imgR=mat2gray(imgR);\n% imgG=mat2gray(imgG);\n% imgB=mat2gray(imgB);\n% cy=mat2gray(cy);\n% cx=mat2gray(cx);\nimgR=imgR/255;\nimgG=imgG/255;\nimgB=imgB/255;\ncy=cy/M;\ncx=cx/N;\n\n% %% Gaussian filter\n% w=fspecial('gaussian',[5,5],4);\n% imgR=imfilter(imgR,w);\n% imgG=imfilter(imgG,w);\n% imgB=imfilter(imgB,w);\n\n%% assign vectors into the matrix raw\nraw=zeros(n,3);\nraw(:,1)=imgR(:);\nraw(:,2)=imgG(:);\nraw(:,3)=imgB(:);\n\n% raw=zeros(n,5);\n% raw(:,1)=cy.';\n% raw(:,2)=cx.';\n% raw(:,3)=imgR(:);\n% raw(:,4)=imgG(:);\n% raw(:,5)=imgB(:);\n\n%% get assignment matrix p, which is also memebership probability here; u\n%% is vector of the estimated means of Gaussian function, v is the vector ot the estimated SD \n[p,u,v]=em(raw,k);\n\n\n\nimgRe=zeros(n,3);\nkColor=jet(k);\nkColor=u(:,1:3);\nimgRe=p*kColor;\n\n\n\nmaskOut=zeros(M,N,3);\nfor ii=1:3\n maskOut(:,:,ii)=reshape(imgRe(:,ii),[M,N]);\nend\n\n% figure; imshow((maskOut))\n% title('based on k Gaussian by EM algorithm on color space')\n\n function [p,u,v]=em(raw,k)\n % this function uses Expectation Maximization method to estimate k\n % Gaussian distribution functions. There are 2 input arguments. Raw's size\n % is [n,dim], where n is the NO of data and dim is the dimention of data.\n % k means using k Gaussin functions to do image segmentation.The output is\n % p, which is assignment matrix.its [ii,jj]th element means the\n % probability that Xii is generated by jjth Gaussian function.\n\n\n\n\n\n\n%% the input of following codes are raw,and K\n\n%% initialize centroid matrix u; u has k raws. NO of column is the same as\n%% raw\n[n,dim]=size(raw);\nu=raw(randint(k,1,[1,n]),:);\n%u=[0,0;40,40;-40,-40];\n\n%% initialize standard diviation v, v has k raws, one column.\nv=zeros(k,1);\nfor ii=1:k\n raw_tmp=raw(ii:k:end,1);\n v(ii,:)=std(raw_tmp);\nend\n%v=.5*[4,4,4]';\n%% initialize weight w\nw=ones(k,1)/k;\n\n\n\n%% initialize membership probability matrix (assignment matrix) p, which is p(k|x)\np=zeros(n,k);\n\n%% do interation to get best r\nu0=u*0;\nv0=0*v;\nw0=w*0;\nenergy=sum(sum((u-u0).^2))+sum(sum((v-v0).^2))+(sum((w-w0).^2));\niteration=1;\nx_u=zeros(size(raw));\nwhile energy>10^(-6)\n\n %% calculate membership probability, which is also assignment matrix\n for jj=1:k\n for ss=1:dim\n x_u(:,ss)=raw(:,ss)-u(jj,ss)*ones(n,1);\n end\n x_u=x_u.*x_u;\n p(:,jj)=power(sqrt(2*pi)*v(jj),-1*dim)*exp((-1/2)*sum(x_u,2)./(v(jj).^2));\n p(:,jj)=p(:,jj)*w(jj);\n \n end\n %% normalize p on the x dimention\n pSum=sum(p,2);\n for jj=1:k\n p(:,jj)=p(:,jj)./pSum;\n end\n \n %% normlaize p on the y dimention, yielding pNorm\n pSum2=sum(p,1);\n pNorm=p*0;\n for jj=1:k\n pNorm(:,jj)=p(:,jj)/pSum2(jj);\n end\n \n %% save current u, v, and w as u0, v0 and w0\n u0=u;v0=v;w0=w;\n \n %%update u\n u=(pNorm.')*raw;\n \n %% update v\n for jj=1:k\n for ss=1:dim\n x_u(:,ss)=raw(:,ss)-u(jj,ss)*ones(n,1);\n end\n x_u=x_u.*x_u;\n x_uSum=sum(x_u,2);\n v(jj)=sqrt(1/dim*(pNorm(:,jj).')*x_uSum);\n end\n\n\n\n %% update w\n w=(sum(p)/n).';\n \n %% update and display iteration and energy\n \n %disp(sprintf(['iteration=',num2str(iteration),'; energy=',num2str(energy,'%g')]))\n iteration=iteration+1;\n energy=sum(sum((u-u0).^2))+sum(sum((v-v0).^2))+(sum((w-w0).^2));\n \n \n \n \nend\n\n\n\n\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34164-image-segmentation-with-em-algorithm/kGaussian_color_EM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7342856471118356}} {"text": "function [ xtab, weight ] = laguerre_compute ( norder, alpha )\n\n%*****************************************************************************80\n%\n%% LAGUERRE_COMPUTE computes a Gauss-Laguerre quadrature rule.\n%\n% Discussion:\n%\n% In the simplest case, ALPHA is 0, and we are approximating the\n% integral from 0 to +oo of EXP(-X) * F(X). When this is so,\n% it is easy to modify the rule to approximate the integral from\n% A to +oo as well.\n%\n% If ALPHA is nonzero, then there is no simple way to extend the\n% rule to approximate the integral from A to +oo. The simplest\n% procedures would be to approximate the integral from 0 to A.\n%\n% The integration interval is [ A, +oo ) or [ 0, +oo ).\n%\n% The weight function w(x) = EXP ( - X ) or EXP ( - X ) * X^ALPHA.\n%\n%\n% If the integral to approximate is:\n%\n% Integral ( A <= X < +oo ) EXP ( - X ) * F(X) dX\n% or\n% Integral ( 0 <= X < +oo ) EXP ( - X ) * X^ALPHA * F(X) dX\n%\n% then the quadrature rule is:\n%\n% EXP ( - A ) * Sum ( 1 <= I <= ORDER ) WEIGHT(I) * F ( A+XTAB(I) )\n% or\n% sum ( 1 <= I <= ORDER ) WEIGHT(I) * F ( XTAB(I) )\n%\n%\n% If the integral to approximate is:\n%\n% Integral ( A <= X < +oo ) F(X) dX\n% or\n% Integral ( 0 <= X < +oo ) X^ALPHA * F(X) dX\n%\n% then the quadrature rule is:\n%\n% EXP ( - A ) * sum ( 1 <= I <= ORDER ) \n% WEIGHT(I) * EXP(A+XTAB(I)) * F ( A+XTAB(I) )\n% or\n% sum ( 1 <= I <= ORDER ) WEIGHT(I) * EXP(XTAB(I)) * F ( XTAB(I) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 October 2005\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, integer NORDER, the order of the quadrature rule to be computed.\n% NORDER must be at least 1.\n%\n% Input, real ALPHA, the exponent of the X factor.\n% Set ALPHA = 0.0 for the simplest rule.\n% ALPHA must be nonnegative.\n%\n% Output, real XTAB(NORDER), the Gauss-Laguerre abscissas.\n%\n% Output, real WEIGHT(NORDER), the Gauss-Laguerre weights.\n%\n\n%\n% Set the recursion coefficients.\n%\n for i = 1 : norder\n b(i) = ( alpha + 2 * i - 1 );\n end\n\n for i = 1 : norder\n c(i) = ( i - 1 ) * ( alpha + i - 1 );\n end\n\n cc = gamma ( alpha + 1.0 ) * prod ( c(2:norder) );\n\n for i = 1 : norder\n%\n% Compute an estimate for the root.\n%\n if ( i == 1 )\n\n x = ( 1.0 + alpha ) * ( 3.0 + 0.92 * alpha ) ...\n / ( 1.0 + 2.4 * norder + 1.8 * alpha );\n\n elseif ( i == 2 )\n\n x = x + ( 15.0 + 6.25 * alpha ) ...\n / ( 1.0 + 0.9 * alpha + 2.5 * norder );\n\n else\n\n r1 = ( 1.0 + 2.55 * ( i - 2 ) ) / ( 1.9 * ( i - 2 ) );\n\n r2 = 1.26 * ( i - 2 ) * alpha / ( 1.0 + 3.5 * ( i - 2 ) );\n\n ratio = ( r1 + r2 ) / ( 1.0 + 0.3 * alpha );\n\n x = x + ratio * ( x - xtab(i-2) );\n\n end\n%\n% Use iteration to find the root.\n%\n [ x, dp2, p1 ] = laguerre_root ( x, norder, alpha, b, c );\n%\n% Set the abscissa and weight.\n%\n xtab(i) = x;\n weight(i) = ( cc / dp2 ) / p1;\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/laguerre_test_int/laguerre_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7342856367598334}} {"text": "function [N]=gold_n(wl)\n\n% the function calculates the index of refraction of gold (complex value), in the range of wavelength\n% between 188nm and 1942nm.\n% the input may be a scalar or vector, but it have to be an integer and in the right range.\n% the values were taken from the paper: \n% P. B. Johnson, and R. W. Christy, \"Optical Constants of the Noble Metals,\" Physical Review B 6, 4370 (1972).\n% (the paper is available here: http://prb.aps.org/abstract/PRB/v6/i12/p4370_1 )\n% the values for wavelength calculated with linear interpolation.\n%\n% Moshe Lindner, August 2010 (C).\n\nif any((max(wl)>1942) || (min(wl)<188))\n error('Wavelength is out of range! (should be in the range of 188nm - 1942nm)')\n return\nelseif any(wl~=ceil(wl))\n error('Wavelength must be an integer!')\n return\nend\n \n\n% n = real part\nn=[0.92 0.56 0.43 0.35 0.27 0.22 0.17 0.16 0.14 0.13 0.14 0.21 0.29 0.43 0.62 1.04 1.31 1.39 1.45 1.46 1.47 1.46 1.48 1.5 1.48 1.48 1.54 1.53 1.53 1.49 1.47 1.43 1.38 1.35 1.33 1.33 1.32 1.32 1.3 1.31 1.3 1.3 1.3 1.3 1.33 1.33 1.34 1.32 1.28]';\nn=n(end:-1:1);\n% k = imaginary part\nk=[13.78 11.21 9.519 8.145 7.15 6.35 5.663 5.083 4.542 4.103 3.697 3.272 2.863 2.455 2.081 1.833 1.849 1.914 1.948 1.958 1.952 1.933 1.895 1.866 1.871 1.883 1.898 1.893 1.889 1.878 1.869 1.847 1.803 1.749 1.688 1.631 1.577 1.536 1.497 1.46 1.427 1.387 1.35 1.304 1.277 1.251 1.226 1.203 1.188]';\nk=k(end:-1:1);\n% ev = photon energy in electronvolts\nev=[0.64 0.77 0.89 1.02 1.14 1.26 1.39 1.51 1.64 1.76 1.88 2.01 2.13 2.26 2.38 2.50 2.63 2.75 2.88 3 3.12 3.25 3.37 3.5 3.62 3.74 3.87 3.99 4.12 4.24 4.36 4.49 4.61 4.74 4.86 4.98 5.11 5.23 5.36 5.48 5.6 5.73 5.85 5.98 6.1 6.22 6.35 6.47 6.6]';\nev=ev(end:-1:1);\nh=6.62606896e-34; % [J*sec] (Plank const.)\nc=3e8; %[m/sec] (speed of light)\nq=1.6e-19; % [C] (electron charge)\nlambda=1e9*h*c./(ev.*q);% wavelength in nanometer\n\nlam=188:1942;\nn1=interp1(lambda,n,lam,'linear');\nk1=interp1(lambda,k,lam,'linear');\n\nfor q=1:length(wl)\n N(q)=n1(lam==wl(q)) + i*k1(lam==wl(q));\nend\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28582-gold-index-of-refraction-dialectric-constant-as-function-of-wavelength/gold_n.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7342856326453051}} {"text": "function B = bernstein_eval(i,n,u)\n % BERNSTERIN_EVAL evaluate a Bernstein polynomial. B_i,n(u)\n %\n % B = bernstein_eval(i,n,u)\n % \n % Inputs:\n % i #i scalar index of polynomial\n % n scalar order of polynomial\n % u #u evaluation points\n % Outputs:\n % B #u by #i values\n % \n u = reshape(u,numel(u),1);\n i = reshape(i,1,numel(i));\n nck = factorial(n)./(factorial(i).*factorial(n-(i)));\n B = nck .* u.^i .* (1-u).^(n-i);\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/bernstein_eval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7342856325960435}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n% \n% Problem 7- Frequency Response and Impulse Response of an ideal bandpass\n% filter \n\n\n\ntd=.05;\nB1=10 ;\nB2=20;\nw1=-30:-B2;\nH1=zeros(size(w1));\nw2=-B2:-B1;\nH2=exp(-j*w2*td);\nw3=-B1:B1;\nH3=zeros(size(w3));\nw4=B1:B2;\nH4= exp(-j*w4*td);\nw5=B2:30;\nH5=zeros(size(w5));\nw=[w1 w2 w3 w4 w5];\nH=[H1 H2 H3 H4 H5];\nplot(w,abs(H))\nylim([-.2 1.2]);\nlegend(' |H(\\Omega) | ')\n\nfigure\nplot(w,angle(H));\nylim([-1.1 1.1]);\nlegend('\\angle H(\\Omega)')\n\n\n\nfigure\nsyms t w\nH1=exp(-j*w*td)*(heaviside(w+B2)-heaviside(w+B1));\nH2=exp(-j*w*td)*(heaviside(w-B1)-heaviside(w-B2));\nh1=ifourier(H1,t);\nh2=ifourier(H2,t);\nh=h1+h2;\nezplot(h, [-3 3]);\nylim([-4 4]);\nlegend('Impulse response h(t) ')\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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/8/c810g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7342583495337732}} {"text": "function [Vc,R]=circlefit(V)\n\n% function [Vc,R]=circlefit(V)\n% ------------------------------------------------------------------------\n% This function fits a circle to 2 or more points. The input is an array\n% containing the points (vertices) V in 2D or 3D. Although 3D data is\n% supported the Z-coordinates should all be equal such that the fitting\n% problem remains 2D.\n% The output consists of the circle centre Vc and radius R. \n%\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% 2019/11/21 Added to GIBBON\n% ------------------------------------------------------------------------\n\n%% Parse input\n\n%Check if empty or not numeric\nif isempty(V)\n error('Empty input')\nelseif ~isnumeric(V)\n error('Input is not numeric');\nend\n\n%Force real\nif ~isreal(V)\n V=real(V);\n warning('Complex data encountered. Complex parts ignored');\nend\n\n%Force double\nif ~isa(V,'double')\n V=double(V); %Attempt conversion to double\nend\n\n%Check size\nsizV=size(V);\nif sizV(1)==1\n error('Only 1 point provided')\nend\n\n%Force 3D\nif sizV(2)==2\n V(:,3)=0;\nend\n\n%% Fit cirlce\nVm=mean(V,1); %Get mean of point set\nVD=V-Vm(ones(sizV(1),1),:); % shift points on mean\nD=sqrt(sum(VD.^2,2)); %Compute distance to centre\n\nif sizV(1)==2 %If only two points provided\n Vc=Vm; %Cirlc centre set to mean\n R=mean(D); %Radius set to mean distance\nelse %Fit circle to more than 2 points \n % Scale data\n scaleFactor=max(max(D,eps));\n VD=VD./scaleFactor; D=D./scaleFactor;\n \n % Solve sytem\n VF=[2*VD(:,1) 2*VD(:,2) ones(sizV(1),1)]\\D.^2;\n \n % Unscale, collect output\n Q=[Vm(1) Vm(2) 0]+[VF(1) VF(2) sqrt(VF(3)+hypot(VF(1),VF(2)).^2)]*scaleFactor;\n \n Vc=[Q(1) Q(2) Vm(3)]; %Cirle centre\n R=Q(3); %Radius\nend\n\nif sizV(2)==2\n Vc=Vc(:,[1 2]);\nend\n\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/circlefit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172602, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7342583495337731}} {"text": "function value = p31_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P31_F evaluates the integrand for problem 31.\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% 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% P31_R8VEC.\n%\n% The coefficient vector C (whose entries are usually positive)\n% controls the steepness and circularity of the pseudo-Gaussian.\n% C(1:DIM_NUM) defaults to 2.0.\n% The user can set, get, or randomize this value by calling\n% P31_R8VEC.\n%\n% Integrand:\n%\n% exp ( - sum ( c(1:dim_num) * 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) ) exp ( - C(1) * abs ( X(1) - Z(1) ) ) \n% * Int ( A(2) <= X(2) <= B(2) ) exp ( - C(2) * abs ( X(2) - Z(2) ) )\n% * ...\n%\n% Hence, the exact integral is computed as the product of\n% one dimensional integrals. Each of these is easily computed\n% once the location of Z(I) with respect to A(I) and B(I) is\n% determined.\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% Alan Genz,\n% [Integral #5]\n% A Package for Testing Multiple Integration Subroutines,\n% in Numerical Integration: Recent Developments, Software\n% and Applications,\n% edited by Patrick Keast and Graeme Fairweather,\n% D. Reidel, 1987, pages 337-340,\n% LC: QA299.3.N38.\n%\n% Kenneth Hanson,\n% Quasi-Monte Carlo: halftoning in high dimensions?\n% in Computatinal Imaging,\n% Edited by CA Bouman and RL Stevenson,\n% Proceedings SPIE,\n% Volume 5016, 2003, pages 161-172.\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 c = [];\n c = p31_r8vec ( 'G', 'C', dim_num, c );\n\n z = [];\n z = p31_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) = exp ( - sum ( c(1:dim_num)' .* ...\n abs ( x(1:dim_num,point) - z(1:dim_num)' ) ) );\n\n end\n\n p31_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/p31_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172604, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7342583474862981}} {"text": "function res = SymPoly2Sym(F,Dexp,MaxCtr)\n%SYMPOLY2SYM Similar to poly2sym but can handle symbolic coefficients and\n%indeterminate variables specified as equations\n%\n% SymPoly2Sym('a*z^2 + b*z + c','z') = [a b c]\n% SymPoly2Sym('a*sin(x)^2 + b*sin(x) + c','sin(x)') = [a b c]\n\n%%This function iteratively takes the derivative then evaluates at 0 to\n%%determine the coefficients\n\nif nargin<2,\n Dexp = 't'; %Default dependent variable\nend\nF = sym(subs(F,Dexp,'XX')); %Substitute independent variable 'XX' for dependent expression Dexp\n \nif nargin<3,\n MaxCtr = 20; %Default maximum order\nend\n\nres = sym([]); %Initialize res as empty sym\nctr = 0; %Initialize counter\nwhile F~=0,\n res(end+1) = subs(F,'XX',0); %Evaluate at XX=0 \n F = diff(F,'XX',1); %Take derivative\n \n %%%%Check ctr as a defense against recursive loops\n ctr = ctr+1; \n if ctr>=MaxCtr,\n disp(['Error: Exceeded maximum number of terms (' num2str(MaxCtr) ')'])\n disp(['Inputs may be in invalid form (not a polynomial)'])\n disp('To increase maximum number, use SymPoly2Sym(F,DV,Max#)')\n res = [];\n return\n end\n %%%%%%%%\n \nend\nFact = [1 cumprod(1:length(res)-1)]; %Create factorial vector\nres = res./Fact; %Divide coefficients by the amount contributed by derivative operations\nres = res(end:-1:1); %Reverse order to match poly2sym convention", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3983-sympoly2sym/sympoly2sym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7342583369741251}} {"text": "%MAIN\n%\n% This script is used for testing the continuous, finite horizon, LQR\n% solver that I'm working on.\n%\n%\nclear; clc;\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% User Set Parameters %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nnSim = 25;\ntestPerturbation = 0.1; %Initial position error amplitude\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% Draw the dynamical system %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nn = 13;\nxLim = [-4,1.5];\nyLim = [-4,1];\nx = linspace(xLim(1),xLim(2),n);\ny = linspace(yLim(1),yLim(2),n);\n\n[xx,yy] = ndgrid(x,y);\n\n[dxx, dyy] = dynamics(xx,yy,zeros(n,n));\n\nfigure(1); clf; hold on;\ntitle('Dynamical System - Simulations');\nquiver(xx,yy,dxx,dyy);\nxlabel('x');\nylabel('y');\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% Compute a reference trajectory %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\noptions = odeset();\noptions.Events = @(t,z)eventFunc(t,z,xLim,yLim);\ntSpan = [0,-10];\n\ncontrol = @(t) -2*sin(0.4*t-0.1)+0.6*cos(0.9*t+0.1);\n\nuserFunc = @(t,z)rhs(t,z,control(t));\nz0 = [0;0];\n\nsol = ode45(userFunc,tSpan,z0,options);\n\nnTime = 70;\ntSol = linspace(sol.x(end),sol.x(1),nTime);\nzSol = deval(sol,tSol);\nxSol = zSol(1,:);\nySol = zSol(2,:);\nuSol = control(tSol);\ntSpan = [tSol(1),tSol(end)];\n\nplot(xSol,ySol,'r-','LineWidth',3);\nplot(0,0,'ro','MarkerSize',10,'LineWidth',2)\naxis(1.2*[xLim,yLim]); axis equal;\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% Store the reference trajectory %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n%We will store each trajectory as a polynomial. For low-order fits, say\n%less than 10th order, Matlab's polyval and polyfit are good. For\n%higher-order fit's, it is best to use different method, based on\n%barycentric interpolation. Google chebyfun.\n\nnFit = 5; %Order of polynomial fitting\nxFit = polyfit(tSol,xSol,nFit);\nyFit = polyfit(tSol,ySol,nFit);\nuFit = polyfit(tSol,uSol,nFit);\n\nfigure(2); clf;\nsubplot(3,1,1); hold on;\nplot(tSol,xSol,'k.','MarkerSize',15)\nplot(tSol,polyval(xFit,tSol),'r-')\nxlim(tSpan);\nylabel('x')\ntitle('Polynomial approximation of trajectory')\nsubplot(3,1,2); hold on;\nplot(tSol,ySol,'k.','MarkerSize',15)\nplot(tSol,polyval(yFit,tSol),'r-')\nxlim(tSpan);\nylabel('y')\nsubplot(3,1,3); hold on;\nplot(tSol,uSol,'k.','MarkerSize',15)\nplot(tSol,polyval(uFit,tSol),'r-')\nxlim(tSpan);\nylabel('u')\nxlabel('t')\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% Compute LQR Gains along trajectory %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n%Function handle for getting linearized system dynamics\nlinSys = @(t)getLinTraj(t,xFit,yFit,uFit);\n\nQ = eye(2); % Running cost on state \nR = 1; % Running cost on input \nF = eye(2); % Terminal cost on state \ntol = 1e-6; % Accuracy of ricatti propagation\n\nSoln = trajectoryLqr(tSol,linSys,Q,R,F,tol);\n\nK = reshape([Soln.K],2,nTime);\nkxFit = polyfit(tSol,K(1,:),nFit);\nkyFit = polyfit(tSol,K(2,:),nFit);\n\nfigure(3); clf;\nsubplot(2,1,1); hold on;\nplot(tSol,K(1,:),'k.','MarkerSize',15)\nplot(tSol,polyval(kxFit,tSol),'r-')\nxlim(tSpan);\nylabel('Kx')\ntitle('Polynomial approximation of lqr gains')\nsubplot(2,1,2); hold on;\nplot(tSol,K(2,:),'k.','MarkerSize',15)\nplot(tSol,polyval(kyFit,tSol),'r-')\nxlim(tSpan);\nylabel('Ky')\nxlabel('t')\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% Compare to infinite-horizon LQR gains %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nssSoln(nTime).t = 0;\nssSoln(nTime).K = zeros(1,2);\nssSoln(nTime).S = zeros(2);\nssSoln(nTime).E = zeros(2,1);\nfor i=1:nTime\n tNow = tSol(i);\n [A,B] = linSys(tNow);\n [KK,SS,EE] = lqr(A,B,Q,R);\n ssSoln(i).t = 0;\n ssSoln(i).K = KK;\n ssSoln(i).S = SS;\n ssSoln(i).E = EE;\nend\n\nssK = reshape([ssSoln.K],2,nTime);\nfigure(4); clf;\nsubplot(2,1,1); hold on;\nplot(tSol,K(1,:),'k.','MarkerSize',15)\nplot(tSol,ssK(1,:),'bo','MarkerSize',10)\nlegend('finite','infinite')\nxlim(tSpan);\nylabel('Kx')\ntitle('Compare finite vs infinite horizon gains')\nsubplot(2,1,2); hold on;\nplot(tSol,K(2,:),'k.','MarkerSize',15)\nplot(tSol,ssK(2,:),'bo','MarkerSize',10)\nlegend('finite','infinite')\nxlim(tSpan);\nylabel('Ky')\nxlabel('t')\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% Lyapunov Stability Analysis %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n% Let V(x) = x'Sx, where S is the cost-to-go matrix from LQR solution:\n\n%%%% TODO %%%%\n\n% Plan:\n%\n% 1) Represent the S matrix, which is time-varying, as a polynomial.\n%\n% 2) Compute the derivative of S wrt time.\n%\n% 3) Try the Lyapunov function:\n% V(x,t) = x'*S(t)*x % x = perturbation from nominal\n% dV(x,t) = 2*x*f(x,t)*S(t)*dS(t) %Chain Rule (check math...)\n% \n% 4) Verify stability by checking signs of lyapunov function and\n% derivative?\n% \n% 5) Not sure if this whole approach is correct - check against papers...\n%\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% Run a bunch of simulations %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\ncontroller = @(t,z)stabilizingController(t,z(1,:),z(2,:),xFit,yFit,uFit,kxFit,kyFit);\nuserFunc = @(t,z)rhs(t,z,controller(t,z));\nzNom = [xSol(1);ySol(1)];\n\nxSim = zeros(nTime,nSim);\nySim = zeros(nTime,nSim);\nuSim = zeros(nTime,nSim);\nfailFlag = false(nSim,1);\nfor i=1:nSim\n try\n z0 = zNom + testPerturbation*randn(2,1);\n [~, yout] = ode45(userFunc,tSol,z0);\n xSim(:,i) = yout(:,1);\n ySim(:,i) = yout(:,2);\n uSim(:,i) = controller(tSol,yout');\n catch ME\n xSim(:,i) = z0(1);\n ySim(:,i) = z0(2);\n uSim(:,i) = 0;\n failFlag(i) = true;\n end\nend\n\n% Plot the simulated trajectories:\nfigure(1); hold on; %Plot on top of dynamics vector field\nfor i=1:nSim\n plot(xSim(:,i),ySim(:,i),'k-','LineWidth',1);\nend\n\n%%%% Plot trajectories against time:\nfigure(5); clf;\n\nfor i=1:nSim\n if ~failFlag(i)\n subplot(3,1,1); hold on;\n plot(tSol,xSim(:,i),'k-','LineWidth',1)\n subplot(3,1,2); hold on;\n plot(tSol,ySim(:,i),'k-','LineWidth',1)\n subplot(3,1,3); hold on;\n plot(tSol,uSim(:,i),'k-','LineWidth',1)\n end\nend\n\nsubplot(3,1,1); hold on;\nplot(tSol,xSol,'r-','LineWidth',3)\nxlim(tSpan);\nylabel('x')\ntitle('Compare simulations against reference trajectory')\nsubplot(3,1,2); hold on;\nplot(tSol,ySol,'r-','LineWidth',3)\nxlim(tSpan);\nylabel('y')\nsubplot(3,1,3); hold on;\nplot(tSol,uSol,'r-','LineWidth',3)\nxlim(tSpan);\nylabel('u')\nxlabel('t')\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% Computate the backward reachable set -- Convex Hull Method %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nnSamples = 500; %How many simulations to run?\nnPointsPerSample = 10; %Used for computing reachable set\n\n% What is \"close enough\" to the final state?\nxRadFinal = 0.015;\nyRadFinal = 0.015;\n\n%Compute a random set of initial conditions\nIC = randDisk(nSamples,[xRadFinal,yRadFinal]);\n\n%Simulation runs backwards in time\ntSpanFlip = linspace(tSpan(2),tSpan(1),nPointsPerSample); %Run system backwards in time\n\n%Create a data structure for storing the point cloud:\nReachCvx.t = ones(nSamples,1)*tSpanFlip; % Time\nReachCvx.x = zeros(nSamples,nPointsPerSample); % x position\nReachCvx.y = zeros(nSamples,nPointsPerSample); % y position\nReachCvx.c(nPointsPerSample).x = []; %x contour\nReachCvx.c(nPointsPerSample).y = []; %x contour\n\n%Run the simulation:\nfor i=1:nSamples\n idxLow = (i-1)*nPointsPerSample+1;\n idxUpp= i*nPointsPerSample;\n [~, yout] = ode45(userFunc,tSpanFlip,IC(:,i));\n ReachCvx.x(i,:) = yout(:,1);\n ReachCvx.y(i,:) = yout(:,2);\nend\n\n%Compute the convex hull at each time step\nfor i=1:nPointsPerSample\n k = convhull(ReachCvx.x(:,i),ReachCvx.y(:,i));\n ReachCvx.c(i).t = ReachCvx.t(k,i);\n ReachCvx.c(i).x = ReachCvx.x(k,i);\n ReachCvx.c(i).y = ReachCvx.y(k,i);\nend\n\n\n%Plot the reachable sets against time:\nfigure(6); clf; hold on;\ncolors = jet(nPointsPerSample);\nfor i=1:nPointsPerSample\n %Convex Hull\n plot3(ReachCvx.c(i).x, ReachCvx.c(i).y, ReachCvx.c(i).t,'color',colors(i,:));\n %Point Cloud:\n plot3(ReachCvx.x(:,i), ReachCvx.y(:,i), ReachCvx.t(:,i),'.','MarkerSize',10,'color',colors(i,:));\nend\n\n%plot the nominal trajectory\nplot3(xSol,ySol,tSol,'k-','LineWidth',3);\n\n\n\ntitle('Convex Hull approximation of the reachable set');\nxlabel('x'); ylabel('y'); zlabel('time');\nview(3);\n\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% Computate the backward reachable set -- Front Propagation %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\nnSamples = 250; %How many simulations to run?\nnPointsPerSample = 10; %Used for computing reachable set\n\n% What is \"close enough\" to the final state?\nxRadFinal = 0.015;\nyRadFinal = 0.015;\n\n%Compute initial conditions on the circle around the final set:\nangle = linspace(0,2*pi,nSamples+1); angle(end) = [];\nIC = [cos(angle); sin(angle)];\nIC(1,:) = IC(1,:)*xRadFinal;\nIC(2,:) = IC(2,:)*yRadFinal;\n\n%Simulation runs backwards in time\ntSpanFlip = linspace(tSpan(2),tSpan(1),nPointsPerSample); %Run system backwards in time\n\n%Create a data structure for storing the point cloud:\nReachFrt.t = ones(nSamples,1)*tSpanFlip; % Time\nReachFrt.x = zeros(nSamples,nPointsPerSample); % x position\nReachFrt.y = zeros(nSamples,nPointsPerSample); % y position\n\n%Run the simulation:\nfor i=1:nSamples\n idxLow = (i-1)*nPointsPerSample+1;\n idxUpp= i*nPointsPerSample;\n [~, yout] = ode45(userFunc,tSpanFlip,IC(:,i));\n ReachFrt.x(i,:) = yout(:,1);\n ReachFrt.y(i,:) = yout(:,2);\nend\n\n%Plot the reachable sets against time:\nfigure(7); clf; hold on;\ncolors = jet(nPointsPerSample);\nidx = [1:size(ReachFrt.x,1),1]; %Make the contours wrap around\nfor i=1:nPointsPerSample\n %Front contour\n plot3(ReachFrt.x(idx,i), ReachFrt.y(idx,i), ReachFrt.t(idx,i),'color',colors(i,:));\n %Point Cloud:\n plot3(ReachFrt.x(:,i), ReachFrt.y(:,i), ReachFrt.t(:,i),'k.','MarkerSize',15);\n %Fill the central region:\n h = patch(ReachFrt.x(idx,i), ReachFrt.y(idx,i), ReachFrt.t(idx,i),colors(i,:));\nend\nplot3(xSol,ySol,tSol,'k-');\n\nhp = findobj(gcf,'type','patch');\nset(hp,'facealpha',0.7)\nset(hp,'edgealpha',0.1)\n\ntitle('Front Propagation approximation of the reachable set');\nxlabel('x'); ylabel('y'); zlabel('time');\nview(3);\n\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% Computation with the Level Set Toolbox %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n\n%This section of code requires the levelSetToolbox to operate:\n% http://www.cs.ubc.ca/~mitchell/ToolboxLS/\nif exist('odeCFLset','file')\n %This section of code is still under development. As of 11/20/2014 the\n %following two scripts should run, but they are slow. It also seems\n %that there is some numerical dissapation, that is causing inaccurate\n %results for any reasonable level of discretization.\n \n %%%% reachableForward\n %%%% reachableForwardRel\nend\n\n\n\n\n\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/Continuous_Finite_LQR/MAIN_trajectory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7342243423572342}} {"text": "function result = tetra_unit_sum ( func, norder, xtab, ytab, ztab, weight )\n\n%*****************************************************************************80\n%\n%% TETRA_UNIT_SUM carries out a quadrature rule in the unit tetrahedron in 3D.\n%\n% Integration region:\n%\n% Points (X,Y,Z) such that\n%\n% 0 <= X,\n% 0 <= Y,\n% 0 <= Z, and\n% X + Y + Z <= 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 26 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the user supplied\n% function of three variables which is to be integrated,\n% of the form:\n% function value = func ( x, y, z )\n%\n% Input, integer NORDER, the order of the rule.\n%\n% Input, real XTAB(NORDER), YTAB(NORDER), ZTAB(NORDER), the\n% abscissas.\n%\n% Input, real WEIGHT(NORDER), the weights.\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n quad = 0.0E+00;\n\n for i = 1 : norder\n quad = quad + weight(i) * feval ( func, xtab(i), ytab(i), ztab(i) );\n end\n\n volume = tetra_unit_volume ( );\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/tetra_unit_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7341411540416162}} {"text": "function result = circle_rt_sum ( func, xc, yc, radius, nr, ra, rw, nt, ta, ...\n tw, zw )\n\n%*****************************************************************************80\n%\n%% CIRCLE_RT_SUM applies an R, THETA product quadrature rule inside a circle.\n%\n% Integration region:\n%\n% Points (X,Y) such that:\n%\n% (X-XC)**2 + (Y-YC)**2 <= RADIUS**2.\n%\n% Discussion:\n%\n% The product rule is assumed to be have the form:\n%\n% Integral_Approx = ZW * F(XC,YC) +\n% Sum ( 1 <= IR <= NR ) Sum ( 1 <= IT <= NT )\n% RW(IR) * TW(IT) * F ( XC + R(IR) * RADIUS * Cos ( TA(IT) ),\n% YC + R(IR) * RADIUS * Sin ( TA(IT) ) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 22 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the user supplied\n% function of two variables which is to be integrated,\n% of the form:\n% function value = func ( x, y )\n%\n% Input, real XC, YC, the coordinates of the center of\n% the circle.\n%\n% Input, realn RADIUS, the radius of the circle.\n%\n% Input, integer NR, the number of R abscissas.\n%\n% Input, real RA(NR), RW(NR), the R abscissas and weights.\n%\n% Input, integer NT, the number of Theta abscissas.\n%\n% Input, real TA(NT), TW(NT), the THETA abscissas and weights.\n%\n% Input, real ZW, the weight to use for the center.\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n quad = 0.0E+00;\n\n if ( zw ~= 0.0E+00 )\n x = xc;\n y = yc;\n quad = quad + zw * feval ( func, x, y );\n end\n\n for it = 1 : nt\n rct = radius * cos ( ta(it) );\n rst = radius * sin ( ta(it) );\n for ir = 1 : nr\n x = xc + ra(ir) * rct;\n y = yc + ra(ir) * rst;\n quad = quad + tw(it) * rw(ir) * feval ( func, x, y );\n end\n end\n\n volume = circle_area_2d ( radius );\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/circle_rt_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.734141147977793}} {"text": "function h=holder(tfr,f,n1,n2,t,pl)\n%HOLDER\tEstimate the Holder exponent through an affine TFR.\n%\tH=HOLDER(TFR,F,N1,N2,T) estimates the Holder exponent of a \n%\tfunction through an affine time-frequency representation of it, \n%\tand plots the frequency marginal and the regression line. \n%\n%\tTFR : affine time-frequency representation. \n%\tF : frequency values of the spectral analysis. \n%\tN1 : indice of the minimum frequency for the linear regression. \n% (default : 1).\n%\tN2 : indice of the maximum frequency for the linear regression. \n% (default : length(F)).\n%\tT : time vector. If T is omitted, the function returns the\n%\t global estimate of the Holder exponent. Otherwise, it\n%\t returns the local estimates H(T) at the instants specified\n%\t in T. \n%\tH : output value (if T omitted) or vector (otherwise) containing\n%\t the Holder estimate(s).\n%\n%\tExample :\n%\t S=altes(128); [TFR,T,F]=tfrscalo(S,1:128,8);\n%\t H=holder(TFR,F,1,length(F));\n\n%\tP. Goncalves, October 1995\n%\tCopyright (c) 1995 Rice University\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\nclf;\ntfr = abs(tfr) ;\n\nif nargin<2,\n error('There must be at least 2 input parameters');\nelseif nargin==2,\n n1=1; n2=length(f);\nelseif nargin==3,\n n2=length(f);\nend\nif nargin<=5,\n pl=1;\nelse\n pl=0;\nend\n\nif nargin <= 4\n fmarg = mean(tfr.').' ;\n if pl, plot(log(f),log(fmarg)) , hold on; end;\n p = polyfit(log(f(n1:n2)),log(fmarg(n1:n2)),1) ;\n drt = p(1)*log(f)+p(2) ;\n if pl,\n plot(log(f),drt,'--g') ; \n legend('Frequency marginal','Regression line');\n plot(log(f([n1 n2])),log(fmarg([n1 n2])),'+r') ;\n xticklabels = round(logspace(log10(min(f)),log10(max(f)),4)*1000)./1000 ;\n set(gca,'XTick',log(xticklabels)) ; \n xlabel('frequency (logarithmically spaced)') ;\n hold off ;\n end\n h = (-p(1)-1)/2 ;\nelse\n if length(t) == 1\n if pl, plot(log(f),log(tfr(:,t))) ; hold on; end\n p = polyfit(log(f(n1:n2)),log(tfr(n1:n2,t)),1) ;\n drt = p(1)*log(f)+p(2) ;\n if pl, \n plot(log(f),drt,'--g') ;\n legend('Frequency marginal','Regression line');\n plot(log(f([n1 n2])),log(tfr([n1 n2],t)),'+r') ;\n xticklabels = round(logspace(log10(min(f)),log10(max(f)),4)*1000)./1000 ;\n set(gca,'XTick',log(xticklabels)) ; \n xlabel('frequency (logarithmically spaced)') ;\n hold off ;\n end\n h = (-p(1)-1)/2 ;\n elseif length(t) > 1 \n [yt,xt] = size(t) ; if yt>xt, t = t.' ; end ;\n j = 1 ;\n for k = t,\n p = polyfit(log(f(n1:n2)),log(tfr(n1:n2,k)),1) ;\n h(j) = (-p(1)-1)/2 ; j = j + 1 ;\n end\n if pl, \n plot(t,h) ;grid\n title('Holder estimates at time instants T');\n end\n end,\nend\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/holder.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7341411414488338}} {"text": "%SerialLink.MANIPLTY Manipulability measure\n%\n% M = R.maniplty(Q, OPTIONS) is the manipulability index measure for the robot\n% at the joint configuration Q. It indicates dexterity, how isotropic the\n% robot's motion is with respect to the 6 degrees of Cartesian motion.\n% The measure is low when the manipulator is close to a singularity.\n% If Q is a matrix M is a column vector of manipulability \n% indices for each pose specified by a row of Q.\n%\n% Two measures can be selected:\n% - Yoshikawa's manipulability measure is based on the shape of the velocity\n% ellipsoid and depends only on kinematic parameters.\n% - Asada's manipulability measure is based on the shape of the acceleration\n% ellipsoid which in turn is a function of the Cartesian inertia matrix and\n% the dynamic parameters. The scalar measure computed here is the ratio of \n% the smallest/largest ellipsoid axis. Ideally the ellipsoid would be \n% spherical, giving a ratio of 1, but in practice will be less than 1.\n%\n% Options::\n% 'T' compute manipulability for just transational motion\n% 'R' compute manipulability for just rotational motion\n% 'yoshikawa' use Asada algorithm (default)\n% 'asada' use Asada algorithm\n%\n% Notes::\n% - by default the measure includes rotational and translational dexterity, but\n% this involves adding different units. It can be more useful to look at the\n% translational and rotational manipulability separately.\n%\n% See also SerialLink.inertia, SerialLink.jacob0.\n\n% Ryan Steindl based on Robotics Toolbox for MATLAB (v6 and v9)\n%\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction [w,mx] = maniplty(robot, q, varargin)\n\tn = robot.n;\n\n opt.yoshikawa = true;\n opt.asada = false;\n opt.axes = {'all', 'T', 'R'};\n\n opt = tb_optparse(opt, varargin);\n\n\tif length(q) == robot.n,\n\t\tq = q(:)';\n\tend\n\n\tw = [];\n MX = [];\n\n if opt.yoshikawa\n\t\tfor Q = q',\n\t\t\tw = [w; yoshi(robot, Q, opt)];\n\t\tend\n\telseif opt.asada\n\t\tfor Q = q',\n if nargout > 1\n [ww,mm] = asada(robot, Q);\n w = [w; ww];\n MX = cat(3, MX, mm);\n else\n w = [w; asada(robot, Q, opt)];\n end\n\t\tend\n\tend\n\n if nargout > 1\n mx = MX;\n end\n\nfunction m = yoshi(robot, q, opt)\n\tJ = jacob0(robot, q);\n switch opt.axes\n case 'T'\n J = J(1:3,:);\n case 'R'\n J = J(4:6,:);\n end\n\tm = sqrt(det(J * J'));\n\nfunction [m, mx] = asada(robot, q, opt)\n\tJ = jacob0(robot, q);\n \n if rank(J) < 6,\n warning('robot is in degenerate configuration')\n m = 0;\n return;\n end\n\n switch opt.axes\n case 'T'\n J = J(1:3,:)\n case 'R'\n J = J(4:6,:);\n end\n\tJi = inv(J);\n\tM = inertia(robot, q);\n\tMx = Ji' * M * Ji;\n\te = eig(Mx(1:3,1:3));\n\tm = min(e) / max(e);\n\n if nargout > 1\n mx = Mx;\n end\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/Octave/@SerialLink/maniplty.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7341343060255622}} {"text": "function x = product_grid ( m, a, b, n, c, d )\n\n%*****************************************************************************80\n%\n%% PRODUCT_GRID produces a product grid of points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 December 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real M, the number of grid points in X.\n%\n% Input, real A, B, the X limits.\n%\n% Input, real N, the number of grid points in Y.\n%\n% Input, real C, D, the Y limits.\n%\n% Output, real X(M*N,2), the points of the product grid.\n%\n x = zeros ( m * n, 2 );\n\n k = 0;\n for i = 1 : m\n for j = 1 : n\n k = k + 1;\n x(k,1) = ( ( m - i ) * a + ( i - 1 ) * b ) / ( m - 1 );\n x(k,2) = ( ( n - j ) * c + ( j - 1 ) * d ) / ( n - 1 );\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/shoreline/product_grid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.8856314783461303, "lm_q1q2_score": 0.7341343022721749}} {"text": "% Fast linear interpolation of ordered values (one dimendionnal)\n%\n% This matlab version is made to illustrate the behavior of the C version.\n% Do not expect speed from this Matlab version !\n% Also, if this function is updated, its C version has to be updated\n% accordingly.\n%\n% Note tha the C version makes absolutely NO check at all.\n% Thus, it can crash very easily. \n%\n% Build the C version using\n% $ mex interp1ordered.c\n%\n% Input\n% x ; [Nx1] Ordered reference abscissa\n% y ; [Nx1] Ordered reference ordinates\n% xi : [Mx1] Ordered abscissa where to interpolate\n% yid : [Mx1] Default out of bounds value\n%\n% Output\n% yi : Interpolated output values\n%\n% Copyright (c) 2012 University of Crete - Computer Science Department (UOC-CSD)\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\nfunction yi = interp1ordered(x, y, xi, yid)\n\n yi = yid*ones(size(xi));\n\n i=1;\n j=1;\n\n while xi(i) scaling factor\n [sx, sy, sz]= parseScalingFactors(varargin{1});\n \nelseif nargin == 2\n % 2 arguments, giving center and uniform scaling\n center = varargin{1};\n [sx, sy, sz]= parseScalingFactors(varargin{2});\n\nelseif nargin == 3\n % 3 arguments, giving scaling in each direction\n sx = varargin{1};\n sy = varargin{2};\n sz = varargin{3};\n \nelseif nargin == 4\n % 4 arguments, giving center and scaling in each direction\n center = varargin{1};\n sx = varargin{2};\n sy = varargin{3};\n sz = varargin{4};\nend\n\n%% create the scaling matrix\ntrans = [...\n sx 0 0 center(1)*(1-sx);...\n 0 sy 0 center(2)*(1-sy);...\n 0 0 sz center(3)*(1-sz);...\n 0 0 0 1];\n\n%% Helper function\nfunction [sx, sy, sz] = parseScalingFactors(var)\n\nif length(var)==1\n % same scaling factor in each direction\n sx = var;\n sy = var;\n sz = var;\nelseif length(var)==3\n % scaling is a vector, giving different scaling in each direction\n sx = var(1);\n sy = var(2);\n sz = var(3);\nelse\n error('wrong size for first parameter of \"createScaling3d\"');\nend\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/createScaling3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7341342860290067}} {"text": "function x = nco_abscissas_ab ( a, b, n )\n\n%*****************************************************************************80\n%\n%% NCO_ABSCISSAS_AB computes the Newton Cotes Open 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 for i = 1 : n\n x(i) = ( ( n - i + 1 ) * a ...\n + ( i ) * 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/nco_abscissas_ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.734121821155451}} {"text": "function mono_between_enum_test ( )\n\n%*****************************************************************************80\n%\n%% MONO_BETWEEN_ENUM_TEST tests MONO_BETWEEN_ENUM.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 November 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONO_BETWEEN_ENUM_TEST\\n' );\n fprintf ( 1, ' MONO_BETWEEN_ENUM can enumerate the number of monomials\\n' );\n fprintf ( 1, ' in M variables, of total degree between N1 and N2.\\n' );\n\n m = 3;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using spatial dimension M = %d\\n', m );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N2:' );\n for n2 = 0 : 8\n fprintf ( 1, ' %4d', n2 );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N1 +------------------------------------------------------\\n' );\n for n1 = 0 : 8\n fprintf ( 1, ' %2d |', n1 );\n for n2 = 0 : 8\n v = mono_between_enum ( m, n1, n2 );\n fprintf ( 1, ' %4d', v );\n end\n fprintf ( 1, '\\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/monomial/mono_between_enum_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7341218069844747}} {"text": "function [h] = fdr(p, q)\n\n% FDR false discovery rate\n%\n% Use as\n% h = fdr(p, q)\n%\n% This implements\n% Genovese CR, Lazar NA, Nichols T.\n% Thresholding of statistical maps in functional neuroimaging using the false discovery rate.\n% Neuroimage. 2002 Apr;15(4):870-8.\n%\n% There are two types of FDR correction (Benjamini-Hochberg & Benjamini-Yekutieli), of\n% which the second is currently implemented.\n\n% Copyright (C) 2005-2015, Robert Oostenveld\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%\n% $Id$\n\n% convert the input into a row vector\ndim = size(p);\np = reshape(p, 1, numel(p));\n\n% sort the observed uncorrected probabilities\n[ps, indx] = sort(p);\n\n% count the number of voxels\nV = length(p);\n\n% compute the threshold probability for each voxel\npi = ((1:V)/V) * q / c(V);\n\nif any(ps<=pi)\n h = ps<=(max(ps(ps<=pi)));\nelse\n h = false(size(ps));\nend\n\n% undo the sorting\n[dum, unsort] = sort(indx);\nh = h(unsort);\n\n% convert the output back into the original format\nh = reshape(h, dim);\n\nfunction s = c(V)\n% See Genovese, Lazar and Holmes (2002) page 872, second column, first paragraph\nif V<1000\n % compute it exactly\n s = sum(1./(1:V));\nelse\n % approximate it\n s = log(V) + 0.57721566490153286060651209008240243104215933593992359880576723488486772677766467093694706329174674951463144724980708248096050401448654283622417399764492353625350033374293733773767394279259525824709491600873520394816567;\nend\n\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/private/fdr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356994, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7340757039661845}} {"text": "function [ po, pc, pe ] = lagrange_partial2 ( d, n, r, nd, xd )\n\n%*****************************************************************************80\n%\n%% LAGRANGE_PARTIAL2: Partial Lagrange polynomial basis from data.\n%\n% Discussion:\n%\n% This function represents algorithm 4.1 in the reference,\n% modified for the case where the number of data points is less\n% than the dimension of the desired polynomial space,\n% with the further modification that a form of \"pivoting\" is used\n% to select the next polynomial as the one with maximum absolute\n% value at the current node.\n%\n% This function is given XD, a set of ND distinct data points in a\n% D dimensional space, and returns information defining a set of \n% ND Lagrange polynomials L(i)(X) with the property that:\n%\n% L(i)(XD(j)) = delta(i,j)\n%\n% This function is used in cases where ND, the number of data points, \n% is less than or equal to R, the dimension of the space of polynomials \n% in D dimensions and total degree N or less, that is:\n%\n% ND <= R = Choose ( N + D, N )\n%\n% There will be ND polynomials returned. Each polynomial can have\n% as many as R coefficients.\n%\n% Each polynomial is given as a vector, with each entry corresponding\n% to a nonzero coefficient. In particular, for polynomial L(i)(X):\n%\n% PO(i) is the order, that is, the number of nonzero coefficients;\n% PC(i,j), for 1 <= j <= PO(i), is the coefficient of the J-th term.\n% PE(i,j), for 1 <= j <= PO(i), encodes the exponents of the J-th term.\n%\n% The exponent codes are a compact way of recording the exponent vector\n% associated with each monomial. If PE(i,j) = k, then the corresponding\n% vector of D exponents can be determined by:\n%\n% E = mono_unrank_grlex ( D, k );\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Tomas Sauer, Yuan Xu,\n% On multivariate Lagrange interpolation,\n% Mathematics of Computation,\n% Volume 64, Number 211, July 1995, pages 1147-1170.\n%\n% Parameters:\n%\n% Input, integer D, the spatial dimension.\n%\n% Input, integer N, the maximum total degree.\n%\n% Input, integer R, the number of monomials in D dimensions \n% of total degree N or less.\n%\n% Input, integer ND, the number of data points.\n% It must be the case that ND <= R.\n%\n% Input, real XD(D,ND), the data points, which must be distinct.\n%\n% Output, integer PO(ND), the order (number of nonzero coefficients) for the \n% Lagrange basis polynomials.\n%\n% Output, real PC(ND,R), the coefficients for the \n% Lagrange basis polynomials.\n%\n% Output, integer PE(ND,R), the exponent indices for the \n% Lagrange basis polynomials.\n%\n\n%\n% Verify that R is correct.\n%\n if ( r ~= mono_upto_enum ( d, n ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_PARTIAL2 - Fatal error!\\n' );\n fprintf ( 1, ' The value R is not correct.\\n' );\n error ( 'LAGRANGE_PARTIAL2 - Fatal error!' );\n end\n\n if ( r < nd )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_PARTIAL2 - Fatal error!\\n' );\n fprintf ( 1, ' The value R = %d is less than ND = %d.\\n', r, nd );\n error ( 'LAGRANGE_PARTIAL2 - Fatal error!' );\n end\n%\n% Verify that the points are sufficiently distinct.\n%\n [ d_min, d_max ] = r8col_separation ( d, nd, xd );\n d_tol = sqrt ( eps );\n\n if ( d_min < d_tol )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_PARTIAL2 - Fatal error!\\n' );\n fprintf ( 1, ' Some points are too close!\\n' );\n fprintf ( 1, ' Minimum data point separation is = %g.\\n', d_min );\n error ( 'LAGRANGE_PARTIAL2 - Fatal error!' );\n end\n%\n% Initialize the polynomials Q to be all monomials of degree exactly N.\n%\n qo = zeros ( r, 1 );\n qc = zeros ( r, r );\n qe = zeros ( r, r );\n\n for k = 1 : r\n qo(k,1) = 1;\n qc(k,1) = 1.0;\n qe(k,1) = k;\n end\n%\n% Now set up the P polynomials.\n%\n po = zeros ( nd, 1 );\n pc = zeros ( nd, r );\n pe = zeros ( nd, r );\n\n for k = 1 : nd\n%\n% Find the polynomial Q(K:R)(X) which is most nonzero at X(K).\n%\n i = r + 1;\n value_max = 0.0;\n\n for j = k : r\n\n o = qo(j);\n value = polynomial_value ( d, o, qc(j,1:o), qe(j,1:o), 1, xd(1:d,k) );\n \n if ( abs ( value_max ) <= abs ( value ) )\n i = j;\n value_max = value;\n end\n\n end\n\n if ( i == r + 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_PARTIAL2 - Fatal error!\\n' );\n fprintf ( 1, ' I = R+1.\\n' );\n fprintf ( 1, ' No polynomial was nonzero at the current node.\\n' );\n error ( 'LAGRANGE_PARTIAL2 - Fatal error!' );\n end\n\n value = value_max;\n%\n% Define P(K)(X) = Q(I)(X) / Q(I)(X(k)\n%\n o = qo(i);\n po(k) = qo(i);\n pc(k,1:o) = qc(i,1:o) / value;\n pe(k,1:o) = qe(i,1:o);\n%\n% Modify P(1:k-1)(X).\n%\n for j = 1 : k - 1\n\n oj = po(j);\n ok = po(k);\n\n value = polynomial_value ( d, oj, pc(j,1:oj), pe(j,1:oj), 1, xd(1:d,k) );\n\n [ o, c, e ] = polynomial_axpy ( - value, ok, pc(k,1:ok), pe(k,1:ok), ...\n oj, pc(j,1:oj), pe(j,1:oj) );\n\n po(j) = o;\n pc(j,1:o) = c(1:o)';\n pe(j,1:o) = e(1:o)';\n\n end\n%\n% Modify Q(I:downto:K+1)\n%\n for j = i : -1 : k + 1\n\n oj = qo(j-1);\n ok = po(k);\n\n value = polynomial_value ( d, oj, qc(j-1,1:oj), qe(j-1,1:oj), ...\n 1, xd(1:d,k) );\n \n [ o, c, e ] = polynomial_axpy ( - value, ok, pc(k,1:ok), pe(k,1:ok), ...\n oj, qc(j-1,1:oj), qe(j-1,1:oj) );\n\n qo(j) = o;\n qc(j,1:o) = c(1:o)';\n qe(j,1:o) = e(1:o)';\n\n end\n%\n% Modify Q(I+1:R)\n%\n for j = i + 1 : r\n\n oj = qo(j);\n ok = po(k);\n\n value = polynomial_value ( d, oj, qc(j,1:oj), qe(j,1:oj), ...\n 1, xd(1:d,k) );\n\n [ o, c, e ] = polynomial_axpy ( - value, ok, pc(k,1:ok), pe(k,1:ok), ...\n oj, qc(j,1:oj), qe(j,1:oj) );\n\n qo(j) = o;\n qc(j,1:o) = c(1:o)';\n qe(j,1:o) = e(1:o)';\n\n end\n\n end\n%\n% Get rid of tiny coefficients.\n%\n for i = 1 : nd\n oi = po(i);\n [ o, c, e ] = polynomial_compress ( ...\n po(i), pc(i,1:oi), pe(i,1:oi) );\n po(i) = o;\n pc(i,1:o) = c(1:o)';\n pe(i,1:o) = e(1:o)';\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/lagrange_nd/lagrange_partial2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7340137008702798}} {"text": "function [Zc mu] = myCenter(Z)\n%--------------------------------------------------------------------------\n% Syntax: Zc = myCenter(Z);\n% [Zc mu] = myCenter(Z);\n% \n% Inputs: Z is an (d x n) matrix containing n samples of a\n% d-dimensional random vector\n% \n% Outputs: Zc is the centered version of Z\n% \n% mu is the (d x 1) sample mean of Z\n% \n% Description: This function returns the centered (i.e., zero mean)\n% version of the input samples\n% \n% NOTE: Z = Zc + repmat(mu,1,n);\n% \n% Author: Brian Moore\n% brimoor@umich.edu\n% \n% Date: April 26, 2015\n%--------------------------------------------------------------------------\n\n% Compute sample mean\nmu = mean(Z,2);\n\n% Subtract mean\nZc = bsxfun(@minus,Z,mu);\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/分类算法/deephypercnn-master/Matlab-Sat-Data/pca_ica/myCenter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.890294225394328, "lm_q1q2_score": 0.7340136844306437}} {"text": "function [xd,xn,option] = denoise(x,h,type,option)\n% [xd,xn,option] = denoise(x,h,type,option); \n%\n% DENOISE is a generic program for wavelet based denoising.\n% The program will denoise the signal x using the 2-band wavelet\n% system described by the filter h using either the traditional \n% discrete wavelet transform (DWT) or the linear shift invariant \n% discrete wavelet transform (also known as the undecimated DWT\n% (UDWT)). \n%\n% Input: \n% x : 1D or 2D signal to be denoised\n% h : Scaling filter to be applied\n% type : Type of transform (Default: type = 0)\n% 0 --> Discrete wavelet transform (DWT)\n% 1 --> Undecimated DWT (UDWT)\n% option : Default settings is marked with '*':\n% *type = 0 --> option = [0 3.0 0 0 0 0]\n% type = 1 --> option = [0 3.6 0 1 0 0]\n% option(1) : Whether to threshold low-pass part\n% 0 --> Don't threshold low pass component \n% 1 --> Threshold low pass component\n% option(2) : Threshold multiplier, c. The threshold is\n% computed as: \n% thld = c*MAD(noise_estimate)). \n% The default values are:\n% c = 3.0 for the DWT based denoising\n% c = 3.6 for the UDWT based denoising\n% option(3) : Type of variance estimator\n% 0 --> MAD (mean absolute deviation)\n% 1 --> STD (classical numerical std estimate)\n% option(4) : Type of thresholding\n% 2 --> Soft thresholding\n% 1 --> Hard thresholding\n% option(5) : Number of levels, L, in wavelet decomposition. By\n% setting this to the default value '0' a maximal\n% decomposition is used.\n% option(6) : Actual threshold to use (setting this to\n% anything but 0 will mean that option(3)\n% is ignored)\n%\n% Output: \n% xd : Estimate of noise free signal \n% xn : The estimated noise signal (x-xd)\n% option : A vector of actual parameters used by the\n% program. The vector is configured the same way as\n% the input option vector with one added element\n% option(7) = type.\n%\n% HERE'S AN EASY WAY TO RUN THE EXAMPLES:\n% Cut-and-paste the example you want to run to a new file \n% called ex.m, for example. Delete out the % at the beginning \n% of each line in ex.m (Can use search-and-replace in your editor\n% to replace it with a space). Type 'ex' in matlab and hit return.\n%\n% Example 1: \n% h = daubcqf(6); [s,N] = makesig('Doppler'); n = randn(1,N);\n% x = s + n/10; % (approximately 10dB SNR)\n% figure;plot(x);hold on;plot(s,'r');\n%\n% %Denoise x with the default method based on the DWT\n% [xd,xn,opt1] = denoise(x,h);\n% figure;plot(xd);hold on;plot(s,'r');\n%\n% %Denoise x using the undecimated (LSI) wavelet transform\n% [yd,yn,opt2] = denoise(x,h,1);\n% figure;plot(yd);hold on;plot(s,'r');\n%\n% Example 2: (on an image) \n% h = daubcqf(6); load lena; \n% noisyLena = lena + 25 * randn(size(lena));\n% figure; colormap(gray); imagesc(lena); title('Original Image');\n% figure; colormap(gray); imagesc(noisyLena); title('Noisy Image'); \n% Denoise lena with the default method based on the DWT\n% [denoisedLena,xn,opt1] = denoise(noisyLena,h);\n% figure; colormap(gray); imagesc(denoisedLena); title('denoised Image');\n% \n%\n% See also: mdwt, midwt, mrdwt, mirdwt, SoftTh, HardTh, setopt\n%\n%Author: Jan Erik Odegard \n\nif(nargin < 2)\n error('You need to provide at least 2 inputs: x and h');\nend;\nif(nargin < 3),\n type = 0;\n option = [];\nelseif(nargin < 4)\n option = [];\nend;\nif(isempty(type)),\n type = 0;\nend;\nif(type == 0),\n default_opt = [0 3.0 0 2 0 0];\nelseif(type == 1),\n default_opt = [0 3.6 0 1 0 0];\nelse\n error(['Unknown denoising method',10,...\n\t 'If it is any good we need to have a serious talk :-)']);\nend;\noption = setopt(option,default_opt);\n[mx,nx] = size(x);\ndim = min(mx,nx);\nif(dim == 1),\n n = max(mx,nx);\nelse\n n = dim;\nend;\nif(option(5) == 0),\n L = floor(log2(n));\nelse\n L = option(5);\nend;\nif(type == 0), \t\t\t% Denoising by DWT\n xd = mdwt(x,h,L);\n if (option(6) == 0),\n tmp = xd(floor(mx/2)+1:mx,floor(nx/2)+1:nx);\n if(option(3) == 0),\n thld = option(2)*median(abs(tmp(:)))/.67;\n elseif(option(3) == 1),\n thld = option(2)*std(tmp(:));\n else\n error('Unknown threshold estimator, Use either MAD or STD');\n end;\n else\n thld = option(6);\n end;\n if(dim == 1)\n ix = 1:n/(2^L);\n ykeep = xd(ix);\n else\n ix = 1:mx/(2^L);\n jx = 1:nx/(2^L);\n ykeep = xd(ix,jx);\n end;\n if(option(4) == 2),\n xd = SoftTh(xd,thld);\n elseif(option(4) == 1),\n xd = HardTh(xd,thld);\n else\n error('Unknown threshold rule. Use either Soft (2) or Hard (1)');\n end;\n if (option(1) == 0),\n if(dim == 1),\n xd(ix) = ykeep;\n else\n xd(ix,jx) = ykeep;\n end;\n end;\n xd = midwt(xd,h,L);\nelseif(type == 1), \t\t\t% Denoising by UDWT\n [xl,xh] = mrdwt(x,h,L);\n if(dim == 1),\n c_offset = 1;\n else\n c_offset = 2*nx + 1;\n end;\n if (option(6) == 0),\n tmp = xh(:,c_offset:c_offset+nx-1);\n if(option(3) == 0),\n thld = option(2)*median(abs(tmp(:)))/.67;\n elseif(option(3) == 1),\n thld = option(2)*std(tmp(:));\n else\n error('Unknown threshold estimator, Use either MAD or STD');\n end;\n else\n thld = option(6);\n end;\n if(option(4) == 2),\n xh = SoftTh(xh,thld);\n if(option(1) == 1),\n xl = SoftTh(xl,thld);\n end;\n elseif(option(4) == 1),\n xh = HardTh(xh,thld);\n if(option(1) == 1),\n xl = HardTh(xl,thld);\n end;\n else\n error('Unknown threshold rule. Use either Soft (2) or Hard (1)');\n end;\n xd = mirdwt(xl,xh,h,L);\nelse \t\t\t\t\t% Denoising by unknown method\n error(['Unknown denoising method',10,...\n 'If it is any good we need to have a serious talk :-)']);\nend;\noption(6) = thld;\noption(7) = type;\nxn = x - xd; \n", "meta": {"author": "ricedsp", "repo": "D-AMP_Toolbox", "sha": "6e597d98c84755697b65554d59485d50a549c01a", "save_path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox", "path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox/D-AMP_Toolbox-6e597d98c84755697b65554d59485d50a549c01a/Packages/rwt/bin/denoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7339923374750519}} {"text": "function alpha = normalizeAngle(alpha, varargin)\n%NORMALIZEANGLE Normalize an angle value within a 2*PI interval.\n%\n% ALPHA2 = normalizeAngle(ALPHA);\n% ALPHA2 is the same as ALPHA modulo 2*PI and is positive.\n%\n% ALPHA2 = normalizeAngle(ALPHA, CENTER);\n% Specifies the center of the angle interval.\n% If CENTER==0, the interval is [-pi ; +pi]\n% If CENTER==PI, the interval is [0 ; 2*pi] (default).\n%\n% Example:\n% % normalization between 0 and 2*pi (default)\n% normalizeAngle(5*pi)\n% ans =\n% 3.1416\n%\n% % normalization between -pi and +pi\n% normalizeAngle(7*pi/2, 0)\n% ans =\n% -1.5708\n%\n% See also\n% vectorAngle, lineAngle\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@nantes.inra.fr\n% Created: 2008-03-10, using Matlab 7.4.0.287 (R2007a)\n% Copyright 2008 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.\n\n% HISTORY\n% 2010-03-31 rename as normalizeAngle, and add psb to specify interval\n% center\n\ncenter = pi;\nif ~isempty(varargin)\n center = varargin{1};\nend\n\nalpha = mod(alpha-center+pi, 2*pi) + center-pi;\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/private/normalizeAngle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7339898685579315}} {"text": "function [ x, seed ] = normal_ms_sample ( mu, sigma, seed )\n\n%*****************************************************************************80\n%\n%% NORMAL_MS_SAMPLE samples the Normal MS PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real MU, SIGMA, the parameters of the PDF.\n% 0.0 < SIGMA.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X, a sample of the PDF.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n [ y, seed ] = normal_01_sample ( seed );\n\n x = mu + sigma * y;\n\n return\nend\n", "meta": {"author": "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/normal_ms_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970717197771, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7339898596969402}} {"text": "function [Ec,Rad,Diam,Cv,Pv]=grEccentricity(E)\n% Function Ec=grEccentricity(E) find the (weighted) \n% eccentricity of all vertexes of graph.\n% Input parameter: \n% E(m,2) or (m,3) - the edges of graph and their weight;\n% 1st and 2nd elements of each row is numbers of vertexes;\n% 3rd elements of each row is weight of arrow;\n% m - number of arrows.\n% If we set the array E(m,2), then all weights is 1.\n% Output parameter:\n% Ec(1,n) - the (weighted) eccentricity of all vertexes.\n% [Ec,Rad,Diam]=grEccentricity(E) find also the radius Rad and \n% diameter Diam of the graph (the scalars).\n% [Ec,Rad,Diam,Cv,Pv]=grEccentricity(E) find also \n% the center vertexes Cv and the periphery vertexes Pv \n% of the graph (the vector-rows with numbers of vertexes).\n% Author: Sergiy Iglin\n% e-mail: siglin@yandex.ru\n% personal page: http://iglin.exponenta.ru\n\nif nargin<1,\n error('There are no input data!')\nend\ndSP=grDistances(E); % the matrix of distances\nEc=max(dSP); % the eccentricity of all vertexes\nRad=min(Ec); % the radius\nDiam=max(Ec); % the diameter\nCv=find(Ec==Rad); % the center vertexes of the graph\nPv=find(Ec==Diam); % the periphery vertexes of the graph\nreturn", "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/GraphTheory(图论)/basic/grEccentricity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7339353057997908}} {"text": "function I=montec2vvar(g,cx,dx,a,b,c,d,n)\n\n%I=montec2vvar('g',cx,dx,a,b,c,d,n)\n%Calculates integral on no rectangular space using monte-carlo method\n%a,b, fixed boundaries\n%cx,dx, variable boundaries (of x)\n%c,d fixed boundaries (of y) that form a rectangular space with a and b\n%boundaries.\nt=rand(1,n);\nu=rand(1,n);\nx=a+t.*(b-a);\t\t\t%extremos a,b fijos\ny=c+u.*(d-c);\t\t\t%extremos c,d variabales\n\ncont=0;\ns=0;\n\nfor i=1:n\n if (y(i)>feval(cx,x(i))&&y(i)=0 & t=tf-tp2 & t=0 & t=tp1 & t=tf-tp2 & t=0 & t=tp1 & t=tf-tp2 & t\n% Copyright © 2010,2014 University of Oxford\n% Version: 0.2.1\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, 1) ;\nnargoutchk(0, 3) ;\n\n% squeeze SCIMAT variables, if necessary\nscimat = scimat_squeeze(scimat);\n\n% extract linear indices of voxels in the segmentation\nidx = find(scimat.data);\n\n% get volume size\nsz = size(scimat.data);\n\n% convert linear index to multiple subscripts\n[ir, ic, iz] = ind2sub(sz, idx);\n\n% convert indices to real world coordinates\nx = scimat_index2world([ir, ic, iz], scimat);\n\n% compute centroid\nm = mean(x);\n\n% compute PCA\n[v, d] = pts_pca(x');\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/scimat_pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7339327432900977}} {"text": "function varargout=gabor3_fwb(aspect,theta,bw,psi,sigma,sz)\n% Returns 3D gabor filter.\n% gb=GABOR_FWB(aspect,theta,bw,psi,sigma,sz)\n%\n% [aspecta, aspectb]\n% = 2 element array giving aspect ratios for 2 minor axis\n% (eg: [0.5, 1], for major < minoraxis1, major = minoraxi2)\n% [theta,phi]\n% = yaw and pitch of major axis (0-2*pi)\n% roll isn't implemented, sorry.\n% bw = spatial bandwidth in pixels (decreasing fine detail,), (eg: >=1)\n% scales the frequency of the cosine modulation\n% psi, = phase shift, [optional, default: 0]\n% sigma = scales the falloff of the gaussian, (must be >=2) [default: = bw]\n% + can set to 'auto' to maintain default functionality\n% [x y z] = size of gabor kernel created [optional, size set automatically\n% to 3 standard deviations of gaussian kernel]\n\n% Frederick Bryan adapted from gabor_fn.m\n% July 2013\n% Vanderbilt Univ\n\n% To Do\n% implement roll:\n% This isn't hard as far as the meshgrid goes. All that needs to be done for that is to\n% uncomment the appropriate lines. I just didn't want to figure out the math\n% for the auto-sizing option. (if nargin < 6)\n%\n\n% handle mandatory args\nif numel(aspect) ~= 2;\n error('1st argument (aspect) must be 2 element array');\nend\nif numel(theta) ~=2;\n error('2nd argument ([theta,phi]) must be 2 element array');\nend\n\n% handle optional inputs\nif nargin<4\n psi = [0 0];\nend\nif nargin<5\n sigma = 'auto';\nend\n% allow 'auto' sizing of guassian kernel\nif strcmp(sigma,'auto');\n sigma = bw;\nend\nif nargin<6\n % figure out size\n phi = theta(2);\n theta = theta(1);\n len1 = 3*sigma; % length along theta direction\n len2 = len1/aspect(1);\n len3 = len1/aspect(2);\n sz(1) = (len1*cos(theta)+len2*sin(theta)); % column/x dimension\n sz(2) = (len1*sin(theta)+len2*cos(theta)); % row/y direction\n sz(1) = round(sz(1)*cos(phi)+len3*sin(phi));\n sz(2) = round(sz(2));\n sz(3) = round(sz(1)*sin(phi)+len3*cos(phi));\nend\n\n% handle incorrectly given optional args\n\nif length(sz)<2; % allow just one number to be given for size\n sz(2) = sz(1);\n sz(3) = sz(1);\nend\n% keyboard;\nsx = sz(1);\nsy = sz(2);\nsz = sz(3);\n\n% figured out size above, now make matrix of points\n[x y z]=meshgrid(-sx:sx, sy:-1:-sy, -sz:sz); % note that y goes backwards\n\n% rotate reference frame to point in theta direction\n% http://en.wikipedia.org/wiki/Rotation_matrix\n% yaw - rotation about z\nxp = x*cos(theta)+y*sin(theta);\nyp = -x*sin(theta)+y*cos(theta);\nzp = z;\n% pitch - rotation about y\nxp = xp*cos(phi)-zp*sin(phi);\nyp = yp;\nzp = xp*sin(phi)+zp*cos(phi);\n% % roll - rotation about x - unimplemented, requires \"roll\" angle\n% xp = xp;\n% yp = yp*cos(roll) + zp*sin(roll);\n% zp = -yp*sin(roll) + zp*cos(roll);\n\n% create gaussian pointing in theta direction with size determined by\n% aspect ration\nsigmajor = sigma;\nsigminor1 = sigma/aspect(1);\nsigminor2 = sigma/aspect(2);\nh1 = exp(-(xp.^2/sigmajor^2+yp.^2/sigminor1^2+zp.^2/sigminor2^2));\n\n% multiply by cosine with appropriate bw\nF=1/bw; % Frequency\nh2 = cos(2*pi*(F*xp)+psi);\n\ng = h1.*h2;\n\nif nargout>0\n varargout{1} = g;\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/42557-2d-and-3d-gabor-filter-creators/gabor3_fwb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7339283668118322}} {"text": "function [ errors ] = test_operators( )\n\nerrors = 0;\n\nerrors = errors + test_fourier_basis_ring();\nerrors = errors + test_fourier_basis_ring_advanced();\n\n%errors = errors + test_translate();\nerrors = errors + test_modulate();\n\nerrors = errors + test_gwft();\nerrors = errors + test_gft();\nerrors = errors + test_ngwft();\n\nerrors = errors + test_divgradient();\nerrors = errors + test_gradient();\nerrors = errors + test_gradient2();\nerrors = errors + test_gradient_mat();\n\nerrors = errors + test_directed();\nerrors = errors + test_advection();\n\nerrors = errors + test_div();\nerrors = errors + test_div2();\nerrors = errors + test_div3();\nerrors = errors + test_laplacian();\n\nerrors = errors + test_kron_reduction();\n\n\n\nend\n\nfunction s = eigvec_ring(input,N)\ns = zeros(N,numel(input));\nn = (0:(N-1))';\nfor ind = 1:numel(input)\n if mod(input(ind),2) % odd\n s(:,ind) = 1/sqrt(N)*exp(2*pi*1i*(N-(input(ind)+1)/2)*n/N);\n else % even \n s(:,ind) = 1/sqrt(N)*exp(pi*1i*input(ind)*n/N); \n end\nend\n\nend\n\nfunction s = eigval_ring(input,N)\ns = zeros(size(input));\nfor ind = 1:numel(input)\n if mod(input(ind),2) % odd\n s(ind) = 1-cos(pi * (input(ind)+1)/N );\n else % even \n s(ind) = 1-cos(pi * (input(ind))/N );\n end\nend\n\nend\n\nfunction errors = test_fourier_basis_ring_advanced()\nerrors = 0;\nN = 10;\ne = 2*eigval_ring(0:N-1,N)';\nU = eigvec_ring(0:N-1,N);\nG = gsp_ring(N);\nG = gsp_compute_fourier_basis(G);\nerrors = errors +gsp_assert_test(G.e,e,1e-14,'test ring eigenvalues N=10');\nerrors = errors +gsp_assert_test(G.U,U,1e-14,'test ring eigenvector N=10');\n\nN = 11;\ne = 2*eigval_ring(0:N-1,N)';\nU = eigvec_ring(0:N-1,N);\nG = gsp_ring(N);\nG = gsp_compute_fourier_basis(G);\nerrors= errors +gsp_assert_test(G.e,e,1e-14,'test ring eigenvalues N=11');\nerrors = errors +gsp_assert_test(G.U,U,1e-14,'test ring eigenvector N=11');\n\nend\n\n\nfunction errors = test_laplacian()\nerrors = 0;\nN = 10;\nG = gsp_path(N);\n\n\nx = rand(N,1);\n\ny1 = G.L*x;\ny2 = -laplacianx_op(x);\n\n\n\nif norm(y1-y2)/norm(y1)>10e-10;\n errors = errors +1;\n norm(y1-y2)/norm(y1)\n warning('OPERATOR: Error in laplacian test 1')\n\nelse\n fprintf('OPERATOR: laplacian 1 ok\\n');\nend\n\n\nend\n\n\nfunction errors = test_div()\nerrors = 0;\nN = 10;\nG = gsp_path(N);\nG = gsp_adj2vec(G);\n\nx = rand(N-1,1);\n\ny1 = gsp_div(G,x);\ny2 = -div_op1d([x;0]);\n\n\n\nif norm(y1-y2)/norm(y1)>10e-10;\n errors = errors +1;\n norm(y1-y2)/norm(y1)\n warning('OPERATOR: Error in div test 1')\n\nelse\n fprintf('OPERATOR: div 1 ok\\n');\nend\n\n\nend\n\n\n\nfunction errors = test_div2()\nerrors = 0;\nN = 10;\nG = gsp_sensor(N);\nG = gsp_adj2vec(G);\n\nM = 5;\n\nx = rand(N,M);\n\nt = gsp_grad(G,x);\n\ny1 = gsp_div(G,t);\ny2 = gsp_div_old(G,t);\n\n\n\nif norm(y1(:)-y2(:))/norm(y1(:))>10e-10;\n errors = errors +1;\n norm(y1(:)-y2(:))/norm(y1(:))\n warning('OPERATOR: Error in div test 2')\n\nelse\n fprintf('OPERATOR: div 2 ok\\n');\nend\n\n\nend\n\nfunction errors = test_div3()\nerrors = 0;\nN = 10;\nG = gsp_sensor(N);\nG = gsp_adj2vec(G);\n\nM = 5;\n\nx = rand(N,M);\n\nt = gsp_grad(G,x);\n\ny1 = gsp_div(G,t);\n\ny2 = zeros(N,M);\nfor ii = 1:M\n y2(:,ii) = gsp_div_old(G,t(:,ii));\nend\n\n\n\nif norm(y1(:)-y2(:))/norm(y1(:))>10e-10;\n errors = errors +1;\n norm(y1(:)-y2(:))/norm(y1(:))\n warning('OPERATOR: Error in div test 3')\n\nelse\n fprintf('OPERATOR: div 3 ok\\n');\nend\n\n\nend\n\n\n\nfunction errors = test_gradient()\nerrors = 0;\nN = 50;\nG = gsp_path(N);\nG = gsp_adj2vec(G);\n\nx = rand(N,1);\n\ny1 = gsp_grad(G,x);\ny2 = gradient_op1d(x);\n\n\n\nif norm(y1-y2(1:(end-1)))/norm(y1)>10e-10;\n errors = errors +1;\n norm(y1-y2(1:(end-1)))/norm(y1)\n warning('OPERATOR: Error in gradient test 1')\n\nelse\n fprintf('OPERATOR: gradient 1 ok\\n');\nend\n\n\nend\n\nfunction errors = test_gradient2()\nerrors = 0;\nN = 50;\nG = gsp_sensor(N);\nG = gsp_adj2vec(G);\n\nM = 5;\n\nx = rand(N,M);\n\ny1 = gsp_grad(G,x);\n\ny2 = zeros(length(G.v_in),M);\nfor ii = 1:M\n y2(:,ii) = gsp_grad(G,x(:,ii));\nend\n\n\n\nif norm(y1(:)-y2(:))/norm(y1(:))>10e-10;\n errors = errors +1;\n norm(y1(:)-y2(:))/norm(y1(:))\n warning('OPERATOR: Error in gradient test 2')\n\nelse\n fprintf('OPERATOR: gradient 2 ok\\n');\nend\n\n\nend\n\nfunction errors = test_gradient_mat()\nerrors = 0;\nN = 50;\nG = gsp_sensor(N);\nG = gsp_adj2vec(G);\n\n\nx = rand(N,1);\n\ny1 = gsp_grad(G,x);\n\nD = gsp_grad_mat(G);\n\n\ny2 = D*x;\n\n\n\nif norm(y1(:)-y2(:))/norm(y1(:))>10e-10;\n errors = errors +1;\n norm(y1(:)-y2(:))/norm(y1(:))\n warning('OPERATOR: Error in gradient mat test')\n\nelse\n fprintf('OPERATOR: gradient mat ok\\n');\nend\n\n\nend\n\n\nfunction errors = test_directed()\nerrors = 0;\n\ntry\n \n G = gsp_sensor(50);\n \n Gd = gsp_assign_rand_direction(G,.5);\n Gd = gsp_adj2vec(Gd);\n \n fprintf('OPERATOR: directed ok\\n');\ncatch\n errors = errors + 1;\n warning('OPERATOR: Error directed test')\nend\n\nend\n\nfunction errors = test_advection()\nerrors = 0;\nG = gsp_sensor();\n\nGd = gsp_assign_rand_direction(G,.5);\nGd = gsp_adj2vec(Gd);\n\n\nW = diag(diag(Gd.Adv)) - Gd.Adv';\n\n\nerr = norm(Gd.W-W,'fro')/norm(Gd.W,'fro');\n\nif err>1e-10;\n errors = errors +1;\n err\n warning('OPERATOR: Error advection test')\n\nelse\n fprintf('OPERATOR: advection ok\\n');\nend\n\nend\n\n\n\n\n\nfunction errors = test_divgradient()\nerrors = 0;\nN = 50;\nG = gsp_sensor(N);\nG = gsp_adj2vec(G);\n\nx = rand(N,1);\n\ny1 = gsp_div(G,gsp_grad(G,x));\ny2 = G.L*x;\n\n\n\nif norm(y1-y2)/norm(y1)>10e-10\n errors = errors +1;\n norm(y1-y2)/norm(y1)\n warning('OPERATOR: Error in divgradient test 1')\n\nelse\n fprintf('OPERATOR: divgradient 1 ok\\n');\nend\n\nif norm(full(G.Diff'*G.Diff-G.L))>10e-10;\n errors = errors +1;\n norm(full(G.Diff'*G.Diff-G.L))\n warning('OPERATOR: Error in divgradient test 2')\n\nelse\n fprintf('OPERATOR: divgradient 2 ok\\n');\nend\n\n\nG = gsp_create_laplacian(G,'normalized');\nG = gsp_adj2vec(G);\n\ny1 = gsp_div(G,gsp_grad(G,x));\ny2 = G.L*x;\n\n\n\nif norm(y1-y2)/norm(y1)>10e-10\n errors = errors +1;\n norm(y1-y2)/norm(y1)\n warning('OPERATOR: Error in divgradient test 3')\n\nelse\n fprintf('OPERATOR: divgradient 3 ok\\n');\nend\n\nif norm(full(G.Diff'*G.Diff-G.L))>10e-10;\n errors = errors +1;\n norm(full(G.Diff'*G.Diff-G.L))\n warning('OPERATOR: Error in divgradient test 3')\n\nelse\n fprintf('OPERATOR: divgradient 3 ok\\n');\nend\n\n\nend\n\nfunction errors = test_fourier_basis_ring()\nerrors = 0;\nN = 50;\nG = gsp_ring(N);\nG = gsp_compute_fourier_basis(G);\n\n\n\nif sum(diff(G.e) < -1e-10)\n errors = errors +1;\n warning('OPERATOR: Error in the Fourier test 1')\n\nelse\n fprintf('OPERATOR: Fourier 1 ok\\n');\nend\n\nif sum(norm(G.L-G.U*diag(G.e)*G.U','fro') < -1e-10)\n errors = errors +1;\n warning('OPERATOR: Error in the Fourier test 2')\n\nelse\n fprintf('OPERATOR: Fourier 2 ok\\n');\nend\n\nN = 51;\nG = gsp_ring(N);\nG = gsp_compute_fourier_basis(G);\n\nif sum(norm(G.L-G.U*diag(G.e)*G.U','fro') < -1e-10)\n errors = errors +1;\n warning('OPERATOR: Error in the Fourier test 2')\n\nelse\n fprintf('OPERATOR: Fourier 2 ok\\n');\nend\n\n\nend\n\nfunction errors = test_translate()\nerrors = 0;\nN = 50;\nk = 10;\nG = gsp_ring(N);\nG = gsp_compute_fourier_basis(G);\n\nf = rand(N,1);\n\nft = gsp_translate(G,f,k);\n\nif norm(ft-circshift(f,[-k+1,0]))<1e-10\n fprintf('OPERATOR: translate ok\\n');\nelse\n errors = errors +1;\n warning('OPERATOR: Error in the translate test')\n\nend\n\nend\n\nfunction errors = test_modulate()\nerrors = 0;\nN = 30;\nk = 10;\nG = gsp_ring(N);\nG = gsp_compute_fourier_basis(G);\n\nf = rand(N,1);\n\n% compute the ordering vectors\nv = gsp_classic2graph_eig_order( N );\niv = 1:N;\niv(v) = iv;\n\nft = gsp_modulate(G,f,iv(k));\n\nfthat(v) = gsp_gft(G,ft);\nft2hat(v) = gsp_gft(G,f); % back into the classical ordering\nft2hat = circshift(ft2hat,[0,-k+1]); % circshift\n\n\nif norm(fthat-ft2hat)<1e-10\n fprintf('OPERATOR: modulate ok\\n');\nelse\n errors = errors +1;\n warning('OPERATOR: Error in the modulate test')\n\nend\n\nend\n\n\nfunction errors = test_kron_reduction()\n\nerrors = 0;\n\ntry\n figure(100)\n N = 64;\n param.distribute = 1;\n param.Nc = 5;\n param.regular = 1;\n G = gsp_sensor(N,param);\n ind = 1:2:N;\n Gnew = gsp_kron_reduce( G,ind );\n subplot(121)\n gsp_plot_graph(G);\n title('Original graph');\n subplot(122)\n gsp_plot_graph(Gnew);\n title('Kron reduction');\n\n close(100)\n\n fprintf('OPERATOR: KRON ok\\n');\ncatch\n errors = errors +1;\n warning('OPERATOR: Error in the KRON test')\n\nend\n\ngsp_reset_seed(1)\n G1 = gsp_kron_reduce( G,ind );\n gsp_reset_seed(1)\n Lnew= gsp_kron_reduce_old( G.L,ind );\nif norm(Lnew-G1.L,'fro')<1e-10\n fprintf('OPERATOR: KRON ok\\n');\nelse\n errors = errors +1;\n norm(G2.W-G1.W,'fro')\n warning('OPERATOR: Error in the KRON test')\nend\n\nend\n\n\nfunction errors = test_gft()\n\nN = 30;\nG = gsp_sensor(N);\nG = gsp_compute_fourier_basis(G);\n\nX = rand(N,20,10);\n\nXhat1 = gsp_gft(G,X);\n\nXhat2 = zeros(N,20,10);\nfor ii = 1:10\n Xhat2(:,:,ii) = gsp_gft(G, X(:,:,ii)); \nend\n\nerrors = gsp_assert_test(Xhat1,Xhat2,1e-10,'GFT');\n\nend", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/test_gsptoolbox/test_operators.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530198, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7339085327865615}} {"text": "function y = load_signal(name, n, options)\n\n% load_signal - load a 1D signal\n%\n% y = load_signal(name, n, options);\n%\n% name is a string that can be :\n% 'regular' (options.alpha gives regularity)\n% 'step', 'rand',\n% 'gaussiannoise' (options.sigma gives width of filtering in pixels),\n% [natural signals]\n% 'tiger', 'bell', 'bird'\n% [WAVELAB signals]\n% 'HeaviSine', 'Bumps', 'Blocks',\n% 'Doppler', 'Ramp', 'Cusp', 'Sing', 'HiSine',\n% 'LoSine', 'LinChirp', 'TwoChirp', 'QuadChirp',\n% 'MishMash', 'WernerSorrows' (Heisenberg),\n% 'Leopold' (Kronecker), 'Piece-Regular' (Piece-Wise Smooth),\n%\t'Riemann','HypChirps','LinChirps', 'Chirps', 'Gabor'\n%\t'sineoneoverx','Cusp2','SmoothCusp','Gaussian'\n%\t'Piece-Polynomial' (Piece-Wise 3rd degree polynomial)\n\nif nargin<2\n n = 1024;\nend\noptions.null = 0;\nif isfield(options, 'alpha')\n alpha = options.alpha;\nelse\n alpha = 2;\nend\n\noptions.rep = '';\nswitch lower(name)\n case 'regular'\n y = gen_signal(n,alpha);\n case 'step'\n y = linspace(0,1,n)>0.5;\n case 'stepregular'\n y = linspace(0,1,n)>0.5; y=y(:);\n a = gen_signal(n,2); a = a(:);\n a = rescale(a,-0.1,0.1);\n y = y+a;\n case 'gaussiannoise'\n % filtered gaussian noise\n y = randn(n,1);\n if isfield(options, 'sigma')\n sigma = options.sigma; % variance in number of pixels\n else\n sigma = 20;\n end\n m = min(n, 6*round(sigma/2)+1);\n h = compute_gaussian_filter(m,sigma/(4*n),n);\n options.bound = 'per';\n y = perform_convolution(y,h, options);\n case 'rand'\n if isfield(options, 'p1')\n p1 = options.p1;\n else\n c = 10;\n p1 = 1:c; p1 = p1/sum(p1);\n end\n p1 = p1(:); c = length(p1);\n if isfield(options, 'p2')\n p2 = options.p2;\n else\n if isfield(options, 'evol')\n evol = options.evol;\n else\n evol = 0;\n end\n p2 = p1(:) + evol*(rand(c,1)-0.5);\n p2 = max(p2,0); p2 = p2/sum(p2);\n end\n y = zeros(n,1);\n for i=1:n\n a = (i-1)/(n-1);\n p = a*p1+(1-a)*p2; p = p/sum(p);\n y(i) = rand_discr(p, 1);\n end\n case 'bird'\n [y,fs] = load_sound([name '.wav'], n, options);\n case 'tiger'\n [y,fs] = load_sound([name '.au'], n, options);\n case 'bell'\n [y,fs] = load_sound([name '.wav'], n, options);\n otherwise\n y = MakeSignal(name,n);\nend\n\ny = y(:);\n\nfunction y = gen_signal(n,alpha)\n\n% gen_signal - generate a 1D C^\\alpha signal of length n.\n%\n% y = gen_signal(n,alpha);\n%\n% The signal is scaled in [0,1].\n% \n% Copyright (c) 2003 Gabriel Peyr?\n\nif nargin<2\n alpha = 2;\nend\n\ny = randn(n,1); \nfy = fft(y);\nfy = fftshift(fy);\n% filter with |omega|^{-\\alpha}\nh = (-n/2+1):(n/2);\nh = (abs(h)+1).^(-alpha-0.5);\nfy = fy.*h';\nfy = fftshift(fy);\ny = real( ifft(fy) );\n\ny = (y-min(y))/(max(y)-min(y));\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction sig = MakeSignal(Name,n)\n% MakeSignal -- Make artificial signal\n% Usage\n% sig = MakeSignal(Name,n)\n% Inputs\n% Name string: 'HeaviSine', 'Bumps', 'Blocks',\n% 'Doppler', 'Ramp', 'Cusp', 'Sing', 'HiSine',\n% 'LoSine', 'LinChirp', 'TwoChirp', 'QuadChirp',\n% 'MishMash', 'WernerSorrows' (Heisenberg),\n% 'Leopold' (Kronecker), 'Piece-Regular' (Piece-Wise Smooth),\n%\t 'Riemann','HypChirps','LinChirps', 'Chirps', 'Gabor'\n%\t 'sineoneoverx','Cusp2','SmoothCusp','Gaussian'\n%\t 'Piece-Polynomial' (Piece-Wise 3rd degree polynomial)\n% n desired signal length\n% Outputs\n% sig 1-d signal\n%\n% References\n% Various articles of D.L. Donoho and I.M. Johnstone\n%\nif nargin > 1,\n t = (1:n) ./n;\nend\nName = lower(Name);\nif strcmp(Name,'heavisine'),\n sig = 4.*sin(4*pi.*t);\n sig = sig - sign(t - .3) - sign(.72 - t);\nelseif strcmp(Name,'bumps'),\n pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];\n hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2];\n wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005];\n sig = zeros(size(t));\n for j =1:length(pos)\n sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;\n end\nelseif strcmp(Name,'blocks'),\n pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];\n hgt = [4 (-5) 3 (-4) 5 (-4.2) 2.1 4.3 (-3.1) 2.1 (-4.2)];\n sig = zeros(size(t));\n for j=1:length(pos)\n sig = sig + (1 + sign(t-pos(j))).*(hgt(j)/2) ;\n end\nelseif strcmp(Name,'doppler'),\n sig = sqrt(t.*(1-t)).*sin((2*pi*1.05) ./(t+.05));\nelseif strcmp(Name,'ramp'),\n sig = t - (t >= .37);\nelseif strcmp(Name,'cusp'),\n sig = sqrt(abs(t - .37));\nelseif strcmp(Name,'sing'),\n k = floor(n * .37);\n sig = 1 ./abs(t - (k+.5)/n);\nelseif strcmp(Name,'hisine'),\n sig = sin( pi * (n * .6902) .* t);\nelseif strcmp(Name,'losine'),\n sig = sin( pi * (n * .3333) .* t);\nelseif strcmp(Name,'linchirp'),\n sig = sin(pi .* t .* ((n .* .500) .* t));\nelseif strcmp(Name,'twochirp'),\n sig = sin(pi .* t .* (n .* t)) + sin((pi/3) .* t .* (n .* t));\nelseif strcmp(Name,'quadchirp'),\n sig = sin( (pi/3) .* t .* (n .* t.^2));\nelseif strcmp(Name,'mishmash'), % QuadChirp + LinChirp + HiSine\n sig = sin( (pi/3) .* t .* (n .* t.^2)) ;\n sig = sig + sin( pi * (n * .6902) .* t);\n sig = sig + sin(pi .* t .* (n .* .125 .* t));\nelseif strcmp(Name,'wernersorrows'),\n sig = sin( pi .* t .* (n/2 .* t.^2)) ;\n sig = sig + sin( pi * (n * .6902) .* t);\n sig = sig + sin(pi .* t .* (n .* t));\n pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];\n hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2];\n wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005];\n for j =1:length(pos)\n sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;\n end\nelseif strcmp(Name,'leopold'),\n sig = (t == floor(.37 * n)/n); % Kronecker\nelseif strcmp(Name,'riemann'),\n sqn = round(sqrt(n));\n sig = t .* 0; % Riemann's Non-differentiable Function\n sig((1:sqn).^2) = 1. ./ (1:sqn);\n sig = real(ifft(sig));\nelseif strcmp(Name,'hypchirps'), % Hyperbolic Chirps of Mallat's book\n alpha\t= 15*n*pi/1024;\n beta = 5*n*pi/1024;\n t \t= (1.001:1:n+.001)./n;\n f1 = zeros(1,n);\n f2 = zeros(1,n);\n f1 \t= sin(alpha./(.8-t)).*(0.1>',Name))\n disp('Allowable Names are:')\n disp('HeaviSine'),\n disp('Bumps'),\n disp('Blocks'),\n disp('Doppler'),\n disp('Ramp'),\n disp('Cusp'),\n disp('Crease'),\n disp('Sing'),\n disp('HiSine'),\n disp('LoSine'),\n disp('LinChirp'),\n disp('TwoChirp'),\n disp('QuadChirp'),\n disp('MishMash'),\n disp('WernerSorrows'),\n disp('Leopold'),\n disp('Sing'),\n disp('HiSine'),\n disp('LoSine'),\n disp('LinChirp'),\n disp('TwoChirp'),\n disp('QuadChirp'),\n disp('MishMash'),\n disp('WernerSorrows'),\n disp('Leopold'),\n disp('Riemann'),\n disp('HypChirps'),\n disp('LinChirps'),\n disp('Chirps'),\n disp('sineoneoverx'),\n disp('Cusp2'),\n disp('SmoothCusp'),\n disp('Gabor'),\n disp('Piece-Regular');\n disp('Piece-Polynomial');\n disp('Gaussian');\nend\n\n%\n% Originally made by David L. Donoho.\n% Function has been enhanced.\n \n \n% \n% Part of WaveLab Version 802\n% Built Sunday, October 3, 1999 8:52:27 AM\n% This is Copyrighted Material\n% For Copying permissions see COPYING.m\n% Comments? e-mail wavelab@stat.stanford.edu\n% \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_wavelets/toolbox/load_signal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.7338579943201976}} {"text": "function line_fekete_rule_test02 ( m )\n\n%*****************************************************************************80\n%\n%% LINE_FEKETE_RULE_TEST02 seeks Fekete points in [-1,+1].\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 March 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% L Bos, N Levenberg,\n% On the calculation of approximate Fekete points: the univariate case,\n% Electronic Transactions on Numerical Analysis,\n% Volume 30, pages 377-397, 2008.\n%\n% Parameters:\n%\n% Input, integer M, the dimension of the polynomial space.\n%\n if ( nargin < 1 )\n m = 5;\n end\n n = 1000;\n a = -1.0;\n b = +1.0;\n x = linspace ( a, b, n );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LINE_FEKETE_RULE_TEST02:\\n' );\n fprintf ( 1, ' Seek Fekete points in [%g,%g]\\n', a, b );\n fprintf ( 1, ' using %d equally spaced sample points\\n', n );\n fprintf ( 1, ' for polynomials of degree M = %d\\n', m );\n fprintf ( 1, ' with the Chebyshev basis\\n' );\n fprintf ( 1, ' and weight 1/sqrt(1-x^2).\\n' );\n\n [ nf, xf, wf, vf ] = line_fekete_chebyshev ( m, a, b, n, x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NF = %d\\n', nf );\n r8vec_print ( nf, xf, ' Estimated Fekete points XF:' );\n\n yf = ones ( size ( xf ) );\n plot ( xf, yf, '*' );\n title ( 'Estimated Fekete points' );\n grid on\n filename = 'line_fekete_rule_test02.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saved plotfile as \"%s\"\\n', filename );\n\n wf_sum = sum ( wf(1:nf) );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sum(WF) = %g\\n', wf_sum );\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/line_fekete_rule/line_fekete_rule_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.7338579898386217}} {"text": "%% Unimodal ODF Shapes\n%\n%%\n% Also take a look at the page .\n%\n% In order to control the shape of unimodal ODF\n% The classes @SO3Kernel and @S2Kernel are needed in MTEX to define the \n% specific form of unimodal and fibre symmetric ODFs. It has to be passed \n% as an argument when calling the methods or\n% . \n%\n% A kernel is defined by specifying its name and its free parameter.\n% Alternatively one can also specify the halfwidth of the kernel. Below you\n% find a list of some important SO3Kernel functions supported by MTEX.\n\npsi{1} = SO3AbelPoissonKernel(0.79);\npsi{2} = SO3DeLaValleePoussinKernel(13);\npsi{3} = SO3BumpKernel(35*degree);\npsi{4} = SO3DirichletKernel(3);\npsi{5} = SO3vonMisesFisherKernel(7.5);\npsi{6} = SO3GaussWeierstrassKernel(0.07);\npsi{7} = fibreVonMisesFisherKernel(7.2);\npsi{8} = SO3SquareSingularityKernel(0.72);\n\n\n%% \n% Lets visualize these kernel functions as one dimensional sections through\n% the orientation space\n\n% the kernel on SO(3)\nclose; \nfigure('position',[100,100,1000,450])\nhold all\nfor i = 1:numel(psi)\n plot(psi{i},'DisplayName',class(psi{i}));\nend\nhold off\nlegend(gca,'show','Location','eastoutside')\n\n\n%%\n% one dimensional sections through the corresponding PDF\n\nclose; figure('position',[100,100,1000,450])\nhold all\nfor i = 1:numel(psi)\n plot(psi{i}.radon,'symmetric','DisplayName',class(psi{i}),'linewidth',2);\nend\nhold off\n\nylim([-5,20])\n\nlegend(gca,'show','Location','eastoutside')\n%%\n% the Fourier coefficients of the kernels\n\nclose; figure('position',[100,100,500,450])\nhold all\nfor i = 1:numel(psi)\n plotSpektra(psi{i},'bandwidth',32,'linewidth',2,'DisplayName',class(psi{i}));\nend\nhold off\nlegend(gca,'show')\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/ODFAnalysis/ODFShapes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.8633916082162402, "lm_q1q2_score": 0.733857970444748}} {"text": "function value = r4_binom ( n, m )\n\n%*****************************************************************************80\n%\n%% R4_BINOM evaluates the binomial coefficient using R4 arithmetic.\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, integer N, M, the arguments.\n%\n% Output, real VALUE, the binomial coefficient.\n%\n persistent sq2pil\n persistent bilnmx\n persistent fintmx\n\n sq2pil = 0.91893853320467274;\n\n if ( isempty ( bilnmx ) )\n bilnmx = log ( r4_mach ( 2 ) );\n fintmx = 0.9 / r4_mach ( 3 );\n end\n\n if ( n < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_BINOM - Fatal error!\\n' );\n fprintf ( 1, ' N < 0.\\n' );\n error ( 'R4_BINOM - Fatal error!' )\n end\n\n if ( m < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_BINOM - Fatal error!\\n' );\n fprintf ( 1, ' M < 0.\\n' );\n error ( 'R4_BINOM - Fatal error!' )\n end\n\n if ( n < m )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_BINOM - Fatal error!\\n' );\n fprintf ( 1, ' N < M.\\n' );\n error ( 'R4_BINOM - Fatal error!' )\n end\n\n k = min ( m, n - m );\n\n if ( k <= 20 && k * log ( max ( n, 1 ) ) <= bilnmx )\n\n value = 1.0;\n\n for i = 1 : k\n value = value * ( n - i + 1 ) / i;\n end\n\n else\n\n if ( k < 9 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_BINOM - Fatal error!\\n' );\n fprintf ( 1, ' Result overflows.\\n' );\n fprintf ( 1, ' N or M is too big.\\n' );\n error ( 'R4_BINOM - Fatal error!' )\n end\n\n xn = n + 1;\n xk = k + 1;\n xnk = n - k + 1;\n\n corr = r4_lgmc ( xn ) - r4_lgmc ( xk ) - r4_lgmc ( xnk );\n\n value = xk * log ( xnk / xk ) ...\n - xn * r4_lnrel ( - ( xk - 1.0 ) / xn ) ...\n - 0.5 * log ( xn * xnk / xk ) + 1.0 - sq2pil + corr;\n\n if ( bilnmx < value )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_BINOM - Fatal error!\\n' );\n fprintf ( 1, ' Result overflows.\\n' );\n fprintf ( 1, ' N or M is too big.\\n' );\n error ( 'R4_BINOM - Fatal error!' )\n end\n\n value = exp ( value );\n\n end\n\n if ( value < fintmx )\n value = r4_aint ( value + 0.5 );\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_binom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7338410516563268}} {"text": "function x = spm_invGcdf(F,h,l,tol)\n% Inverse Cumulative Distribution Function (CDF) of Gamma distribution\n% FORMAT x = spm_invGcdf(p,h,l,tol)\n%\n% F - CDF (lower tail p-value)\n% h - Shape parameter (h>0)\n% l - Scale parameter (l>0)\n% x - Gamma ordinates at which CDF F(x)=F\n% tol - tolerance [default 10^-6]\n%__________________________________________________________________________\n%\n% spm_invGcdf implements the inverse Cumulative Distribution Function\n% for Gamma distributions.\n%\n% Definition:\n%--------------------------------------------------------------------------\n% The Gamma distribution has shape parameter h and scale l, and is\n% defined for h>0 & l>0 and for x in [0,Inf) (See Evans et al., Ch18,\n% but note that this reference uses the alternative parameterisation of\n% the Gamma with scale parameter c=1/l)\n%\n% The Cumulative Distribution Function (CDF) F(x) is the probability\n% that a realisation of a Gamma random variable X has value less than\n% x. F(x)=Pr{X1;\nif sum(xa)>1 && any(any(diff(as(xa,:)),1))\n error('non-scalar args must match in size');\nend\n\n%-Computation - Undefined and special cases\n%--------------------------------------------------------------------------\n%-Initialise result to zeros\nx = zeros(rs);\n\n%-Only defined for F in [0,1] & strictly positive h & l.\n% Return NaN if undefined.\nmd = ( F>=0 & F<=1 & h>0 & l>0 );\nif any(~md(:))\n x(~md) = NaN;\n warning('Returning NaN for out of range arguments');\nend\n\n%-Special cases: x=0 when F=0, x=Inf when F=1\nx(md & F==1) = Inf;\n\n%-Compute where defined & not special case\n%--------------------------------------------------------------------------\nQ = find( md & F>0 & F<1 );\nif isempty(Q), return, end\nif xa(1), FQ=F(Q); FQ=FQ(:); else FQ=F*ones(length(Q),1); end\nif xa(2), hQ=h(Q); hQ=hQ(:); else hQ=h*ones(length(Q),1); end\nif xa(3), lQ=l(Q); lQ=lQ(:); else lQ=l*ones(length(Q),1); end\n%-?Q=?Q(:) stuff is to avoid discrepant orientations of vector arguments!\n\n%-Compute initial interval estimates [0,mean] & Grow to encompass F(QF);\n%--------------------------------------------------------------------------\na = zeros(length(Q),1);\nb = hQ./(2*lQ);\nQQ = 1:length(Q);\nwhile ~isempty(QQ)\n b(QQ) = 2*b(QQ);\n QQ = find(spm_Gcdf(b,hQ,lQ) < FQ);\nend\n\n%-Interval bisection\n%--------------------------------------------------------------------------\nfa = spm_Gcdf(a,hQ,lQ)-FQ;\nfb = spm_Gcdf(b,hQ,lQ)-FQ;\ni = 0;\nxQ = a+(b-a)/2;\nQQ = 1:length(Q);\n\nwhile ~isempty(QQ) && i 0;\n a(QQ(mQQ)) = xQ(QQ(mQQ)); fa(QQ(mQQ)) = fxQQ(mQQ);\n b(QQ(~mQQ)) = xQ(QQ(~mQQ)); fb(QQ(~mQQ)) = fxQQ(~mQQ);\n xQ(QQ) = a(QQ) + (b(QQ)-a(QQ))/2;\n QQ = QQ( (b(QQ)-a(QQ))>tol );\n i = i+1;\nend\n\nif i==maxIt\n warning('convergence criteria not reached - maxIt reached');\nend\n\nx(Q) = xQ;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_invGcdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7338410414235763}} {"text": "function E = quaternion2EulXYZ(Q)\n% Euler/Tait-Bryan angles; x-y-z extrinsic convention\n%\n% Parameters\n% ------------\n% Q : 1 x 4 float vector\n% Quaternion\n%\n% Returns\n% ------------\n% E : 1 x 3 float vector \n% Euler angles equivalent of the quaternion (radian)\n% E(1) rotation about x, E(2) rotation about y, E(3) rotation about z\n% \nE = zeros(3,1);\nE(1) = atan2((2*(Q(1)*Q(2)+Q(3)*Q(4))), (1-2*(Q(2)^2+Q(3)^2)));\nE(2) = asin( 2*(Q(1)*Q(3)-Q(4)*Q(2)));\nE(3) = atan2((2*(Q(1)*Q(4)+Q(2)*Q(3))), (1-2*(Q(3)^2+Q(4)^2)));\nend\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/functions/simulink/model/quaternion2EulXYZ.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686201, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7338053819132085}} {"text": "function R = MatrixExp3(so3mat)\n% *** CHAPTER 3: RIGID-BODY MOTIONS ***\n% Takes a 3x3 so(3) representation of exponential coordinates.\n% Returns R in SO(3) that is achieved by rotating about omghat by theta \n% from an initial orientation R = I.\n% Example Input:\n% \n% clear; clc;\n% so3mat = [[0, -3, 2]; [3, 0, -1]; [-2, 1, 0]];\n% R = MatrixExp3(so3mat) \n% \n% Output:\n% R =\n% -0.6949 0.7135 0.0893\n% -0.1920 -0.3038 0.9332\n% 0.6930 0.6313 0.3481\n\nomgtheta = so3ToVec(so3mat);\nif NearZero(norm(omgtheta))\n R = eye(3);\nelse\n [omghat, theta] = AxisAng3(omgtheta);\n omgmat = so3mat / theta;\n R = eye(3) + sin(theta) * omgmat + (1 - cos(theta)) * omgmat * omgmat;\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/MatrixExp3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7337885437784056}} {"text": "function [ux,u,m] = applypca2(X)\n% [ux,u,m] = applypca(X)\n%\n% finds principal components of \n%\n% input: \n% x input data (each column is an input vector)\n%\n% output:\n% ux data projected onto pca (1st row=leading principal component)\n% u the orthogonal matrix with all principal components\n% m mean of the data\n%\n% You can recover the original data with\n% \n% xoriginal=u*ux+repmat(m,1,size(ux,2));\n%\n% See also pca\n%\n% copyright by Kilian Q. Weinberger, 2006\n\n% [u,v]=pca(X);\n[d,N] = size(X);\n\nm = mean(X,2);\nX = X - m*ones(1,N); % remove mean from data\n\ncc = cov(X',1); % compute covariance \n[cvv,cdd] = eig(cc); % compute eignvectors\n[zz,ii] = sort(diag(-cdd)); % sort according to eigenvalues\nu = cvv(:,ii); % pick leading eigenvectors\n\nux=u'*X;\n\n", "meta": {"author": "liangzheng06", "repo": "MARS-evaluation", "sha": "3a91bbc762fad7629fecde8c53e170742d3700f9", "save_path": "github-repos/MATLAB/liangzheng06-MARS-evaluation", "path": "github-repos/MATLAB/liangzheng06-MARS-evaluation/MARS-evaluation-3a91bbc762fad7629fecde8c53e170742d3700f9/utils/applypca2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871158, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7337885362140321}} {"text": "function g=comp_pchirp(L,n)\n%COMP_PCHIRP Compute periodic chirp\n% Usage: g=comp_pchirp(L,n);\n%\n% `pchirp(L,n)` returns a periodic, discrete chirp of length *L* that\n% revolves *n* times around the time-frequency plane in frequency. *n* must be\n% an integer number.\n%\n% This is a computational routine. Do not call it unless you have\n% verified the input parameters.\n\n% AUTHOR : Peter L. Søndergaard\n% TESTING: OK\n% REFERENCE: OK\n\nl= (0:L-1).';\nX = mod(mod(mod(n*l,2*L).*l,2*L)*(L+1),2*L);\ng = exp(pi*1i*X/L);\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_pchirp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8198933381139646, "lm_q1q2_score": 0.7336319245723418}} {"text": "function [A_hat E_hat iter] = exact_alm_rpca(D, lambda, tol, maxIter)\n\n% Oct 2009\n% This matlab code implements the augmented Lagrange multiplier method for\n% Robust PCA.\n%\n% D - m x n matrix of observations/data (required input)\n%\n% lambda - weight on sparse error term in the cost function\n%\n% tol - tolerance for stopping criterion.\n% - DEFAULT 1e-7 if omitted or -1.\n%\n% maxIter - maximum number of iterations\n% - DEFAULT 1000, if omitted or -1.\n% \n% Initialize A,E,Y,u\n% while ~converged \n% minimize\n% L(A,E,Y,u) = |A|_* + lambda * |E|_1 + + mu/2 * |D-A-E|_F^2;\n% Y = Y + \\mu * (D - A - E);\n% \\mu = \\rho * \\mu;\n% end\n%\n% Minming Chen, October 2009. Questions? v-minmch@microsoft.com ; \n% Arvind Ganesh (abalasu2@illinois.edu)\n%\n% Copyright: Perception and Decision Laboratory, University of Illinois, Urbana-Champaign\n% Microsoft Research Asia, Beijing\n\n% addpath PROPACK;\n\n[m n] = size(D);\n\nif nargin < 2\n lambda = 1 / sqrt(m);\nend\n\nif nargin < 3\n tol = 1e-7;\nelseif tol == -1\n tol = 1e-7;\nend\n\nif nargin < 4\n maxIter = 1000;\nelseif maxIter == -1\n maxIter = 1000;\nend\n\n% initialize\nY = sign(D);\n%norm_two = lansvd(Y, 1, 'L');\nnorm_two = svdex(Y, 1, struct('svd_solver','svds'));\nnorm_inf = norm( Y(:), inf) / lambda;\ndual_norm = max(norm_two, norm_inf);\nY = Y / dual_norm;\n\nA_hat = zeros( m, n);\nE_hat = zeros( m, n);\ndnorm = norm(D, 'fro');\ntolProj = 1e-6 * dnorm;\ntotal_svd = 0;\nmu = .5/norm_two; % this one can be tuned\nrho = 6; % this one can be tuned\n\niter = 0;\nconverged = false;\nstopCriterion = 1;\nsv = 5;\nsvp = sv;\n\n% excelly\ntemp_T = D - A_hat + (1/mu)*Y;\ntemp_E = max( temp_T - lambda/mu,0) + min( temp_T + lambda/mu,0); \n[U dummy dummy] = svdex(D - temp_E + (1/mu)*Y, 1, struct('svd_solver','svds'));\nwhile ~converged \n iter = iter + 1;\n \n % solve the primal problem by alternative projection\n primal_converged = false;\n primal_iter = 0;\n sv = sv + round(n * 0.1);\n while primal_converged == false\n \n temp_T = D - A_hat + (1/mu)*Y;\n temp_E = max( temp_T - lambda/mu,0) + min( temp_T + lambda/mu,0); \n \n [U diagS V] = svdex(D - temp_E + (1/mu)*Y, sv, struct('init',U(:,1)));\n % if choosvd(n, sv) == 1\n % [U S V] = lansvd(D - temp_E + (1/mu)*Y, sv, 'L');\n % else\n % [U S V] = svd(D - temp_E + (1/mu)*Y, 'econ');\n % end\n % diagS = diag(S);\n svp = length(find(diagS > 1/mu));\n if svp < sv\n sv = min(svp + 1, n);\n else\n sv = min(svp + round(0.05*n), n);\n end\n temp_A = U(:,1:svp)*diag(diagS(1:svp)-1/mu)*V(:,1:svp)'; \n \n if norm(A_hat - temp_A, 'fro') < tolProj && norm(E_hat - temp_E, 'fro') < tolProj\n primal_converged = true;\n end\n A_hat = temp_A;\n E_hat = temp_E;\n primal_iter = primal_iter + 1;\n total_svd = total_svd + 1;\n \n end\n \n Z = D - A_hat - E_hat; \n Y = Y + mu*Z;\n mu = rho * mu;\n \n %% stop Criterion \n stopCriterion = norm(Z, 'fro') / dnorm;\n if stopCriterion < tol\n converged = true;\n end \n \n disp(['Iteration' num2str(iter) ' #svd ' num2str(total_svd) ' r(A) ' num2str(svp)...\n ' |E|_0 ' num2str(length(find(abs(E_hat)>0)))...\n ' stopCriterion ' num2str(stopCriterion)]);\n \n if ~converged && iter >= maxIter\n disp('Maximum iterations reached') ;\n converged = 1 ; \n end\nend\n\nif nargin == 5\n fclose(fid);\nend\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/nmf/DRMF/exact_alm_rpca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7335766660569251}} {"text": "function determ = ris_determinant ( n )\n\n%*****************************************************************************80\n%\n%% RIS_DETERMINANT returns the determinant of the Ris matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real DETERM the determinant.\n%\n top = 1.0;\n for i = 1 : n\n for j = i + 1 : n\n top = top * ( 4 * ( i - j ) * ( i - j ) );\n end\n end\n\n bottom = 1.0;\n for i = 1 : n\n for j = 1 : n\n bottom = bottom * ( 3 + 2 * n - 2 * i - 2 * j );\n end\n end\n\n determ = top / bottom;\n\n return\nend\n", "meta": {"author": "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/ris_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7335766659507624}} {"text": "% Procedure to get nodal stresses using Extrapolation method\nfunction [sigma] = Extrapolation(stressGP)\n\n%--------------------------------------------------------------------------\n% Purpose : Extrapolating stress at Gaussian points to get nodal stress\n% values\n%\n% Synopsis : sigma = extrapolation(stressGP)\n% \n% Variable Description :\n% sigma - Stress at nodal points\n% stressGP - Stressat gaussian points\n%--------------------------------------------------------------------------\n% Extrapolation matrix obtained from Shape Functions\n% Stress points are at (-1,-1),(-1,1),(1,1),1,-1)\nexplmt = [1+sqrt(3)/2 -1/2 1-sqrt(3)/2 -1/2;\n -1/2 1-sqrt(3)/2 -1/2 1+sqrt(3)/2 ;\n 1-sqrt(3)/2 -1/2 1+sqrt(3)/2 -1/2; \n -1/2 1+sqrt(3)/2 -1/2 1-sqrt(3)/2 ] ;\n\nsigmax = explmt*stressGP(:,1) ;\nsigmay = explmt*stressGP(:,2) ;\nsigmaxy = explmt*stressGP(:,3) ;\n\nsigma = [sigmax sigmay sigmaxy]; \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/32519-stress-recovery/Stress Recovery/Extrapolation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535095, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.7335559049058434}} {"text": "function z = makebw(or,ph)\n% function z = makebw(or,ph)\n%\n% Create BWT wavelets\n% Version 1.2\n%\n% Arguments:\n% or: Orientation { -1 (DC), 0, 45, 90, 135 }\n% ph: Phase { 0 (odd), 90 (even) }\n%\n% Result:\n% z: The selected wavelet, or NaN if the parameters are not recognized\n%\n% Citation:\n% Willmore B, Prenger RJ, Wu MC and Gallant JL (2008). The Berkeley \n% Wavelet Transform: A biologically-inspired orthogonal wavelet transform.\n% Neural Computation 20:6, 1537-1564 \n%\n% The article is available at:\n% \n%\n% Copyright (c) 2008 Ben Willmore\n%\n% Permission is hereby granted, free of charge, to any person\n% obtaining a copy of this software and associated documentation\n% files (the \"Software\"), to deal in the Software without\n% restriction, including without limitation the rights to use,\n% copy, modify, merge, publish, distribute, sublicense, and/or sell\n% copies of the Software, and to permit persons to whom the\n% Software is furnished to do so, subject to the following\n% conditions:\n% \n% The above copyright notice and this permission notice shall be\n% included in all copies or substantial portions of the Software.\n% \n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n% OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n% HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n% WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n% OTHER DEALINGS IN THE SOFTWARE.\n\nz = nan;\n\nif (or==-1)\n z = ones(3,3)/sqrt(9);\n \nelseif (or==0)\n if (ph==0)\n z = [-1 0 1; -1 0 1; -1 0 1]/sqrt(6);\n elseif (ph==90)\n z = [-1 2 -1; -1 2 -1; -1 2 -1]/sqrt(18);\n end\n \nelseif (or==45)\n if (ph==0)\n z = [-1 1 0; 1 0 -1; 0 -1 1]/sqrt(6);\n elseif (ph==90)\n z = [-1 -1 2; -1 2 -1; 2 -1 -1]/sqrt(18);\n end\n \nelseif (or==90)\n if (ph==0)\n z = [-1 -1 -1; 0 0 0; 1 1 1]/sqrt(6);\n elseif (ph==90)\n z = [-1 -1 -1; 2 2 2; -1 -1 -1]/sqrt(18);\n end\n \nelseif (or==135)\n if (ph==0)\n z = [0 -1 1; 1 0 -1; -1 1 0]/sqrt(6);\n elseif (ph==90)\n z = [2 -1 -1; -1 2 -1; -1 -1 2]/sqrt(18);\n end \n \nend\n\nif (isnan(z))\n disp('Wavelet parameters not recognized');\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/19860-berkeley-wavelet-transform/bwt/makebw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7335345688268174}} {"text": "%% RATE OF CONVERGENCE OF MIXED FINITE ELEMENT METHOD (RT0-P0) FOR POISSON EQUATION\n%\n% This example is to show the rate of convergence of RT0-P0 mixed finite\n% element approximation of the Poisson equation on the unit square with the\n% following boundary conditions:\n%\n% - pure Dirichlet boundary condition.\n% - Pure Neumann boundary condition.\n% - mxied boundary condition.\n%\n% The basis, data structure and numerical test is summarized in PoissonRT0femrate.\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% Triangular preconditioned GMRES (default solver) and Uzawa preconditioned\n% CG converges uniformly in all cases. Traingular preconditioner is two\n% times faster than PCG although GMRES is used.\n% See also PoissonBDM1mfemrate, Poissonfemrate, Poissonafemrate\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n\n%% Setting\n[node,elem] = squaremesh([0,1,0,1],0.25); \nmesh = struct('node',node,'elem',elem);\noption.L0 = 1;\noption.maxIt = 4;\noption.printlevel = 1;\noption.elemType = 'RT0';\noption.solver = 'tri';\npde = sincosNeumanndata;\n\n%% Pure Neumann boundary condition.\nmesh.bdFlag = setboundary(node,elem,'Neumann');\nmfemPoisson(mesh,pde,option);\n\n%% Pure Dirichlet boundary condition.\nmesh.bdFlag = setboundary(node,elem,'Dirichlet');\nmfemPoisson(mesh,pde,option);\n\n%% Mix Dirichlet and Neumann boundary condition.\noption.solver = 'uzawapcg';\nmesh.bdFlag = setboundary(node,elem,'Dirichlet','~(x==0)','Neumann','x==0');\nmfemPoisson(mesh,pde,option);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/fem/mixedPoisson/PoissonRT0mfemrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7335216501583576}} {"text": "function loc_2d_shapes(NumOfSamples)\n% Create Localized 2-d data from uniform distribution.\n% Data are bount to the rectangle between points A(0,6) and B(4,10),\n% a circle with center at C(7.5,2.5) and radius R = 2,\n% and an isosceles triangle defined by the intesection points\n% of the lines y=6, y=2x-5 and y=-2x+25.\n% Every local set has the same number of samples (NumOfSamples/4).\n\nclc;\ninput_dims = 2;\n\n% Initialize Sample counters.\nk1 = 0; k2 = 1; k3 = 0; k4 = 0;\n\n% Initialize Data\nData = [7.5; 2.5;];\n\nwhile size(Data,2)0)&&(In1(2,1)<10)&&(In1(2,1)>6)&&(k1<=NumOfSamples/4)\n Data = [Data In1];\n k1 = k1 + 1;\nelseif norm(In1-[7.5; 2.5;])<=2&&(k2<=NumOfSamples/4)\n Data = [Data In1];\n k2 = k2 + 1;\nelseif (In1(2,1)>6)&&(In1(2,1)<2*In1(1,1)-5)&&(In1(2,1)<-2*In1(1,1)+25)&&(k3<=NumOfSamples/4)\n Data = [Data In1];\n k3 = k3 + 1;\nelseif (abs(In1(2,1)-In1(1,1))<.1)&&(In1(2,1)<5)&&(In1(2,1)>.5)&&(In1(1,1)<5)&&(In1(1,1)>.5)&&(k4<=NumOfSamples/4)\n Data = [Data In1];\n k4 = k4 + 1;\nend \nend\n\na = randperm(NumOfSamples);\nData = Data(:,a);\n\nsave local_uniform_2d Data;\nplot(Data(1,:),Data(2,:),'.','MarkerSize',1);\ngrid on;\nclear;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43572-unsupervised-learning-with-dynamic-cell-structures-dcs-neural-network/Data Generators/loc_2d_shapes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7335216486690622}} {"text": "function y = jed_to_year_hebrew ( jed )\n\n%*****************************************************************************80\n%\n%% JED_TO_YEAR_HEBREW: the year in the Hebrew calendar when a JED occurred.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 June 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Richards,\n% Algorithm H,\n% Mapping Time, The Calendar and Its History,\n% Oxford, 1999, page 331.\n%\n% Parameters:\n%\n% Input, real JED, the Julian Ephemeris Date.\n%\n% Output, integer Y, the year in the Hebrew calendar that\n% included the JED. If the input JED is less than the epoch of the Hebrew\n% calendar, then Y is always returned as -1.\n%\n jed_epoch = epoch_to_jed_hebrew ( );\n\n if ( jed < jed_epoch )\n y = -1;\n return\n end\n%\n% Using integer arithmetic in this computation may cause overflow.\n%\n% Compute the number of months elapsed up to the date.\n%\n m = 1 + floor ( ( 25920.0 * ( jed - jed_epoch + 2.5 ) ) / 765433.0 );\n%\n% Estimate the number of years represented by these months.\n%\n y = 19 * floor ( m / 235 ) + floor ( ( 19 * ( i4_modp ( m, 235 ) - 2 ) ) / 235 ) + 1;\n y = max ( y, 1 );\n%\n% Determine the JED of the first day of that year.\n%\n jed2 = new_year_to_jed_hebrew ( y );\n%\n% We might have been off by 1 year.\n%\n if ( jed < jed2 )\n y = y - 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/calpak/jed_to_year_hebrew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7335216398441735}} {"text": "% Builds and solves a simple least-squares problem using cvx\n\necho on\n\nn = 100;\nA = randn(2*n,n);\nb = randn(2*n,1);\n\ncvx_begin\n variable x1(n)\n minimize( norm( A*x1-b ) )\ncvx_end\nv1 = cvx_optval;\n\ncvx_begin\n variable x2(n)\n minimize( sum_square( A*x2-b ) )\ncvx_end\nv2 = cvx_optval;\n\n% The differences between the unsquared and squared versions should be small\nnorm( x1 - x2 ) / norm( x1 ) %#ok\nabs( v1 - sqrt(v2) ) / v1 %#ok\n\necho off\n\n\n\n\n", "meta": {"author": "yu-jiang", "repo": "radpbook", "sha": "88b9fa7d0a541099cdd1ac29383c89e087d1d895", "save_path": "github-repos/MATLAB/yu-jiang-radpbook", "path": "github-repos/MATLAB/yu-jiang-radpbook/radpbook-88b9fa7d0a541099cdd1ac29383c89e087d1d895/tools/cvx-w64/cvx/examples/simple_LS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7335216304409642}} {"text": "%% AMG TEST II: Different boundary conditions\n%\n% We consider the linear finite element discretization of Poisson equation\n% on the unstructured mesh with Dirichlet or Neumann boundary conditions. \n\n%%\nload lakemesh\n%% Dirichlet problem\n[N,itStep,time,err] = amgtest(node,elem,1);\n%% \ncolHeaders = {'Unknowns','Iterations','Time(sec)','Error'};\nmakeHtmlTable([N itStep time err],[],[],colHeaders,[],6);\n%%\nr = showrate(N.*log(N),time,3);\nxlabel('NlogN'); ylabel('Time');\ntitle(['Complexity is (NlogN)^{' num2str(r) '}'] );\n\n%% Neumann problem\n[N,itStep,time,err] = amgtest(node,elem,0);\n%% \ncolHeaders = {'Unknowns','Iterations','Time(sec)','Error'};\nmakeHtmlTable([N itStep time err],[],[],colHeaders,[],6);\n%%\nr = showrate(N.*log(N),time,3);\nxlabel('NlogN'); ylabel('Time');\ntitle(['Complexity is (NlogN)^{' num2str(r) '}'] );", "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/amgtest2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107931567177, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7335197274246121}} {"text": "% ASTROTIK by Francesco Santilli\n% R2BP (Restricted Two Bodies Problem)\n% M2E inverts the keplerian equation for an elliptical orbit and finds\n% eccentric anomaly with a numeric iterative method.\n%\n% Usage: E = M2E(M,e)\n%\n% where: M(k) = mean anomaly [rad]\n% e = eccentricity [-] (0=1)\n error('e must be in the range (0,1)')\n end\n \n E = zeros(K,1);\n for k = 1:K\n F = @(E) E-e*sin(E)-M(k);\n E1 = M(k)-e-eps;\n E2 = M(k)+e+eps;\n E(k) = regulafalsi(F,E1,E2);\n end\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/M2E.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7335197266853015}} {"text": "function [ num_int, pint ] = plane_normal_triangle_int_3d ( pp, normal, t )\n\n%*****************************************************************************80\n%\n%% PLANE_NORMAL_TRIANGLE_INT_3D: intersection ( normal plane, triangle ) in 3D.\n%\n% Discussion:\n%\n% The normal form of a plane in 3D is:\n%\n% PP is a point on the plane,\n% N is a normal vector to the plane.\n%\n% There may be 0, 1, 2 or 3 points of intersection returned.\n%\n% If two intersection points are returned, then the entire line\n% between them comprises points of intersection.\n%\n% If three intersection points are returned, then all points of\n% the triangle intersect the plane.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real PP(3), a point on the plane.\n%\n% Input, real NORMAL(3), a normal vector to the plane.\n%\n% Input, real T(3,3), the vertices of the triangle.\n%\n% Output, integer NUM_INT, the number of intersection points returned.\n%\n% Output, real PINT(3,3), the coordinates of the\n% intersection points.\n%\n dim_num = 3;\n\n num_int = 0;\n pint = [];\n%\n% Compute the signed distances between the vertices and the plane.\n%\n d = - normal(1:dim_num) * pp(1:dim_num)';\n\n dist1 = normal(1:dim_num) * t(1:dim_num,1) + d;\n dist2 = normal(1:dim_num) * t(1:dim_num,2) + d;\n dist3 = normal(1:dim_num) * t(1:dim_num,3) + d;\n%\n% Consider any zero distances.\n%\n if ( dist1 == 0.0 )\n\n num_int = num_int + 1;\n pint(1:dim_num,num_int) = t(1:dim_num,1);\n\n end\n\n if ( dist2 == 0.0 )\n\n num_int = num_int + 1;\n pint(1:dim_num,num_int) = t(1:dim_num,2);\n\n end\n\n if ( dist3 == 0.0 )\n\n num_int = num_int + 1;\n pint(1:dim_num,num_int) = t(1:dim_num,3);\n\n end\n%\n% If 2 or 3 of the nodes intersect, we're already done.\n%\n if ( 2 <= num_int )\n return\n end \n%\n% If one node intersects, then we're done unless the other two\n% are of opposite signs.\n%\n if ( num_int == 1 )\n\n if ( dist1 == 0.0 )\n\n [ num_int, pint ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,2), ...\n t(1:dim_num,3), dist2, dist3, num_int, pint );\n\n elseif ( dist2 == 0.0 )\n\n [ num_int, pint ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,1), ...\n t(1:dim_num,3), dist1, dist3, num_int, pint );\n\n elseif ( dist3 == 0.0 )\n\n [ num_int, pint ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,1), ...\n t(1:dim_num,2), dist1, dist2, num_int, pint );\n\n end\n\n return\n\n end\n%\n% All nodal distances are nonzero, and there is at least one\n% positive and one negative.\n%\n if ( dist1 * dist2 < 0.0 & dist1 * dist3 < 0.0 )\n\n [ num_int, pint ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,1), ...\n t(1:dim_num,2), dist1, dist2, num_int, pint );\n\n [ num_int, pint ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,1), ...\n t(1:dim_num,3), dist1, dist3, num_int, pint );\n\n elseif ( dist2 * dist1 < 0.0 & dist2 * dist3 < 0.0 )\n\n [ num_int, pint ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,2), ...\n t(1:dim_num,1), dist2, dist1, num_int, pint );\n\n [ num_int, pint ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,2), ...\n t(1:dim_num,3), dist2, dist3, num_int, pint );\n\n elseif ( dist3 * dist1 < 0.0 & dist3 * dist2 < 0.0 )\n\n [ num_int, pint ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,3), ...\n t(1:dim_num,1), dist3, dist1, num_int, pint );\n\n [ num_int, pint ] = plane_imp_triangle_int_add_3d ( t(1:dim_num,3), ...\n t(1:dim_num,2), dist3, dist2, num_int, pint );\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/plane_normal_triangle_int_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7334625106703013}} {"text": "function a = sweet3 ( )\n\n%*****************************************************************************80\n%\n%% SWEET3 returns the SWEET3 matrix.\n%\n% Example:\n%\n% 8 4 1 6 2 3\n% 4 8 4 1 6 2\n% -34 4 8 4 1 6\n% 5 -34 4 8 4 1\n% 3 5 -34 4 8 4\n% 1 3 5 -34 4 8\n%\n% Properties:\n%\n% A is Toeplitz: constant along diagonals.\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% 21 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Per Hansen, Tony Chan,\n% FORTRAN Subroutines for General Toeplitz Systems,\n% ACM Transactions on Mathematical Software,\n% Volume 18, Number 3, September 1992, pages 256-273.\n%\n% Douglas Sweet,\n% The use of pivoting to improve the numerical performance of\n% Toeplitz solvers,\n% In \"Advanced Algorithms and Architectures for Signal Processing\",\n% Edited by J M Speiser,\n% Proceedings SPIE 696, 1986, pages 8-18.\n%\n% Parameters:\n%\n% Output, real A(6,6), the matrix.\n%\n n = 6;\n\n v = [ 1.0, 3.0, 5.0, -34.0, 4.0, 8.0, 4.0, ...\n 1.0, 6.0, 2.0, 3.0 ];\n\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n\n a(i,j) = v ( j - i + 6 );\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/sweet3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7334625051674993}} {"text": "function rank = rgf_rank ( m, f )\n\n%*****************************************************************************80\n%\n%% RGF_RANK ranks a restricted growth function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 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 M, the domain of the RGF is the integers\n% from 1 to M. M must be positive.\n%\n% Input, integer F(M), the restricted growth function.\n%\n% Output, integer RANK, the rank of the restricted growth\n% function.\n%\n\n%\n% Check.\n%\n ierror = rgf_check ( m, f );\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RGF_RANK - Fatal error!\\n' );\n fprintf ( 1, ' The input array is illegal!\\n' );\n fprintf ( 1, ' IERROR = %d\\n', ierror );\n error ( 'RGF_RANK - Fatal error!' );\n end\n%\n% Get the generalized restricted growth function table.\n%\n offset = 1;\n d = rgf_g_table ( m );\n\n rank = 0;\n j = 1;\n for i = 2 : m\n rank = rank + ( f(i) - 1 ) * d(m-i+offset,j+offset);\n j = max ( j, f(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/combo/rgf_rank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.733462348009824}} {"text": "function funhan = piecewise(varargin)\n%PIECEWISE Piecewise-defined functions.\n%\n% F = PIECEWISE(COND1,DEFN1,...CONDn,DEFNn,DEFAULT) returns a callable\n% function F that applies different definitions according to supplied\n% conditions. For a given X, F(X) will test COND1 and apply DEFN1 if true,\n% etc. If all conditions fail, then DEFAULT is applied. For any particular\n% input, the first condition to match is the only one applied.\n%\n% Each condition should be either a:\n% * function handle evaluating to logical values, or\n% * vector [a b] representing membership in the half-open interval [a,b).\n% Each definition should be either a:\n% * function handle, or\n% * scalar value.\n% The DEFAULT definition is optional; if omitted, it will be set to NaN.\n% \n% All function definitions can accept multiple input variables, but they\n% all must accept the same number as in the call to F. They also should\n% all be vectorized, returning results the same size and shape as their\n% inputs. Complex inputs will work if the definitions are set up\n% accordingly; in that case, intervals will be tested using only Re parts.\n%\n% The special syntax F() displays all the conditions and definitions for F.\n%\n% Examples:\n% f = piecewise([-1 1],@(x) 1+cos(pi*x),0); % a \"cosine bell\" \n% ezplot(f,[-2 2])\n% g = piecewise(@(x) sin(x)<0.5,@sin,@(x) 1-sin(x));\n% ezplot(g,[-2*pi 2*pi])\n% h = piecewise(@(x,y) (x<0)|(y<0),@(x,y) sin(x-y)); % defined on L\n% ezsurf(h,[-1 1])\n% chi = piecewise(@(x,y,z) x.^2+y.^2+z.^2<1,1,0); % characteristic func\n% [ triplequad(chi,-1,1,-1,1,-1,1), 4/3*pi ]\n% ans =\n% 4.1888 4.1888\n%\n% See also FUNCTION_HANDLE.\n\n% Copyright (c) 2007 by Toby Driscoll.\n% Version 1, 6 Aug 2007.\n\n\n\n% If an even number of inputs was given, no default value exists.\nif rem(nargin,2)==0\n default = NaN;\nelse \n default = varargin{end};\nend\n\n% Number of condition/definition pairs.\nnumdefs = floor(nargin/2);\ncondn = varargin(1:2:2*numdefs);\ndefn = varargin(2:2:2*numdefs);\n\nfunhan = @piecewisefun; % this is the return value\n\n % This is the defintion of the returned function.\n function f = piecewisefun(varargin)\n % Special syntax to display the function.\n if nargin==0\n fprintf('\\nPiecewise function with conditions/definitions:\\n')\n for k = 1:numdefs\n fprintf(' If %s : %s\\n',funcornum2str(condn{k}),funcornum2str(defn{k}))\n end\n fprintf(' Otherwise : %s\\n\\n',funcornum2str(default))\n return\n end\n \n % Normal call\n f = zeros(size(varargin{1}));\n mask = false(size(f));\n for k = 1:numdefs\n % Determine the values satistfying condition k.\n if isa(condn{k},'function_handle')\n newpts = logical( condn{k}(varargin{:}) );\n else\n newpts = (varargin{1}>=condn{k}(1)) & (varargin{1}' );\n ylabel ( '<--- Y --->' );\n title ( prefix );\n%\n% Plot the convex hull as computed by MATLAB.\n%\n figure ( 2 )\n clf\n k = convhull ( xy(:,1), xy(:,2) );\n plot ( xy(:,1), xy(:,2), 'b.', 'MarkerSize', 20 );\n hold on\n plot( xy(k,1), xy(k,2), 'r-', 'LineWidth', 2 );\n grid on\n axis tight\n axis equal\n xlabel ( '<--- X --->' );\n ylabel ( '<--- Y --->' );\n title ( sprintf ( '%s by MATLAB convhull', prefix ) );\n hold off\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CONVEX_HULL:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\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/convex_hull/convex_hull.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245617, "lm_q2_score": 0.8670357477770337, "lm_q1q2_score": 0.7334623303405884}} {"text": "function rational_quadratic_test ( )\n\n%*****************************************************************************80\n%\n%% RATIONAL_QUADRATIC_TEST examines the rational_quadratic correlation.\n%\n% Discussion:\n%\n% This code is based substantially on a document by Toby Driscoll.\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% Reference:\n%\n% Toby Driscoll,\n% Mercer's theorem and the Karhunen-Loeve expansion,\n% Oxford University Mathematical Institute,\n% http://www2.maths.ox.ac.uk/chebfun/examples/stats/pdf/MercerKarhunenLoeve.pdf\n%\n rmpath ( '/usr/local/matlab/toolbox/datafeed/datafeed' )\n addpath ( '../chebfun' )\n\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RATIONAL_QUADRATIC_TEST:\\n' );\n fprintf ( 1, ' Demonstrate Mercer''s theorem and the KL expansion\\n' );\n fprintf ( 1, ' for the rational_quadratic kernel.\\n' );\n%\n% Set the interval.\n%\n a = 0.0;\n b = +10.0;\n fprintf ( 1, ' Using interval [%g,%g]\\n', a, b );\n s_num = 21;\n s_vec = linspace ( a, b, s_num );\n%\n% FRED is a function from the CHEBFUN library.\n%\n% It constructs a \"chebop\" representing the Fredholm integral operator\n% with kernel K for functions in domain [A,B].\n%\n F = fred ( @rational_quadratic_correlation, domain ( [ a, b ] ) );\n%\n% EIGS has been extended to be able to compute the eigenvalues Lambda\n% and eigenfunctions Psi of the Fredholm integral operator represented by F.\n%\n% The \"LM\" switch requests that we return the eigenvalues of largest magnitude.\n%\n% Each Psi is a CHEBFUN, that is, it takes a real number argument.\n%\n eigen_num = 20;\n [ Psi, Lambda ] = eigs ( F, eigen_num, 'lm' );\n\n eigen_found = length ( Lambda );\n fprintf ( 1, ' Requested %d eigenmodes, computed %d\\n', eigen_num, eigen_found );\n eigen_num = min ( eigen_num, eigen_found );\n%\n% Print the eigenvalues.\n%\n lambda_vec = diag ( Lambda );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I Lambda(I)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : eigen_num\n fprintf ( 1, ' %2d %10g\\n', i, lambda_vec(i) );\n end\n%\n% Plot the eigenvalues.\n%\n figure ( 1 )\n clf\n plot ( lambda_vec, 'Linewidth', 2 );\n hold on\n plot ( lambda_vec, 'b.', 'Markersize', 20 );\n title ( 'rational_quadratic: Mercer eigenvalues' );\n xlabel ( '<--- N --->')\n grid on\n print -dpng 'rational_quadratic_figure1.png'\n%\n% Plot selected eigenfunctions.\n%\n figure ( 2 )\n subplot ( 4, 1, 1 )\n plot ( Psi(:,1), 'Linewidth', 2 );\n title ( 'rational_quadratic: Mercer eigenfunction PSI(1)' )\n grid on\n subplot ( 4, 1, 2 )\n plot ( Psi(:,2), 'Linewidth', 2 );\n title ( 'rational_quadratic: Mercer eigenfunction PSI(2)' )\n grid on\n subplot ( 4, 1, 3 )\n plot ( Psi(:,5), 'Linewidth', 2 );\n title ( 'rational_quadratic: Mercer eigenfunction PSI(5)' )\n grid on\n subplot ( 4, 1, 4 )\n plot ( Psi(:,10), 'Linewidth', 2 );\n title ( 'rational_quadratic: Mercer eigenfunction PSI(10)' )\n grid on\n print -dpng 'rational_quadratic_figure2.png'\n%\n% Orthonormality check.\n%\n ptp = Psi' * Psi;\n error_frobenius = r8mat_is_identity ( eigen_num, ptp );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Frobenius norm of I - Psi'' * Psi = %g\\n', error_frobenius );\n%\n% K(S,S) should be exactly 1.\n% Because we are using a truncated representation of K, our estimate of K(S,S)\n% will be smaller than 1.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Truncated estimate of K(s,s) = 1 for S in the interval.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' S K(s,s) estimate\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : 21\n s = s_vec(i);\n ptlp = Psi(s,:) * Lambda * Psi(s,:)';\n fprintf ( 1, ' %10g %14g\\n', s, ptlp );\n end\n%\n% Look at eigenvalue decay.\n%\n x = diff ( log ( ( 1:eigen_num ) ) );\n y = diff ( log ( lambda_vec ) )';\n c = y ./ x;\n figure ( 3 );\n clf\n plot ( c, 'Linewidth', 2 );\n grid on\n hold on\n plot ( c, 'b.', 'Markersize', 20 );\n xlabel ( '<-- N -->' )\n title ( 'rational_quadratic: Eigenvalue decay rate' );\n print -dpng 'rational_quadratic_figure3.png'\n%\n% Look at eigenvalue sum.\n%\n% The trace of K(s,s) over [a,b] should be the integral of 1 over [a,b],\n% that is, b - a.\n%\n% We compare the trace to the partial sums of the lambda's to see how much\n% of the variance of the process we have captured.\n%\n trace_K = b - a;\n lambda_cum = cumsum ( lambda_vec ) / trace_K;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Index Cumulative Eigenvalue sum\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : eigen_num\n fprintf ( 1, ' %5d %10g\\n', i, lambda_cum(i) );\n end\n%\n% We decide to use the first 10 eigenfunctions.\n%\n eigen_use = 10;\n%\n% Find 400 realizations of the process by selecting, for each realization,\n% 10 random parameters Z in the truncated KL expansion.\n%\n Z = randn ( eigen_use, 400 );\n X = Psi(:,1:eigen_use) * ( sqrt ( Lambda(1:eigen_use,1:eigen_use) ) * Z ); \n%\n% Plot 40 of the realizations;\n% Plot their mean, computed from all 400.\n%\n figure ( 4 )\n clf\n plot ( X(:,1:40) )\n mu = sum ( X, 2 ) / 400;\n hold on;\n plot ( mu, 'k', 'linewidth', 3 );\n title ( 'rational_quadratic: 40 Random Realizations X(t,omega), and their Mean.' )\n print -dpng 'rational_quadratic_figure4.png'\n%\n% Estimate the covariance from the data.\n%\n figure ( 5 )\n clf\n [ S, T ] = meshgrid ( s_vec, s_vec );\n C = cov ( X(s_vec,:)' );\n mesh ( S, T, C );\n hold on;\n D = rational_quadratic_correlation ( S, T );\n plot3 ( S, T, D, 'k.', 'markersize', 10 )\n title ( 'rational_quadratic: Covariance K(S,T) (dots), and Estimate from Realizations (mesh)' )\n print -dpng 'rational_quadratic_figure5.png'\n%\n% Using just 10 functions in the expansion,\n% reduce the correlation length,\n% and examine the sum of the lambda's.\n%\n if ( 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Use a fixed number of eigenfunctions = %d\\n', eigen_use );\n fprintf ( 1, ' but vary the correlation length RHOBAR.\\n' );\n fprintf ( 1, ' (We used RHOBAR = 1 above.)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The sum of the eigenvalues, divided by (B-A),\\n' );\n fprintf ( 1, ' discloses the relative amount of the total variation\\n' );\n fprintf ( 1, ' that is captured by the truncated expansion.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' RHOBAR VARSUM\\n' );\n fprintf ( 1, '\\n' );\n rhobar = 4.0;\n for i = 1 : 10\n K = @ ( s, t ) exp ( - abs ( s - t ) / rhobar );\n F = fred ( K, domain ( [ a, b ] ) );\n lambda_vec = eigs ( F, 20, 'lm' );\n varsum = sum ( lambda_vec(1:eigen_use) ) / ( b - a );\n fprintf ( 1, ' %10g %10g\\n', rhobar, varsum );\n rhobar = rhobar / 2.0;\n end\n\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'RATIONAL_QUADRATIC_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n rmpath ( '../chebfun' )\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/correlation_chebfun/rational_quadratic_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7334237780060712}} {"text": "function J = lotkaObjectiveFCN(u,x,Ts,N,xref,u0,p,Q,R,Ru)\n%% Cost function of nonlinear MPC for Lotka-Volterra system\n%\n% Inputs:\n% u: optimization variable, from time k to time k+N-1 \n% x: current state at time k\n% Ts: controller sample time\n% N: prediction horizon\n% xref: state references, constant from time k+1 to k+N\n% u0: previous controller output at time k-1\n%\n% Output:\n% J: objective function cost\n%\n\n%% Nonlinear MPC design parameters\n\n\n%% Cost Calculation\n% Set initial plant states, controller output and cost\nxk = x;\nuk = u(1);\nJ = 0;\n% Loop through each prediction step\nfor ct=1:N\n % Obtain plant state at next prediction step\n xk1 = rk4u(@sparseGalerkinControl_Discrete,xk,uk,Ts,1,[],p); \n \n % Accumulate state tracking cost from x(k+1) to x(k+N)\n J = J + (xk1-xref)'*Q*(xk1-xref);\n % Accumulate MV rate of change cost from u(k) to u(k+N-1)\n if ct==1\n J = J + (uk-u0)'*R*(uk-u0) + uk'*Ru*uk;\n else\n J = J + (uk-u(ct-1))'*R*(uk-u(ct-1)) + uk'*Ru*uk;\n end\n % Update xk and uk for the next prediction step\n xk = xk1;\n if ct.\n%\n% http://www.petercorke.com\n\nfunction [qt,qdt,qddt] = jtraj(q0, q1, tv, qd0, qd1)\n if length(tv) > 1\n tscal = max(tv);\n t = tv(:)/tscal;\n else\n tscal = 1;\n t = (0:(tv-1))'/(tv-1); % normalized time from 0 -> 1\n end\n\n q0 = q0(:);\n q1 = q1(:);\n\n if nargin == 3\n qd0 = zeros(size(q0));\n qd1 = qd0;\n elseif nargin == 5\n qd0 = qd0(:);\n qd1 = qd1(:);\n else\n error('incorrect number of arguments')\n end\n\n % compute the polynomial coefficients\n A = 6*(q1 - q0) - 3*(qd1+qd0)*tscal;\n B = -15*(q1 - q0) + (8*qd0 + 7*qd1)*tscal;\n C = 10*(q1 - q0) - (6*qd0 + 4*qd1)*tscal;\n E = qd0*tscal; % as the t vector has been normalized\n F = q0;\n\n tt = [t.^5 t.^4 t.^3 t.^2 t ones(size(t))];\n c = [A B C zeros(size(A)) E F]';\n \n qt = tt*c;\n\n % compute optional velocity\n if nargout >= 2\n c = [ zeros(size(A)) 5*A 4*B 3*C zeros(size(A)) E ]';\n qdt = tt*c/tscal;\n end\n\n % compute optional acceleration\n if nargout == 3\n c = [ zeros(size(A)) zeros(size(A)) 20*A 12*B 6*C zeros(size(A))]';\n qddt = tt*c/tscal^2;\n end\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/jtraj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7332373585951426}} {"text": "function DEM_demo_convolution\n% DEM demo for linear deconvolution: This demo considers the deconvolution\n% of the responses of a single-input-multiple output input-state-output\n% model (DCM) to disclose the input or causes. It focuses on estimating the\n% causes and hidden states: The notes provide a comparative evaluation with \n% extended Kalman filtering (see script after return).\n \n \n% get a simple convolution model\n%==========================================================================\nM = spm_DEM_M('convolution model');\nM(1).V = exp(8); % error precision\nM(1).W = exp(8); % error precision\n \n% and generate data\n%==========================================================================\nN = 32; % length of data sequence\nU = exp(-([1:N] - 12).^2/(2.^2)); % this is the Gaussian cause;\nDEM = spm_DEM_generate(M,U,{},{[] 16},{16});\n \n% invert model\n%==========================================================================\nDEM = spm_DEM(DEM);\n \n% overlay true values\n%--------------------------------------------------------------------------\nspm_DEM_qU(DEM.qU,DEM.pU)\n\n\nreturn\n \n \n% explore dimensions (n)\n%==========================================================================\nfor i = 1:8\n DEM.M(1).E.n = i;\n DEM.M(1).E.d = 3;\n \n D{i} = spm_DEM(DEM);\n F(i) = D{i}.F;\n Sx(i) = sum(sum((D{i}.qU.x{1} - DEM.pU.x{1}).^2));\n Sv(i) = sum(sum((D{i}.qU.v{2} - DEM.pU.v{2}).^2));\nend\n \n% plot\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 1');\n\nsubplot(2,1,1)\nbar(Sv)\nxlabel('n - 1 (d = 2)')\nylabel('sum squared error (causal states)')\ntitle('embedding dimension (n)','FontSize',16)\naxis square\n \nd = [1 8];\nfor i = 1:length(d)\n subplot(2,length(d),i + length(d))\n hold on\n plot([1:N],D{d(i)}.qU.v{2})\n plot([1:N],DEM.pU.v{2},'linewidth',2,'color',[1 1 1]/2)\n hold off\n axis square\n xlabel('time')\n title(sprintf('n = %i',d(i)),'FontSize',16)\n if i == 1, a = axis; else, axis(a); end\nend\n \n% and d\n%--------------------------------------------------------------------------\nclear D F Sx Sv\nfor i = 1:6\n DEM.M(1).E.n = 15;\n DEM.M(1).E.d = i - 1;\n \n D{i} = spm_DEM(DEM);\n F(i) = D{i}.F;\n Sx(i) = sum(sum((D{i}.qU.x{1} - DEM.pU.x{1}).^2));\n Sv(i) = sum(sum((D{i}.qU.v{2} - DEM.pU.v{2}).^2));\n \nend\n \n% plot\n%--------------------------------------------------------------------------\nspm_figure('GetWin','Figure 2'); clf\n\nsubplot(2,2,1)\nbar(Sx)\nxlabel('d (n = 15)')\nylabel('sum squared error (hidden states)')\ntitle('embedding dimension (d)','FontSize',16)\naxis square\nset(gca,'XTickLabel',[0:7])\n\nsubplot(2,2,2)\nbar(F - min(F) + 32)\nxlabel('d (n = 15)')\nylabel('log-evidence')\ntitle('log-evidence','FontSize',16)\naxis square\nset(gca,'XTickLabel',[0:7])\n \nd = [1 4];\nfor i = 1:length(d)\n subplot(2,length(d),i + length(d))\n hold on\n plot([1:N],D{d(i)}.qU.x{1})\n plot([1:N],DEM.pU.x{1},'linewidth',2,'color',[1 1 1]/2)\n hold off\n axis square\n xlabel('time')\n title(sprintf('d = %i',d(i) - 1),'FontSize',16)\n if i == 1, a = axis; else, axis(a); end\nend\n \n \n% Comparison with EKF\n%==========================================================================\nclear SSE\nfor i = 1:8\n \n % i.i.d.\n %----------------------------------------------------------------------\n DEM = spm_DEM_generate(M,U,{},{[] 16});\n DEM = spm_DEM(DEM);\n \n % serial correlations\n %----------------------------------------------------------------------\n D0 = DEM;\n D0.M(1).E.s = 0;\n D0 = spm_DEM(D0);\n \n % extended kalman filter - i.i.d.\n %----------------------------------------------------------------------\n e_x = spm_ekf(DEM.M,DEM.Y);\n d_x = DEM.qU.x{1};\n t_x = DEM.pU.x{1};\n i_x = D0.qU.x{1};\n \n SSE(i,1) = sum(sum((e_x - t_x).^2));\n SSE(i,2) = sum(sum((i_x - t_x).^2));\n SSE(i,3) = sum(sum((d_x - t_x).^2));\n \nend\n \nspm_figure('GetWin','Figure 3');\n\nsubplot(2,1,1)\nplot(1:N,i_x,'g',1:N,d_x,'r',1:N,e_x,'b',1:N,t_x,'k')\nlegend('DEM(0)',' ','DEM(0.5)',' ','EKF',' ','true',' ')\nxlabel('time')\ntitle({'hidden states','comparison with EKF'},'FontSize',16)\naxis square\n \nsubplot(2,1,2)\nplot(SSE','k:'), hold on\nplot(SSE','k.','Markersize',16), hold off\nset(gca,'Xtick',[1 2 3],'XLim',[0 4])\nset(gca,'Xticklabel',{'EKF','DEM(0)','DEM(0.5)'})\ntitle('sum of squared error (hidden states)','FontSize',16)\naxis square\n \n \n% Show equivalence when causes are not structured\n%==========================================================================\nM(1).E.s = 0;\nM(1).pE.h = eye(2);\nM(1).pC = [];\n\nM(2).v = [0;0];\nM(2).V = eye(2);\nU = [U; 0*U];\n\nDEM = spm_DEM_generate(M,U,{},{[] 16});\nDEM = spm_DEM(DEM);\ne_x = spm_ekf(DEM.M,DEM.Y);\nd_x = DEM.qU.x{1};\n\n\nspm_figure('GetWin','Figure 4');\n\nsubplot(2,1,1)\nplot(1:N,d_x,'r',1:N,e_x,'b')\nlegend('DEM(0)',' ','EKF',' ')\nxlabel('time')\ntitle({'hidden states';'no correlations'},'FontSize',16)\naxis square\n\n% Show equivalence when causes are removed\n%--------------------------------------------------------------------------\nDEM.M(1).pE.h = sparse(2,2);\nDEM.M(1).W = speye(2);\n\nDEM = spm_DEM(DEM);\ne_x = spm_ekf(DEM.M,DEM.Y);\nd_x = DEM.qU.x{1};\n\nspm_figure('GetWin','Figure 4');\n\nsubplot(2,1,2)\nplot(1:N,d_x,'r',1:N,e_x,'b')\nlegend('DEM(0)',' ','EKF',' ')\nxlabel('time')\ntitle({'hidden states';'no causes'},'FontSize',16)\naxis square\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/DEM_demo_convolution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7332373523454242}} {"text": "function [v,beta,s] = house (x)\n%HOUSE find a Householder reflection.\n% real or complex case.\n% Example:\n% [v,beta,s] = house (x)\n% See also: cs_demo\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\nv = x ;\ns = norm (x) ;\nif (s == 0)\n beta = 0 ;\n v (1) = 1 ;\nelse\n if (x (1) ~= 0)\n s = sign (x (1)) * s ;\n end\n v (1) = v (1) + s ;\n beta = 1 / real (conj (s) * v (1)) ;\nend\ns = - s ;\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/SuiteSparse/CXSparse_newfiles/MATLAB/Test/house.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7332373504026471}} {"text": "function [x, istop, itn, normr, normAr, normA, condA, normx]...\n = lsmr(A, b, lambda, atol, btol, conlim, itnlim, localSize, show)\n\n% LSMR Iterative solver for least-squares problems.\n% X = LSMR(A,B) solves the system of linear equations A*X=B. If the system\n% is inconsistent, it solves the least-squares problem min ||b - Ax||_2. \n% A is a rectangular matrix of dimension m-by-n, where all cases are\n% allowed: m=n, m>n, or m 0\n u = u/beta;\n end\n\n if explicitA\n v = A'*u;\n [m n] = size(A);\n else \n v = A(u,2);\n m = size(b,1);\n n = size(v,1);\n end\n\n minDim = min([m n]);\n\n % Set default parameters.\n\n if nargin < 3 || isempty(lambda) , lambda = 0; end\n if nargin < 4 || isempty(atol) , atol = 1e-6; end\n if nargin < 5 || isempty(btol) , btol = 1e-6; end\n if nargin < 6 || isempty(conlim) , conlim = 1e+8; end\n if nargin < 7 || isempty(itnlim) , itnlim = minDim; end\n if nargin < 8 || isempty(localSize), localSize = 0; end\n if nargin < 9 || isempty(show) , show = false; end\n\n if show\n fprintf('\\n\\nLSMR Least-squares solution of Ax = b')\n fprintf('\\nVersion 1.11 09 Jun 2010')\n fprintf('\\nThe matrix A has %8g rows and %8g cols', m,n)\n fprintf('\\nlambda = %16.10e', lambda )\n fprintf('\\natol = %8.2e conlim = %8.2e', atol,conlim)\n fprintf('\\nbtol = %8.2e itnlim = %8g' , btol,itnlim)\n end\n\n alpha = norm(v);\n if alpha > 0\n v = (1/alpha)*v;\n end\n\n % Initialization for local reorthogonalization.\n\n localOrtho = false;\n if localSize > 0\n localPointer = 0;\n localOrtho = true;\n localVQueueFull = false;\n\n % Preallocate storage for the relevant number of latest v_k's.\n\n localV = zeros(n, min([localSize minDim]));\n end\n\n % Initialize variables for 1st iteration.\n\n itn = 0;\n zetabar = alpha*beta;\n alphabar = alpha;\n rho = 1;\n rhobar = 1;\n cbar = 1;\n sbar = 0;\n\n h = v;\n hbar = zeros(n,1);\n x = zeros(n,1);\n\n % Initialize variables for estimation of ||r||.\n\n betadd = beta;\n betad = 0;\n rhodold = 1;\n tautildeold = 0;\n thetatilde = 0;\n zeta = 0;\n d = 0;\n\n % Initialize variables for estimation of ||A|| and cond(A).\n\n normA2 = alpha^2;\n maxrbar = 0;\n minrbar = 1e+100;\n\n % Items for use in stopping rules.\n normb = beta;\n istop = 0;\n ctol = 0; if conlim > 0, ctol = 1/conlim; end;\n normr = beta;\n\n % Exit if b=0 or A'b = 0.\n\n normAr = alpha * beta;\n if normAr == 0, disp(msg(1,:)); return, end\n\n % Heading for iteration log.\n\n if show\n test1 = 1;\n test2 = alpha/beta;\n fprintf('\\n\\n%s%s' , hdg1 , hdg2 )\n fprintf('\\n%6g %12.5e' , itn , x(1) )\n fprintf(' %10.3e %10.3e', normr, normAr )\n fprintf(' %8.1e %8.1e' , test1, test2 )\n end\n\n\n %------------------------------------------------------------------\n % Main iteration loop.\n %------------------------------------------------------------------\n while itn < itnlim\n itn = itn + 1;\n\n % Perform the next step of the bidiagonalization to obtain the\n % next beta, u, alpha, v. These satisfy the relations\n % beta*u = A*v - alpha*u,\n % alpha*v = A'*u - beta*v.\n\n if explicitA\n u = A*v - alpha*u;\n else \n u = A(v,1) - alpha*u; \n end\n beta = norm(u);\n\n if beta > 0\n u = (1/beta)*u;\n if localOrtho\n localVEnqueue(v); % Store old v for local reorthogonalization of new v.\n end\n if explicitA\n v = A'*u - beta*v;\n else\n v = A(u,2) - beta*v;\n end\n\n if localOrtho\n v = localVOrtho(v); % Local-reorthogonalization of new v.\n end\n alpha = norm(v);\n if alpha > 0, v = (1/alpha)*v; end\n end\n \n % At this point, beta = beta_{k+1}, alpha = alpha_{k+1}.\n \n % Construct rotation Qhat_{k,2k+1}.\n\n alphahat = norm([alphabar lambda]);\n chat = alphabar/alphahat;\n shat = lambda/alphahat;\n\n % Use a plane rotation (Q_i) to turn B_i to R_i.\n\n rhoold = rho;\n rho = norm([alphahat beta]);\n c = alphahat/rho;\n s = beta/rho;\n thetanew = s*alpha;\n alphabar = c*alpha;\n\n % Use a plane rotation (Qbar_i) to turn R_i^T to R_i^bar.\n \n rhobarold = rhobar;\n zetaold = zeta;\n thetabar = sbar*rho;\n rhotemp = cbar*rho;\n rhobar = norm([cbar*rho thetanew]);\n cbar = cbar*rho/rhobar;\n sbar = thetanew/rhobar;\n zeta = cbar*zetabar;\n zetabar = - sbar*zetabar;\n\n % Update h, h_hat, x.\n\n hbar = h - (thetabar*rho/(rhoold*rhobarold))*hbar;\n x = x + (zeta/(rho*rhobar))*hbar;\n h = v - (thetanew/rho)*h;\n\n % Estimate of ||r||.\n \n % Apply rotation Qhat_{k,2k+1}.\n betaacute = chat* betadd;\n betacheck = - shat* betadd;\n\n % Apply rotation Q_{k,k+1}.\n betahat = c*betaacute;\n betadd = - s*betaacute;\n \n % Apply rotation Qtilde_{k-1}.\n % betad = betad_{k-1} here.\n\n thetatildeold = thetatilde;\n rhotildeold = norm([rhodold thetabar]);\n ctildeold = rhodold/rhotildeold;\n stildeold = thetabar/rhotildeold;\n thetatilde = stildeold* rhobar;\n rhodold = ctildeold* rhobar;\n betad = - stildeold*betad + ctildeold*betahat;\n\n % betad = betad_k here.\n % rhodold = rhod_k here.\n\n tautildeold = (zetaold - thetatildeold*tautildeold)/rhotildeold;\n taud = (zeta - thetatilde*tautildeold)/rhodold;\n d = d + betacheck^2;\n normr = sqrt(d + (betad - taud)^2 + betadd^2);\n \n % Estimate ||A||.\n normA2 = normA2 + beta^2;\n normA = sqrt(normA2);\n normA2 = normA2 + alpha^2;\n \n % Estimate cond(A).\n maxrbar = max(maxrbar,rhobarold);\n if itn>1 \n minrbar = min(minrbar,rhobarold);\n end\n condA = max(maxrbar,rhotemp)/min(minrbar,rhotemp);\n\n % Test for convergence.\n\n % Compute norms for convergence testing.\n normAr = abs(zetabar);\n normx = norm(x);\n\n % Now use these norms to estimate certain other quantities,\n % some of which will be small near a solution.\n\n test1 = normr /normb;\n test2 = normAr/(normA*normr);\n test3 = 1/condA;\n t1 = test1/(1 + normA*normx/normb);\n rtol = btol + atol*normA*normx/normb;\n\n % The following tests guard against extremely small values of\n % atol, btol or ctol. (The user may have set any or all of\n % the parameters atol, btol, conlim to 0.)\n % The effect is equivalent to the normAl tests using\n % atol = eps, btol = eps, conlim = 1/eps.\n\n if itn >= itnlim, istop = 7; end\n if 1 + test3 <= 1, istop = 6; end\n if 1 + test2 <= 1, istop = 5; end\n if 1 + t1 <= 1, istop = 4; end\n\n % Allow for tolerances set by the user.\n\n if test3 <= ctol, istop = 3; end\n if test2 <= atol, istop = 2; end\n if test1 <= rtol, istop = 1; end\n\n % See if it is time to print something.\n\n if show\n prnt = 0;\n if n <= 40 , prnt = 1; end\n if itn <= 10 , prnt = 1; end\n if itn >= itnlim-10, prnt = 1; end\n if rem(itn,10) == 0 , prnt = 1; end\n if test3 <= 1.1*ctol , prnt = 1; end\n if test2 <= 1.1*atol , prnt = 1; end\n if test1 <= 1.1*rtol , prnt = 1; end\n if istop ~= 0 , prnt = 1; end\n\n if prnt\n\tif pcount >= pfreq\n\t pcount = 0;\n fprintf('\\n\\n%s%s' , hdg1 , hdg2 )\n\tend\n\tpcount = pcount + 1;\n fprintf('\\n%6g %12.5e' , itn , x(1) )\n fprintf(' %10.3e %10.3e', normr, normAr)\n fprintf(' %8.1e %8.1e' , test1, test2 )\n fprintf(' %8.1e %8.1e' , normA, condA )\n end\n end\n\n if istop > 0, break, end\n end % iteration loop\n\n % Print the stopping condition.\n\n if show\n fprintf('\\n\\nLSMR finished')\n fprintf('\\n%s', msg(istop+1,:))\n fprintf('\\nistop =%8g normr =%8.1e' , istop, normr )\n fprintf(' normA =%8.1e normAr =%8.1e', normA, normAr)\n fprintf('\\nitn =%8g condA =%8.1e' , itn , condA )\n fprintf(' normx =%8.1e\\n', normx)\n end\n\n% end function lsmr\n\n%---------------------------------------------------------------------\n% Nested functions.\n%---------------------------------------------------------------------\n\n function localVEnqueue(v)\n\n % Store v into the circular buffer localV.\n\n if localPointer < localSize\n localPointer = localPointer + 1;\n else\n localPointer = 1;\n localVQueueFull = true;\n end\n localV(:,localPointer) = v;\n\n end % nested function localVEnqueue\n\n%---------------------------------------------------------------------\n\n function vOutput = localVOrtho(v)\n\n % Perform local reorthogonalization of V.\n\n vOutput = v;\n if localVQueueFull\n localOrthoLimit = localSize;\n else\n localOrthoLimit = localPointer;\n end\n for localOrthoCount = 1:localOrthoLimit\n vtemp = localV(:, localOrthoCount);\n vOutput = vOutput - (vOutput'*vtemp)*vtemp;\n end\n\n end % nested function localVOrtho\n\nend % function lsmr\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/SignalProcessing/Q76333/lsmr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7332373417887645}} {"text": "function X = positive_definite_intrinsic_mean(A)\n% Computes an intrinsic mean of a collection of positive definite matrices.\n%\n% function X = positive_definite_intrinsic_mean(A)\n%\n% Input: A 3D matrix A of size nxnxm such that each slice A(:, :, k) is a\n% positive definite matrix of size nxn.\n% \n% Output: A positive definite matrix X of size nxn which is an intrinsic mean\n% of the m matrices in A, that is, X minimizes the sum of squared\n% Riemannian distances to the matrices in A:\n% f(X) = sum_k=1^m .5*dist^2(X, A(:, :, k))\n% The distance is defined by the natural metric on the set of\n% positive definite matrices: see sympositivedefinitefactory.\n% \n% This simple example is not the best way to compute intrinsic means. Its\n% purpose it to serve as base code to explore other algorithms. In\n% particular, in the presence of large noise, this algorithm seems not to\n% be able to reach points with a very small gradient norm. This may be\n% caused by insufficient accuracy in the gradient computation.\n%\n% See also: sympositivedefinitefactory\n\n% This file is part of Manopt and is copyrighted. See the license file.\n% \n% Main author: Nicolas Boumal, Sept. 3, 2013\n% Contributors:\n% \n% Change log:\n% Sep. 15, 2022 (NB):\n% Changed name from positive_definite_karcher_mean, clarified\n% some comments.\n \n % Generate some random data to test the function if none is given.\n if ~exist('A', 'var') || isempty(A)\n n = 5;\n m = 50;\n A = zeros(n, n, m);\n ref = diag(max(.1, 1+.1*randn(n, 1)));\n for i = 1 : m\n noise = 0.01*randn(n);\n noise = (noise + noise')/2;\n [V, D] = eig(ref + noise);\n A(:, :, i) = V*diag(max(.01, diag(D)))*V';\n end\n end\n \n % Retrieve the size of the problem:\n % There are m matrices of size nxn to average.\n n = size(A, 1);\n m = size(A, 3);\n assert(n == size(A, 2), ...\n ['The slices of A must be square, i.e., the ' ...\n\t 'first and second dimensions of A must be equal.']);\n \n % Our search space is the set of positive definite matrices of size n.\n % Notice that this is the only place we specify on which manifold we\n % wish to compute Karcher means. Replacing this factory for another\n % geometry will yield code to compute Karcher means on that other\n % manifold, provided that manifold is equipped with a dist function and\n % a logarithmic map log.\n M = sympositivedefinitefactory(n);\n \n % Define a problem structure, specifying the manifold M, the cost\n % function and its gradient.\n problem.M = M;\n problem.cost = @cost;\n problem.grad = @grad;\n \n % Explicitly pick an approximate Hessian for the trust-region method.\n % (This is only to show an example of how it can be done; the solver\n % below, rlbfgs, does not use the approximate Hessian; trustregions\n % would, but it would figure it out automatically with default\n % stepsize if the line below is omitted.)\n problem.approxhess = approxhessianFD(problem, struct('stepsize', 1e-4));\n \n % The functions below make many redundant computations. This\n % performance hit can be alleviated by using the caching system. We go\n % for a simple implementation here, as a tutorial example.\n \n % Cost function\n function f = cost(X)\n f = 0;\n for k = 1 : m\n f = f + M.dist(X, A(:, :, k))^2;\n end\n f = f/(2*m);\n end\n\n % Riemannian gradient of the cost function\n function g = grad(X)\n g = M.zerovec(X);\n for k = 1 : m\n % Update g in a linear combination of the form\n % g = g - [something]/m.\n g = M.lincomb(X, 1, g, -1/m, M.log(X, A(:, :, k)));\n end\n end\n \n % Execute some checks on the derivatives for early debugging.\n % These things can be commented out of course.\n % The slopes should agree on part of the plot at least. In this case,\n % it is sometimes necessary to inspect the plot visually to make the\n % call, but it is indeed correct.\n % checkgradient(problem);\n % pause;\n \n % Execute this if you want to force using a proper parallel vector\n % transport. This is not necessary. If you omit this, the default\n % vector transport is the identity map, which is (of course) cheaper\n % and seems to perform well in practice.\n % M.transp = M.paralleltransp;\n \n % Issue a call to a solver. Default options are selected.\n % Our initial guess is the first data point. Most solvers work well\n % with this problem. Limited-memory BFGS is one good example:\n X = rlbfgs(problem, A(:, :, 1));\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/examples/positive_definite_intrinsic_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7332373390032133}} {"text": "% Fig. 6.30 Feedback Control of Dynamic Systems, 5e \n% Franklin, Powell, Emami\n%\n\nclear all;\nclose all;\n\nnum=[1 1];\nden=conv([1 0],[0.1 -1]);\nw=logspace(-1,2,100);\n[m,p]=bode(num,den,w);\nsubplot(2,1,1),loglog(w,m,'-',w,ones(size(w)),'-');\ngrid;\nylabel('Magnitude');\ntitle('Fig. 6.30 Bode Plot for G=(s+1)/[s(s/10 -1)] (a) magnitude');\nsubplot(2,1,2)\nif p>0, p=p-360; end % Matlab quadrant control varies in different versions\nsemilogx(w,p,'-',w,-180*ones(size(w)),'-');\naxis([.1 100 -270 -90])\ngrid;\nxlabel('\\omega (rad/sec)');\nylabel('Phase (deg)');\ntitle('(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_30.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7332001784294614}} {"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 PresponseIL\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,iL,'erasemode','none','color',[0.9 0 0.8]), grid\n if Is==0\n title(['I_L(t) = (', num2str(A1i), ') e^{(', num2str(s(1)), 't)} + (', num2str(A2i), ') e^{(', num2str(s(2)), 't)}'],'color',[0.9 0 0.8])\n elseif Is~=0 \n title(['i_L(t) = ',num2str(Is), ' + (', num2str(A1i), ') e^{(', num2str(s(1)), 't)} + (', num2str(A2i), ') e^{(', num2str(s(2)), 't)}'],'color',[0.9 0 0.8])\n end\n xlabel(['\\alpha = ',num2str(alpha), ', \\omega_0 = ', num2str(w0), ' (O.D.) t, sec'])\n ylabel('i_L(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,iL,'erasemode','none','color',[.9 0 0.8]), grid\n if Is == 0\n title(['I_L(t) = e^{(-', num2str(alpha), 't)}[(', num2str(B1i), ')cos',num2str(wd),'t + (' , num2str(B2i), ')sin',num2str(wd),'t]'],'color',[0.9 0 0.8])\n elseif Is~= 0 \n title(['i_L(t) = ',num2str(Is), ' + e^{(-', num2str(alpha), 't)}[(', num2str(B1i), ')cos',num2str(wd),'t + (' , num2str(B2i), ')sin',num2str(wd),'t]'],'color',[0.9 0 0.8])\n end\n xlabel(['\\alpha = ',num2str(alpha), ', \\omega_0 = ', num2str(w0), ' (U.D.) t, sec'])\n ylabel('i_L(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,iL,'erasemode','none','color',[0.9 0 0.80]), grid\n \tif Is == 0\n \ttitle(['I_L(t) = (', num2str(B1i), ')cos',num2str(wd),'t + (' , num2str(B2i), ')sin',num2str(wd),'t'],'color',[0.9 0 0.8])\n \telseif Is ~= 0 \n \ttitle(['i_L(t) = ',num2str(Is), ' + (', num2str(B1i), ')cos',num2str(wd),'t + (' , num2str(B2i), ')sin',num2str(wd),'t'],'color',[0.9 0 0.8])\n \tend \n xlabel(['\\alpha = ',num2str(alpha), ', \\omega_0 = ', num2str(w0), ' (Undamped) t, sec'])\n ylabel('i_L(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,iL,'erasemode','none','color',[0.9 0 0.8]), grid\n \tif Is == 0\n title(['i_L(t) = e^{(-', num2str(alpha), 't)}[(', num2str(D1i), ')t + (' , num2str(D2i), ')]'],'color',[0.9 0 0.8])\n elseif Is ~= 0\n title(['i_L(t) = ',num2str(Is), ' + e^{(-', num2str(alpha), 't)}[(', num2str(D1i), ')t + (' , num2str(D2i), ')]'],'color',[0.9 0 0.8])\n end \n xlabel(['\\alpha = ',num2str(alpha), ', \\omega_0 = ', num2str(w0), ' (C.D.) t, sec'])\n ylabel('i_L(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/PresponseIL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7332001680506286}} {"text": "function [out, idxtrain,eigvector, eigvalue] = kpca(spectraldata, No_Train, dimension, kernel, parameter)\n\n%\n% Kernel principal component analysis, KPCA\n%\n% [out, eigvector, eigvalue] = kpca(spectraldata, No_Train, dimension, kernel, parameter)\n%\n% Input\n%\n% spectraldata - input hyperspectral data with 3-D, ncols by nrows by nbands\n% No_Train - randomly selected samples for training (<= 5000),\n% depending on the memory of your PC\n% dimension - the dimension of extracted kernelized PCs (with largest eigen values)\n% kernel - kernel function\n% parameter - parameters for kernel fuction\n% - kernel = 'linear';% linear kernel\n% - kernel = 'Gaussian'; parameter=1; %Gausian kernel\n% - kernel = 'poly'; parameter=[1,3];% third order polynomial \n%\n%\n% Output\n%\n% out - the extracted kernelized PCs\n% eigvector - the eigenvectors divided by square root of corresponding eigenvalues\n% eigvalue - the first dimension largest eigenvalues\n\nif nargin < 3, error('not enough input'); end\nif nargin < 4\n if strncmp(kernel,'Gaussian',1)\n parameter=1;\n elseif strncmp(kernel,'poly',1) \n parameter=[1, 3];\n end\nend\n \n[nrows,ncols,nbands] = size(spectraldata);\nX0 = reshape(spectraldata,nrows*ncols,nbands);\nclear spectraldata\n\n%% sub-sample for training, select No_Train samples randomly\nrand('state',4711007);% initialization of rand\nif No_Train>nrows*ncols, No_Train = nrows*ncols; end\nidxtrain = randsample(nrows*ncols, No_Train);\nX = double(X0(idxtrain,:));\nntrain = size(X,1);\n\nXtest = X0;\nntest = size(Xtest,1);\nclear X0;\n\n%% kernelized training data and centering the kernel matrix\n[K scale sums] = kernelize_training(kernel, X, parameter);\nmeanK = mean(K(:));\nmeanrowsK = mean(K);\nK = centering(K);\n\n%% select the first dimension eigvectors\ndimout = ntrain;\nif dimout>dimension, dimout=dimension; end\n[eigvector,eigvalue,flagk] = eigs(K, dimout, 'LM');\n\nif flagk~=0, warning('*** Convergence problems in eigs ***'); end\neigvalue = diag(abs(eigvalue))';\neigvector = sqrt(ntrain-1)*eigvector*diag(1./sqrt(eigvalue));\nclear K\n\nout = NaN(ntest,dimout);\n%% kernelized the test samples, center kernel and calculate kernel PCs\nfor rr=1:nrows\n idx = (rr-1)*ncols+1;\n idx = idx:(idx+ncols-1);\n Xk = kernelize_test(kernel, X, Xtest(idx,:), scale, sums);\n Xk = Xk - repmat(meanrowsK,ncols,1)' - repmat(mean(Xk),ntrain,1) + meanK;\n out(idx,:) = Xk'*eigvector;\nend\n\nout = reshape(out,nrows,ncols,dimout);\n", "meta": {"author": "BehnoodRasti", "repo": "HyFTech-Hyperspectral-Shallow-Deep-Feature-Extraction-Toolbox", "sha": "effc9ee5970306a2e822b1831c32ab5580c1bbfe", "save_path": "github-repos/MATLAB/BehnoodRasti-HyFTech-Hyperspectral-Shallow-Deep-Feature-Extraction-Toolbox", "path": "github-repos/MATLAB/BehnoodRasti-HyFTech-Hyperspectral-Shallow-Deep-Feature-Extraction-Toolbox/HyFTech-Hyperspectral-Shallow-Deep-Feature-Extraction-Toolbox-effc9ee5970306a2e822b1831c32ab5580c1bbfe/ShallowFE/UFE/MSTV/functions/kpca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.7331692646129716}} {"text": "function [d, pt1, pt2] = distanceLines3d(line1, line2)\n%DISTANCELINES3D Minimal distance between two 3D lines.\n%\n% D = distanceLines3d(LINE1, LINE2);\n% Returns the distance between line LINE1 and the line LINE2, given as:\n% LINE1 : [x0 y0 z0 dx dy dz] (or M-by-6 array)\n% LINE2 : [x0 y0 z0 dx dy dz] (or N-by-6 array)\n% D : (positive) array M-by-N\n%\n% [D, PT1, PT2] = distanceLines3d(LINE1, LINE2);\n% Also returns the points located on LINE1 and LINE2 corresponding to the\n% shortest distance. \n% One should get the following:\n% distancePoints3d(PT1, PT2) - D == 0\n%\n%\n% Example\n% line1 = [2 3 4 0 1 0];\n% line2 = [8 8 8 0 0 1];\n% distanceLines3d(line1, line2)\n% ans = \n% 6.0000\n%\n% See also:\n% lines3d, distancePoints3d\n%\n% ---------\n% authors: Brandon Baker, oqilipo, David Legland\n% created January 19, 2011\n%\n\n% number of points of each array\nn1 = size(line1, 1);\nn2 = size(line2, 1);\n\nif nargout <= 1\n % express line coordinate as n1-by-n2 arrays\n v1x = repmat(line1(:,4), [1 n2]);\n v1y = repmat(line1(:,5), [1 n2]);\n v1z = repmat(line1(:,6), [1 n2]);\n p1x = repmat(line1(:,1), [1 n2]);\n p1y = repmat(line1(:,2), [1 n2]);\n p1z = repmat(line1(:,3), [1 n2]);\n\n v2x = repmat(line2(:,4)', [n1 1]);\n v2y = repmat(line2(:,5)', [n1 1]);\n v2z = repmat(line2(:,6)', [n1 1]);\n p2x = repmat(line2(:,1)', [n1 1]);\n p2y = repmat(line2(:,2)', [n1 1]);\n p2z = repmat(line2(:,3)', [n1 1]);\n\n % calculates distance for each set of lines\n vcross = cross([v1x(:) v1y(:) v1z(:)], [v2x(:) v2y(:) v2z(:)]);\n num = ([p1x(:) p1y(:) p1z(:)] - [p2x(:) p2y(:) p2z(:)]) .* vcross;\n t1 = sum(num,2);\n d = abs(t1) ./ (vectorNorm3d(vcross) + eps);\n \n % returns result as n1-by-n2 array\n d = reshape(d, n1, n2);\n\nelse\n % check input dimension, as we need to be able to match each pair of\n % lines\n if n1 ~= n2\n error('geom3d:distanceLines3d:IllegalInputArgument', ...\n 'when output points are requested, number of lines should be the same');\n end\n \n p1 = line1(:, 1:3);\n p2 = line2(:, 1:3);\n dp = p2 - p1;\n v1 = line1(:, 4:6);\n v2 = line2(:, 4:6);\n\n % compute distance\n vcross = cross(v1, v2, 2);\n num = dp .* vcross;\n t1 = sum(num, 2);\n d = abs(t1) ./ (vectorNorm3d(vcross) + eps);\n\n % precomputations\n a = dot(v1, v1, 2);\n b = dot(v1, v2, 2);\n e = dot(v2, v2, 2);\n den = a.*e - b.*b; % 0, if lines are parallel\n \n % vector between origin of both lines\n r = line1(:,1:3) - line2(:,1:3);\n \n % solve linear system\n c = dot(v1, r, 2);\n f = dot(v2, r, 2);\n s = (b .* f - c .* e) ./ den;\n t = (a .* f - c .* b) ./ den;\n\n % convert to coordinates of points on lines\n pt1 = line1(:,1:3) + v1 .* s;\n pt2 = line2(:,1:3) + v2 .* t;\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/distanceLines3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7331692585372473}} {"text": "function [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes,varargin)\n% gridfit: estimates a surface on a 2d grid, based on scattered data\n% Replicates are allowed. All methods extrapolate to the grid\n% boundaries. Gridfit uses a modified ridge estimator to\n% generate the surface, where the bias is toward smoothness.\n%\n% Gridfit is not an interpolant. Its goal is a smooth surface\n% that approximates your data, but allows you to control the\n% amount of smoothing.\n%\n% usage #1: zgrid = gridfit(x,y,z,xnodes,ynodes);\n% usage #2: [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes);\n% usage #3: zgrid = gridfit(x,y,z,xnodes,ynodes,prop,val,prop,val,...);\n%\n% Arguments: (input)\n% x,y,z - vectors of equal lengths, containing arbitrary scattered data\n% The only constraint on x and y is they cannot ALL fall on a\n% single line in the x-y plane. Replicate points will be treated\n% in a least squares sense.\n%\n% ANY points containing a NaN are ignored in the estimation\n%\n% xnodes - vector defining the nodes in the grid in the independent\n% variable (x). xnodes need not be equally spaced. xnodes\n% must completely span the data. If they do not, then the\n% 'extend' property is applied, adjusting the first and last\n% nodes to be extended as necessary. See below for a complete\n% description of the 'extend' property.\n%\n% If xnodes is a scalar integer, then it specifies the number\n% of equally spaced nodes between the min and max of the data.\n%\n% ynodes - vector defining the nodes in the grid in the independent\n% variable (y). ynodes need not be equally spaced.\n%\n% If ynodes is a scalar integer, then it specifies the number\n% of equally spaced nodes between the min and max of the data.\n%\n% Also see the extend property.\n%\n% Additional arguments follow in the form of property/value pairs.\n% Valid properties are:\n% 'smoothness', 'interp', 'regularizer', 'solver', 'maxiter'\n% 'extend', 'tilesize', 'overlap'\n%\n% Any UNAMBIGUOUS shortening (even down to a single letter) is\n% valid for property names. All properties have default values,\n% chosen (I hope) to give a reasonable result out of the box.\n%\n% 'smoothness' - scalar - determines the eventual smoothness of the\n% estimated surface. A larger value here means the surface\n% will be smoother. Smoothness must be a non-negative real\n% number.\n%\n% Note: the problem is normalized in advance so that a\n% smoothness of 1 MAY generate reasonable results. If you\n% find the result is too smooth, then use a smaller value\n% for this parameter. Likewise, bumpy surfaces suggest use\n% of a larger value. (Sometimes, use of an iterative solver\n% with too small a limit on the maximum number of iterations\n% will result in non-convergence.)\n%\n% DEFAULT: 1\n%\n%\n% 'interp' - character, denotes the interpolation scheme used\n% to interpolate the data.\n%\n% DEFAULT: 'triangle'\n%\n% 'bilinear' - use bilinear interpolation within the grid\n% (also known as tensor product linear interpolation)\n%\n% 'triangle' - split each cell in the grid into a triangle,\n% then linear interpolation inside each triangle\n%\n% 'nearest' - nearest neighbor interpolation. This will\n% rarely be a good choice, but I included it\n% as an option for completeness.\n%\n%\n% 'regularizer' - character flag, denotes the regularization\n% paradignm to be used. There are currently three options.\n%\n% DEFAULT: 'gradient'\n%\n% 'diffusion' or 'laplacian' - uses a finite difference\n% approximation to the Laplacian operator (i.e, del^2).\n%\n% We can think of the surface as a plate, wherein the\n% bending rigidity of the plate is specified by the user\n% as a number relative to the importance of fidelity to\n% the data. A stiffer plate will result in a smoother\n% surface overall, but fit the data less well. I've\n% modeled a simple plate using the Laplacian, del^2. (A\n% projected enhancement is to do a better job with the\n% plate equations.)\n%\n% We can also view the regularizer as a diffusion problem,\n% where the relative thermal conductivity is supplied.\n% Here interpolation is seen as a problem of finding the\n% steady temperature profile in an object, given a set of\n% points held at a fixed temperature. Extrapolation will\n% be linear. Both paradigms are appropriate for a Laplacian\n% regularizer.\n%\n% 'gradient' - attempts to ensure the gradient is as smooth\n% as possible everywhere. Its subtly different from the\n% 'diffusion' option, in that here the directional\n% derivatives are biased to be smooth across cell\n% boundaries in the grid.\n%\n% The gradient option uncouples the terms in the Laplacian.\n% Think of it as two coupled PDEs instead of one PDE. Why\n% are they different at all? The terms in the Laplacian\n% can balance each other.\n%\n% 'springs' - uses a spring model connecting nodes to each\n% other, as well as connecting data points to the nodes\n% in the grid. This choice will cause any extrapolation\n% to be as constant as possible.\n%\n% Here the smoothing parameter is the relative stiffness\n% of the springs connecting the nodes to each other compared\n% to the stiffness of a spting connecting the lattice to\n% each data point. Since all springs have a rest length\n% (length at which the spring has zero potential energy)\n% of zero, any extrapolation will be minimized.\n%\n% Note: I don't terribly like the 'springs' strategy.\n% It tends to drag the surface towards the mean of all\n% the data. Its been left in only because the paradigm\n% interests me.\n%\n%\n% 'solver' - character flag - denotes the solver used for the\n% resulting linear system. Different solvers will have\n% different solution times depending upon the specific\n% problem to be solved. Up to a certain size grid, the\n% direct \\ solver will often be speedy, until memory\n% swaps causes problems.\n%\n% What solver should you use? Problems with a significant\n% amount of extrapolation should avoid lsqr. \\ may be\n% best numerically for small smoothnesss parameters and\n% high extents of extrapolation.\n%\n% Large numbers of points will slow down the direct\n% \\, but when applied to the normal equations, \\ can be\n% quite fast. Since the equations generated by these\n% methods will tend to be well conditioned, the normal\n% equations are not a bad choice of method to use. Beware\n% when a small smoothing parameter is used, since this will\n% make the equations less well conditioned.\n%\n% DEFAULT: 'normal'\n%\n% '\\' - uses matlab's backslash operator to solve the sparse\n% system. 'backslash' is an alternate name.\n%\n% 'symmlq' - uses matlab's iterative symmlq solver\n%\n% 'lsqr' - uses matlab's iterative lsqr solver\n%\n% 'normal' - uses \\ to solve the normal equations.\n%\n%\n% 'maxiter' - only applies to iterative solvers - defines the\n% maximum number of iterations for an iterative solver\n%\n% DEFAULT: min(10000,length(xnodes)*length(ynodes))\n%\n%\n% 'extend' - character flag - controls whether the first and last\n% nodes in each dimension are allowed to be adjusted to\n% bound the data, and whether the user will be warned if\n% this was deemed necessary to happen.\n%\n% DEFAULT: 'warning'\n%\n% 'warning' - Adjust the first and/or last node in\n% x or y if the nodes do not FULLY contain\n% the data. Issue a warning message to this\n% effect, telling the amount of adjustment\n% applied.\n%\n% 'never' - Issue an error message when the nodes do\n% not absolutely contain the data.\n%\n% 'always' - automatically adjust the first and last\n% nodes in each dimension if necessary.\n% No warning is given when this option is set.\n%\n%\n% 'tilesize' - grids which are simply too large to solve for\n% in one single estimation step can be built as a set\n% of tiles. For example, a 1000x1000 grid will require\n% the estimation of 1e6 unknowns. This is likely to\n% require more memory (and time) than you have available.\n% But if your data is dense enough, then you can model\n% it locally using smaller tiles of the grid.\n%\n% My recommendation for a reasonable tilesize is\n% roughly 100 to 200. Tiles of this size take only\n% a few seconds to solve normally, so the entire grid\n% can be modeled in a finite amount of time. The minimum\n% tilesize can never be less than 3, although even this\n% size tile is so small as to be ridiculous.\n%\n% If your data is so sparse than some tiles contain\n% insufficient data to model, then those tiles will\n% be left as NaNs.\n%\n% DEFAULT: inf\n%\n%\n% 'overlap' - Tiles in a grid have some overlap, so they\n% can minimize any problems along the edge of a tile.\n% In this overlapped region, the grid is built using a\n% bi-linear combination of the overlapping tiles.\n%\n% The overlap is specified as a fraction of the tile\n% size, so an overlap of 0.20 means there will be a 20%\n% overlap of successive tiles. I do allow a zero overlap,\n% but it must be no more than 1/2.\n%\n% 0 <= overlap <= 0.5\n%\n% Overlap is ignored if the tilesize is greater than the\n% number of nodes in both directions.\n%\n% DEFAULT: 0.20\n%\n%\n% 'autoscale' - Some data may have widely different scales on\n% the respective x and y axes. If this happens, then\n% the regularization may experience difficulties. \n% \n% autoscale = 'on' will cause gridfit to scale the x\n% and y node intervals to a unit length. This should\n% improve the regularization procedure. The scaling is\n% purely internal. \n%\n% autoscale = 'off' will disable automatic scaling\n%\n% DEFAULT: 'on'\n%\n%\n% Arguments: (output)\n% zgrid - (nx,ny) array containing the fitted surface\n%\n% xgrid, ygrid - as returned by meshgrid(xnodes,ynodes)\n%\n%\n% Speed considerations:\n% Remember that gridfit must solve a LARGE system of linear\n% equations. There will be as many unknowns as the total\n% number of nodes in the final lattice. While these equations\n% may be sparse, solving a system of 10000 equations may take\n% a second or so. Very large problems may benefit from the\n% iterative solvers or from tiling.\n%\n%\n% Example usage:\n%\n% x = rand(100,1);\n% y = rand(100,1);\n% z = exp(x+2*y);\n% xnodes = 0:.1:1;\n% ynodes = 0:.1:1;\n%\n% g = gridfit(x,y,z,xnodes,ynodes);\n%\n% Note: this is equivalent to the following call:\n%\n% g = gridfit(x,y,z,xnodes,ynodes, ...\n% 'smooth',1, ...\n% 'interp','triangle', ...\n% 'solver','normal', ...\n% 'regularizer','gradient', ...\n% 'extend','warning', ...\n% 'tilesize',inf);\n%\n%\n% Author: John D'Errico\n% e-mail address: woodchips@rochester.rr.com\n% Release: 2.0\n% Release date: 5/23/06\n\n% set defaults\nparams.smoothness = 1;\nparams.interp = 'triangle';\nparams.regularizer = 'gradient';\nparams.solver = 'normal';\nparams.maxiter = [];\nparams.extend = 'warning';\nparams.tilesize = inf;\nparams.overlap = 0.20;\nparams.mask = []; \nparams.autoscale = 'on';\nparams.xscale = 1;\nparams.yscale = 1;\n\n% was the params struct supplied?\nif ~isempty(varargin)\n if isstruct(varargin{1})\n % params is only supplied if its a call from tiled_gridfit\n params = varargin{1};\n if length(varargin)>1\n % check for any overrides\n params = parse_pv_pairs(params,varargin{2:end});\n end\n else\n % check for any overrides of the defaults\n params = parse_pv_pairs(params,varargin);\n\n end\nend\n\n% check the parameters for acceptability\nparams = check_params(params);\n\n% ensure all of x,y,z,xnodes,ynodes are column vectors,\n% also drop any NaN data\nx=x(:);\ny=y(:);\nz=z(:);\nk = isnan(x) | isnan(y) | isnan(z);\nif any(k)\n x(k)=[];\n y(k)=[];\n z(k)=[];\nend\nxmin = min(x);\nxmax = max(x);\nymin = min(y);\nymax = max(y);\n\n% did they supply a scalar for the nodes?\nif length(xnodes)==1\n xnodes = linspace(xmin,xmax,xnodes)';\n xnodes(end) = xmax; % make sure it hits the max\nend\nif length(ynodes)==1\n ynodes = linspace(ymin,ymax,ynodes)';\n ynodes(end) = ymax; % make sure it hits the max\nend\n\nxnodes=xnodes(:);\nynodes=ynodes(:);\ndx = diff(xnodes);\ndy = diff(ynodes);\nnx = length(xnodes);\nny = length(ynodes);\nngrid = nx*ny;\n\n% set the scaling if autoscale was on\nif strcmpi(params.autoscale,'on')\n params.xscale = mean(dx);\n params.yscale = mean(dy);\n params.autoscale = 'off';\nend\n\n% check to see if any tiling is necessary\nif (params.tilesize < max(nx,ny))\n % split it into smaller tiles. compute zgrid and ygrid\n % at the very end if requested\n zgrid = tiled_gridfit(x,y,z,xnodes,ynodes,params);\nelse\n % its a single tile.\n \n % mask must be either an empty array, or a boolean\n % aray of the same size as the final grid.\n nmask = size(params.mask);\n if ~isempty(params.mask) && ((nmask(2)~=nx) || (nmask(1)~=ny))\n if ((nmask(2)==ny) || (nmask(1)==nx))\n error 'Mask array is probably transposed from proper orientation.'\n else\n error 'Mask array must be the same size as the final grid.'\n end\n end\n if ~isempty(params.mask)\n params.maskflag = 1;\n else\n params.maskflag = 0;\n end\n\n % default for maxiter?\n if isempty(params.maxiter)\n params.maxiter = min(10000,nx*ny);\n end\n\n % check lengths of the data\n n = length(x);\n if (length(y)~=n) || (length(z)~=n)\n error 'Data vectors are incompatible in size.'\n end\n if n<3\n error 'Insufficient data for surface estimation.'\n end\n\n % verify the nodes are distinct\n if any(diff(xnodes)<=0) || any(diff(ynodes)<=0)\n error 'xnodes and ynodes must be monotone increasing'\n end\n\n % do we need to tweak the first or last node in x or y?\n if xminxnodes(end)\n switch params.extend\n case 'always'\n xnodes(end) = xmax;\n case 'warning'\n warning(['xnodes(end) was increased by: ',num2str(xmax-xnodes(end)),', new node = ',num2str(xmax)])\n xnodes(end) = xmax;\n case 'never'\n error(['Some x (',num2str(xmax),') falls above xnodes(end) by: ',num2str(xmax-xnodes(end))])\n end\n end\n if yminynodes(end)\n switch params.extend\n case 'always'\n ynodes(end) = ymax;\n case 'warning'\n warning(['ynodes(end) was increased by: ',num2str(ymax-ynodes(end)),', new node = ',num2str(ymax)])\n ynodes(end) = ymax;\n case 'never'\n error(['Some y (',num2str(ymax),') falls above ynodes(end) by: ',num2str(ymax-ynodes(end))])\n end\n end\n\n % determine which cell in the array each point lies in\n [junk,indx] = histc(x,xnodes); %#ok\n [junk,indy] = histc(y,ynodes); %#ok\n % any point falling at the last node is taken to be\n % inside the last cell in x or y.\n k=(indx==nx);\n indx(k)=indx(k)-1;\n k=(indy==ny);\n indy(k)=indy(k)-1;\n ind = indy + ny*(indx-1);\n\n % Do we have a mask to apply?\n if params.maskflag\n % if we do, then we need to ensure that every\n % cell with at least one data point also has at\n % least all of its corners unmasked.\n params.mask(ind) = 1;\n params.mask(ind+1) = 1;\n params.mask(ind+ny) = 1;\n params.mask(ind+ny+1) = 1;\n end\n\n % interpolation equations for each point\n tx = min(1,max(0,(x - xnodes(indx))./dx(indx)));\n ty = min(1,max(0,(y - ynodes(indy))./dy(indy)));\n % Future enhancement: add cubic interpolant\n switch params.interp\n case 'triangle'\n % linear interpolation inside each triangle\n k = (tx > ty);\n L = ones(n,1);\n L(k) = ny;\n\n t1 = min(tx,ty);\n t2 = max(tx,ty);\n A = sparse(repmat((1:n)',1,3),[ind,ind+ny+1,ind+L], ...\n [1-t2,t1,t2-t1],n,ngrid);\n\n case 'nearest'\n % nearest neighbor interpolation in a cell\n k = round(1-ty) + round(1-tx)*ny;\n A = sparse((1:n)',ind+k,ones(n,1),n,ngrid);\n\n case 'bilinear'\n % bilinear interpolation in a cell\n A = sparse(repmat((1:n)',1,4),[ind,ind+1,ind+ny,ind+ny+1], ...\n [(1-tx).*(1-ty), (1-tx).*ty, tx.*(1-ty), tx.*ty], ...\n n,ngrid);\n\n end\n rhs = z;\n\n % Build regularizer. Add del^4 regularizer one day.\n switch params.regularizer\n case 'springs'\n % zero \"rest length\" springs\n [i,j] = meshgrid(1:nx,1:(ny-1));\n ind = j(:) + ny*(i(:)-1);\n m = nx*(ny-1);\n stiffness = 1./(dy/params.yscale);\n Areg = sparse(repmat((1:m)',1,2),[ind,ind+1], ...\n stiffness(j(:))*[-1 1],m,ngrid);\n\n [i,j] = meshgrid(1:(nx-1),1:ny);\n ind = j(:) + ny*(i(:)-1);\n m = (nx-1)*ny;\n stiffness = 1./(dx/params.xscale);\n Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny], ...\n stiffness(i(:))*[-1 1],m,ngrid)];\n\n [i,j] = meshgrid(1:(nx-1),1:(ny-1));\n ind = j(:) + ny*(i(:)-1);\n m = (nx-1)*(ny-1);\n stiffness = 1./sqrt((dx(i(:))/params.xscale).^2 + ...\n (dy(j(:))/params.yscale).^2);\n \n Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny+1], ...\n stiffness*[-1 1],m,ngrid)];\n\n Areg = [Areg;sparse(repmat((1:m)',1,2),[ind+1,ind+ny], ...\n stiffness*[-1 1],m,ngrid)];\n\n case {'diffusion' 'laplacian'}\n % thermal diffusion using Laplacian (del^2)\n [i,j] = meshgrid(1:nx,2:(ny-1));\n ind = j(:) + ny*(i(:)-1);\n dy1 = dy(j(:)-1)/params.yscale;\n dy2 = dy(j(:))/params.yscale;\n\n Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...\n [-2./(dy1.*(dy1+dy2)), 2./(dy1.*dy2), ...\n -2./(dy2.*(dy1+dy2))],ngrid,ngrid);\n\n [i,j] = meshgrid(2:(nx-1),1:ny);\n ind = j(:) + ny*(i(:)-1);\n dx1 = dx(i(:)-1)/params.xscale;\n dx2 = dx(i(:))/params.xscale;\n\n Areg = Areg + sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ...\n [-2./(dx1.*(dx1+dx2)), 2./(dx1.*dx2), ...\n -2./(dx2.*(dx1+dx2))],ngrid,ngrid);\n\n case 'gradient'\n % Subtly different from the Laplacian. A point for future\n % enhancement is to do it better for the triangle interpolation\n % case.\n [i,j] = meshgrid(1:nx,2:(ny-1));\n ind = j(:) + ny*(i(:)-1);\n dy1 = dy(j(:)-1)/params.yscale;\n dy2 = dy(j(:))/params.yscale;\n\n Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...\n [-2./(dy1.*(dy1+dy2)), 2./(dy1.*dy2), ...\n -2./(dy2.*(dy1+dy2))],ngrid,ngrid);\n\n [i,j] = meshgrid(2:(nx-1),1:ny);\n ind = j(:) + ny*(i(:)-1);\n dx1 = dx(i(:)-1)/params.xscale;\n dx2 = dx(i(:))/params.xscale;\n\n Areg = [Areg;sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ...\n [-2./(dx1.*(dx1+dx2)), 2./(dx1.*dx2), ...\n -2./(dx2.*(dx1+dx2))],ngrid,ngrid)];\n\n end\n nreg = size(Areg,1);\n\n % Append the regularizer to the interpolation equations,\n % scaling the problem first. Use the 1-norm for speed.\n NA = norm(A,1);\n NR = norm(Areg,1);\n A = [A;Areg*(params.smoothness*NA/NR)];\n rhs = [rhs;zeros(nreg,1)];\n % do we have a mask to apply?\n if params.maskflag\n unmasked = find(params.mask);\n end\n % solve the full system, with regularizer attached\n switch params.solver\n case {'\\' 'backslash'}\n if params.maskflag\n % there is a mask to use\n % permute for minimum fill in for R (in the QR)\n p = colamd(A(:,unmasked));\n zgrid=nan(ny,nx);\n zgrid(unmasked(p)) = A(:,unmasked(p))\\rhs;\n else\n % permute for minimum fill in for R (in the QR)\n p = colamd(A);\n zgrid=zeros(ny,nx);\n zgrid(p) = A(:,p)\\rhs;\n end\n\n case 'normal'\n % The normal equations, solved with \\. Can be fast\n % for huge numbers of data points.\n if params.maskflag\n % there is a mask to use\n % Permute for minimum fill-in for \\ (in chol)\n APA = A(:,unmasked)'*A(:,unmasked);\n p = symamd(APA);\n zgrid=nan(ny,nx);\n zgrid(unmasked(p)) = APA(p,p)\\(A(:,unmasked(p))'*rhs);\n else\n % Permute for minimum fill-in for \\ (in chol)\n APA = A'*A;\n p = symamd(APA);\n zgrid=zeros(ny,nx);\n zgrid(p) = APA(p,p)\\(A(:,p)'*rhs);\n end\n\n case 'symmlq'\n % iterative solver - symmlq - requires a symmetric matrix,\n % so use it to solve the normal equations. No preconditioner.\n tol = abs(max(z)-min(z))*1.e-13;\n if params.maskflag\n % there is a mask to use\n zgrid=nan(ny,nx);\n [zgrid(unmasked),flag] = symmlq(A(:,unmasked)'*A(:,unmasked), ...\n A(:,unmasked)'*rhs,tol,params.maxiter);\n else\n [zgrid,flag] = symmlq(A'*A,A'*rhs,tol,params.maxiter);\n zgrid = reshape(zgrid,ny,nx);\n end\n % display a warning if convergence problems\n switch flag\n case 0\n % no problems with convergence\n case 1\n % SYMMLQ iterated MAXIT times but did not converge.\n warning(['Symmlq performed ',num2str(params.maxiter), ...\n ' iterations but did not converge.'])\n case 3\n % SYMMLQ stagnated, successive iterates were the same\n warning 'Symmlq stagnated without apparent convergence.'\n otherwise\n warning(['One of the scalar quantities calculated in',...\n ' symmlq was too small or too large to continue computing.'])\n end\n\n case 'lsqr'\n % iterative solver - lsqr. No preconditioner here.\n tol = abs(max(z)-min(z))*1.e-13;\n if params.maskflag\n % there is a mask to use\n zgrid=nan(ny,nx);\n [zgrid(unmasked),flag] = lsqr(A(:,unmasked),rhs,tol,params.maxiter);\n else\n [zgrid,flag] = lsqr(A,rhs,tol,params.maxiter);\n zgrid = reshape(zgrid,ny,nx);\n end\n\n % display a warning if convergence problems\n switch flag\n case 0\n % no problems with convergence\n case 1\n % lsqr iterated MAXIT times but did not converge.\n warning(['Lsqr performed ',num2str(params.maxiter), ...\n ' iterations but did not converge.'])\n case 3\n % lsqr stagnated, successive iterates were the same\n warning 'Lsqr stagnated without apparent convergence.'\n case 4\n warning(['One of the scalar quantities calculated in',...\n ' LSQR was too small or too large to continue computing.'])\n end\n\n end\n\nend % if params.tilesize...\n\n% only generate xgrid and ygrid if requested.\nif nargout>1\n [xgrid,ygrid]=meshgrid(xnodes,ynodes);\nend\n\n% ============================================\n% End of main function - gridfit\n% ============================================\n\n% ============================================\n% 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\n\n% ============================================\n% subfunction - check_params\n% ============================================\nfunction params = check_params(params)\n\n% check the parameters for acceptability\n% smoothness == 1 by default\nif isempty(params.smoothness)\n params.smoothness = 1;\nelse\n if (length(params.smoothness)>1) || (params.smoothness<=0)\n error 'Smoothness must be scalar, real, finite, and positive.'\n end\nend\n\n% regularizer - must be one of 4 options - the second and\n% third are actually synonyms.\nvalid = {'springs', 'diffusion', 'laplacian', 'gradient'};\nif isempty(params.regularizer)\n params.regularizer = 'diffusion';\nend\nind = find(strncmpi(params.regularizer,valid,length(params.regularizer)));\nif (length(ind)==1)\n params.regularizer = valid{ind};\nelse\n error(['Invalid regularization method: ',params.regularizer])\nend\n\n% interp must be one of:\n% 'bilinear', 'nearest', or 'triangle'\n% but accept any shortening thereof.\nvalid = {'bilinear', 'nearest', 'triangle'};\nif isempty(params.interp)\n params.interp = 'triangle';\nend\nind = find(strncmpi(params.interp,valid,length(params.interp)));\nif (length(ind)==1)\n params.interp = valid{ind};\nelse\n error(['Invalid interpolation method: ',params.interp])\nend\n\n% solver must be one of:\n% 'backslash', '\\', 'symmlq', 'lsqr', or 'normal'\n% but accept any shortening thereof.\nvalid = {'backslash', '\\', 'symmlq', 'lsqr', 'normal'};\nif isempty(params.solver)\n params.solver = '\\';\nend\nind = find(strncmpi(params.solver,valid,length(params.solver)));\nif (length(ind)==1)\n params.solver = valid{ind};\nelse\n error(['Invalid solver option: ',params.solver])\nend\n\n% extend must be one of:\n% 'never', 'warning', 'always'\n% but accept any shortening thereof.\nvalid = {'never', 'warning', 'always'};\nif isempty(params.extend)\n params.extend = 'warning';\nend\nind = find(strncmpi(params.extend,valid,length(params.extend)));\nif (length(ind)==1)\n params.extend = valid{ind};\nelse\n error(['Invalid extend option: ',params.extend])\nend\n\n% tilesize == inf by default\nif isempty(params.tilesize)\n params.tilesize = inf;\nelseif (length(params.tilesize)>1) || (params.tilesize<3)\n error 'Tilesize must be scalar and > 0.'\nend\n\n% overlap == 0.20 by default\nif isempty(params.overlap)\n params.overlap = 0.20;\nelseif (length(params.overlap)>1) || (params.overlap<0) || (params.overlap>0.5)\n error 'Overlap must be scalar and 0 < overlap < 1.'\nend\n\n% ============================================\n% subfunction - tiled_gridfit\n% ============================================\nfunction zgrid=tiled_gridfit(x,y,z,xnodes,ynodes,params)\n% tiled_gridfit: a tiled version of gridfit, continuous across tile boundaries \n% usage: [zgrid,xgrid,ygrid]=tiled_gridfit(x,y,z,xnodes,ynodes,params)\n%\n% Tiled_gridfit is used when the total grid is far too large\n% to model using a single call to gridfit. While gridfit may take\n% only a second or so to build a 100x100 grid, a 2000x2000 grid\n% will probably not run at all due to memory problems.\n%\n% Tiles in the grid with insufficient data (<4 points) will be\n% filled with NaNs. Avoid use of too small tiles, especially\n% if your data has holes in it that may encompass an entire tile.\n%\n% A mask may also be applied, in which case tiled_gridfit will\n% subdivide the mask into tiles. Note that any boolean mask\n% provided is assumed to be the size of the complete grid.\n%\n% Tiled_gridfit may not be fast on huge grids, but it should run\n% as long as you use a reasonable tilesize. 8-)\n\n% Note that we have already verified all parameters in check_params\n\n% Matrix elements in a square tile\ntilesize = params.tilesize;\n% Size of overlap in terms of matrix elements. Overlaps\n% of purely zero cause problems, so force at least two\n% elements to overlap.\noverlap = max(2,floor(tilesize*params.overlap));\n\n% reset the tilesize for each particular tile to be inf, so\n% we will never see a recursive call to tiled_gridfit\nTparams = params;\nTparams.tilesize = inf;\n\nnx = length(xnodes);\nny = length(ynodes);\nzgrid = zeros(ny,nx);\n\n% linear ramp for the bilinear interpolation\nrampfun = inline('(t-t(1))/(t(end)-t(1))','t');\n\n% loop over each tile in the grid\nh = mrvWaitbar(0,'Relax and have a cup of JAVA. Its my treat.');\nwarncount = 0;\nxtind = 1:min(nx,tilesize);\nwhile ~isempty(xtind) && (xtind(1)<=nx)\n \n xinterp = ones(1,length(xtind));\n if (xtind(1) ~= 1)\n xinterp(1:overlap) = rampfun(xnodes(xtind(1:overlap)));\n end\n if (xtind(end) ~= nx)\n xinterp((end-overlap+1):end) = 1-rampfun(xnodes(xtind((end-overlap+1):end)));\n end\n \n ytind = 1:min(ny,tilesize);\n while ~isempty(ytind) && (ytind(1)<=ny)\n % update the mrvWaitbar\n mrvWaitbar((xtind(end)-tilesize)/nx + tilesize*ytind(end)/ny/nx)\n \n yinterp = ones(length(ytind),1);\n if (ytind(1) ~= 1)\n yinterp(1:overlap) = rampfun(ynodes(ytind(1:overlap)));\n end\n if (ytind(end) ~= ny)\n yinterp((end-overlap+1):end) = 1-rampfun(ynodes(ytind((end-overlap+1):end)));\n end\n \n % was a mask supplied?\n if ~isempty(params.mask)\n submask = params.mask(ytind,xtind);\n Tparams.mask = submask;\n end\n \n % extract data that lies in this grid tile\n k = (x>=xnodes(xtind(1))) & (x<=xnodes(xtind(end))) & ...\n (y>=ynodes(ytind(1))) & (y<=ynodes(ytind(end)));\n k = find(k);\n \n if length(k)<4\n if warncount == 0\n warning 'A tile was too underpopulated to model. Filled with NaNs.'\n end\n warncount = warncount + 1;\n \n % fill this part of the grid with NaNs\n zgrid(ytind,xtind) = NaN;\n \n else\n % build this tile\n zgtile = gridfit(x(k),y(k),z(k),xnodes(xtind),ynodes(ytind),Tparams);\n \n % bilinear interpolation (using an outer product)\n interp_coef = yinterp*xinterp;\n \n % accumulate the tile into the complete grid\n zgrid(ytind,xtind) = zgrid(ytind,xtind) + zgtile.*interp_coef;\n \n end\n \n % step to the next tile in y\n if ytind(end)=ny\n % extend this tile to the edge\n ytind = ytind(1):ny;\n end\n else\n ytind = ny+1;\n end\n \n end % while loop over y\n \n % step to the next tile in x\n if xtind(end)=nx\n % extend this tile to the edge\n xtind = xtind(1):nx;\n end\n else\n xtind = nx+1;\n end\n\nend % while loop over x\n\n% close down the mrvWaitbar\nclose(h)\n\nif warncount>0\n warning([num2str(warncount),' tiles were underpopulated & filled with NaNs'])\nend\n\n\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/mrAnatomy/hydrationLayer/gridfit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7331692523898844}} {"text": "function det = r8ge_np_det ( n, a_lu )\n\n%*****************************************************************************80\n%\n%% R8GE_NP_DET computes the determinant of a matrix factored by R8GE_NP_FA.\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% 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 must be positive.\n%\n% Input, real A_LU(N,N), the LU factors from R8GE_NP_FA.\n%\n% Output, real DET, the determinant of the matrix.\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/r8ge_np_det.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7331418430799671}} {"text": "function model = ml_trainlda(varargin)\n% Learn a linear predictive model by (regularized) Linear Discriminant Analysis.\n% Model = ml_trainlda(Trials, Targets, Lambda, Options...)\n%\n% LDA is one of the simplest and oldest learning algorithms, originally introduced by Fisher in [1].\n% Its basic assumption is that the data originates from two classes (extended to more via 1-vs-1\n% voting), where the data in each class is distributed in the feature space according to a normal\n% distribution. The shape of the distribution is assumed to be identical for both classes, and the\n% relative weight/prior probability of each class is (by default) assumed to be identical, as well.\n% An example would be data with features generated as a weighted sum of some latent variables which\n% take on different values between conditions (but identical values within each condition), and\n% which are superimposed with gaussian noise (which is identically distributed across conditions,\n% e.g. from a large sum of independent random variables).\n%\n% Despite its simplicity, LDA assumes more structure in the data than is usually necessary (namely a\n% certain normal distribution per class), and sometimes, more than what can be satisfactorily\n% learned from the data, so that, even when the assumptions are fulfilled, the method is not\n% guaranteed to give the optimal result. The estimation of the per-class covariance matrix is a\n% notoriously data-hungry (and especially outlier-sensitive) step, and the main weakness of standard\n% LDA.\n%\n% ml_trainlda offers three advanced covariance estimators, with different trade-offs to mitigate\n% these problems. The variants 'shrinkage' and 'independence' each introduce a regularization\n% parameter [2] which controls the complexity of the estimated matrix, and which need to be selected\n% in a parameter search (which is orders of magnitude more time-consuming). The 'auto' variant\n% computes the degree of regularization analyically in closed form, and is therefore both fast and\n% (in some sense) optimal (but more restricted than 'independence') [3]. When enough trials are\n% available, full covariance matrices are learned, but the less trials are given, the more the\n% covariance estimates degrade to spherical (though well-formed) ones. Auto is the default for lda.\n%\n% While regularization can automatically control the complexity of a classifier, it is not a panacea\n% which allows to add arbitrarily many features, since with each additional feature, the amount of\n% structure (here:correlation) that can be captured in the remaining ones gets reduced.\n%\n% Within the toolbox, LDA is one of the bread-and-butter classifiers, and is worth trying in every\n% reasonably simple classification task, especially for its speed. The major problem with LDA\n% compared to other available classifiers is that it easier to break it with outliers than, for\n% example, support vector machines or logistic regression. Another weakness is that the outputs are\n% relatively primitive probability estimates, in contrast to, for example, logistic regression\n% (somewhat better) or relevance vector machines (clearly better).\n%\n% In:\n% Trials : training data, as in ml_train\n%\n% Targets : target variable, as in ml_train\n%\n% Lambda : optional regularization parameter, reasonable range: 0:0.1:1, greater is stronger\n% requires that the regularization mode is set to either 'shrinkage' or 'independence' (default: [])\n% \n% Options : optional name-value parameters to control the training details:\n% 'regularization' -> 'shrinkage': covariance shrinkage, depends on plambda \n% 'independence': feature independence, depends on plambda\n% 'auto': analytical covariance shrinkage, plambda is ignored (default)\n% 'weight_bias' -> 0/1, take unequal class priors into account for bias calculation\n% default: 0\n% 'weight_cov' -> 0/1, take unequal class priors into account for covariance calculation\n% default: 0\n% Out:\n% Model : a linear model; w is the linear weights, b is the bias; classes indicates the class labels which the model predicts\n%\n% Examples:\n% % learn a standard shrinkage LDA model\n% model = ml_trainlda(trials,targets);\n%\n% % take unequal class priors into account for both the bias and the covariance matrix\n% model = ml_trainlda(trials,targets,[],'weight_bias',1,'weight_cov',1);\n%\n% % use a different type of regularization, which controls feature independence and requires cross-validation\n% model = utl_searchmodel({trials,target},'args',{{'lda',search(0:0.1:1),'regularization','independence'}})\n%\n%\n% See also:\n% ml_predictlda\n%\n% References:\n% [1] Fisher, R. \"The use of multiple measurements in taxonomic problems.\"\n% Annals Eugen. 7 (1936), 188, 179.\n% [2] Friedman, J. \"Regularized discriminant analysis.\" \n% Journal of the American Statistical Association 84, 405 (1989), 175, 165.\n% [3] O. Ledoit and M. Wolf, \"A well-conditioned estimator for large-dimensional covariance matrices\"\n% J Multivar Anal, 88(2): 365-411, 2004.\n%\n% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD\n% 2010-04-03\ndp; \n\narg_define([0 3],varargin, ...\n arg_norep('trials'), ...\n arg_norep('targets'), ...\n arg({'plambda','Lambda','lambda'}, [], [0 1], 'Optional regularization parameter. Reasonable range: 0:0.1:1 - greater is stronger. Requires that the regularization mode is set to either \"shrinkage\" or \"independence\" (not necessary in \"auto\" mode).'), ...\n arg({'regularization','Regularizer','Regularization'}, 'auto', {'none','auto','shrinkage','independence'}, 'Type of regularization. Regularizes the robustness / flexibility of covariance estimates. Auto is analytical covariance shrinkage, shrinkage is shrinkage as selected via plambda, and independence is feature independence, also selected via plambda.'), ...\n arg({'weight_bias','WeightedBias'}, false, [], 'Account for class priors in bias. If you do have unequal probabilities for the different classes, this should be enabled.'), ...\n arg({'weight_cov','WeightedCov'}, false, [], 'Account for class priors in covariance. If you do have unequal probabilities for the different classes, it makes sense to enable this.'), ...\n arg({'robust','Robust'}, false, [], 'Use robust estimation. Uses geometric medians in place of means; can help if some trials are very noisy.'), ...\n arg({'votingScheme','VotingScheme'},'1vR',{'1v1','1vR'},'Voting scheme. If multi-class classification is used, this determine how binary classifiers are arranged to solve the multi-class problem. 1v1 gets slow for large numbers of classes (as all pairs are tested), but can be more accurate than 1vR.'));\n\n% find the class labels\nclasses = unique(targets);\nif length(classes) > 2\n % learn a voting arrangement of models...\n model = ml_trainvote(trials, targets, votingScheme, @ml_trainlda, @ml_predictlda, varargin{:},'weight_bias',true); %#ok<*NODEF>\nelseif length(classes) == 1\n error('BCILAB:only_one_class','Your training data set has no trials for one of your classes; you need at least two classes to train a classifier.\\n\\nThe most likely reasons are that one of your target markers does not occur in the data, or that all your trials of a particular class are concentrated in a single short segment of your data (10 or 20 percent). The latter would be a problem with the experiment design.');\nelse\n % pre-prune degenerate features\n retain = true(1,size(trials,2));\n for c = 1:length(classes)\n X = trials(targets==classes(c),:);\n n{c} = size(X,1);\n mu{c} = mean(X,1);\n v{c} = var(X,[],1);\n retain = retain & isfinite(mu{c}) & isfinite(v{c}) & (n{c}==1 | v{c} > eps);\n end \n % apply feature mask...\n trials = trials(:,retain);\n % estimate distribution of each class...\n for c = 1:length(classes)\n lams{c} = NaN;\n X = trials(targets==classes(c),:);\n n{c} = size(X,1);\n if robust\n mu{c} = geometric_median(X);\n else\n mu{c} = mean(X,1);\n end\n if n{c} == 1\n sig{c} = zeros(size(X,2));\n elseif strcmp(regularization,'auto')\n if robust\n % for lack of a better solution in this case we estimate lambda using a non-robust\n % Ledoit-Wolf estimator and then use it in a subsequent robust re-estimation\n [dummy,lams{c}] = cov_shrink(X); %#ok\n sig{c} = cov_blockgeom(X,1);\n sig{c} = (1-lams{c})*sig{c} + lams{c}*eye(length(sig{c}))*abs(mean(diag(sig{c})));\n else\n [sig{c},lams{c}] = cov_shrink(X);\n end\n else\n if robust\n sig{c} = cov_blockgeom(X,1);\n else\n sig{c} = cov(X);\n end\n if ~isempty(plambda) && ~strcmp(regularization,'none')\n % plambda-dependent regularization\n if strcmp(regularization,'independence')\n sig{c} = (1-plambda)*sig{c} + plambda * diag(diag(sig{c}));\n elseif strcmp(regularization,'shrinkage')\n sig{c} = (1-plambda)*sig{c} + plambda*eye(length(sig{c}))*abs(mean(diag(sig{c})));\n else\n error('unknown regularization mode');\n end\n end\n end\n end\n \n ns = quickif(weight_cov,n,{1 1});\n nb = quickif(weight_bias,n,{1 1});\n % do the math\n mu_both = (mu{1}*nb{2} + mu{2}*nb{1}) / (nb{1}+nb{2}); \n sig_both = (sig{1}*ns{1} + sig{2}*ns{2}) / (ns{1}+ns{2});\n w = (mu{2} - mu{1}) / sig_both;\n w = w / (mu{2}*w' - mu_both*w');\n model = struct('w',{w}, 'b',{mu_both*w'}, 'classes',{classes},'featuremask',{retain},'lams',{lams});\n 1;\nend\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/code/machine_learning/ml_trainlda.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7331370811890328}} {"text": "function [samples,gammas,Lambda,joints2D,hists] = DGAnyMarginal(pmfs,Sigma,supports,Nsamples)\n\n% [samples,gammas,Lambda,joints2D,hists] = DGAnyMarginal(pmfs,Sigma,supports,Nsamples)\n% Generates samples from a Multivariate Discretized Gaussian with specified marginals\n% and covariance. Also returns parameters of the fitted DG.\n%\n% Inputs:\n% pmfs: the probability mass functions of the marginal distribution of the\n% input-random variables. Must be a cell-array with n elements, each of\n% which is a vector which sums to one\n% Sigma: The covariance matrix of the input-random variable. The function\n% does not check for admissability, i.e. results might be wrong if there\n% exists no random variable which has the specified marginals and\n% covariance.\n% supports: The support of each dimension of the input random variable.\n% Must be a cell-array with n elements, each of whcih is a vector with\n% increasing entries giving the possible values of each random variable,\n% e.g. if the first dimension of the rv is 1 with probability .2, 3 with\n% prob .8, then pmfs{1}=[.2,.8], supports{1}=[1,3]; If empty support is\n% specified, then each is taken to be [0:numel(pdfs{k}-1];\n% Nsamples: The number of samples to be generated.\n%\n% Outputs:\n% samples: a matrix of size Nsamples by n, where each row is a sample from\n% the DG.\n% gammas: the discretization thresholds, as described in the paper. When\n% sampling. The k-th dimension of the output random variable is f if e.g.\n% supports{k}(1)=f and gammas{k}(f) <= U(k) <= gammas{k}(f+1)\n% Lambda: the covariance matrix of the latent Gaussian random variable U\n% joints2D: An n by n cell array, where each entry contains the 2\n% dimensional joint distribution of a pair of dimensions of the DG.\n% hists: the empirical marginals of the samples returned in \"samples\"\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\n[gammas,Lambda,joints2D]=FindDGAnyMarginal(pmfs,Sigma,supports);\n\n[samples,hists]=SampleDGAnyMarginal(gammas,Lambda,supports,Nsamples);\n\nsamples = samples';\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/interface/DGAnyMarginal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7331188005580177}} {"text": "function [dist, proj] = distancePointEllipse(point, elli)\n%DISTANCEPOINTELLIPSE Distance from a point to an ellipse.\n%\n% DIST = distancePointEllipse(POINT, ELLI)\n% Computes the Euclidean distance between the point POINT and the ellipse\n% ELLI.\n% POINT may also be a N-by-2 array of point coordinates. In that case the\n% result is a N-by-1 array of distances.\n%\n% [DIST, PROJ] = distancePointEllipse(POINT, ELLI)\n% Also return the coordinates of the projection of the point onto the\n% ellipse. PROJ has same dimensions as the array POINT.\n%\n% Example\n% % create an ellipse\n% elli = [50 50 40 30 20];\n% % generate points along a regular grid\n% [x, y] = meshgrid(1:100, 1:100);\n% pts = [x(:) y(:)];\n% % compute distance map\n% distMap = reshape(distancePointEllipse(pts, elli), size(x));\n% figure; imshow(distMap, []); colormap parula;\n%\n%\n% References:\n% https://blog.chatfield.io/simple-method-for-distance-to-ellipse/\n%\n% See also \n% ellipses2d, projPointOnEllipse, distancePoints\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inrae.fr\n% Created: 2022-07-17, using Matlab 9.12.0.1884302 (R2022a)\n% Copyright 2022 INRAE - BIA Research Unit - BIBS Platform (Nantes)\n\nproj = projPointOnEllipse(point, elli);\n\ndist = distancePoints(point, proj, 'diag');\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/distancePointEllipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7331187726576383}} {"text": "function [ fea, out ] = ex_poisson1( varargin )\n%EX_POISSON1 1D Poisson equation example.\n%\n% [ FEA, OUT ] = EX_POISSON1( VARARGIN ) Poisson equation on a line with a\n% constant source term equal to 1, homogenous boundary conditions, and\n% exact solution (-x^2+x)/2. Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% hmax scalar {1/10} Grid cell size\n% sfun string {sflag1} Finite element shape function\n% iphys scalar 0/{1} Use physics mode to define problem (=1)\n% or directly define fea.eqn/bdr fields (=0)\n% or use core assembly functions (<0)\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 = { 'hmax', 1/10;\n 'sfun', 'sflag1';\n 'refsol', '(-x^2+x)/2';\n 'fsrc', '1';\n 'iphys', 1;\n 'icub', 2;\n 'iplot', 1;\n 'tol', 2e-2;\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid = opt.fid;\n\n\n% Grid generation.\nif( opt.hmax>0 )\n nx = round( 1/opt.hmax );\n fea.grid = linegrid( nx, 0, 1 );\nelse % Scrambled testing grid.\n fea.grid.p = [ 0 1/10 4/10 1/3 1 1-1/3 ];\n fea.grid.c = [ 1 4 2 6 3 ;\n 2 3 4 5 6 ];\n fea.grid.a = [ 0 2 1 4 3 ;\n 2 4 3 0 5 ];\n fea.grid.b = [ 1 1 1 -1 ;\n 4 2 2 1 ]';\n fea.grid.s = ones(1,5);\nend\nn_bdr = 2; % Number of boundaries.\n\n\n% Problem definition.\nfea.sdim = { 'x' }; % Coordinate name.\nswitch opt.iphys\n\n case 0 % Directly define fea.eqn/bdr fields.\n\n fea.dvar = { 'u' }; % Dependent variable name.\n fea.sfun = { opt.sfun }; % Shape function.\n\n % Define equation system.\n fea.eqn.a.form = { [2;2] }; % First row indicates test function space (2=x-derivative),\n % second row indicates trial function space (2=x-derivative).\n fea.eqn.a.coef = { 1 }; % Coefficient used in assembling stiffness matrix.\n\n fea.eqn.f.form = { 1 }; % Test function space to evaluate in right hand side (1=function values).\n fea.eqn.f.coef = { opt.fsrc }; % Coefficient used in right hand side.\n\n % Define boundary conditions.\n if( strcmp(opt.sfun(end-1:end),'H3') ) % Prescribed derivatives at end points for Hermite elements.\n fea.bdr.d = {{ 0 0 ; 1/2 -1/2 }};\n else\n fea.bdr.d = cell(1,n_bdr);\n [fea.bdr.d{:}] = deal(0); % Assign zero to all boundaries (homogenous Dirichlet conditions).\n end\n\n fea.bdr.n = cell(1,n_bdr); % No Neumann boundaries ('fea.bdr.n' empty).\n\n % Parse and solve problem.\n fea = parseprob(fea); % Check and parse problem struct.\n fea.sol.u = solvestat(fea,'fid',fid,'icub',opt.icub); % Call to stationary solver.\n\n case 1 % Use physics mode.\n\n fea = addphys(fea,@poisson); % Add Poisson equation physics mode.\n fea.phys.poi.sfun = { opt.sfun }; % Set shape function.\n fea.phys.poi.eqn.coef{3,4} = { opt.fsrc }; % Set source term coefficient.\n fea.phys.poi.bdr.coef{1,end} = repmat({0},1,n_bdr); % Set Dirichlet boundary coefficient to zero.\n fea = parsephys(fea); % Check and parse physics modes.\n if( strcmp(opt.sfun(end-1:end),'H3') ) % Prescribed derivatives at end points for Hermite elements.\n fea.bdr.d = {{ 0 0 ; 1/2 -1/2 }};\n end\n\n % Parse and solve problem.\n fea = parseprob(fea); % Check and parse problem struct.\n fea.sol.u = solvestat(fea,'fid',fid,'icub',opt.icub); % Call to stationary solver.\n\n otherwise % Use core assembly functions.\n\n fea.dvar = { 'u' }; % Dependent variable name.\n fea.sfun = { opt.sfun }; % Shape function.\n fea = parseprob(fea); % Check and parse problem struct.\n\n % Assemble stiffness matrix.\n form = [2;2];\n sfun = {opt.sfun;opt.sfun};\n coefa = 1;\n sind = 1;\n i_cub = opt.icub;\n\n [vRowInds,vColInds,vAvals,n_rows,n_cols] = ...\n assemblea(form,sfun,coefa,i_cub,fea.grid.p,fea.grid.c,fea.grid.a,fea.grid.s,[]);\n A = sparse(vRowInds,vColInds,vAvals,n_rows,n_cols);\n\n % Check and compare with finite difference stencil.\n if (strcmp(opt.sfun,'sflag1'))\n h = 1/nx;\n n = nx+1;\n e = ones(n,1);\n A_ref = 1/h*spdiags([-e 2*e -e], -1:1, n, n);\n A_ref(1) = A_ref(1)/2;\n A_ref(end) = A_ref(end)/2;\n\n err = norm(A(:)-A_ref(:));\n if err>opt.tol\n out.err = err;\n out.pass = -1;\n return\n end\n end\n\n form = 1;\n sfun = sfun{1};\n coeff = 1;\n\n f = assemblef(form,sfun,coeff,i_cub,fea.grid.p,fea.grid.c,fea.grid.a,fea.grid.s,[]);\n\n\n % Check and compare with finite difference stencil.\n if (strcmp(opt.sfun,'sflag1'))\n f_ref = coeff*h*ones(n,1);\n f_ref([1 end]) = coeff*1/2*h;\n\n err = norm(f-f_ref);\n if err>1e-6\n out.err = err;\n out.pass = -2;\n return\n end\n end\n\n % Set homogenous Dirichlet boundary conditions on first and last dof/node.\n bind = [1 nx+1];\n A = A'; %'\n A(:,bind) = 0; % Zero out Dirichlet BC rows.\n for i=1:length(bind) % Loop to set diagonal entry to 1.\n i_a = bind(i);\n A(i_a,i_a) = 1;\n end\n A = A'; %'\n f(bind) = 0; % Set corresponding source term entries to Dirichlet BC values.\n\n % Solve problem.\n fea.sol.u = A\\f;\n\nend\n\n\n% Postprocessing.\nif ( opt.iplot>0 )\n x = linspace( 0, 1, 41 );\n u = evalexpr( 'u', x, fea )';\n figure\n subplot(3,1,1)\n plot( x, u )\n axis( [0 1 0 0.2])\n grid on\n title('Solution u')\n subplot(3,1,2)\n ux = (-x.^2+x)/2;\n plot( x, ux )\n axis( [0 1 0 0.2])\n grid on\n title('Exact solution')\n subplot(3,1,3)\n plot( x, abs(ux-u) )\n title('Error')\nend\n\n\n% Error checking.\nxi = [1/2; 1/2];\ns_err = ['abs(',opt.refsol,'-u)'];\nerr = evalexpr0(s_err,xi,1,1:size(fea.grid.c,2),[],fea);\nref = evalexpr0('u',xi,1,1:size(fea.grid.c,2),[],fea);\nerr = sqrt(sum(err.^2)/sum(ref.^2));\n\nif( ~isempty(fid) )\n fprintf(fid,'\\nL2 Error: %e\\n',err)\n fprintf(fid,'\\n\\n')\nend\n\nout.err = err;\nout.tol = opt.tol;\nout.pass = out.err\n% Copyright (C) 2003 Doug Stewart \n% Copyright (C) 2011 Alexander Klein \n%\n% This program 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\n% FITNESS 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% Generate a butterworth filter.\n% Default is a discrete space (Z) filter.\n% \n% [b,a] = butter(n, Wc)\n% low pass filter with cutoff pi*Wc radians\n%\n% [b,a] = butter(n, Wc, 'high')\n% high pass filter with cutoff pi*Wc radians\n%\n% [b,a] = butter(n, [Wl, Wh])\n% band pass filter with edges pi*Wl and pi*Wh radians\n%\n% [b,a] = butter(n, [Wl, Wh], 'stop')\n% band reject filter with edges pi*Wl and pi*Wh radians\n%\n% [z,p,g] = butter(...)\n% return filter as zero-pole-gain rather than coefficients of the\n% numerator and denominator polynomials.\n% \n% [...] = butter(...,'s')\n% return a Laplace space filter, W can be larger than 1.\n% \n% [a,b,c,d] = butter(...)\n% return state-space matrices \n%\n% References: \n%\n% Proakis & Manolakis (1992). Digital Signal Processing. New York:\n% Macmillan Publishing Company.\n\nfunction [a, b, c, d] = oc_butter (n, W, varargin)\n\nif (nargin>4 || nargin<2) || (nargout>4 || nargout<2)\n print_usage;\nend\n\n% interpret the input parameters\nif (~(length(n)==1 && n == round(n) && n > 0))\n error ('butter: filter order n must be a positive integer');\nend\n\nstop = 0;\ndigital = 1;\nfor i=1:length(varargin)\n switch varargin{i}\n case 's', digital = 0;\n case 'z', digital = 1;\n case { 'high', 'stop' }, stop = 1;\n case { 'low', 'pass' }, stop = 0;\n otherwise, error ('butter: expected [high|stop] or [s|z]');\n end\nend\n\n\n[r, c]=size(W);\nif (~(length(W)<=2 && (r==1 || c==1)))\n error ('butter: frequency must be given as w0 or [w0, w1]');\nelseif (~(length(W)==1 || length(W) == 2))\n error ('butter: only one filter band allowed');\nelseif (length(W)==2 && ~(W(1) < W(2)))\n error ('butter: first band edge must be smaller than second');\nend\n\nif ( digital && ~all(W >= 0 & W <= 1))\n error ('butter: critical frequencies must be in (0 1)');\nelseif ( ~digital && ~all(W >= 0 ))\n error ('butter: critical frequencies must be in (0 inf)');\nend\n\n% Prewarp to the band edges to s plane\nif digital\n T = 2; % sampling frequency of 2 Hz\n W = 2/T*tan(pi*W/T);\nend\n\n% Generate splane poles for the prototype butterworth filter\n% source: Kuc\nC = 1; % default cutoff frequency\npole = C*exp(1i*pi*(2*(1:n) + n - 1)/(2*n));\nif mod(n,2) == 1, pole((n+1)/2) = -1; end % pure real value at exp(i*pi)\nzero = [];\ngain = C^n;\n\n% splane frequency transform\n[zero, pole, gain] = oc_sftrans(zero, pole, gain, W, stop);\n\n% Use bilinear transform to convert poles to the z plane\nif digital\n [zero, pole, gain] = oc_bilinear(zero, pole, gain, T);\nend\n\n% convert to the correct output form\nif nargout==2,\n a = real(gain*poly(zero));\n b = real(poly(pole));\nelseif nargout==3,\n a = zero;\n b = pole;\n c = gain;\nelse\n % output ss results\n % [a, b, c, d] = oc_zp2ss(zero, pole, gain);\n error('Not supported');\nend\n\nend\n\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/octave/oc_butter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7331088062067238}} {"text": "%% Ex. 13 Making a quick plot\nx = [0:0.1:20]; \ny = sin(x);\nplot(x,y)\n\n\n\n\n% remaks : Remarks: This only serves as a very quick example of what Matlab can do in making\n% plots.The first line is equivalent to x = [0 0.1 0.2 0.3 ... 19.8 19.9 20]. It\n% assigns the content of x which is an array of 201 elements. The \"0:0.1:20\" means the\n% 201 numbers are evenly spaced. They start from 0 and end at 20 with an increment of\n% 0.1. The second line gives the content of the new array, y, as\n % y = [sin(x(1)) sin(x(2)) sin(x(3)) ... sin(x(200)) sin(x(201))] ,\n% or\n% y = [sin(0) sin(0.1) sin(0.2) ... sin(19.9) sin(20)] .\n% The 3rd line makes a plot of y vs. x. ", "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_1(learn_basic_programing)/make_graph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7331087982717645}} {"text": "% Count the number of multiple edges in the graph.\n%\n% INPUT: adjacency matrix, nxn\n% OUTPUT: integer, number of multiple edges\n%\n% Examples: multiEdges([0 2; 2 0])=1, and multiEdges([0 0 1; 2 0 0; 0 1 0])=1\n%\n% Note 1: The definition of number of multi-arcs/edges (node pairs\n% that have multiple edges across them) here is: \n% mA = length(find(adj>1)); (normalized by 2 if the graph is directed).\n%\n% Note 2: This creates a natural difference in counting for\n% undirected and directed graphs.\n%\n% Other routines used: isSymmetric.m\n% GB: last updated, Sep 26 2014\n\nfunction mE=multiEdges(adj)\n\nif isSymmetric(adj) % here use \"is symmetric\" as surrogate for \"is directed\"\n mE=length(find(adj>1))/2;\nelse\n mE=length(find(adj>1));\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/multiEdges.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213880824789, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7329929674361049}} {"text": "function [ r, seed ] = r8mat_uniform_01 ( m, n, seed )\n\n%*****************************************************************************80\n%\n%% R8MAT_UNIFORM_01 returns a unit pseudorandom R8MAT.\n%\n% Modified:\n%\n% 21 September 2006\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 the array.\n%\n% Input, integer SEED, the integer \"seed\" used to generate\n% the output random number.\n%\n% Output, real R(M,N), an array of random values between 0 and 1.\n%\n% Output, integer SEED, the updated seed. This would\n% normally be used as the input seed on the next call.\n%\n if ( seed == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_UNIFORM_01 - Fatal error!\\n' );\n fprintf ( 1, ' Input SEED = 0!\\n' );\n error ( 'R8MAT_UNIFORM_01 - Fatal error!' );\n end\n\n for j = 1 : n\n for i = 1 : m\n\n seed = floor ( seed );\n\n seed = mod ( seed, 2147483647 );\n\n if ( seed < 0 ) \n seed = seed + 2147483647;\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 + 2147483647;\n end\n\n r(i,j) = seed * 4.656612875E-10;\n\n end\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/test_triangulation/r8mat_uniform_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7329929626576012}} {"text": "function a = dorr_inverse ( alpha, n )\n\n%*****************************************************************************80\n%\n%% DORR_INVERSE returns the inverse of the DORR matrix.\n%\n% Discussion:\n%\n% The DORR matrix is a special case of the TRIV matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 February 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% CM daFonseca, J Petronilho,\n% Explicit Inverses of Some Tridiagonal Matrices,\n% Linear Algebra and Its Applications,\n% Volume 325, 2001, pages 7-21.\n%\n% Parameters:\n%\n% Input, real ALPHA, the parameter.\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real A(N,N), the inverse of the matrix.\n%\n\n%\n% Form the three diagonals.\n%\n x = zeros ( n - 1, 1 );\n y = zeros ( n, 1 );\n z = zeros ( n - 1, 1 );\n\n for i = 1 : n\n for j = 1 : n\n\n if ( i <= floor ( ( n + 1 ) / 2 ) )\n\n if ( j == i - 1 )\n x(i-1) = - alpha * ( n + 1 )^2;\n elseif ( j == i )\n y(i) = 2.0 * alpha * ( n + 1 )^2 + 0.5 * ( n + 1 ) - i;\n elseif ( j == i + 1 )\n z(i) = - alpha * ( n + 1 )^2 - 0.5 * ( n + 1 ) + i;\n end\n\n else\n\n if ( j == i - 1 )\n x(i-1) = - alpha * ( n + 1 )^2 + 0.5 * ( n + 1 ) - i;\n elseif ( j == i )\n y(i) = 2.0 * alpha * ( n + 1 )^2 - 0.5 * ( n + 1 ) + i;\n elseif ( j == i + 1 )\n z(i) = - alpha * ( n + 1 )^2;\n end\n\n end\n\n end\n end\n%\n% Now evaluate the inverse.\n%\n a = zeros ( n, n );\n\n d = zeros ( n, 1 );\n e = zeros ( n, 1 );\n\n d(n) = y(n);\n for i = n - 1 : -1 : 1\n d(i) = y(i) - x(i) * z(i) / d(i+1);\n end\n\n e(1) = y(1);\n for i = 2 : n\n e(i) = y(i) - x(i-1) * z(i-1) / e(i-1);\n end\n\n for i = 1 : n\n for j = 1 : i\n a(i,j) = r8_mop ( i + j ) * prod ( x(j:i-1) ) ...\n * prod ( d(i+1:n) ) / prod ( e(j:n) );\n end\n for j = i + 1 : n\n a(i,j) = r8_mop ( i + j ) * prod ( z(i:j-1) ) ...\n * prod ( d(j+1:n) ) / prod ( e(i:n) );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/dorr_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7328911150966667}} {"text": "function [lambda_vec, error_train, error_val] = ...\n validationCurve(X, y, Xval, yval)\n%VALIDATIONCURVE Generate the train and validation errors needed to\n%plot a validation curve that we can use to select lambda\n% [lambda_vec, error_train, error_val] = ...\n% VALIDATIONCURVE(X, y, Xval, yval) returns the train\n% and validation errors (in error_train, error_val)\n% for different values of lambda. You are given the training set (X,\n% y) and validation set (Xval, yval).\n%\n\n% Selected values of lambda (you should not change this)\nlambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';\n\n% You need to return these variables correctly.\nerror_train = zeros(length(lambda_vec), 1);\nerror_val = zeros(length(lambda_vec), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return training errors in \n% error_train and the validation errors in error_val. The \n% vector lambda_vec contains the different lambda parameters \n% to use for each calculation of the errors, i.e, \n% error_train(i), and error_val(i) should give \n% you the errors obtained after training with \n% lambda = lambda_vec(i)\n%\n% Note: You can loop over lambda_vec with the following:\n%\n% for i = 1:length(lambda_vec)\n% lambda = lambda_vec(i);\n% % Compute train / val errors when training linear \n% % regression with regularization parameter lambda\n% % You should store the result in error_train(i)\n% % and error_val(i)\n% ....\n% \n% end\n%\n%\nfor i = 1:length(lambda_vec)\n\tlambda = lambda_vec(i);\n\ttheta = trainLinearReg(X, y, lambda);\n error_train(i) = linearRegCostFunction(X, y, theta, 0);\n\terror_val(i) = linearRegCostFunction(Xval,yval,theta,0);\nend\n\n\n\n\n\n\n\n\n% =========================================================================\n\nend\n", "meta": {"author": "AvaisP", "repo": "machine-learning-programming-assignments-coursera-andrew-ng", "sha": "45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf", "save_path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng", "path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng/machine-learning-programming-assignments-coursera-andrew-ng-45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf/machine-learning-ex5/ex5/validationCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8705972650509008, "lm_q1q2_score": 0.7328911130565628}} {"text": "function tanh_plot ( )\n\n%*****************************************************************************80\n%\n%% TANH_PLOT makes a plot of certain tanh() functions.\n%\n% Discussion:\n%\n% The value is +1 if the number is positive or zero, and it is -1 otherwise.\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 m = 101;\n x = ( linspace ( -1.0, +1.0, m ) )';\n\n u = zeros ( m, 6 );\n for j = 0 : 5\n s = 2^j;\n u(:,j+1) = tanh ( s * x(:) / 2.0 ) / ( tanh ( s * -1.0 / 2.0 ) );\n end\n\n plot ( x, u, 'Linewidth', 3 )\n grid on\n axis ( [-1, +1, -1.1, +1.1 ] )\n xlabel ( '<--- X --->' )\n ylabel ( '<--- U(X) ---> ' )\n title ( 'tanh ( 2^J * x / 2.0 ), J = 0, 1, ..., 5 scaled to be +1 at -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/burgers_steady_viscous/tanh_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7328911091296622}} {"text": "function lattice_rule_test06 ( )\n\n%*****************************************************************************80\n%\n%% LATTICE_RULE_TEST06 tests FIBONACCI_LATTICE_Q3;\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.\n%\n dim_num = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LATTICE_RULE_TEST06\\n' );\n fprintf ( 1, ' FIBONACCI_LATTICE_Q3 applies a Fibonacci lattice rule\\n' );\n fprintf ( 1, ' to integrate a function over the unit square.\\n' );\n fprintf ( 1, ' A nonlinear coordinate transformation is applied.\\n' );\n fprintf ( 1, ' These Fibonacci rules are only available in 2D.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The spatial dimension DIM_NUM = %d\\n', dim_num );\n\n a(1:dim_num) = 0.0;\n b(1:dim_num) = 1.0;\n\n exact = e_01_2d ( dim_num, a, b );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' K M EXACT ESTIMATE ERROR\\n' );\n fprintf ( 1, '\\n' );\n\n for k = 3 : 18\n\n quad = fibonacci_lattice_q3 ( k, @f_01_2d );\n\n error = abs ( exact - quad );\n m = fibonacci ( k );\n\n fprintf ( 1, ' %8d %8d %10.6f %10.6f %10.6e\\n', k, 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_test06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8418256432832332, "lm_q1q2_score": 0.732891099865702}} {"text": "%% Transient diffusion equation\n%% PDE and boundary conditions\n% The transient diffusion equation reads\n%\n% $$\\alpha\\frac{\\partial c}{\\partial t}+\\nabla.\\left(-D\\nabla c\\right)=0,$$\n%\n% where $c$ is the independent variable (concentration, temperature, etc)\n% , $D$ is the diffusion coefficient, and $\\alpha$ is a constant.\n% Written by Ali A. Eftekhari\n% Last checked: June 2021\nclc\n\n%% Define the domain and create a mesh structure\nL = 50; % domain length\nNx = 20; % number of cells\nm = createMesh2D(Nx,Nx, L,L);\n%% Create the boundary condition structure\nBC = createBC(m); % all Neumann boundary condition structure\nBC.left.a(:) = 0; BC.left.b(:)=1; BC.left.c(:)=0; % left boundary\nBC.right.a(:) = 0; BC.right.b(:)=1; BC.right.c(:)=0; % right boundary\nBC.top.a(:) = 0; BC.top.b(:)=1; BC.top.c(:)=0; % top boundary\nBC.bottom.a(:) = 0; BC.bottom.b(:)=1; BC.bottom.c(:)=0; % bottom boundary\n%% define the transfer coeffs\nD_val = 1;\nD = createCellVariable(m, D_val);\nalfa = createCellVariable(m, 1);\n%% define initial values\nc_init = 1;\nc_old = createCellVariable(m, c_init,BC); % initial values\nc = c_old; % assign the old value of the cells to the current values\n%% loop\ndt = 1; % time step\nfinal_t = 100;\nfor t=dt:dt:final_t\n [M_trans, RHS_trans] = transientTerm(c_old, dt, alfa);\n Dave = harmonicMean(D);\n Mdiff = diffusionTerm(Dave);\n [Mbc, RHSbc] = boundaryCondition(BC);\n M = M_trans-Mdiff+Mbc;\n RHS = RHS_trans+RHSbc;\n c = solvePDE(m,M, RHS);\n c_old = c;\n figure(1);visualizeCells(c);drawnow;\nend\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Examples/Tutorial/diffusiontutorial2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7328448209178412}} {"text": "% Figure 3.26 Feedback Control of Dynamic Systems, 6e\n% Franklin, Powell, Emami\n% script to generate Fig. 3.26\n\nclf;\nzeta=.5;\nk=1/zeta;\nden=[1 1 1];\n\na=10;\nnum=[k/a 1];\nt=0:.1:10;\ny1=step(num,den,t);\n\na=4;\nnum=[k/a 1];\nt=0:.1:10;\ny2=step(num,den,t);\n\na=2;\nnum=[k/a 1];\nt=0:.1:10;\ny3=step(num,den,t);\n\na=1;\nnum=[k/a 1];\nt=0:.1:10;\ny4=step(num,den,t);\n\nplot(t,y1,'-',t,y2,'-',t,y3,'-',t,y4,'-'),grid\ntitle('Fig. 3.26 Step response with \\xi = 0.5')\nxlabel('\\omega_n t')\nylabel('Step response of H(s)')\ntext(.1,.9,'\\alpha=')\ntext(.6,.9,'1')\ntext(1.1,.9,'2')\ntext(1.5,.85,'4')\ntext(1.8,.8,'100')\n% grid\nnicegrid", "meta": {"author": "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_26.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769412, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.732844817092969}} {"text": "function f = f_function ( x, y1, y2, Md, Nd, L )\n\n%*****************************************************************************80\n%\n%% F_FUNCTION: RHS function from exact coefficient Q and the exact solution U.\n%\n% Discussion:\n%\n% The differential equation has the form:\n%\n% ( q(x) u_x(x) )_x = f(x)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Parameters:\n%\n% x = physical space point of length one\n%\n% y1 = stochastic vector of length Md (from the expansion for u)\n%\n% y2 = stochastic vector of length Nd (from the expansion for q)\n%\n% Md = dimension of the probability space for u\n%\n% Nd = dimension of the probability space for q\n%\n% L = the correlation length of the random variables\n%\n [n_nodes, dim] = size(x);\n f = zeros( n_nodes, 1 );\n\n for n=1:Nd\n\n \tfor m=1:Md\n\n \t f = f + qn(n) * um( m ) * pn(y2, n) * pm(y1, m) * ...\n \t ( -(pi/L)^2 * m^2 .* sin((m*pi*x)/L) .* cos((n*pi*x)/L) ...\n \t -n*m * (pi/L)^2 * cos((m*pi*x)/L) .* sin((n*pi*x)/L) );\n\n \tend\n\n end\n\n return\nend\nfunction p_m = pm( y, m )\n\n%*****************************************************************************80\n%\n%% PM\n%\n p_m = y(m);\n\n return\nend\nfunction p_n = pn( y, n )\n\n%*****************************************************************************80\n%\n%% PN\n%\n p_n = y(n);\n\n return\nend\nfunction q_n = qn( n )\n\n%*****************************************************************************80\n%\n%% QN\n%\n q_n = 1;\n\n return\nend\nfunction u_m = um( m )\n\n%*****************************************************************************80\n%\n%% UM\n%\n u_m = 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/stochastic_gradient_nd_noise/f_function.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7328448166190629}} {"text": "function [P1, P2, spectrum] = slcopca(X1, X2, d, varargin)\n%SLCOPCA Performs Coupled PCA Learning\n%\n% $ Syntax $\n% - [P1, P2] = slcopca(X1, X2, sch, ...)\n% - [P1, P2, spectrum] = slcopca(...)\n%\n% $ Arguments $\n% - X1: The samples in the first modality\n% - X2: The samples in the second modality\n% - d: The target space dimension\n% - P1: The projection matrix (bases) of the first modality space\n% - P2: The projection matrix (bases) of the second modality space\n% - spectrum: The covariance energy along dimensions of target space\n% \n% $ Description $\n% - [P1, P2] = slcopca(X1, X2, sch, ...) performs coupled PCA learning\n% for two correlated sample spaces. The learning objective is to\n% pursue two subspaces such that they are maximally correlated. The\n% objective function is formulated as\n%\n% maximize trace( P1^T * C_12 * P2 * P2^T * C_21 * P1 ) / n\n% s.t. P1^T * P1 = I, and P2^T * P2 = I\n% where C_12 is the covariance between X1 and X2, \n% C_21 is the covariance between X2 and X1\n%\n% Suppose the dimensions for the two spaces are d1 and d2 respectively, \n% and n pairs of corresponding samples are given in X1 and X2. Then X1 \n% and X2 should be d1 x n and d2 x n matrices respectively. \n% You can further specify the following properties to control the\n% learning procedure:\n% - 'weights': The weights of the samples, default = []\n% - 'mean1': The pre-computed mean vector for X1, default = []\n% if mean1 is set as 0, then it means that X1 has \n% been centralized.\n% - 'mean2': The pre-computed mean vector for X2, default = []\n% \n% - [P1, P2, spectrum] = slcopca(...) also outputs the spectrum. You\n% can specify the following properties to control the type of the\n% output spectrum:\n% - 'spectype': The type of output spectrum\n% - 'normal': The average energies along target\n% dimensions.\n% - 'ratio': The ratio of preserved energy along\n% target dimensions to the total\n% energy.\n% default = 'normal'.\n% \n% $ History $\n% - Created by Dahua Lin, on Sep 16, 2006\n%\n\n%% parse and verify input arguments\n\nif nargin < 3\n raise_lackinput('slcopca', 3);\nend\n\nif ~isnumeric(X1) || ~isnumeric(X2) || ndims(X1) ~= 2 || ndims(X2) ~= 2\n error('sltoolbox:invalidarg', ...\n 'X1 and X2 should be 2D numeric matrices');\nend\n\n[d1, n] = size(X1);\n[d2, n2] = size(X2);\nif n ~= n2\n error('sltoolbox:sizmismatch', ...\n 'The numbers of samples in X1 and X2 do not match');\nend\n\ndmax = min(d1, d2);\nif d > dmax\n error('sltoolbox:invalidarg', ...\n 'The target dimension d should not exceed d1 or d2');\nend\n\nopts.weights = [];\nopts.mean1 = [];\nopts.mean2 = [];\nopts.spectype = 'normal';\nopts = slparseprops(opts, varargin{:});\n\nw = opts.weights;\nif ~isempty(w)\n if ~isequal(size(w), [1, n])\n error('sltoolbox:sizmismatch', ...\n 'w should be a 1 x n row vector');\n end\nend\n\nvmean1 = opts.mean1;\nvmean2 = opts.mean2;\nif ~isempty(vmean1) && ~isequal(vmean1, 0) && ~isequal(size(vmean1), [d1, 1])\n error('sltoolbox:sizmismatch', ...\n 'The size of mean1 is illegal');\nend\nif ~isempty(vmean2) && ~isequal(vmean2, 0) && ~isequal(size(vmean2), [d2, 1])\n error('sltoolbox:sizmismatch', ...\n 'The size of mean1 is illegal');\nend\n\n%% main skeleton\n\n% preprocess sample matrices\n\nX1 = preprocess_samples(X1, vmean1, w);\nX2 = preprocess_samples(X2, vmean2, w);\n\n% construct problem\nS = X1 * X2';\n\nswitch opts.spectype\n case 'normal'\n if isempty(w)\n tw = n;\n else\n tw = sum(w);\n end\n case 'ratio'\n tw = trace(S * S');\n otherwise\n error('sltoolbox:invalidarg', ...\n 'Invalid spectrum type: %s', opts.spectype);\nend\n\n\nif d > dmax / 3;\n [P1, D, P2] = svd(S, 'econ');\n spectrum = diag(D);\n spectrum = spectrum(1:d);\n P1 = P1(:, 1:d);\n P2 = P2(:, 1:d);\nelse\n [P1, D, P2] = svds(S, d);\n spectrum = diag(D);\nend\n\n% post-process spectrum\nif nargout >= 3\n spectrum = spectrum .* spectrum / tw;\nend\n\n\n%% Auxiliary functions\n\nfunction Xp = preprocess_samples(X, vmean, w)\n\nif ~isequal(vmean, 0)\n if isempty(vmean)\n vmean = slmean(X, w, true);\n end\n Xp = sladdvec(X, -vmean, 1);\nelse\n Xp = X;\nend\n\nif ~isempty(w) \n Xp = slmulvec(Xp, w, 2);\nend\n\n\n \n \n \n\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/slcopca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8031737869342624, "lm_q1q2_score": 0.732844800608715}} {"text": "function [ n_data, n, k, x, b ] = bernstein_poly_01_values ( n_data )\n\n%*****************************************************************************80\n%\n%% BERNSTEIN_POLY_01_VALUES returns some values of the Bernstein polynomials.\n%\n% Discussion:\n%\n% The Bernstein polynomials are assumed to be based on [0,1].\n%\n% The formula for the Bernstein polynomials is\n%\n% B(N,I)(X) = [N!/(I!*(N-I)!)] * (1-X)**(N-I) * X**I\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Binomial[n,i] * (1-x)^(n-i) * x^i\n%\n% First values:\n%\n% B(0,0)(X) = 1\n%\n% B(1,0)(X) = 1-X\n% B(1,1)(X) = X\n%\n% B(2,0)(X) = (1-X)**2\n% B(2,1)(X) = 2 * (1-X) * X\n% B(2,2)(X) = X**2\n%\n% B(3,0)(X) = (1-X)**3\n% B(3,1)(X) = 3 * (1-X)**2 * X\n% B(3,2)(X) = 3 * (1-X) * X**2\n% B(3,3)(X) = X**3\n%\n% B(4,0)(X) = (1-X)**4\n% B(4,1)(X) = 4 * (1-X)**3 * X\n% B(4,2)(X) = 6 * (1-X)**2 * X**2\n% B(4,3)(X) = 4 * (1-X) * X**3\n% B(4,4)(X) = X**4\n%\n% Special values:\n%\n% B(N,I)(X) has a unique maximum value at X = I/N.\n%\n% B(N,I)(X) has an I-fold zero at 0 and and N-I fold zero at 1.\n%\n% B(N,I)(1/2) = C(N,K) / 2**N\n%\n% For a fixed X and N, the polynomials add up to 1:\n%\n% Sum ( 0 <= I <= N ) B(N,I)(X) = 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 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 degree of the polynomial.\n%\n% Output, integer K, the index of the polynomial.\n%\n% Output, real X, the argument of the polynomial.\n%\n% Output, real B, the value of the polynomial B(N,K)(X).\n%\n n_max = 15;\n\n b_vec = [ ...\n 0.1000000000000000E+01, ...\n 0.7500000000000000E+00, ...\n 0.2500000000000000E+00, ...\n 0.5625000000000000E+00, ...\n 0.3750000000000000E+00, ...\n 0.6250000000000000E-01, ...\n 0.4218750000000000E+00, ...\n 0.4218750000000000E+00, ...\n 0.1406250000000000E+00, ...\n 0.1562500000000000E-01, ...\n 0.3164062500000000E+00, ...\n 0.4218750000000000E+00, ...\n 0.2109375000000000E+00, ...\n 0.4687500000000000E-01, ...\n 0.3906250000000000E-02 ];\n\n k_vec = [ ...\n 0, ...\n 0, 1, ...\n 0, 1, 2, ...\n 0, 1, 2, 3, ...\n 0, 1, 2, 3, 4 ];\n\n n_vec = [ ...\n 0, ...\n 1, 1, ...\n 2, 2, 2, ...\n 3, 3, 3, 3, ...\n 4, 4, 4, 4, 4 ];\n\n x_vec = [ ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+00, ...\n 0.25E+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 k = 0;\n x = 0.0;\n b = 0.0;\n else\n n = n_vec(n_data);\n k = k_vec(n_data);\n x = x_vec(n_data);\n b = b_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/bernstein_polynomial/bernstein_poly_01_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.732814479388797}} {"text": "function binv = beta_inv (x, a, b)\n% BETA_INV Inverse of the beta cumulative distribution function (cdf).\n% X = BETA_INV(P,A,B) returns the inverse of the beta cdf with\n% parameters A and B at the values in P.\n\n% Copyright (c) 1995-1997, 2005-2007 Kurt Hornik\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 error('must provide 3 parameters')\nend\n\nif (~isscalar (a) || ~isscalar(b))\n if ((size(a,1) ~= size(b,1)) || (size(b,1) ~= size(x,1)))\n error ('betainv: x, a and b must be of common size or scalars');\n end\nend\n\n[n,nin] = size(x);\nbinv = zeros(n,nin);\n\nk = find ((x<0) || (x>1) || (a<0) || (b<0) || isnan(x));\nif (any(k))\n binv(k) = NaN;\nend\n\nk = find ((x==1) && (a>0) && (b>0));\nif (any (k))\n binv(k) = 1;\nend\n\nk = find ((x > 0) & (x < 1) & (a > 0) & (b > 0));\nif (any (k))\n if (~isscalar(a) || ~isscalar(b))\n a = a(k);\n b = b(k);\n y = a./(a+b);\n else\n y = a/(a + b)*ones(size(k));\n end\n x = x(k);\n l = find (y < eps);\n if (any (l))\n y(l) = sqrt (eps) * ones (length (l), 1);\n end\n l = find (y > 1 - eps);\n if (any (l))\n y(l) = 1 - sqrt (eps) * ones (length (l), 1);\n end\n \n y_old = y;\n for i = 1 : 10000\n h = (beta_cdf (y_old, a, b) - x) ./ beta_pdf (y_old, a, b);\n y_new = y_old - h;\n ind = find (y_new <= eps);\n if (any (ind))\n y_new (ind) = y_old (ind) / 10;\n end\n ind = find (y_new >= 1 - eps);\n if (any (ind))\n y_new (ind) = 1 - (1 - y_old (ind)) / 10;\n end\n h = y_old - y_new;\n if (max (abs (h)) < sqrt (eps))\n break;\n end\n y_old = y_new;\n end\n \n binv(k) = y_new;\nend\n\nend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/dist/beta_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7328144724557805}} {"text": "% Laplacian Smoothing Transform for face recognition\n\nfunction [gammak,lambda]=lst_basis(M,N,k)\n% By Suicheng Gu at Peking University, Jan. 5, 2009\n% Email: gusuch@gmail.com\n\n% Output: v: basis. vv: k minimal eigenvalues\n% Input:\n% N: width of input image, or columns of a matrix\n% M: height of input image, or rows of a matrix\n% k: Number of low frequency features\n\n%************ An Example ************\n% To extract 30 LST low frequency coefficients of an grey image: \n% Im=rand(50,40); [M,N]=size(Im); \n% v=lst_basis(M,N,30);\n% temp=zeros(1,M*N);temp(:)=Im(:);\n% Im_feature=temp*v;\n%*********** End ******************\n\nW = sparse([],[],[],M*N,M*N,4*M*N-2*M-2*N);\nfor x=0:N-2;\n for y=0:M-1;\n W(x*M+y+1,x*M+M+y+1)=1;\n W(x*M+M+y+1,x*M+y+1)=1;\n end;\nend;\nfor x=0:N-1;\n for y=0:M-2;\n W(x*M+y+1,x*M+y+2)=1;\n W(x*M+y+2,x*M+y+1)=1;\n end;\nend;\nL=sparse(diag(sum(W)))-W;\noptions.disp = 0; options.isreal = 1; options.issym = 1; \n[v,lambda]=eigs(L,k,0,options);\n[vv,index] = sort(diag(lambda));\ngammak = v(:,index); ", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23251-laplacian-smoothing-transform-lst-for-face-recognition/Laplacian_Smoothing_Transform/lst_basis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7327951497431272}} {"text": "function img = discreteTrefoil(varargin)\n%DISCRETETREFOIL Discretize a trefoil curve\n%\n% IMG = discreteTrefoil(LX, LY, TREFOIL);\n% Computes the discretisation of a trefoil curve. Inputs are LX and LY,\n% two row vectors specifying pixel positions along each direction, and\n% TREFOIL = [XC YC ROUT RIN THETA], where (XC YC) is the center of the\n% trefoil, ROUT and RIN are the outer and the inner radius, and THETA is\n% the orientation of the first lobe, in degrees counted counter\n% clockwise.\n%\n% Example\n% trefoil = [50.12 50.23 45 15 10];\n% img = discreteTrefoil(1:100, 1:100, trefoil);\n% imshow(img)\n%\n% See also\n% imShapes, discreteEllipse, discreteStarfish\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-07-13, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n% compute coordinate of image pixels\n[lx, ly, varargin] = parseGridArgs(varargin{:});\n[x, y] = meshgrid(lx, ly);\n\n% process input parameters\nvar = varargin{1};\ncenter = var(:, 1:2);\nrOut = var(:, 3);\nrIn = var(:, 4);\ntheta = var(:, 5);\n\n% compute middle radius, and radius extent\nrc = (rOut + rIn) / 2;\ndr = (rOut - rIn) / 2;\n\n% transforms pixels according to shape position\ntra = createTranslation(-center);\nrot = createRotation(-deg2rad(theta));\n\n[x, y] = transformPoint(x, y, rot*tra);\n\n% convert to polar coordinates\n[th, rho] = cart2pol(x(:), y(:));\n\n% compute theoretical polar distance\nrhoTh = rc + dr * cos(3 * th);\n\n% create image \nimg = false(size(x));\nimg(rho < rhoTh) = 1;\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/discreteTrefoil.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7327522474750627}} {"text": "function [varargout]=ellipsoidFit_centered(varargin)\n\n% function [M,s,R,MU]=ellipsoidFit_centered(X,MU)\n% ------------------------------------------------------------------------\n%\n% Kevin Mattheus Moerman\n% kevinmoerman@hotmail.com\n% 2014/11/11\n%------------------------------------------------------------------------\n\n%%\n\nswitch nargin\n case 1\n X=varargin{1};\n MU=mean(X,1); %Point set mean\n case 2\n X=varargin{1};\n MU=varargin{2}; \nend\n\nif isempty(MU)\n MU=mean(X,1); %Point set mean\nend\n\n%%\n\n%Centre on mean\nX=X-MU(ones(size(X,1),1),:); %Centre points around mean\n\n%Compute singular value decomposition to get principal directions\n[~,D,V]=svd(X,0);\n\n%Compute input radii\nr = sqrt(sum(X.^2,2));\n\n%Create sphere coordinates\nXr=(V\\X')'; %Rotate back\nXc=(D\\Xr')'; %Scale back to unit sphere\n[theta,phi,~] = cart2sph(Xc(:,1),Xc(:,2),Xc(:,3));\n[Xc(:,1),Xc(:,2),Xc(:,3)]=sph2cart(theta,phi,ones(size(theta)));\n\n%Transforming sphere to ellipsoid according to fit\nX_fit=Xc;\nX_fit=(D*X_fit')'; %Scale\nX_fit=(V*X_fit')'; %Rotate\n[~,~,r_fit] = cart2sph(X_fit(:,1),X_fit(:,2),X_fit(:,3));\n\nw=mean(r./r_fit); %Determine SVD weight factor\n\nD=D*w; %Scale singular values using weight to convert to ellipsoid semi-axis constants\n\n%Identity\nI=eye(4,4);\n\n%Rotation\nR=I;\nR(1:3,1:3)=V;\n\n%Stretch factors\n\ns=diag(D)';\n\nS=I;\nS(1:3,1:3)=D; %Stretch\n\n\nT=I;\nT(1:3,4)=MU(:); %Translation\n\nM = T * R * S; %The transformation matrix\n\n%%\nvarargout{1}=M;\nvarargout{2}=s;\nvarargout{3}=R;\nvarargout{4}=MU;\n\n%%\n\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/ellipsoidFit_centered.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7327522429437963}} {"text": "function idx = findClosestCentroids(X, centroids)\n%FINDCLOSESTCENTROIDS computes the centroid memberships for every example\n% idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids\n% in idx for a dataset X where each row is a single example. idx = m x 1\n% vector of centroid assignments (i.e. each entry in range [1..K])\n%\n\n% Set K\nK = size(centroids, 1);\n\n% You need to return the following variables correctly.\nidx = zeros(size(X,1), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Go over every example, find its closest centroid, and store\n% the index inside idx at the appropriate location.\n% Concretely, idx(i) should contain the index of the centroid\n% closest to example i. Hence, it should be a value in the\n% range 1..K\n%\n% Note: You can use a for-loop over the examples to compute this.\n%\n\nfor i = 1:size(X, 1),\n min_d = inf;\n for k = 1:K,\n dis = X(i, :)' - centroids(k, :)';\n dis_sq = dis' * dis;\n if min_d > dis_sq,\n idx(i) = k;\n min_d = dis_sq;\n endif\n endfor\nendfor\n\n\n\n\n% =============================================================\n\nend\n\n", "meta": {"author": "fewtime", "repo": "ML", "sha": "fd9679e9d6648d01e36047e97434f38c8d2d6168", "save_path": "github-repos/MATLAB/fewtime-ML", "path": "github-repos/MATLAB/fewtime-ML/ML-fd9679e9d6648d01e36047e97434f38c8d2d6168/coursera-machine-learning/machine-learning-ex7/ex7/findClosestCentroids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.8887587942290704, "lm_q1q2_score": 0.7327477875742177}} {"text": "function result = bdf_sum ( func, n, x, w )\n\n%*****************************************************************************80\n%\n%% BDF_SUM carries out an explicit backward difference quadrature rule for [0,1].\n%\n% Discussion:\n%\n% The integral:\n%\n% Integral ( 0 <= X <= 1 ) F(X) dX\n%\n% The quadrature rule:\n%\n% sum ( 1 <= I <= N ) W(I) * BDF^(I-1) FUNC ( 0 )\n%\n% The integral from 0 to 1 is approximated using data at X = 0,\n% -1, -2, ..., -N+1. This is a form of extrapolation, and\n% the approximation can become poor as N increases.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 June 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, external FUNC, the function which evaluates\n% the integrand. The function must have the form\n% function value = func ( x ).\n%\n% Input, integer N, the order.\n%\n% Input, real X(N), the abscissas.\n%\n% Input, real W(N), the weights.\n%\n% Output, real RESULT, the approximate value of the integral.\n%\n diftab = zeros ( n, 1 );\n\n for i = 1 : n\n diftab(i) = func ( x(i) );\n end\n\n for i = 2 : n\n for j = i : n\n diftab(n+i-j) = ( diftab(n+i-j-1) - diftab(n+i-j) );\n end\n end\n\n result = w(1:n)' * diftab(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/quadrule/bdf_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7326337724991333}} {"text": "function x=complexBarycentricCoords2Pt(c,v)\n%%COMPLEXBARYCENTRICCOORDS2PT Given a set of complex barycentric\n% coordinates and a st of vertices, get the real 2D point that is\n% specified by the coordinates.\n%\n%INPUTS: c A numVertXnumPts set of complex coordinate vectors to convert.\n% v This is either a 2XN set of real vertices, or a length N vctor\n% of complex scalar vertices (x coordinate is real and y\n% coordinate is imaginery). These define the polygon over which\n% the vertices are specified.\n%\n%OUTPUTS: x The 2XnumPts set of the points given by the complex barycentric\n% coordinates.\n%\n%Complex barycentric coordinates are discussed in [1].\n%\n%REFERENCES:\n%[1] O. Weber, M. Ben-Chen, C. Gotsman, and K. Hormann, \"A complex view of\n% barycentric mappings,\" Computer Graphics Forum, vol. 30, no. 5, pp.\n% 1533-1542, Aug. 2011.\n%\n%October 2021 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumPts=size(c,2);\n\nif(isvector(v))\n zj=v;\nelse\n zj=v(1,:).'+1j*v(2,:).';\nend\n\nx=zeros(2,numPts);\nfor curPt=1:numPts\n xComplex=sum(c(:,curPt).*zj);\n x(:,curPt)=[real(xComplex);imag(xComplex)];\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/Barycentric_Coordinate_Systems/Complex_Barycentric_Coordinates/complexBarycentricCoords2Pt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7326146270747791}} {"text": "\nfunction draw_mandelbrot(x0, x1, y0, y1)\n\nn_grid = 1000;\n\n[x,y] = meshgrid(linspace(x0,x1,n_grid), linspace(y0,y1,n_grid));\n\nc = x + 1i*y;\nz = c;\nn_iter = 100;\nM = zeros(size(c));\n\nfor i = 1:n_iter\n z = z.^2 + c;\n M(M==0 & abs(z)>2) = n_iter-i;\nend\n\n\nimagesc(x(1,:), y(:,1),M)\ncolormap jet\n\n\n\n ", "meta": {"author": "angeloyeo", "repo": "gongdols", "sha": "7be9fbd988dec6edab1dc881cb22d63e6f69398d", "save_path": "github-repos/MATLAB/angeloyeo-gongdols", "path": "github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/만델브로집합_그리기/draw_mandelbrot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067276593031, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7326103388411461}} {"text": "function [phi, Dphi, J] = hexbasis(node,elem,GaussPt)\n%% HEXBASIS the basis and their derivatives and the det of Jacobi.\n% \n% [phi, Dphi, J] = hexbasis(node,elem,GaussPts) compute the values of \n% bilinear basis and their derivatives and Jacobi det at a gauss point GaussPt in a\n% hex.\n%\n% Author: Huayi Wei < huayiwei1984@gmail.com>\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nNT = size(elem,1);\n\nxi = GaussPt(1);\neta = GaussPt(2);\ntheta = GaussPt(3);\n\n%% basis function and their derivatives\n% for a point (x, y) in real element, there exist a point in reference\n% element (xi, eta), satisfy\n% x = x_1*phi_1 + x_2*phi_2 + x_3*phi_3 + x_4 *phi_4 +\n% x_5*phi_5 +x_6*phi_6 + x_7*phi_7 + x_8 *phi_8\n% y = y_1*phi_1 + y_2*phi_2 + y_3*phi_3 + y_4 *phi_4+\n% y_5*phi_5 +y_6*phi_6 + y_7*phi_7 + y_8 *phi_8\n% z = z_1*phi_1 + z_2*phi_2 + z_3*phi_3 + z_4 *phi_4+\n% z_5*phi_5 +z_6*phi_6 + z_7*phi_7 + z_8 *phi_8\n\n\ng1 = [xi, 1 - xi];\ng2 = [eta, 1 - eta];\ng3 = [theta, 1 - theta];\n\nphi = zeros(8,1);\nphi(1) = g1(2)*g2(2)*g3(2);\nphi(2) = g1(1)*g2(2)*g3(2);\nphi(3) = g1(1)*g2(1)*g3(2);\nphi(4) = g1(2)*g2(1)*g3(2);\nphi(5) = g1(2)*g2(2)*g3(1);\nphi(6) = g1(1)*g2(2)*g3(1);\nphi(7) = g1(1)*g2(1)*g3(1);\nphi(8) = g1(2)*g2(1)*g3(1);\n\nrDphi = zeros(8,3);\nrDphi(1,:) = [ -g2(2)*g3(2), -g1(2)*g3(2), -g1(2)*g2(2)];\nrDphi(2,:) = [ g2(2)*g3(2), -g1(1)*g3(2), -g1(1)*g2(2)];\nrDphi(3,:) = [ g2(1)*g3(2), g1(1)*g3(2), -g1(1)*g2(1)];\nrDphi(4,:) = [ -g2(1)*g3(2), g1(2)*g3(2), -g1(2)*g2(1)];\nrDphi(5,:) = [ -g2(2)*g3(1), -g1(2)*g3(1), g1(2)*g2(2)];\nrDphi(6,:) = [ g2(2)*g3(1), -g1(1)*g3(1), g1(1)*g2(2)];\nrDphi(7,:) = [ g2(1)*g3(1), g1(1)*g3(1), g1(1)*g2(1)];\nrDphi(8,:) = [ -g2(1)*g3(1), g1(2)*g3(1), g1(2)*g2(1)];\n\nX = node(:,1);\nY = node(:,2);\nZ = node(:,3);\n\nJM = zeros(NT,3,3);\nJM(:,:,1) = X(elem)*rDphi;\nJM(:,:,2) = Y(elem)*rDphi;\nJM(:,:,3) = Z(elem)*rDphi;\n\nJ = JM(:,1,1).*JM(:,2,2).*JM(:,3,3) + JM(:,2,1).*JM(:,3,2).*JM(:,1,3)+ ...\n JM(:,3,1).*JM(:,1,2).*JM(:,2,3) - JM(:,3,1).*JM(:,2,2).*JM(:,1,3)- ...\n JM(:,1,1).*JM(:,3,2).*JM(:,2,3) - JM(:,2,1).*JM(:,1,2).*JM(:,3,3);\n\nInvJM = zeros(NT,3,3);\nInvJM(:,:,1) = [JM(:,2,2).*JM(:,3,3) - JM(:,3,2).*JM(:,2,3), JM(:,3,1).*JM(:,2,3)-JM(:,2,1).*JM(:,3,3), JM(:,2,1).*JM(:,3,2) - JM(:,3,1).*JM(:,2,2)];\nInvJM(:,:,2) = [JM(:,3,2).*JM(:,1,3) - JM(:,1,2).*JM(:,3,3), JM(:,1,1).*JM(:,3,3)-JM(:,3,1).*JM(:,1,3), JM(:,3,1).*JM(:,1,2) - JM(:,1,1).*JM(:,3,2)];\nInvJM(:,:,3) = [JM(:,1,2).*JM(:,2,3) - JM(:,2,2).*JM(:,1,3), JM(:,2,1).*JM(:,1,3)-JM(:,1,1).*JM(:,2,3), JM(:,1,1).*JM(:,2,2) - JM(:,2,1).*JM(:,1,2)];\n\nInvJM(:,:,1) = InvJM(:,:,1)./[J,J,J];\nInvJM(:,:,2) = InvJM(:,:,2)./[J,J,J];\nInvJM(:,:,3) = InvJM(:,:,3)./[J,J,J];\n\nDphi = zeros(NT, 3, 8);\n\nfor i = 1:8\n Dphi(1:NT,:,i) = [InvJM(:,:,1)*rDphi(i,:)', InvJM(:,:,2)*rDphi(i,:)', InvJM(:,:,3)*rDphi(i,:)'];\nend\n\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/hexbasis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801274759925, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7326019521510412}} {"text": "function phiFaceAverage = geometricMean(phi)\n% This function gets the value of the field variable phi defined\n% over the MeshStructure and calculates the geometric average on\n% the cell faces, for a uniform mesh.\n%\n% SYNOPSIS:\n% phiFaceAverage = geometricMean(phi)\n%\n% PARAMETERS:\n%\n%\n% RETURNS:\n%\n%\n% EXAMPLE:\n%\n% SEE ALSO:\n%\n\n% Written by Ali A. Eftekhari\n% See the license file\n\n% extract data from the mesh structure\n\nd = phi.domain.dimension;\nif (d ==1) || (d==1.5) || (d==1.8)\n dx = phi.domain.cellsize.x;\n xvalue=exp((dx(1:end-1).*log(phi.value(1:end-1))+dx(2:end).*log(phi.value(2:end)))./(dx(2:end)+dx(1:end-1)));\n yvalue=[];\n zvalue=[];\nelseif (d == 2) || (d == 2.5) || (d == 2.8)\n Nx = phi.domain.dims(1);\n Ny = phi.domain.dims(2);\n dx = repmat(phi.domain.cellsize.x, 1, Ny);\n dy = repmat(phi.domain.cellsize.y', Nx, 1);\n\txvalue=exp((dx(1:end-1,:).*log(phi.value(1:end-1,2:end-1))+...\n dx(2:end,:).*log(phi.value(2:end,2:end-1)))./(dx(2:end,:)+dx(1:end-1,:)));\n yvalue=exp((dy(:,1:end-1).*log(phi.value(2:end-1,1:end-1))+...\n dy(:,2:end).*log(phi.value(2:end-1,2:end)))./(dy(:,2:end)+dy(:,1:end-1)));\n zvalue=[];\nelseif (d == 3) || (d==3.2)\n Nx = phi.domain.dims(1);\n Ny = phi.domain.dims(2);\n Nz = phi.domain.dims(3);\n dx = repmat(phi.domain.cellsize.x, 1, Ny, Nz);\n dy = repmat(phi.domain.cellsize.y', Nx, 1, Nz);\n DZ = zeros(1,1,Nz+2);\n DZ(1,1,:) = phi.domain.cellsize.z;\n dz=repmat(DZ, Nx, Ny, 1);\n xvalue=exp((dx(1:end-1,:,:).*log(phi.value(1:end-1,2:end-1,2:end-1))+...\n dx(2:end,:,:).*log(phi.value(2:end,2:end-1,2:end-1)))./(dx(2:end,:,:)+dx(1:end-1,:,:)));\n yvalue=exp((dy(:,1:end-1,:).*log(phi.value(2:end-1,1:end-1,2:end-1))+...\n dy(:,2:end,:).*log(phi.value(2:end-1,2:end,2:end-1)))./(dy(:,1:end-1,:)+dy(:,2:end,:)));\n zvalue=exp((dz(:,:,1:end-1).*log(phi.value(2:end-1,2:end-1,1:end-1))+...\n dz(:,:,2:end).*log(phi.value(2:end-1,2:end-1,2:end)))./(dz(:,:,1:end-1)+dz(:,:,2:end)));\nend\nphiFaceAverage=FaceVariable(phi.domain, xvalue, yvalue, zvalue);\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Utilities/geometricMean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813526452771, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.7325624232362095}} {"text": "function [T, Y]=FOChuaNR(parameters, orders, TSim, Y0)\n%\n% Numerical Solution of the Fractional-Order Chua's System\n% with piecewise linear nonlinearity defined in function f_x()\n%\n% D^q1 x(t) = alpha(y(t) - x(t) - f(x)) \n% D^q2 y(t) = x(t) - y(t) + z(t)\n% D^q3 z(t) = -beta y(t) - gamma z(t)\n% where f(x) is defined as f_x(m0, m1, x);\n%\n% function [T, Y] = FOChuaNR(parameters, orders, TSim, Y0)\n%\n% Input: parameters - model parameters [alpha, beta, gamma, m0, m1]\n% orders - derivatives orders [q1, q2, q3]\n% TSim - simulation time (0 - TSim) in sec\n% Y0 - initial conditions [Y0(1), Y0(2), Y0(3)]\n%\n% Output: T - simulation time (0 : Tstep : TSim)\n% Y - solution of the system (x=Y(1), y=Y(2), z=Y(3))\n%\n% Author: (c) Ivo Petras (ivo.petras@tuke.sk), 2010.\n%\n\n% time step:\nh=0.005; \n% number of calculated mesh points:\nn=round(TSim/h);\n%orders of derivatives, respectively:\nq1=orders(1); q2=orders(2); q3=orders(3);\n% constants of Volta's system:\nalpha=parameters(1); beta=parameters(2); gamma=parameters(3);\nm0=parameters(4); m1=parameters(5);\n% binomial coefficients calculation:\ncp1=1; cp2=1; cp3=1;\nfor j=1:n\n c1(j)=(1-(1+q1)/j)*cp1;\n c2(j)=(1-(1+q2)/j)*cp2;\n c3(j)=(1-(1+q3)/j)*cp3;\n cp1=c1(j); cp2=c2(j); cp3=c3(j);\nend\n% initial conditions setting:\nx(1)=Y0(1); y(1)=Y0(2); z(1)=Y0(3);\n% calculation of phase portraits /numerical solution/:\nfor i=2:n\n x(i)=(alpha*(y(i-1)-x(i-1)-f_x(m1,m0,x(i-1))))*h^q1 - memo(x, c1, i);\n y(i)=(x(i)-y(i-1)+z(i-1))*h^q2 - memo(y, c2, i);\n z(i)=(-beta*y(i)-gamma*z(i-1))*h^q3 - memo(z, c3, i);\nend\nfor j=1:n\n Y(j,1)=x(j);\n Y(j,2)=y(j);\n Y(j,3)=z(j);\nend\nT=h:h:TSim;\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/27336-fractional-order-chaotic-systems/FOChuaNR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742806, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.732553884804293}} {"text": "function legendre_2d_exactness ( a, b, n, x, y, w, t )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_2D_EXACTNESS: monomial exactness for the 2D Legendre integral.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 30 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A(2), the lower limits of integration.\n%\n% Input, real B(2), the upper limits of integration.\n%\n% Input, integer N, the number of points in the rule.\n%\n% Input, real X(N), Y(N), the quadrature points.\n%\n% Input, real W(N), the quadrature weights.\n%\n% Input, integer T, the maximum total degree.\n% 0 <= T.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Quadrature rule for the 2D Legendre integral.\\n' );\n fprintf ( 1, ' Number of points in rule is %d\\n', n );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' D I J Relative Error\\n' );\n\n for tt = 0 : t\n\n fprintf ( 1, ' %2d\\n', tt );\n\n for j = 0 : tt\n\n i = tt - j;\n\n p(1) = i;\n p(2) = j;\n\n s = legendre_2d_monomial_integral ( a, b, p );\n\n v(1:n,1) = x(1:n,1) .^ p(1) .* y(1:n,1) .^ p(2);\n\n q = w' * v;\n\n if ( s == 0.0 )\n e = abs ( q );\n else\n e = abs ( q - s ) / abs ( s );\n end\n\n fprintf ( 1, ' %6d %6d %24.16g\\n', p(1), p(2), 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/square_exactness/legendre_2d_exactness.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7325397256258236}} {"text": "function X = positive_definite_karcher_mean(A)\n% Computes a Karcher mean of a collection of positive definite matrices.\n%\n% function X = positive_definite_karcher_mean(A)\n%\n% Input: A 3D matrix A of size nxnxm such that each slice A(:,:,k) is a\n% positive definite matrix of size nxn.\n% \n% Output: A positive definite matrix X of size nxn which is a Karcher mean\n% of the m matrices in A, that is, X minimizes the sum of squared\n% Riemannian distances to the matrices in A:\n% f(X) = sum_k=1^m .5*dist^2(X, A(:, :, k))\n% The distance is defined by the natural metric on the set of\n% positive definite matrices: dist(X,Y) = norm(logm(X\\Y), 'fro').\n% \n% This simple example is not the best way to compute Karcher means. Its\n% purpose it to serve as base code to explore other algorithms. In\n% particular, in the presence of large noise, this algorithm seems to not\n% be able to reach points with a very small gradient norm. This may be\n% caused by insufficient accuracy in the gradient computation.\n\n% This file is part of Manopt and is copyrighted. See the license file.\n% \n% Main author: Nicolas Boumal, Sept. 3, 2013\n% Contributors:\n% \n% Change log:\n% \n \n % Generate some random data to test the function if none is given.\n if ~exist('A', 'var') || isempty(A)\n n = 5;\n m = 10;\n A = zeros(n, n, m);\n ref = diag(max(.1, 1+.1*randn(n, 1)));\n for i = 1 : m\n noise = 0.01*randn(n);\n noise = (noise + noise')/2;\n [V, D] = eig(ref + noise);\n A(:, :, i) = V*diag(max(.01, diag(D)))*V';\n end\n end\n \n % Retrieve the size of the problem:\n % There are m matrices of size nxn to average.\n n = size(A, 1);\n m = size(A, 3);\n assert(n == size(A, 2), ...\n ['The slices of A must be square, i.e., the ' ...\n\t 'first and second dimensions of A must be equal.']);\n \n % Our search space is the set of positive definite matrices of size n.\n % Notice that this is the only place we specify on which manifold we\n % wish to compute Karcher means. Replacing this factory for another\n % geometry will yield code to compute Karcher means on that other\n % manifold, provided that manifold is equipped with a dist function and\n % a logarithmic map log.\n M = sympositivedefinitefactory(n);\n \n % Define a problem structure, specifying the manifold M, the cost\n % function and its gradient.\n problem.M = M;\n problem.cost = @cost;\n problem.grad = @grad;\n \n % Explicitly pick an approximate Hessian for the trust-region method\n problem.approxhess = approxhessianFD(problem, struct('stepsize', 1e-4));\n \n % The functions below make many redundant computations. This\n % performance hit can be alleviated by using the caching system. We go\n % for a simple implementation here, as a tutorial example.\n \n % Cost function\n function f = cost(X)\n f = 0;\n for k = 1 : m\n f = f + M.dist(X, A(:, :, k))^2;\n end\n f = f/(2*m);\n end\n\n % Riemannian gradient of the cost function\n function g = grad(X)\n g = M.zerovec(X);\n for k = 1 : m\n % Update g in a linear combination of the form\n % g = g - [something]/m.\n g = M.lincomb(X, 1, g, -1/m, M.log(X, A(:, :, k)));\n end\n end\n \n % Execute some checks on the derivatives for early debugging.\n % These things can be commented out of course.\n % The slopes should agree on part of the plot at least. In this case,\n % it is sometimes necessary to inspect the plot visually to make the\n % call, but it is indeed correct.\n % checkgradient(problem);\n % pause;\n \n % Execute this if you want to force using a proper parallel vector\n % transport. This is not necessary. If you omit this, the default\n % vector transport is the identity map, which is (of course) cheaper\n % and seems to perform well in practice.\n % M.transp = M.paralleltransp;\n \n % Issue a call to a solver. Default options are selected.\n % Our initial guess is the first data point.\n X = trustregions(problem, A(:, :, 1));\n\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/examples/positive_definite_karcher_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7324184276934845}} {"text": "function U = unionHull(varargin)\n%unionHull - computes the convex hull of the union of other bounded convex polyhedra. \n%Any number of polyhedra can be input to the union operation. They can\n%be expressed using either vertices or linear in/equalities, according to\n%the input scheme,\n%\n%\n% I = intersectionHull('vert', V1, 'lcon', A2,b2,...,'qlcon', x3,A3,b3,...)\n%\n%The arguments specifying different polyhedra are separated using labels\n%'vert', 'lcon', or 'qlcon'. The label 'vert' signifies that an input polyhedron will\n%be expressed using vertices and is to be followed by any string of input arguments \n%accepted by vert2lcon(). The label 'lcon' signifies that an input polyhedron will\n%be expressed using linear constraints and is to be followed by any string of \n%input arguments accepted by lcon2vert(). The label 'qlcon' signifies that an input \n%polyhedron will be expressed using linear constraints and a known interior point and\n%is to be followed by input arguments accepted by qlcon2vert().\n%\n%The output, U, is a struct containing fields\n%\n% U.vert: A matrix whose rows are the vertices of the output polyhedron.\n% U.lcon: The quadruplet of linear constraint data {A,b,Aeq,beq}\n% describing the output polyhedron.\n%\n%EXAMPLE 1: The unit simplex in 3D is formed as the convex hull of the union \n%of a cube and a triangle, both expressed in terms of their vertices.\n% \n% V1=(dec2bin(0:2^3-1,3)-'0')/3.0001; %vertices of 3D cube\n% V2=eye(3); %vertices of triangle\n% \n% U=unionHull('vert',V1,'vert',V2); %compute the union\n%\n%One can verify that the vertices of the result are those of the unit\n%simplex,\n%\n% >> U.vert\n% \n% ans =\n% \n% 0 0 0\n% 0 0 1\n% 0 1 0\n% 1 0 0\n%\n%We also demonstrate the use of separateBounds() to convert the result to \n%Optimization Toolbox representation. The tolerance parameter 0.99 is used\n%to deal with residual floating point noise.\n%\n% >> [A,b,Aeq,beq,lb,ub]=separateBounds(U.lcon{:},.99)\n% \n% A =\n% \n% 0.5774 0.5774 0.5774\n% \n% \n% b =\n% \n% 0.5774\n%\n% \n% Aeq =\n% \n% []\n% \n% \n% beq =\n% \n% Empty matrix: 0-by-1\n% \n% \n% lb =\n% \n% 0\n% 0\n% 0\n% \n% \n% ub =\n% \n% Inf\n% Inf\n% Inf \n% \n% \n% \n%EXAMPLE 2: The unit cube is formed as the union of a simplex, a square,\n%and a single 3D point. The simplex and square are both represented using\n%equalites and inequalities. For convenience, we use the addBounds() utility\n%to compose the in/equality matrices. The representation of the square illustrates\n%the use of the 'qlcon' label, when a known interior point is available.\n% \n% \n% [A1,b1,Aeq1,beq1] = addBounds([1 1 1],1,[],[],[0;0;0]); %unit simplex\n% \n% [A2,b2,Aeq2,beq2] = addBounds([],[],[],[],[1;0;0],[1;1;1]); %a square face of the unit cube\n% \n% x2 = [1,0.5,0.5];%a point in the relative interior of the square \n% \n% V3 = [0,1,1]; %one vertex of the unit cube\n% \n% \n% U=unionHull('lcon',A1,b1,Aeq1,beq1,... %compute the union\n% 'qlcon',x2,A2,b2,Aeq2,beq2,...\n% 'vert',V3);\n%\n%One can verify that the result contains the 8 vertices of the unit cube,\n%\n% >> U.vert\n% \n% ans =\n% \n% 0 -0.0000 -0.0000\n% 0.0000 -0.0000 1.0000\n% -0.0000 1.0000 -0.0000\n% 0 1.0000 1.0000\n% 1.0000 0.0000 0.0000\n% 1.0000 0.0000 1.0000\n% 1.0000 1.0000 0.0000\n% 1.0000 1.0000 1.0000\n%\n%As before, we can use separateBounds() to convert to Optimization Toolbox\n%form,\n% \n% >> [A,b,Aeq,beq,lb,ub]=separateBounds(U.lcon{:},.99) \n%\n%which results in A=b=Aeq=beq=[] and\n%\n% lb =\n% \n% 0\n% 0\n% 0\n% \n% \n% ub =\n% \n% 1.0000\n% 1.0000\n% 1.0000\n\n\n%%%%begin parsing\n\nif isnumeric(varargin{1})\n TOLcell=varargin(1);\n varargin(1)=[];\nelse\n TOLcell={};\nend\n\nN=length(varargin);\nidxType = [find(cellfun(@ischar,varargin)),N+1];\n\nL=length(idxType)-1;\nS(L).type=[];\nS(L).args={};\n\n\nfor i=1:L\n \n j=idxType(i);\n k=idxType(i+1);\n S(i).type=varargin{j};\n S(i).args=varargin(j+1:k-1);\n \n if isempty(S(i).args)\n error 'Syntax error - arguments missing' \n end\n \n switch S(i).type\n \n case 'lcon'\n \n S(i).V = lcon2vert(S(i).args{:});\n \n case 'qlcon'\n \n S(i).V = qlcon2vert(S(i).args{:});\n \n case 'vert'\n \n S(i).V = S(i).args{1};\n \n otherwise\n \n error(['Unrecognized representation label of polyhedron ' num2str(i)]);\n \n \n end\n \n\n end\n\n\n\n%%%%end parsing\n\n\n V=vertcat(S.V);\n \n x0=mean(V,1);\n \n [U.lcon{1:4}]=vert2lcon(V,TOLcell{:});\n \n U.vert=qlcon2vert(x0,U.lcon{:},TOLcell{:});\n \n\n \n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/polytopes_2017_10_04_v1.9/unionHull.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7324184250015128}} {"text": "function mb_lbfgs\n\n% 2010 m.bangert@dkfz.de\n% fitting a gaussian distribution to data with a quasi newton method using\n% a lbfgs update for the inverse hessian matrix\n%\n% example : mb_bfgs (function does not take any argument)\n\n% options\nvisLineSearch = 1;\nvisBool = 1;\n\n% sample data from a gaussian distribution\nrandn('seed',12345); %set the seed of the random number generator - if you do not want to do that comment...\nnumOfSamples = 250;\ndata(:,1) = linspace(-2,4,numOfSamples) + 6/numOfSamples*randn(1,numOfSamples);\ndata(:,2) = exp(-(linspace(-2,4,250)-1.5).^2) + .05*randn(1,250);\n\n% plot data\nif visBool\n close all\n figure\n hold on\n plot(data(:,1),data(:,2),'b+')\n xlabel('X')\n ylabel('Y')\n visHandle = [];\nend\n\n% specify input\nmem = 10; % number of past gradients and function values used for inverse hessian contruction\nx = NaN*ones(3,mem);\nx(:,1) = [1 1 1]'; % starting value for parameters\nobjFuncValue = NaN*ones(1,mem);\ndx = NaN*ones(3,mem);\n\ns_k = ones(3,mem-1);\ny_k = ones(3,mem-1);\nr_k = ones(mem-1,1);\na_k = ones(1,mem-1);\n\nfprintf(['\\nFitting a gaussian distribution to data with an L-BFGS-B algorithm...\\n\\n']);\n\n% 1st calculation of objective function and gradient\nobjFunc = @(x) sum((x(3,1).*exp(-(data(:,1)-x(1,1)).^2./x(2,1))-data(:,2)).^2);\nobjFuncValue(1) = objFunc(x(:,1));\nobjFuncValue(2) = objFuncValue(1) + 1;\ndx(:,1) = mb_numDiff(objFunc,x(:,1));\n\n% iterate\niter = 0;\nnumOfIter = 100;\nprec = 1e-5;\n\n% convergence if gradient smaller than prec, change in objective function\n% smaller than prec or maximum number of iteration reached...\nwhile iter < numOfIter && abs((objFuncValue(2)-objFuncValue(1))/objFuncValue(1))>prec && norm(dx(:,1))>prec\n \n % implementation of L-BFGS according to\n % http://en.wikipedia.org/wiki/L-BFGS\n \n % inverse hessian update\n q = dx(:,1);\n for i = 1:min(iter,mem-1)\n a_k(i) = r_k(i)*s_k(:,i)'*q;\n q = q - a_k(i)*y_k(:,i);\n end\n z = s_k(:,1)'*y_k(:,1)/(y_k(:,1)'*y_k(:,1))*q; % this corresponds to H*q where H is approximated as described in Nocedal 9.1\n for i = min(iter,mem-1):-1:1\n b = r_k(i)*y_k(:,i)'*z;\n z = z + s_k(:,i)*(a_k(i)-b);\n end\n \n % obtain search direction\n dir = -z;\n \n % 2.1 armijo linesearch to to find acceptable stepsize alpha\n alpha = mb_backtrackingLineSearch(objFunc,objFuncValue(1),x(:,1),dx(:,1),dir);\n \n % 3\n p = alpha*dir;\n \n % visualize the line search (optional) used for debugging\n if visLineSearch\n figure\n hold on\n alphas = linspace(0,2*alpha,100);\n alphaVis = NaN*alphas;\n for i = 1:100\n alphaVis(i) = objFunc(x(:,1)+alphas(i)*dir);\n end\n plot(alphas,alphaVis,'b') % function in direction of line search\n plot(alpha,objFunc(x(:,1)+alpha*dir),'r.') % the steplength found\n plot(alphas,objFuncValue(1) + 1e-1*alphas*(dir'*dx(:,1)),'g') % constraint\n pause(.5)\n close\n end\n \n % 2.2 update x\n x(:,2:end) = x(:,1:end-1);\n x(:,1) = x(:,1) + p;\n s_k = -diff(x,[],2);\n \n % update objective function (and remember old objective function to\n % check for convergence)\n objFuncValue(2) = objFuncValue(1);\n objFuncValue(1) = objFunc(x(:,1));\n \n % increment iteration counter\n iter = iter + 1;\n \n fprintf(1,'Iteration %d: alpha_min=%f, OF=%f\\n',iter,alpha,objFuncValue(1));\n \n % calculate difference of gradients\n dx(:,2:end) = dx(:,1:end-1);\n dx(:,1) = mb_numDiff(objFunc,x(:,1));\n y_k = -diff(dx,[],2);\n\n r_k = 1./diag(y_k'*s_k);\n\n % update function with new x and plot\n if visBool\n pause(0.5)\n fitFunc = @(t) x(3).*exp(-(t-x(1)).^2./x(2));\n delete(visHandle);\n visHandle = plot(data(:,1),fitFunc(data(:,1)),'r','LineWidth',4);\n drawnow;\n end\n \nend\n\nfprintf(['\\n' num2str(iter) ' iteration(s) performed to converge\\n'])\n\nfprintf(1,'Final solution: x=(%f,%f,%f)\\n',x(1),x(2),x(3));\n\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34835-optimization-tutorial/mb_lbfgs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7324184242752039}} {"text": "function R = Rroll(phi)\n\nc = cos(phi); s = sin(phi);\nR = [1 0 0; 0 c -s; 0 s c];", "meta": {"author": "s-kajita", "repo": "IntroductionToHumanoidRobotics", "sha": "55c46ce6902c97897596fda581f93555c426736c", "save_path": "github-repos/MATLAB/s-kajita-IntroductionToHumanoidRobotics", "path": "github-repos/MATLAB/s-kajita-IntroductionToHumanoidRobotics/IntroductionToHumanoidRobotics-55c46ce6902c97897596fda581f93555c426736c/Rroll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9489172630429474, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7324156244470784}} {"text": "function value = i4_modp ( i, j )\n\n%*****************************************************************************80\n%\n%% I4_MODP returns the nonnegative remainder of I4 division.\n%\n% Discussion:\n%\n% If\n% NREM = I4_MODP ( I, J )\n% NMULT = ( I - NREM ) / J\n% then\n% I = J * NMULT + NREM\n% where NREM is always nonnegative.\n%\n% The MOD function computes a result with the same sign as the\n% quantity being divided. Thus, suppose you had an angle A,\n% and you wanted to ensure that it was between 0 and 360.\n% Then mod(A,360) would do, if A was positive, but if A\n% was negative, your result would be between -360 and 0.\n%\n% On the other hand, I4_MODP(A,360) is between 0 and 360, always.\n%\n% Example:\n%\n% I J MOD I4_MODP Factorization\n%\n% 107 50 7 7 107 = 2 * 50 + 7\n% 107 -50 7 7 107 = -2 * -50 + 7\n% -107 50 -7 43 -107 = -3 * 50 + 43\n% -107 -50 -7 43 -107 = 3 * -50 + 43\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 26 August 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, the number to be divided.\n%\n% Input, integer J, the number that divides I.\n%\n% Output, integer VALUE, the nonnegative remainder when I is\n% divided by J.\n%\n if ( j == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_MODP - Fatal error!\\n' );\n fprintf ( 1, ' Illegal divisor J = %d\\n', j );\n error ( 'I4_MODP - Fatal error!' );\n end\n\n value = mod ( i, j );\n\n if ( value < 0 )\n value = value + abs ( 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/sparse_grid_hermite/i4_modp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.8596637505099167, "lm_q1q2_score": 0.7323929539232208}} {"text": "function sftpack_test02 ( )\n\n%*****************************************************************************80\n%\n%% TEST02 tests R8VEC_SFTB and R8VEC_SFTF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n n = 36;\n alo = 0.0;\n ahi = 5.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST02\\n' );\n fprintf ( 1, ' For real slow Fourier transforms,\\n' );\n fprintf ( 1, ' R8VEC_SFTF computes the forward transform.\\n' );\n fprintf ( 1, ' R8VEC_SFTB computes the backward transform.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of data values, N = %d\\n', n );\n\n seed = 123456789;\n\n [ x, seed ] = r8vec_uniform ( n, alo, ahi, seed );\n\n r8vec_print_part ( n, x, 10, ' The original data:' );\n%\n% Compute the slow Fourier transform of the data.\n%\n [ azero, a, b ] = r8vec_sftf ( n, x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A (cosine) coefficients:\\n' );\n fprintf ( 1, '\\n' );\n\n fprintf ( 1, ' %4d %f\\n', 0, azero );\n\n for i = 1 : floor ( n / 2 )\n fprintf ( 1, ' %4d %f\\n', i, a(i) );\n end \n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' B (sine) coefficients:\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : floor ( n / 2 )\n fprintf ( 1, ' %4d %f\\n', i, b(i) );\n end\n%\n% Now try to retrieve the data from the coefficients.\n%\n x = r8vec_sftb ( n, azero, a, b );\n\n r8vec_print_part ( n, x, 10, ' The retrieved data:' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sftpack/sftpack_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7323929443972448}} {"text": "function spline_test125 ( )\n\n%*****************************************************************************80\n%\n%% TEST125 tests LEAST_SET_OLD, LEAST_VAL_OLD.\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 maxdeg = 6;\n ntab = 21;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST125\\n' );\n fprintf ( 1, ' LEAST_SET_OLD sets a least squares polynomial,\\n' );\n fprintf ( 1, ' LEAST_VAL_OLD evaluates it.\\n' );\n\n for i = 1 : ntab\n xtab(i) = ( ( ntab - i ) * ( -1.0 ) ...\n + ( i - 1 ) * ( +1.0 ) ) ...\n / ( ntab - 1 );\n ytab(i) = ( floor ( exp ( xtab(i) ) * 100.0 + 0.5 ) ) / 100.0;\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The data to be interpolated:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of data values = %d\\n', ntab );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X Y\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : ntab\n fprintf ( 1, '%14f %14f\\n', xtab(i), ytab(i) );\n end\n\n for ndeg = 1 : maxdeg\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Use a polynomial of degree: %d\\n', ndeg );\n fprintf ( 1, '\\n' );\n\n [ ptab, b, c, d, eps, ierror ] = least_set_old ( ntab, xtab, ytab, ndeg );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Total approximation error = %f\\n', eps );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X, F(X), P(X), Error\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : ntab\n\n if ( i < ntab )\n jhi = 2;\n else\n jhi = 0;\n end\n\n for j = 0 : jhi\n\n if ( i < ntab )\n\n xval = ( ( 3 - j ) * xtab(i) ...\n + ( j ) * xtab(i+1) ) ...\n / ( 3 );\n\n else\n\n xval = xtab(i);\n\n end\n\n yval = least_val_old ( xval, ndeg, b, c, d );\n\n ytrue = ( floor ( exp ( xval ) * 100.0 + 0.5 ) ) / 100.0;\n\n fprintf ( 1, '%14f %14f %14f %14f\\n', xval, yval, ytrue, ...\n yval - ytrue );\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/spline/spline_test125.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7323929314715337}} {"text": "function [B1, C1, c1, B2, C2, c2] = ssad(a, b, A)\n%SSAD gives both solutions to the side-side-angle problem, in degrees.\n%\n% SSAD(a, b, A) will result in NaNs if the existence condition \n% |sin b * sin A| <= | sin a | is not met. \n%\n% See also SSA, MALD, MSLD.\n\n% Rody P.S. Oldenhuis\n% Delft University of Technology\n% oldenhuis@gmail.com\n%\n% Crated : 23/Feb/2009\n% Last edited: 30/Nov/2012\n \n % find both solutions by calling ssa directly\n r2d = 180/pi; \n d2r = 1/r2d; \n [B1, C1, c1, B2, C2, c2] = ssa(a*d2r, b*d2r, A*d2r);\n [B1, C1, c1, B2, C2, c2] = deal(B1*r2d, C1*r2d, c1*r2d, B2*r2d, C2*r2d, c2*r2d);\n \nend", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/SphericalTrigToolbox/ssad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7323350894206966}} {"text": "% Chapter 17 - Neural Networks.\n% Programs_17a - The Generalized Delta Learning Rule (Figure 17.7).\n% Copyright Birkhauser 2013. Stephen Lynch.\n\nfunction Programs_17a\n% Load Boston housing data.\nload housing.txt\nX = housing(:,[6 9 13]);\nt = housing(:,14);\n\n% Scale to zero mean, unit variance and introduce bias on input.\nxmean = mean(X);\nxstd = std(X);\nX = (X-ones(size(X,1),1)*xmean)./(ones(size(X,1),1)*xstd);\nX = [ones(size(X,1),1) X];\ntmean = (max(t)+min(t))/2;\ntstd = (max(t)-min(t))/2;\nt = (t-tmean)/tstd;\n\n% Initialise random weight vector.\nrandn('seed', 123456);\nw(:,1) = 0.1*randn(size(X,2),1);\ny1 = tanh(X*w(:,1));\ne1 = t-y1;\nmse(1) = var(e1);\n\n\n% Do numEpochs iterations.\nnumEpochs = 10;\nnumPatterns = size(X,1);\neta = 0.001;\nk = 1;\nfor m=1:numEpochs\n for n=1:numPatterns\n\t% Calculate feedforward output, error, and gradient.\n\tyk = tanh(X(n,:)*w(:,k));\n\terr = yk-t(n);\n\tg = X(n,:)'*((1-yk^2)*err);\n\t% Update the weight.\n\tw(:,k+1) = w(:,k) - eta*g;\n\tk = k+1;\n end\nend\n\nfor m=1:size(w,1)\nplot(1:k, w(m,:))\nhold on\nend\n\nfsize=15;\nset(gca,'XTick',0:2000:6000,'FontSize',fsize)\nset(gca,'YTick',-0.3:0.1:0.3,'FontSize',fsize)\nxlabel('Number of Iterations','FontSize',fsize)\nylabel('Weights','FontSize',fsize)\nhold off\n\n% End of Programs_17a.\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/2374-dynamical-systems-with-applications-using-matlab/MATLAB files 20013a/Programs_17a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7322711794537841}} {"text": "function [W, Zhat] = ica(X,Nsources,Wprev)\n%ICA Perform independent component analysis\n% [W, ZHAT] = ICA(X) performs independent component analysis on data\n% observation matrix X of physiological observations.\n%\n% Inputs:\n% X = Observation matrix: rows should be observations, cols samples.\n% Nsources = Number of source signals (optional).\n% Wprev = Timepoint at which to start process (default = 0 seconds).\n%\n% Outputs:\n% W = Demixing matrix.\n% Zhat = Source signal matrix.\n%\n% This approach uses Cardoso's ICA\n% algorithm to estimate sources (ZHAT) and the de-mixing matrix W, an\n% approximation to A^{-1}, the original (unknown) mixing matrix. \n%\n% Daniel McDuff, Ethan Blackford, Justin Estepp, December 2018\n% Based on an implementation by: G D Clifford (2004) gari AT mit DOT edu\n% Licensed under the MIT License and the RAIL AI License.\n\n[nRows, nCols] = size(X);\nif nRows > nCols\n fprintf('Warning - The number of rows is cannot be greater than the number of columns.\\n');\n error('Please transpose input.');\nend\n\nif Nsources > min([nRows nCols])\n Nsources = min([nRows nCols]);\n fprintf('Warning - The number of soures cannot exceed number of observation channels. \\n')\n fprintf('The number of sources will be reduced to the number of observation channels (%i) \\n',Nsources)\nend\n\nif exist('Vprev','var')\n [Winv, Zhat] = jade(X,Nsources,Wprev); \nelse\n [Winv, Zhat] = jade(X,Nsources); \nend\nW = pinv(Winv);\n", "meta": {"author": "danmcduff", "repo": "iphys-toolbox", "sha": "65deeb46aea80c04009fe304a6612e4ef1497f08", "save_path": "github-repos/MATLAB/danmcduff-iphys-toolbox", "path": "github-repos/MATLAB/danmcduff-iphys-toolbox/iphys-toolbox-65deeb46aea80c04009fe304a6612e4ef1497f08/tools/ica/ica.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145178, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.732263587673396}} {"text": "function varargout = sphereMesh(sphere, varargin)\n%SPHEREMESH Create a 3D mesh representing a sphere.\n%\n% [V, F] = sphereMesh(S)\n% Creates a 3D mesh representing the sphere S given by [xc yc zy r].\n%\n% [V, F] = sphereMesh();\n% Assumes sphere is the unit sphere centered at the origin.\n%\n% [V, F] = sphereMesh(S, 'nTheta', NT, 'nPhi', NP);\n% Specifies the number of discretisation steps for the meridians and the\n% parallels. Default values are nTheta = 16 and nPhi = 32.\n%\n%\n% Example\n% s = [10 20 30 40];\n% [v, f] = sphereMesh(s);\n% drawMesh(v, f);\n% view(3); axis equal; light; lighting gouraud;\n%\n% See also \n% meshes3d, drawSphere, ellipsoidMesh, cylinderMesh, surfToMesh\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2012-10-25, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012-2022 INRA - Cepia Software Platform\n\nif nargin == 0\n sphere = [0 0 0 1];\nend\n\n% number of meridians\nnPhi = 32;\n \n% number of parallels\nnTheta = 16;\n\n% process input arguments\nwhile length(varargin) > 1\n paramName = varargin{1};\n switch lower(paramName)\n case 'ntheta', nTheta = varargin{2};\n case 'nphi', nPhi = varargin{2};\n otherwise\n error(['Could not recognise parameter: ' paramName]);\n end\n varargin(1:2) = [];\nend\n\n% extract sphere data\nxc = sphere(:,1);\nyc = sphere(:,2);\nzc = sphere(:,3);\nr = sphere(:,4);\n\n\n% compute spherical coordinates\ntheta = linspace(0, pi, nTheta+1);\nphi = linspace(0, 2*pi, nPhi+1);\n\n% convert to cartesian coordinates\nsintheta = sin(theta);\nx = xc + cos(phi') * sintheta * r;\ny = yc + sin(phi') * sintheta * r;\nz = zc + ones(length(phi),1) * cos(theta) * r;\n\n% convert to FV mesh\n[vertices, faces] = surfToMesh(x, y, z, 'yperiodic', true);\n\n% format output\nvarargout = formatMeshOutput(nargout, vertices, faces);\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/sphereMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7321619933779308}} {"text": "function [f, finv, pol, polinv] = conformal(C, varargin)\n%% CONFORMAL Conformal map to unit disk\n% [F, FINV] = CONFORMAL(C, ctr) computes a conformal map F of the region\n% bounded by the complex periodic chebfun C to the unit disk and its inverse\n% FINV, with F(ctr) = 0 and F'(ctr) > 0. Both maps are represented by\n% function handles evaluating rational functions. If ctr is omitted it is\n% set to 0.\n%\n% CONFORMAL(..., 'tol', tol) uses tolerance tol instead of the default 1e-5.\n%\n% CONFORMAL(..., 'plots') produces plots of the map and its inverse.\n%\n% CONFORMAL(..., 'numbers') prints various quantities.\n%\n% CONFORMAL(..., 'poly') uses a less robust algorithm based on polynomials\n% instead of the Kerzman-Stein integral equation.\n%\n% [F, FINV, POL, POLINV] = CONFORMAL(...) returns the poles of F and FINV.\n%\n% This experimental code is good for smooth simple regions, but easy to break.\n%\n% Examples:\n%\n% C = chebfun('exp(pi*1i*t)','trig')*(1+.15*randnfun(.2,'trig'));\n% [f, finv] = conformal(C, 'plots'); % random\n%\n% C = chebfun('2*cos(t)+1i*(sin(t)+2*cos(t).^3)',[0 2*pi],'trig'); % Ellacott\n% conformal(C, 'poly', 'plots'); % blade\n%\n% C = chebfun('exp(pi*1i*t)*(1+.3*cos(6*pi*t))','trig');\n% conformal(C, 'plots', 'tol', 1e-8, 'numbers'); % snowflake\n%\n% s = chebfun('s'); C = join(s-.5i,1+.5i*s,.5i-s,-1-.5i*s);\n% conformal(C, 'poly', 'plots'); % rectangle\n%\n% References:\n% \n% A. Gopal and L. N. Trefethen, Representation of conformal maps by\n% rational functions, Numer. Math. 142 (2019), 359--382.\n%\n% L. N. Trefethen, Numerical conformal mapping with rational \n% functions, Comp. Meth. Funct. Th. 20 (2020), 369-387.\n%\n% See also CONFORMAL2.\n\n%%\n% Default algorithm:\n% (1) Solve discretized Kerzman-Stein integral equation\n% (2) Use AAA to approximate f and its inverse by rational functions\n%\n% Alternative algorithm if 'poly' is specified:\n% (1) Use least-squares to find harmonic u s.t. u(z) = -log(abs(z-ctr)) on C\n% (2) Set w = u+iv (v = harmonic conjugate of u)\n% (3) Set f = z*exp(w(z-ctr));\n% (4) Use AAA to approximate f and its inverse by rational functions\n%\n% Although in principle these algorithms should be embedded in the\n% Chebfun constructor, for simplicity in this numerically challenging\n% area we have not done that.\n%\n% This code was written by L. N. Trefethen in September 2019. The\n% Kerzman-Stein part originates with Anne Greenbaum and Trevor Caldwell.\n\nt1 = tic;\n[ctr, tol, plots, numbers, poly] = parseinputs(C, varargin{:});\nerr = Inf;\nscl = norm(C-ctr, inf);\n\nif poly == 0 % DEFAULT ALGORITHM: KERZMAN-STEIN INTEGRAL EQUATION\n\n M = 300;\n while err > tol\n M = M + 300;\n [g, Z, W] = kerzstein((C-ctr)/scl, M, 0);\n Z = Z*scl + ctr;\n gc = trigcoeffs(g);\n err = norm(gc([1:10 end-9:end])); % a crude error measure\n if (err > tol) && (M >= 1200)\n warning('CONFORMAL did not converge')\n break\n end\n end\n\nelse % ALTERNATIVE ALGORITHM: POLYNOMIAL EXPANSION\n\n w1 = warning('off', 'MATLAB:rankDeficientMatrix');\n logn = 4;\n dom = domain(C); \n dom = dom([1 end]);\n while err > tol\n n = round(2^logn); % degree of polynomial\n M = 8*n; % number of sample points\n logn = logn + 1/2;\n Z = C(dom(1) + (1:M)'*diff(dom)/M); % sample points\n Zscl = (Z-ctr)/scl; % rescale to improve conditioning\n G = -log(abs(Zscl)); % RHS for Dirichlet problem\n n1 = 0:n; % exponents for real part\n n2 = 1:n; % of exponents for imag part\n Q = ones(size(Zscl)); % Arnoldi. Q has orthog cols of norm sqrt(M).\n H = zeros(n+1,n); \n for k = 1:n\n v = Zscl.*Q(:,k);\n v = v - Q*(Q'*v)/M; % or execute twice for better orthogonality!\n H(k+1,k) = norm(v)/sqrt(M); % At end, Zscl.*Q(:,1:n)/M = Q*H\n Q = [Q v/H(k+1,k)]; % Q has orthog cols of norm sqrt(M)\n end\n A = [real(Q) imag(Q(:,2:end))];\n c = A\\G; % soln of least-squares problem\n err = norm(A*c-G, inf); % max error\n cc = c(n1+1)-1i*[0; c(n+1+n2)]; % coeffs for harmonic -> analytic\n W = Zscl.*exp(Q*cc); % images on boundary\n if (err > tol) && (logn >= 9.5)\n warning('CONFORMAL did not converge')\n break\n end\n end\n warning(w1.state, 'MATLAB:rankDeficientMatrix')\n\nend\n\nw2 = warning('off', 'CHEBFUN:aaa:Froissart');\n[f0, pol] = aaa(W, Z, 'tol', tol); % forward map\nzz = 1e-4*scl*[1 1i -1 -1i]; % finite diff for simplicity\ndwdz = sum(f0(ctr+zz)./zz); % derivative at ctr\nrot = exp(-1i*angle(dwdz)); % rotation for f'(ctr) > 0\nf = @(z) rot*f0(z); % rotate mapping function\nW = rot*W; % rotate points on circle\n[finv, polinv] = aaa(Z, W, 'tol', tol); % inverse map\nwarning(w2.state, 'CHEBFUN:aaa:Froissart')\n\ninC = inpolygon(real(pol), imag(pol), ... % check for poles of f in region\n\treal(Z), imag(Z));\nif max(inC) > 0\nwarning('CONFORMAL: pole in region')\nend\nif min(abs(polinv)) < 1 % check for poles of finv in disk\n warning('CONFORMAL: pole in disk')\nend\ntcomp = toc(t1);\n\n% Plot solution if requested\nif plots\n t2 = tic;\n clf\n LW = 'linewidth'; PO = 'position'; MS = 'markersize';\n FW = 'fontweight'; NO = 'normal'; XT = 'xtick'; YT = 'ytick';\n circ = exp(2i*pi*(0:300)/300);\n \n h1 = axes(PO, [.04 .38 .45 .53]); % plot C and poles of f\n plot(C, 'b', LW, 1)\n axis([real(ctr)+1.4*scl*[-1 1] imag(ctr)+1.4*scl*[-1 1]])\n axis square, hold on, plot(pol, '.r', MS, 8)\n title([num2str(length(pol)) ' poles'],FW,NO)\n \n h2 = axes(PO, [.52 .38 .45 .53]); % plot disk and poles of finv\n plot(circ, 'b', LW, 1), axis(1.6*[-1 1 -1 1])\n axis square, hold on, set(gca,XT,-1:1,YT,-1:1)\n plot(polinv, '.r', MS, 8)\n title([num2str(length(polinv)) ' poles'],FW,NO)\n \n ncirc = 8; % plot concentric circles and their images\n for r = (1:ncirc-1)/ncirc\n axes(h1), plot(finv(r*circ), '-k', LW, .5)\n axes(h2), plot(r*circ, '-k', LW, .5)\n end\n\n nrad = 16; % plot radii and their images\n ray = chebpts(301);\n ray = ray(ray>=0);\n for k = 1:nrad\n axes(h1), plot(finv(ray*exp(2i*pi*k/nrad)), '-k', LW, .5)\n axes(h2), plot(ray*exp(2i*pi*k/nrad), '-k', LW, .5)\n end\n\n axes(h1), hold off\n axes(h2), hold off\n tplot = toc(t2);\n\nend\n\n% Print various quantities if requested\nif numbers\n disp(' ')\n fprintf(' computation time in seconds:%6.2f\\n', tcomp)\n if plots\n fprintf(' plotting time in seconds:%6.2f\\n', tplot)\n end\n fprintf(' number of sample points Z on boundary, M: %d\\n', M)\n fprintf(' numbers of poles of f and finv: %d, %d\\n', ...\n length(pol), length(polinv))\n fprintf('back-and-forth boundary error norm(Z-finv(f(Z)),inf): %6.1e\\n',...\n norm(Z-finv(f(Z)), inf))\n fprintf(' inverse back-and-forth error norm(W-f(finv(W)),inf): %6.1e\\n',...\n norm(W-f(finv(W)), inf))\n fprintf(' interior inverse error norm(.9*W-f(finv(.9*W)),inf): %6.1e\\n',...\n norm(.9*W-f(finv(.9*W)), inf))\n if poly\n fprintf(' max error of least-squares problem, err: %6.1e\\n', err)\n fprintf(' polynomial degree, n: %d\\n', n)\n fprintf(' number of real degrees of freedom, N: %d\\n', 2*n+1)\n fprintf(' condition number of least-squares matrix A: %6.1e\\n', cond(A))\n else\n fprintf(' rough error measure, err: %6.1e\\n', err)\n end\n disp(' ')\nend\n\nend % of conformal\n\nfunction [ctr, tol, plots, numbers, poly] = parseinputs(C, varargin)\nctr = 0; % defaults\ntol = 1e-5; \nplots = 0;\nnumbers = 0;\npoly = 0;\nj = 1;\nwhile j < nargin\n j = j+1;\n v = varargin{j-1};\n if isnumeric(v)\n ctr = v;\n elseif strcmp(v, 'tol')\n j = j+1;\n tol = varargin{j-1};\n elseif strcmp(v, 'plots')\n plots = 1;\n elseif strcmp(v, 'numbers')\n numbers = 1;\n elseif strcmp(v, 'poly')\n poly = 1;\n end\nend\nwinding_number = sum(diff(C)/(C-ctr))/(2i*pi);\nif abs(winding_number - 1) > tol\n error('CONFORMAL:parseinputs','C must wind once counterclockwise around ctr')\nend\nend % end of parseinputs\n\nfunction [g, Z, W] = kerzstein(C, M, ctr)\n%\n% Given a smooth periodic chebfun C defining the boundary of a region Omega \n% in the counterclockwise direction, this function computes the boundary\n% correspondence function g for a conformal mapping from Omega to the unit\n% disk, mapping ctr to 0. It first finds M points (Z) on C that are equally\n% spaced in arclength. It then solves an integral equation to determine the\n% images of these points (W) on the unit circle. Finally, a periodic\n% chebfun g is defined to map the arclengths associated with Z to their\n% images on the unit circle. The original version of this code cones\n% from Anne Greenbaum and Trevor Caldwell.\n% Reference: Kerzman and Trummer, \"Numerical conformal mapping via the Szego\n% kernel,\" Journal of Computational and Applied Mathematics 14 (1986), 111-123.\n\n% Express C as a function of arclength and compute its derivative\n\nS = arcLength(C);\ns = cumsum(abs(diff(C)));\ndC_arg = angle(diff(C));\ndC_arg = unwrap(dC_arg - dC_arg(0));\nu = inv(s);\nC = newDomain(C, minandmax(u));\nD = C(u);\nDprime = diff(D);\n\n% Set up and solve the integral equation\n\nds = S/M;\nsvec = [0:M-1]'*ds;\nDvec = D(svec);\nZ = Dvec;\nDprimevec = Dprime(svec);\ngamdotvec = Dprimevec ./ abs(Dprimevec); % unit tangents\nd = 1/(2i*pi);\ngvec = d*conj(gamdotvec./(ctr - Dvec));\nA = eye(M);\nfor j = 1:M\n w = Dvec(j);\n for i = 1:M\n z = Dvec(i);\n if i ~= j\n A(i,j) = A(i,j) - d*(conj(gamdotvec(i)/(z-w)) + gamdotvec(j)/(w-z))*ds;\n end\n end\nend\nfvec = A\\gvec;\n\n% Compute boundary correspondence function g\n\nRprimevec = fvec.^2;\nRvec = -1i*gamdotvec.*(Rprimevec./abs(Rprimevec));\nW = Rvec;\ng = chebfun(Rvec, [0,S], 'trig');\n\nend % of kerzstein\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/conformal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809304, "lm_q2_score": 0.8267118026095992, "lm_q1q2_score": 0.7321619871769581}} {"text": "function thePartition=unrankPartition(rank,n)\n%%UNRANKPARTITION Given the rank of a partiion of the integer n, when\n% considering the partitions given in reverse lexicographic\n% order, find the partition of the given rank. A partition\n% of the integer n is a set of integers that sum to n.\n%\n%INPUTS: rank The integer rank of the partition. rank>0.\n% n The integer being partitioned.\n%\n%OUTPUTS: thePartition A numElementsX1 partition of n of the given rank.\n%\n%Let p(n,m) be the number of partitions of n with up to m parts. It is\n%known that p(n,m)=p(n,m-1)+p(n-m,m). This relation is given in Chapter\n%7.2.1.4 of [1]. The rank obtained here is derived using that recurrence\n%relation.\n%\n%EXAMPLE:\n%Here, we demonstrate that the unrankPartition function is consistent with\n%the rankPartition function.\n% n=20;\n% [thePartition,theData]=getNextPartition(n);\n% while(~isempty(thePartition))\n% assert(all(unrankPartition(rankPartition(thePartition),n)==thePartition))\n% [thePartition,theData]=getNextPartition(n,theData);\n% end\n%There should be no error indicating that the unranked partitions are all\n%the same as the ranked partitions.\n%\n%REFERENCES:\n%[1] D. E. Knuth, The Art of Computer Programming. Vol. 4, Fascicle 3:\n% Generating all Combinations and Partitions, Upper Saddle River, NJ:\n% Addison-Wesley, 2009.\n%\n%September 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nthePartition=zeros(n,1);%We do not know how many parts to have...\n\nrank=numberOfPartitions(n)-rank;\n\nif(rank<0)\n error('The rank given is more than the total number of partitions of n')\nend\n\ncurIdx=0;\nnLeft=n;\nwhile(rank>0)\n parts=1;\n numParts=numMPartitions(nLeft,parts,true);\n while(numPartsrank)\n parts=parts-1;\n numParts=numMPartitions(nLeft,parts,true);\n end\n \n curIdx=curIdx+1;\n thePartition(curIdx)=parts+1;\n rank=rank-numParts;\n nLeft=nLeft-thePartition(curIdx);\nend\n\nwhile(nLeft>0)\n curIdx=curIdx+1;\n thePartition(curIdx)=1;\n nLeft=nLeft-1;\nend\n\n%Shrink to fit.\nthePartition=thePartition(1:curIdx);\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/Combinatorics/unrankPartition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.7321619827151031}} {"text": "function [label, R] = mixGaussPred(model, X)\n% Predict label and responsibility for Gaussian mixture model.\n% Input:\n% X: d x n data matrix\n% model: trained model structure outputed by the EM algirthm\n% Output:\n% label: 1 x n cluster label\n% R: k x n responsibility\n% Written by Mo Chen (sth4nth@gmail.com).\nmu = model.mu;\nSigma = model.Sigma;\nw = model.w;\n\nn = size(X,2);\nk = size(mu,2);\nlogRho = zeros(n,k);\n\nfor i = 1:k\n logRho(:,i) = loggausspdf(X,mu(:,i),Sigma(:,:,i));\nend\nlogRho = bsxfun(@plus,logRho,log(w));\nT = logsumexp(logRho,2);\nlogR = bsxfun(@minus,logRho,T);\nR = exp(logR);\n[~,label(1,:)] = max(R,[],2);\n\nfunction y = loggausspdf(X, mu, Sigma)\nd = size(X,1);\nX = bsxfun(@minus,X,mu);\n[U,p]= chol(Sigma);\nif p ~= 0\n error('ERROR: Sigma is not PD.');\nend\nQ = U'\\X;\nq = dot(Q,Q,1); % quadratic term (M distance)\nc = d*log(2*pi)+2*sum(log(diag(U))); % normalization constant\ny = -(c+q)/2;", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter09/mixGaussPred.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7321009007051852}} {"text": "% Copyright (C) 2016, 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 jacobian_symbolic_3dof_planar\n\nsyms q1 q2 q3\n% matrices DH\nA01 = dh_sym(q1, 0, 0.5, 0);\nA12 = dh_sym(q2, 0, 0.5, 0);\nA23 = dh_sym(q3, 0, 0.5, 0);\n\nA02 = A01*A12;\nA03 = A01*A12*A23;\nA03 = simplify(A03);\n\nz0 = [0 0 1]';\n\np03=A03(1:3,4);\np13=A03(1:3,4)-A01(1:3,4);\np23=A03(1:3,4)-A02(1:3,4);\n\nJv = [cross(z0, p03) cross(z0, p13) cross(z0, p23)];\nJv = simplify(Jv)\n\nJw = [z0 z0 z0];\nJ = [Jv; Jw]\n% transform to valid dimensions\nJ = [J(1:2,:); J(6,:)]\n\nJ = simplify(J)\n\nsingularities = det(J)\nsingularities = simplify(singularities)\n\n%Redefine J\nJ = [J(1:2,:)]\n% compute moore-penrose pseudo inverse\nJp = J'*inv(J*J')\nJp = simplify(Jp)\n\n% compute projector P\nP = eye(3)-Jp*J\n\n\n\n\n\nfunction A = dh_sym(theta, d, a, alpha)\nsyms q1 q2 q3 q4\n% avoid almost zero elements in cos(alpha) and sin(alpha)\nca = cos(alpha);\nsa = sin(alpha);\nif abs(ca) < 1e-6\n ca = 0;\nend\nif abs(sa) < 1e-6\n sa = 0;\nend\n\n\nA=[cos(theta) -ca*sin(theta) sa*sin(theta) a*cos(theta);\n sin(theta) ca*cos(theta) -sa*cos(theta) a*sin(theta);\n 0 sa ca d;\n 0 0 0 1];\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/jacobian_symbolic_3dof_planar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7321008986801125}} {"text": "function x=irdct(y,n,a,b)\n%IRDCT Inverse discrete cosine transform of real data X=(Y,N) \n% Data is truncated/padded to length N.\n%\n% This routine is equivalent to multiplying by the matrix\n%\n% irdct(eye(n)) = cos((0.5:n)'*(0:n-1)*pi/n)*diag([sqrt(0.5)*a/b repmat(a,1,n-1)])/n\n%\n%\n% Default values of the scaling factors are A=sqrt(2N) and B=1 which\n% results in an orthogonal matrix. Other common values are A=1 or N and/or B=1 or sqrt(2). \n% If b~=1 then the columns are no longer orthogonal.\n% See also RCDT\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: irdct.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\nfl=size(y,1)==1;\nif fl y=y(:); end\n[m,k]=size(y);\nif nargin<4 b=1;\n if nargin<3 a=sqrt(2*m);\n if nargin<2 n=m;\n end\n end\nend\nif n>m y=[y; zeros(n-m,k)];\nelseif n= ri+rj\n% M(i,j) = 0;\n% Case 2: spheres i & j fully overlap, the overlap volume has to be\n% computed.\n% Condition: d(i,j)<= abs(ri-rj)\n% M(i,j) = 4/3*pi*min(ri,rj).^3\n% Case 3: spheres i & j partially overlap, the overlap volume has to be\n% computed decomposing the overlap volume.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Guillaume JACQUENOT\n% guillaume dot jacquenot at gmail dot com\n% 2008 01 31\n% 2009 09 10\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin==0\n % Performs an example\n % Creation of 5 spheres\n x = [0,1,5,3,-5];\n y = [0,4,3,7,0];\n z = [0,4,3,7,0];\n r = [1,5,3,2,2];\n Display_solution = true;\nelseif nargin==1 || nargin==2\n temp = varargin{1};\n x = temp(:,1);\n y = temp(:,2);\n z = temp(:,3);\n r = temp(:,4);\n if nargin == 2\n Display_solution = varargin{2};\n else\n Display_solution = false;\n end\nelseif nargin==4 || nargin==5\n x = varargin{1};\n y = varargin{2};\n z = varargin{3};\n r = varargin{4};\n if nargin == 5\n Display_solution = varargin{5};\n else\n Display_solution = false;\n end\nelse\n help volume_intersect_sphere_analytical\n error('volume_intersect_sphere_analytical:e0',...\n 'The number of arguments must 0, 1, 2, 4 or 5');\nend\n\n% Checking input argument\nif ~islogical(Display_solution)\n error('volume_intersect_sphere_analytical:e1',...\n 'Display_solution should be logical variable')\nend\n\n% Inputs are reshaped\nsize_x = numel(x);\nsize_y = numel(y);\nsize_z = numel(z);\nsize_r = numel(r);\n\nx = reshape(x,size_x,1);\ny = reshape(y,size_y,1);\nz = reshape(z,size_z,1);\nr = reshape(r,size_r,1);\n\n% Checking if the three input vectors have the same length\nif (size_x~=size_y)||(size_x~=size_z)||(size_x~=size_r)\n error('volume_intersect_sphere_analytical:e2',...\n 'Input of function must be the same length');\nend\n\n% Checking if there is any negative or null radius\nif any(r<=0)\n disp(['spheres with null or negative radius'...\n ' won''t be taken into account in the computation.'])\n temp = (r>0);\n x = x(temp);\n y = y(temp);\n z = z(temp);\n r = r(temp);\nend\n\n% Checking the size of the input argument\nif size_x==1\n M = 4/3*pi*r.^3;\n return\nend\n\n% Computation of distance between all spheres, which will allow to\n% determine which cases to use.\nX = meshgrid(x);\nY = meshgrid(y);\nZ = meshgrid(z);\nD = sqrt((X-X').^2+(Y-Y').^2+(Z-Z').^2);\n\n\n% Since the resulting matrix M is symmetric M(i,j)=M(j,i), computations are\n% performed only on the upper part of the matrix\nD = triu(D,1);\n\n[R1,R2] = meshgrid(r);\nsumR = triu(R1+R2,1);\ndifR = triu(abs(R1-R2),1);\n\n% Creating the resulting vector\nM = zeros(size_x*size_x,1);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% C2: Case 2: spheres i & j fully overlap\n% One of the spheres is inside the other one.\nC2 = triu(D<=difR);\nM(C2) = 4/3*pi*min(R1(C2),R2(C2)).^3;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Case 3: spheres i & j partially overlap\n% Partial intersection between spheres i & j\nC3 = (D>difR)&(Dxlen)\n error('TRI Must Be a Valid Triangulation of the Data in X, Y, Z.')\nend\n\nzs=z(tri);\nzmax=max(max(zs)); % find max and min in z data that is in tri\nzmin=min(min(zs));\n\nif length(nv)==1 % nv is number of contours\n zlev=linspace(zmax,zmin,nv+2);\nelseif length(nv)==2 && nv(1)==nv(2) % nv is one contour level\n zlev=nv(1);\nelse % nv is vector of contour levels\n zlev=sort(nv,'descend');\nend\nzlev(zlev>=zmax | zlev<=zmin)=[]; % eliminate contours outside data limits\nnlev=length(zlev);\n\nif nlev==0\n error('No Contours to Plot. Chosen Contours Outside Limits of Data.')\nend\n\n% precondition the input data\n[zs,zidx]=sort(zs,2); % sort vertices by z value ascending\nfor k=1:size(zs,1) % shuffle triangles to match\n tri(k,:)=tri(k,zidx(k,:));\nend\n\nhax=newplot; % create new axis if needed\nh=[]; % patch handle storage\nC=zeros(2,0); % Clabel data storage\ncs=[2 1]; % column swap vector cs(1)=2, cs(2)=1;\n\n% Main Loop ---------------------------------------------------------------\nfor v=1:nlev % one contour level at a time\n zc=zlev(v); % chosen level\n above=zs>=zc; % true for vertices above given contour\n numabove=sum(above,2); % number of triangle vertices above contour\n tri1=tri(numabove==1,:); % triangles with one vertex above contour\n tri2=tri(numabove==2,:); % triangles with two vertices above contour\n n1=size(tri1,1); % number with one vertex above\n n2=size(tri2,1); % number with two vertices above\n\n edge=[tri1(:,[1 3]) % first column is indices below contour level\n tri1(:,[2 3]) % second column is indices above contour level\n tri2(:,[1 2])\n tri2(:,[1 3])];\n if n1==0 % assign edges to triangle number\n n=[1:n2 1:n2]';\n elseif n2==0\n n=[1:n1 1:n1]';\n else\n n=[1:n1 1:n1 n1+(1:n2) n1+(1:n2)]';\n end\n\n [edge,idx]=sortrows(edge); % put shared edges next to each other\n n=n(idx); % shuffle triangle numbers to match\n\n idx=all(diff(edge)==0,2); % find shared edges\n idx=[idx;false]|[false;idx]; % True for all shared edges\n \n % eliminate redundant edges, two triangles per interior edge\n edgeh=edge(~idx,:); % hull edges\n nh=n(~idx); % hull triangle numbers\n if ~isempty(nh)\n nh(end,2)=0; % zero second column for hull edges\n end\n edges=edge(idx,:); % shared edges\n edges=edges(1:2:end-1,:); % take only unique edges\n ns=n(idx); % interior triangle numbers\n ns=[ns(1:2:end) ns(2:2:end)]; % second column is second triangle\n edge=[edgeh;edges]; % unique edges\n nn=[nh;ns]; % two columns of triangle numbers\n ne=size(edge,1); % number of edges\n \n flag=true(ne,2); % true for each unused edge per triangle\n tmp=zeros(ne+1,1); % contour data temporary storage\n \n xe=x(edge); % x values at vertices of edges\n ye=y(edge); % y values at vertices of edges\n ze=z(edge); % z data at vertices of edges\n\n alpha=(zc-ze(:,1))./(ze(:,2)-ze(:,1)); % interpolate all edges\n xc=alpha.*(xe(:,2)-xe(:,1)) + xe(:,1); % x values on this contour\n yc=alpha.*(ye(:,2)-ye(:,1)) + ye(:,1); % y values on this contour\n\n while any(flag)\t% while there are still unused edges -----------------\n \n xtmp=tmp;\n ytmp=tmp;\n [ir,ic]=find(flag,1); % find next unused edge\n flag(ir,ic)=false; % mark this edge used\n \n k=1; % first data point in subcontour\n xtmp(k)=xc(ir); % store data from this edge\n ytmp(k)=yc(ir);\n \n while true % complete this subcontour ---------------------------\n \n [ir,ic]=find(flag&nn(ir,ic)==nn,1);% find other edge of triangle\n flag(ir,ic)=false; % mark this edge used\n k=k+1;\n xtmp(k)=xc(ir); % store data from this edge\n ytmp(k)=yc(ir);\n \n ic=cs(ic); % other triangle that shares edge\n\n if nn(ir,ic)==0 % reached hull, subcontour complete\n k=k+1;\n xtmp(k)=nan; % don't let subcontour close\n ytmp(k)=nan;\n break\n elseif ~flag(ir,ic) % complete closed subcontour\n break\n else % more points remain on subcontour\n flag(ir,ic)=false; % mark this edge used\n end\n end % while true ----------------------------------------------------\n xtmp(k+1:end)=[]; % throw away unused storage\n ytmp(k+1:end)=[]; % xtmp,ytmp contain subcontour\n \n if nargout<2 % plot the subcontour\n patch('XData',xtmp,'YData',ytmp,'CData',repmat(zc,k,1),...\n 'Parent',hax,'FaceColor','none','EdgeColor','flat',...\n 'UserData',zc)\n C=horzcat(C,[zc xtmp';k ytmp']); % contour label data\n else % plot subcontour and create output\n h=[h;patch('XData',xtmp,'YData',ytmp,'CData',repmat(zc,k,1),...\n 'Parent',hax,'FaceColor','none','EdgeColor','flat',...\n 'UserData',zc)]; %#ok\n C=horzcat(C,[zc xtmp';k ytmp']); % contour label data\n end\n end % while any(flag) --------------------------------------------------\nend % for v=1:nlev\nif nargout\n c=C;\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/38858-contour-plot-for-scattered-data/tricontour.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7320683723779317}} {"text": "function ANew=ellipsCoveringEllipsAndPoint(z,A,p,gammaVal,interiorOpt)\n%%ELLIPSCOVERINGELLIPSEANDPOINT Given an ellipse (or ellipsoid) and a\n% point, find the minimum volume ellipse/ellipsoid that is\n% centered at the center of the original ellipse and that covers\n% the original ellipse and the point.\n%\n%INPUTS: z The numDimX1 center of the ellipsoid.\n% A A numDimXnumDim symmetric, positive definite matrix that\n% specifies the size and shape of the ellipse or ellipsoid, where\n% a point zp is on the ellipse/ellipsoid if\n% (zp-z)'*A*(zp-z)=gammaVal.\n% p A numDimX1 point.\n% gammaVal The threshold for declaring a point to be in the ellipsoid. If\n% this parameter is omitted or an empty matrix is passed, the\n% default value of 1 is used.\n% interiorOpt An optional parameter specifying what should be done if the\n% point p is inside of the ellipsoid. Possible values are\n% 0 (The default if omitted or an empty matrix is passed) The\n% original ellipsoid is returned if the point is inside it.\n% 1 The ellipse that is returned is the maximum volume ellipsoid\n% such that p is on the boundary and the ellipse is entirely\n% contained in the original ellipsoid.\n%\n%OUTPUTS: ANew The numDimXnumDim new positive definite matrix specifying\n% the shape of the minimum volume ellipsoid covering the\n% original ellipsoid and the point.\n%\n%The algorithm is taken from Section 10 of [1]. The basic idea is that\n%first, we divide A by gammaVal so that the equation for the ellipse is\n%(zp-z)'*A*(zp-z)=1. Next, let L be the lower-triangular Cholesky\n%decomposition of A. We then do the transformation y=L'*(zp-z) and in the\n%transformed domain, the ellipse is the unit sphere norm(y)=1. We can then\n%apply the transformation to p to get pTilde=L'*(p-z). We basically now\n%just want to transform p so that it is on the x-axis, and then expand the\n%sphere in that direction minimally to intersect p and then transform back.\n%\n%The sphere in y has an equvalent matrix ATilde=eye(numDiom,numDim). We\n%want to expand it just enough in a single direction to touch pTilde. This\n%is a rank-one modification problem, which is described in a little detail\n%in Sections 4 and 10 of [1].\n%\n%EXAMPLE 1:\n%Here we have an ellipse and a point outside of the ellipse.\n% A=[1,0;\n% 0,10];\n% M=[0.413074198133900, 0.910697373904216;\n% -0.910697373904216, 0.413074198133900];%A rotation matrix\n% A=M*A*M';\n% z=[5;6];\n% p=[6;7];\n% ANew=ellipsCoveringEllipsAndPoint(z,A,p);\n% figure(1)\n% clf\n% hold on \n% drawEllipse(z,A,1,'b','linewidth',2)\n% drawEllipse(z,ANew,1,'m','linewidth',2)\n% scatter(p(1),p(2),'xr','linewidth',2)\n%The new ellipse engulf the original ellipse and the point.\n%\n%EXAMPLE 2:\n%In this instance, we have an ellipse and a point inside the ellipse.\n% A=[1,0;\n% 0,10];\n% M=[0.413074198133900, 0.910697373904216;\n% -0.910697373904216, 0.413074198133900];%A rotation matrix\n% A=M*A*M';\n% z=[5;6];\n% p=[5.2;6];\n% ANew=ellipsCoveringEllipsAndPoint(z,A,p);\n% figure(1)\n% clf\n% hold on \n% drawEllipse(z,A,1,'b','linewidth',2)\n% drawEllipse(z,ANew,1,'m','linewidth',2)\n% scatter(p(1),p(2),'xr','linewidth',2)\n%The new ellipse is the same as the orignal ellipse, because the point is\n%inside the original ellipse.\n%\n%REFERENCES:\n%[1] S. B. Pope, \"Algorithms for ellipsoids,\" Cornell University, Tech.\n% Rep. FDA-08-01, Feb. 2008. [Online].\n% Available: https://tcg.mae.cornell.edu/pubs/Pope_FDA_08.pdf\n%\n%May 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<5||isempty(interiorOpt))\n interiorOpt=0;\nend\n\nif(nargin<4||isempty(gammaVal))\n gammaVal=1; \nend\n\nn=length(z);\n\nA=A/gammaVal;\n\n%Check for the point being inside the ellipse.\ndiff=p-z;\nif(interiorOpt==0&&diff'*A*diff<=1)\n %The point is already inside the ellipse.\n ANew=A;\n return;\nend\n\nL=chol(A,'lower');\n\npTilde=L'*(p-z);%Eq 62.\n\npN=norm(pTilde);\ng=(1/pN-1)*(1/pN^2);\nG=eye(n,n)+g*(pTilde*pTilde');\nANew=L*G*(L*G)'*gammaVal;\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Geometry/ellipsCoveringEllipsAndPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7320683645758603}} {"text": "function [predicted,memberships, numhits] = fknn(data, labels, test, ...\n\t testlabels, k_values, info, fuzzy)\n% FKNN Fuzzy k-nearest neighbor classification algorithm.\n% \tY = FKNN(DATA, LABELS, TEST, TESTLABELS, K, INFO) Runs fuzzy\n% \tk-nearest neighbors on the given data. DATA is a N-by-D data matrix\n% \tconsisting of N patterns each of which is D-dimensional. LABELS is a\n% \tN-vector containing the class labels (1,2,...,C) for each pattern.\n%\tTEST is a M-by-D matrix consisting of M test patterns. TESTLABELS \n%\tis an optional M-vector for the true class labels of the given test\n%\tdata. If you don't have true labels, just give an empty matrix for this\n%\tTESTLABELS.\n%\tK is the number of nearest neighbors to look at. \n%\tThe algorithm will print an information line at every INFO test\n%\tpatterns, if INFO>0. If INFO is zero, nothing will be printed. \n%\tY is a M-vector containing the predicted class labels for the given test\n%\tpatterns.\n%\n% \t[Y,MEMS,HITS] = FKNN(DATA, LABELS, TEST, TESTLABELS, K, INFO) returns\n% \tthe fuzzy class-memberships values in MEMS, for each test pattern. It is\n% \ta M-by-C matrix, C being the number of classes. \n%\tHITS is the number of correctly predicted test patterns. Note that HITS\n%\tis meaningless if TESTLABELS is not provided. \n%\n% \t[Y,MEMS,HITS] = FKNN(DATA, LABELS, TEST, TESTLABELS, K, INFO, FUZZY) If\n% \tyou don't want to do \"fuzzy\" k-nn, then give FUZZY as 'false'.\n%\n%\tThis m-file is capable of testing several k-values simultaneously. If\n%\tyou pass a vector of k-values, rather than a single scalar, in K, then\n%\teach output variable is populated accordingly. So, if you give K as \n%\t[5 10 15], then Y becomes M-by-3, MEMS M-by-C-by-3 and HITS 3-by-1.\n%\n%\tReferences:\n%\tJ. M. Keller, M. R. Gray, and J. A. Givens, Jr.,\n%\t\"A Fuzzy K-Nearest Neighbor Algorithm\",\n%\tIEEE Transactions on Systems, Man, and Cybernetics,\n%\tVol. 15, No. 4, pp. 580-585. \n%\n% TODO: Generalize this m-file to Lp norm\n%\n% Emre Akbas [eakbas2 @ uiuc.edu] Dec 2006.\n%\n\nif nargin<7\n fuzzy = true;\nend\n\nnum_train = size(data,1);\nnum_test = size(test,1);\n\n% scaling factor for fuzzy weights. see [1] for details\nm = 2;\n\n% convert class labels to unary membership vectors (of 1s and 0s)\nmax_class = max(labels);\ntemp = zeros(length(labels),max_class);\nfor i=1:num_train\n temp(i,:) = [zeros(1, labels(i)-1) 1 zeros(1,max_class - labels(i))];\nend\nlabels = temp;\nclear temp;\n\n% allocate space for storing predicted labels \npredicted = zeros(num_test, length(k_values));\n\n% allocate space for 'numhits'. This will only be used if 'testlabels' is\n% provided\nnumhits = zeros(length(k_values),1);\n\n% will the memberships be stored? if yes, allocate space\nstore_memberships = false;\nif nargout > 1,\n store_memberships=true;\n memberships = zeros(num_test, max_class, length(k_values));\nend\n\n%% BEGIN kNN\n% for each test point, do:\nt0=clock;\ntstart = t0;\nfor i=1:num_test\n distances = (repmat(test(i,:), num_train,1) - data).^2;\n % for efficiency, no need to take sqrt since it is a non-decreasing function\n distances = sum(distances,2)';\n\n % sort the distances\n [junk, indeces] = sort(distances);\n\n for k=1:length(k_values)\n\tneighbor_index = indeces(1:k_values(k));\n\tweight = ones(1,length(neighbor_index));\n\tif fuzzy, \n \t % originally, this weight calculation should be: \n \t % weight = distances(neighbor_index).^(-2/(m-1));\n \t % but since we didn't take sqrt above and the inverse 2th power\n \t % the weights are: \n \t % weight = sqrt(distances(neighbor_index)).^(-2/(m-1));\n\t % which is equaliavent to:\n \t weight = distances(neighbor_index).^(-1/(m-1));\n \n \t % set the Inf (infite) weights, if there are any, to 1.\n \t if max(isinf(weight))\n \t\twarning(['Some of the weights are Inf for sample: ' ...\n\t\t\tnum2str(i) '. These weights are set to 1.']);\n \t\tweight(isinf(weight))=1;\n \t end\n\tend\n\ttest_out = weight*labels(neighbor_index,:)/(sum(weight));\n\n\tif store_memberships, memberships(i,:,k) = test_out; end;\n\n\t% find predicted class (the one with the max. fuzzy vote)\n\t[junk, index_of_max] = max(test_out');\n\n\tpredicted(i,k) = index_of_max;\n\n\t% compute current hit rate, if test labels are given\n\tif ~isempty(testlabels) && predicted(i,k)==testlabels(i)\n\t numhits(k) = numhits(k)+1;\n\tend\n end\n\n % print info\n if mod(i,info)==0\n\telapsed = etime(clock, t0);\n\tfprintf(1,['%dth sample done. Elapsed (from previous info): %.2f' ...\n\t ' sn. Estimated left: %.2f sn.\\n\\tHit rate(s) so far: '], ...\n\t i, elapsed, etime(clock, tstart)*((num_test-i)/i) );\n\tfor k=1:length(k_values)\n\t fprintf(1,'%3d: %.3f\\t',k_values(k), 100*numhits(k)/i);\n\tend\n\tfprintf(1,'\\n');\n\n\tt0=clock; % start timer again\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/13358-fuzzy-k-nn/fknn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.7320683572078421}} {"text": "function X=stft(x,wl,olr,window,alpha)\n% STFT Short Time Fourier Transform\n%\n% X = stfth(x,wl,olr,window,alpha) returns the short time Fourier Transform of\n% a signal \"x\" with a window length \"wl\", overlap ratio \"olr\" and window \n% type \"window\". Valid window types are as follows:\n%\n% 'rectwin' - Rectangular Window\n% 'hann' - Hann window\n% 'hamming' - Hamming window\n% 'gausswin' - Gaussian window\n%\n% If a Gaussian window is used, alpha is the reciprocal of the standard \n% deivation of the Gaussian window (if used), as per the GAUSSWIN function\n%\n% Modified by Al-Hafeez Dhalla, PhD. Contact email: hafeez.dhalla@gmail.com\n%\n% Original version produced by Suraj Kamya, available at:\n%\n% www.mathworks.com/matlabcentral/fileexchange/38035-stft-short-time-fourier-transform\n\nif nargin < 5\n alpha = 2.5;\nend\n\nL=length(x);\nif LL % If window size excceds the L of signal for 1st time\n z=len-L;\n x=[x,zeros(1,z)]; % padding zeros\n i=1+1;\n end\n x1=x(str:len);\n X=[X;fft(x1.*win)]; % Matrix mul\n str=str+hop; len=str+wl-1; % to make window overlapping\n end\nend\n\nX = fftshift(X,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/38773-short-time-fourier-transform/stft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.73201183335435}} {"text": "function [L, D] = ldlt_sytr(A)\n%LDLT_SYTR Block LDL^T factorization for a symmetric tridiagonal matrix.\n% [L, D] = LDLT_SYTR(A) factorizes A = L*D*L', where A is\n% Hermitian tridiagonal, L is unit lower triangular, and D is\n% block diagonal with 1x1 and 2x2 diagonal blocks. It uses\n% Bunch's strategy for choosing the pivots.\n\n% References:\n% J. R. Bunch, Partial pivoting strategies for symmetric\n% matrices. SIAM J. Numer. Anal., 11(3):521-528, 1974.\n% N. J. Higham, Accuracy and Stability of Numerical Algorithms,\n% Second edition, Society for Industrial and Applied Mathematics,\n% Philadelphia, PA, 2002; sec. 11.1.4.\n\nn = length(A);\nif norm( tril(A,-2), 1) | norm( triu(A,2), 1) | ~isequal(A,A')\n error('Matrix must be Hermitian tridiagonal.')\nend\n\ns = norm(A(:), inf);\na = (sqrt(5)-1)/2;\nL = eye(n);\nD = zeros(n);\nk = 1;\n\nwhile k < n\n\n if s*abs(A(k,k)) >= a*abs(A(k+1,k))^2\n\n % 1-by-1 pivot.\n D(k,k) = A(k,k);\n L(k+1,k) = A(k+1,k)/A(k,k);\n A(k+1,k+1) = A(k+1,k+1) - abs(A(k+1,k))^2/A(k,k);\n k = k+1;\n\n else\n\n % 2-by-2 pivot.\n E = A(k:k+1,k:k+1);\n D(k:k+1,k:k+1) = E;\n if k+2 <= n\n L(k+2:n,k:k+1) = A(k+2:n,k:k+1)/E;\n A(k+2,k+2) = A(k+2,k+2) - abs(A(k+2,k+1))^2*A(k,k)/det(E);\n end\n k = k+2;\n\n end\n\nend\nif k == n\n D(k,k) = A(k,k);\nend\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/matrixcomp/ldlt_sytr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7320118251269693}} {"text": "%% SIMPLE_ODE113 solves the three body problem using MATLAB's ODE113.\n%\n% Discussion:\n%\n% Three bodies, regarded as point masses, are constrained to lie in a plane.\n% The masses of each body are given, as are the positions and velocities\n% at a starting time T = 0. The bodies move in accordance with the gravitational\n% force between them.\n%\n% The force exerted on the 0-th body by the 1st body can be written:\n%\n% F = - m0 m1 ( p0 - p1 ) / |p0 - p1|^3\n%\n% assuming that units have been normalized to that the gravitational\n% coefficient is 1. Newton's laws of motion can be written:\n%\n% m0 p0'' = - m0 m1 ( p0 - p1 ) / |p0 - p1|^3 \n% - m0 m2 ( p0 - p2 ) / |p0 - p2|^3\n%\n% m1 p1'' = - m1 m0 ( p1 - p0 ) / |p1 - p0|^3 \n% - m1 m2 ( p1 - p2 ) / |p1 - p2|^3\n%\n% m2 p2'' = - m2 m0 ( p2 - p0 ) / |p2 - p0|^3 \n% - m2 m1 ( p2 - p1 ) / |p2 - p1|^3\n%\n% Letting\n%\n% y1 = p0(x)\n% y2 = p0(y)\n% y3 = p0'(x)\n% y4 = p0'(y)\n%\n% and using similar definitions for p1 and p2, the 3 second order vector \n% equations can be rewritten as 12 first order equations. In particular,\n% the first four are:\n%\n% y1' = y3\n% y2' = y4\n% y3' = - m1 ( y1 - y5 ) / |(y1,y2) - (y5,y6) |^3 \n% - m2 ( y1 - y9 ) / |(y1,y2) - (y9,y10)|^3\n% y4' = - m1 ( y2 - y6 ) / |(y1,y2) - (y5,y6) |^3 \n% - m2 ( y2 - y10 ) / |(y1,y2) - (y9,y10)|^3\n%\n% and so on.\n%\n% This first order system can be integrated by a standard ODE solver.\n%\n% Note that when any two bodies come close together, the solution changes\n% very rapidly, and very small steps must be taken by the ODE solver.\n% For this system, the first near collision occurs around T=15.8299, and\n% the results produced by MATLAB's ode113 will not be very accurate after\n% that point.\n%\n% Modified:\n%\n% 03 April 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Dominik Gruntz, Joerg Waldvogel,\n% \"Orbits in the Planar Three-Body Problem\",\n% Walter Gander, Jiri Hrebicek,\n% Solving Problems in Scientific Computing using Maple and Matlab,\n% Springer, 1997,\n% ISBN: 3-540-61793-0,\n% LC: Q183.9.G36.\n%\n addpath ( '../rkf45' );\n\n global m0 m1 m2\n\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SIMPLE_RKF45:\\n' );\n fprintf ( 1, ' A simple formulation of the planar three-body problem.\\n' );\n fprintf ( 1, ' This program uses RKF45 for the ODE solver.\\n' );\n%\n% Set the masses.\n%\n m0 = 5.0;\n m1 = 3.0;\n m2 = 4.0;\n%\n% Set the time range.\n%\n t_start = 0.0;\n t_stop = 63.0;\n step_num = 631;\n%\n% Set input to RKF45.\n%\n neqn = 12;\n y = [ 1.0; -1.0; 0.0; 0.0;\n 1.0; 3.0; 0.0; 0.0;\n -2.0; -1.0; 0.0; 0.0 ];\n yp = simple_f ( t_start, y );\n relerr = 1.0E-10;\n abserr = 1.0E-10;\n flag = 1;\n%\n% Set up the array that stores the data.\n%\n T1 = zeros ( step_num + 1 );\n Y1 = zeros ( step_num + 1, neqn );\n step = 0;\n T1(step+1) = t_start;\n Y1(step+1,1:neqn) = y';\n\n for step = 1 : step_num\n\n t = ( ( step_num - step + 1 ) * t_start ...\n + ( step - 1 ) * t_stop ) ...\n / ( step_num );\n\n t_out = ( ( step_num - step ) * t_start ...\n + ( step ) * t_stop ) ...\n / ( step_num );\n \n [ y, yp, t, flag ] = r8_rkf45 ( @simple_f, neqn, y, yp, t, t_out, ...\n relerr, abserr, flag );\n\n T1(step+1) = t;\n Y1(step+1,1:neqn) = y';\n\n end\n%\n% Display the results.\n%\n figure ( 1 )\n\n [ ~, i10 ] = min ( abs ( T1 - 10.0 ) );\n\n R1 = 1 : i10;\n\n plot ( Y1(R1,1), Y1(R1,2), 'b.', ...\n Y1(R1,5), Y1(R1,6), 'r.', ...\n Y1(R1,9), Y1(R1,10), 'g.' )\n title ( '0 <= T <= 10' )\n\n figure ( 2 )\n\n [ ~, i20 ] = min ( abs ( T1 - 20.0 ) );\n\n R2 = i10 : i20;\n\n plot ( Y1(R2,1), Y1(R2,2), 'b.', ...\n Y1(R2,5), Y1(R2,6), 'r.', ...\n Y1(R2,9), Y1(R2,10), 'g.' )\n title ( '10 <= T <= 20' )\n\n figure ( 3 )\n\n [ ~, i50 ] = min ( abs ( T1 - 50.0 ) );\n i63 = length ( T1 );\n\n R3 = i50 : i63;\n\n plot ( Y1(R3,1), Y1(R3,2), 'b.', ...\n Y1(R3,5), Y1(R3,6), 'r.', ...\n Y1(R3,9), Y1(R3,10), 'g.' )\n title ( '50 <= T <= 63' )\n\n figure ( 4 )\n\n R4 = 1 : i63;\n\n plot ( Y1(R4,1), Y1(R4,2), 'b.', ...\n Y1(R4,5), Y1(R4,6), 'r.', ...\n Y1(R4,9), Y1(R4,10), 'g.' )\n title ( '0 <= T <= 63' )\n\n rmpath ( '../rkf45' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SIMPLE_RKF45:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/three_body_simulation/simple_rkf45.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7319902318050383}} {"text": "function [f cumf] = sumlog2(S)\n% returns log2(sum(2.^S)) in a stable way\n\n% We compute log2(f) using our log-sum method. Precision of this\n% method is approximately 2^(-1024) * (number of summands). So it is\n% much less than eps = 2^(-52).\n%\n% Indeed, we compute (assume A>B)\n% log(A + B) = log A + log (1 + B/A);\n% B/A = 2^{log B - log A}. So we only lose precision when B/A gets below 2^{-1024}.\n% But log (1 + x) <= x. Thus each time we get error less than 2^{-1024}.\n%\n\nconst_log2e = 1/log(2);\nlog_sum = -Inf;\ncumf = zeros(size(S));\nidx = 1;\nfor cur_term = S;\n\tif cur_term > -Inf\n\t\tif cur_term > log_sum\n\t\t\tlog_sum = cur_term + log1p(2^(log_sum - cur_term))*const_log2e;\n\t\telse\n\t\t\tlog_sum = log_sum + log1p(2^(cur_term - log_sum))*const_log2e;\n\t\tend;\n\tend\n\tcumf(idx) = log_sum;\n\tidx = idx + 1;\nend\n\nf = log_sum;\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/bsc/sumlog2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257062, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7319476534977746}} {"text": "function y = nigcdf(x, alpha, beta, mu, delta)\n%NIGCDF Normal-Inverse-Gaussian cumulative distribution function (cdf).\n% Y = NIGCDF(X, ALPHA, BETA, MU, DELTA) returns the cdf of the \n% Normal-Inverse-Gaussian distribution with the parameter BETA which \n% determines the skewness, shape parameter ALPHA, location parameter MU \n% and scale parameter DELTA, evaluated at the values in X.\n% \n% ALPHA, BETA, MU, DELTA must be scalar values.\n% \n% ALPHA and DELTA must be positive values.\n%\n% MU must be a value greater than -inf and smaller than inf.\n%\n% Default values for ALPHA = 1, BETA = 0; MU = 0; DELTA = 1.\n%\n% See also NIGFITC, NIGFITG, NIGFITM, NIGFITP, NIGINV, NIGMM, NIGPAR, \n% NIGPDF, NIGRND, NIGSTAT.\n\n% References:\n% [1] de Beus, P., Bressers, M. and de Graaf, T. (2003) Alternative\n% Investments and Risk Measurement, Appendix 2.\n\n% -------------------------------------------------------------------------\n% \n% risklab germany GmbH\n% Nymphenburger Strasse 112 - 116\n% D-80636 Muenchen\n% Germany\n% Internet: www.risklab.de\n% email: info@risklab.de\n% \n% Implementation Date: 2004 - 10 - 14\n% Author: Dr. Ralf Werner, Michaela Tempes\n% ralf.werner@risklab.de\n% -------------------------------------------------\n\n\n% Default values\nif nargin < 2\n alpha = 1;\nend\nif nargin < 3\n beta = 0;\nend\nif nargin < 4\n mu = 0;\nend\nif nargin < 5\n delta = 1;\nend\n\n% Constraints for the parameters\nif alpha <= 0\n error('ALPHA must be positive.');\nend\nif delta <= 0\n error('DELTA must be positive.');\nend\nif ((mu == -inf) || (mu == inf))\n error('MU muss aus (-inf,inf) sein');\nend\nif abs(beta)>=alpha\n error('|BETA| muss kleiner gleich ALPHA sein');\nend\n\n% approximation of the integral through a summation\nN = 1000; % number of addends\nind = (1:N-1);\nind = 1./ind;\ndummy = N*ind-1;\n\nif size(x, 1) <= 1 % make x a column vector\n x = x';\nend\n\nM = length(x);\n\n% the following is necessary due to limitations in available memory\n% this accelerates computation time\n\nmaxSize = 1000;\nnSteps = ceil(M / maxSize);\nxLarge = x;\ny = [];\n\nfor iSteps = 1:nSteps\n \n xSize = min(length(xLarge), maxSize); \n x = xLarge(1:xSize);\n \n constFact = N*delta/sqrt(2*pi)*exp(delta*sqrt(alpha^2-beta^2));\n firstFact = ind.^2;\n secondFact = dummy.^(-1.5);\n expFact = exp(-1/2*(delta^2./dummy + (alpha^2-beta^2)*dummy));\n\n X = repmat(x, 1, N-1);\n DUMMY = repmat(dummy, xSize, 1);\n normalFact = normcdf(X, mu + beta*DUMMY, sqrt(DUMMY));\n\n y1 = constFact*firstFact.*secondFact.*expFact;\n ySmall = repmat(y1, xSize, 1).*normalFact;\n \n ySmallSum = sum(ySmall, 2);\n y = [y; ySmallSum];\n \n xLarge = xLarge(xSize + 1:end);\n \nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6050-normal-inverse-gaussion-distribution/nigcdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654165937868, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7319476476001514}} {"text": "function current_sensor()\n\n# Opamp gain resistors\nR = 68000.0; # 5400\nr = 1000.0; # 1000\n\n# Opamp input resistor network\nr1 = 665.0; # 660\nr2 = 562.0; # 560\nr3 = 56000.0; # 4700\n\n# Shunt resistance\nshunt = 0.0025;\n\n# Opamp gain\nprintf(\"Opamp gain: \");\nG = (R + r)/r\n\n# Relation between the input signal e and signal v calculation\n\nA = -100.0:1.0:100.0;\nshunt_v = shunt * A;\n\n# k parameter\nk = ( 1/r1 + 1/r2 + 1/r3);\nU = 5.0;\n\n# translation voltage\nprintf(\"Input translate: \");\ntrans = U/(k*r3)\n\nprintf(\"Oputput translate: \");\nout_trans = trans * G\n\n# opamp input\nv = (trans + shunt_v/(k*r1));\n\n# opamp output\nS = v * G;\n\n# maxi/min value\nprintf(\"Max: \");\nmax(S)\nprintf(\"Min: \");\nmin(S)\n\n\nplot(A, shunt_v, \"1\", A, v, \"2\", A, S, \"3\")\nlegend('e', 'v', 'S');\n\n# calculate output voltage for 1A\nshunt_v_1 = shunt * 1;\nv_1 = (trans + shunt_v_1/(k*r1));\n\nprintf(\"Output voltage at 1A\");\nS_1 = v_1 * G\n", "meta": {"author": "open-bldc", "repo": "open-bldc-hardware", "sha": "893f36f76b5f663e171f747ce2cd5f0c01dd3374", "save_path": "github-repos/MATLAB/open-bldc-open-bldc-hardware", "path": "github-repos/MATLAB/open-bldc-open-bldc-hardware/open-bldc-hardware-893f36f76b5f663e171f747ce2cd5f0c01dd3374/clogic/doc/current_sensor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004808, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7319476463274106}} {"text": "% first casadi test for mpc fpr mobile robots\nclear all\nclose all\nclc\n\n% CasADi v3.1.1\naddpath('C:\\Users\\mehre\\OneDrive\\Desktop\\CasADi\\casadi-windows-matlabR2016a-v3.4.5')\nimport casadi.*\n\nT = 0.2; %[s]\nN = 10; % prediction horizon\nrob_diam = 0.3;\n\nv_max = 0.6; v_min = -v_max;\nomega_max = pi/4; omega_min = -omega_max;\n\nx = SX.sym('x'); y = SX.sym('y'); theta = SX.sym('theta');\nstates = [x;y;theta]; n_states = length(states);\n\nv = SX.sym('v'); omega = SX.sym('omega');\ncontrols = [v;omega]; n_controls = length(controls);\nrhs = [v*cos(theta);v*sin(theta);omega]; % system r.h.s\n\nf = Function('f',{states,controls},{rhs}); % nonlinear mapping function f(x,u)\nU = SX.sym('U',n_controls,N); % Decision variables (controls)\nP = SX.sym('P',n_states + n_states);\n% parameters (which include at the initial state of the robot and the reference state)\n\nX = SX.sym('X',n_states,(N+1));\n% A vector that represents the states over the optimization problem.\n\nobj = 0; % Objective function\ng = []; % constraints vector\n\nQ = zeros(3,3); Q(1,1) = 1;Q(2,2) = 5;Q(3,3) = 0.1; % weighing matrices (states)\nR = zeros(2,2); R(1,1) = 0.5; R(2,2) = 0.05; % weighing matrices (controls)\n\nst = X(:,1); % initial state\ng = [g;st-P(1:3)]; % initial condition constraints\nfor k = 1:N\n st = X(:,k); con = U(:,k);\n obj = obj+(st-P(4:6))'*Q*(st-P(4:6)) + con'*R*con; % calculate obj\n st_next = X(:,k+1);\n f_value = f(st,con);\n st_next_euler = st+ (T*f_value);\n g = [g;st_next-st_next_euler]; % compute constraints\nend\n% make the decision variable one column vector\nOPT_variables = [reshape(X,3*(N+1),1);reshape(U,2*N,1)];\n\nnlp_prob = struct('f', obj, 'x', OPT_variables, 'g', g, 'p', P);\n\nopts = struct;\nopts.ipopt.max_iter = 2000;\nopts.ipopt.print_level =0;%0,3\nopts.print_time = 0;\nopts.ipopt.acceptable_tol =1e-8;\nopts.ipopt.acceptable_obj_change_tol = 1e-6;\n\nsolver = nlpsol('solver', 'ipopt', nlp_prob,opts);\n\n\nargs = struct;\n\nargs.lbg(1:3*(N+1)) = 0;\nargs.ubg(1:3*(N+1)) = 0;\n\nargs.lbx(1:3:3*(N+1),1) = -2; %state x lower bound\nargs.ubx(1:3:3*(N+1),1) = 2; %state x upper bound\nargs.lbx(2:3:3*(N+1),1) = -2; %state y lower bound\nargs.ubx(2:3:3*(N+1),1) = 2; %state y upper bound\nargs.lbx(3:3:3*(N+1),1) = -inf; %state theta lower bound\nargs.ubx(3:3:3*(N+1),1) = inf; %state theta upper bound\n\nargs.lbx(3*(N+1)+1:2:3*(N+1)+2*N,1) = v_min; %v lower bound\nargs.ubx(3*(N+1)+1:2:3*(N+1)+2*N,1) = v_max; %v upper bound\nargs.lbx(3*(N+1)+2:2:3*(N+1)+2*N,1) = omega_min; %omega lower bound\nargs.ubx(3*(N+1)+2:2:3*(N+1)+2*N,1) = omega_max; %omega upper bound\n%----------------------------------------------\n% ALL OF THE ABOVE IS JUST A PROBLEM SET UP\n\n\n% THE SIMULATION LOOP SHOULD START FROM HERE\n%-------------------------------------------\nt0 = 0;\nx0 = [0.1 ; 0.1 ; 0.0]; % initial condition.\nxs = [1.5 ; 1.5 ; 0.0]; % Reference posture.\n\nxx(:,1) = x0; % xx contains the history of states\nt(1) = t0;\n\nu0 = zeros(N,2); % two control inputs for each robot\nX0 = repmat(x0,1,N+1)'; % initialization of the states decision variables\n\nsim_tim = 20; % total sampling times\n\n% Start MPC\nmpciter = 0;\nxx1 = [];\nu_cl=[];\n\n% the main simulaton loop... it works as long as the error is greater\n% than 10^-6 and the number of mpc steps is less than its maximum\n% value.\ntic\nwhile(norm((x0-xs),2) > 0.05 && mpciter < sim_tim / T)\n args.p = [x0;xs]; % set the values of the parameters vector\n % initial value of the optimization variables\n args.x0 = [reshape(X0',3*(N+1),1);reshape(u0',2*N,1)];\n sol = solver('x0', args.x0, 'lbx', args.lbx, 'ubx', args.ubx,...\n 'lbg', args.lbg, 'ubg', args.ubg,'p',args.p);\n u = reshape(full(sol.x(3*(N+1)+1:end))',2,N)'; % get controls only from the solution\n xx1(:,1:3,mpciter+1)= reshape(full(sol.x(1:3*(N+1)))',3,N+1)'; % get solution TRAJECTORY\n u_cl= [u_cl ; u(1,:)];\n t(mpciter+1) = t0;\n % Apply the control and shift the solution\n [t0, x0, u0] = shift(T, t0, x0, u,f);\n xx(:,mpciter+2) = x0;\n X0 = reshape(full(sol.x(1:3*(N+1)))',3,N+1)'; % get solution TRAJECTORY\n % Shift trajectory to initialize the next step\n X0 = [X0(2:end,:);X0(end,:)];\n mpciter\n mpciter = mpciter + 1;\nend;\ntoc\n\nss_error = norm((x0-xs),2)\n%Draw_MPC_point_stabilization_v1 (t,xx,xx1,u_cl,xs,N,rob_diam)\n%-----------------------------------------\n%-----------------------------------------\n%-----------------------------------------\n% Start MHE implementation from here\n%-----------------------------------------\n%-----------------------------------------\n%-----------------------------------------\n% plot the ground truth\nfigure(1)\nsubplot(311)\nplot(t,xx(1,1:end-1),'b','linewidth',1.5); axis([0 t(end) 0 1.8]);hold on\nylabel('x (m)')\ngrid on\nsubplot(312)\nplot(t,xx(2,1:end-1),'b','linewidth',1.5); axis([0 t(end) 0 1.8]);hold on\nylabel('y (m)')\ngrid on\nsubplot(313)\nplot(t,xx(3,1:end-1),'b','linewidth',1.5); axis([0 t(end) -pi/4 pi/2]);hold on\nxlabel('time (seconds)')\nylabel('\\theta (rad)')\ngrid on\n\n% Synthesize the measurments\ncon_cov = diag([0.005 deg2rad(2)]).^2;\nmeas_cov = diag([0.1 deg2rad(2)]).^2;\n\nr = [];\nalpha = [];\nfor k = 1: length(xx(1,:))-1\n r = [r; sqrt(xx(1,k)^2+xx(2,k)^2) + sqrt(meas_cov(1,1))*randn(1)];\n alpha = [alpha; atan(xx(2,k)/xx(1,k)) + sqrt(meas_cov(2,2))*randn(1)];\nend\ny_measurements = [ r , alpha ];\n\n% Plot the cartesian coordinates from the measurements used\nfigure(1)\nsubplot(311)\nplot(t,r.*cos(alpha),'r','linewidth',1.5); hold on\ngrid on\nlegend('Ground Truth','Measurement')\nsubplot(312)\nplot(t,r.*sin(alpha),'r','linewidth',1.5); hold on\ngrid on\n\n% plot the ground truth mesurements VS the noisy measurements\nfigure(2)\nsubplot(211)\nplot(t,sqrt(xx(1,1:end-1).^2+xx(2,1:end-1).^2),'b','linewidth',1.5); hold on\nplot(t,r,'r','linewidth',1.5); axis([0 t(end) -0.2 3]); hold on\nylabel('Range: [ r (m) ]')\ngrid on\nlegend('Ground Truth','Measurement')\nsubplot(212)\nplot(t,atan(xx(2,1:end-1)./xx(1,1:end-1)),'b','linewidth',1.5); hold on\nplot(t,alpha,'r','linewidth',1.5); axis([0 t(end) 0.2 1]); hold on\nylabel('Bearing: [ \\alpha (rad) ]')\ngrid on\n\n% The following two matrices contain what we know about the system, i.e.\n% the nominal control actions applied (measured) and the range and bearing\n% measurements.\n%-------------------------------------------------------------------------\nu_cl;\ny_measurements;\n\n% Let's now formulate our MHE problem\n%------------------------------------\nT = 0.2; %[s]\nN_MHE = 6; % prediction horizon\n\nv_max = 0.6; v_min = -v_max;\nomega_max = pi/4; omega_min = -omega_max;\n\nx = SX.sym('x'); y = SX.sym('y'); theta = SX.sym('theta');\nstates = [x;y;theta]; n_states = length(states);\nv = SX.sym('v'); omega = SX.sym('omega');\ncontrols = [v;omega]; n_controls = length(controls);\nrhs = [v*cos(theta);v*sin(theta);omega]; % system r.h.s\nf = Function('f',{states,controls},{rhs}); % MOTION MODEL\n\nr = SX.sym('r'); alpha = SX.sym('alpha'); % range and bearing\nmeasurement_rhs = [sqrt(x^2+y^2); atan(y/x)];\nh = Function('h',{states},{measurement_rhs}); % MEASUREMENT MODEL\n%y_tilde = [r;alpha];\n\n% Decision variables\nU = SX.sym('U',n_controls,N_MHE); %(controls)\nX = SX.sym('X',n_states,(N_MHE+1)); %(states) [remember multiple shooting]\n\nP = SX.sym('P', 2 , N_MHE + (N_MHE+1));\n% parameters (include r and alpha measurements as well as controls measurements)\n\nV = inv(sqrt(meas_cov)); % weighing matrices (output) y_tilde - y\nW = inv(sqrt(con_cov)); % weighing matrices (input) u_tilde - u\n\nobj = 0; % Objective function\ng = []; % constraints vector\nfor k = 1:N_MHE+1\n st = X(:,k);\n h_x = h(st);\n y_tilde = P(:,k);\n obj = obj+ (y_tilde-h_x)' * V * (y_tilde-h_x); % calculate obj\nend\n\nfor k = 1:N_MHE\n con = U(:,k);\n u_tilde = P(:,N_MHE+ k);\n obj = obj+ (u_tilde-con)' * W * (u_tilde-con); % calculate obj\nend\n\n% multiple shooting constraints\nfor k = 1:N_MHE\n st = X(:,k); con = U(:,k);\n st_next = X(:,k+1);\n f_value = f(st,con);\n st_next_euler = st+ (T*f_value);\n g = [g;st_next-st_next_euler]; % compute constraints\nend\n\n\n% make the decision variable one column vector\nOPT_variables = [reshape(X,3*(N_MHE+1),1);reshape(U,2*N_MHE,1)];\n\nnlp_mhe = struct('f', obj, 'x', OPT_variables, 'g', g, 'p', P);\n\nopts = struct;\nopts.ipopt.max_iter = 2000;\nopts.ipopt.print_level =0;%0,3\nopts.print_time = 0;\nopts.ipopt.acceptable_tol =1e-8;\nopts.ipopt.acceptable_obj_change_tol = 1e-6;\n\nsolver = nlpsol('solver', 'ipopt', nlp_mhe,opts);\n\n\nargs = struct;\n\nargs.lbg(1:3*(N_MHE)) = 0;\nargs.ubg(1:3*(N_MHE)) = 0;\n\nargs.lbx(1:3:3*(N_MHE+1),1) = -2; %state x lower bound\nargs.ubx(1:3:3*(N_MHE+1),1) = 2; %state x upper bound\nargs.lbx(2:3:3*(N_MHE+1),1) = -2; %state y lower bound\nargs.ubx(2:3:3*(N_MHE+1),1) = 2; %state y upper bound\nargs.lbx(3:3:3*(N_MHE+1),1) = -pi/2; %state theta lower bound\nargs.ubx(3:3:3*(N_MHE+1),1) = pi/2; %state theta upper bound\n\nargs.lbx(3*(N_MHE+1)+1:2:3*(N_MHE+1)+2*N_MHE,1) = v_min; %v lower bound\nargs.ubx(3*(N_MHE+1)+1:2:3*(N_MHE+1)+2*N_MHE,1) = v_max; %v upper bound\nargs.lbx(3*(N_MHE+1)+2:2:3*(N_MHE+1)+2*N_MHE,1) = omega_min; %omega lower bound\nargs.ubx(3*(N_MHE+1)+2:2:3*(N_MHE+1)+2*N_MHE,1) = omega_max; %omega upper bound\n%----------------------------------------------\n% ALL OF THE ABOVE IS JUST A PROBLEM SET UP\n\n% MHE Simulation loop starts here\n%------------------------------------------\nX_estimate = []; % X_estimate contains the MHE estimate of the states\nU_estimate = []; % U_estimate contains the MHE estimate of the controls\n\nU0 = zeros(N_MHE,2); % two control inputs for each robot\nX0 = zeros(N_MHE+1,3); % initialization of the states decision variables\n\n% Start MHE\nmheiter = 0;\n\nU0 = u_cl(1:N_MHE,:); % initialize the control actions by the measured\n% initialize the states from the measured range and bearing\nX0(:,1:2) = [y_measurements(1:N_MHE+1,1).*cos(y_measurements(1:N_MHE+1,2)),...\n y_measurements(1:N_MHE+1,1).*sin(y_measurements(1:N_MHE+1,2))];\n\ntic\nfor k = 1: size(y_measurements,1) - (N_MHE)\n mheiter = k\n % Get the measurements window and put it as parameters in p\n args.p = [y_measurements(k:k+N_MHE,:)',u_cl(k:k+N_MHE-1,:)'];\n % initial value of the optimization variables\n args.x0 = [reshape(X0',3*(N_MHE+1),1);reshape(U0',2*N_MHE,1)];\n sol = solver('x0', args.x0, 'lbx', args.lbx, 'ubx', args.ubx,...\n 'lbg', args.lbg, 'ubg', args.ubg,'p',args.p);\n U_sol = reshape(full(sol.x(3*(N_MHE+1)+1:end))',2,N_MHE)'; % get controls only from the solution\n X_sol = reshape(full(sol.x(1:3*(N_MHE+1)))',3,N_MHE+1)'; % get solution TRAJECTORY\n X_estimate = [X_estimate;X_sol(N_MHE+1,:)];\n U_estimate = [U_estimate;U_sol(N_MHE,:)];\n \n % Shift trajectory to initialize the next step\n X0 = [X_sol(2:end,:);X_sol(end,:)];\n U0 = [U_sol(2:end,:);U_sol(end,:)];\nend;\ntoc\n\nfigure(1)\nsubplot(311)\nplot(t(N_MHE+1:end),X_estimate(:,1),'g','linewidth',1.5); hold on\nlegend('Ground Truth','Measurement','MHE')\n\nsubplot(312)\nplot(t(N_MHE+1:end),X_estimate(:,2),'g','linewidth',1.5); axis([0 t(end) 0 1.8]);hold on\n\nsubplot(313)\nplot(t(N_MHE+1:end),X_estimate(:,3),'g','linewidth',1.5); axis([0 t(end) -pi/4 pi/2]);hold on\n\n\n", "meta": {"author": "MMehrez", "repo": "MPC-and-MHE-implementation-in-MATLAB-using-Casadi", "sha": "8937ba42c932e1935bcf394e0566bcf981bc6d33", "save_path": "github-repos/MATLAB/MMehrez-MPC-and-MHE-implementation-in-MATLAB-using-Casadi", "path": "github-repos/MATLAB/MMehrez-MPC-and-MHE-implementation-in-MATLAB-using-Casadi/MPC-and-MHE-implementation-in-MATLAB-using-Casadi-8937ba42c932e1935bcf394e0566bcf981bc6d33/workshop_github/Codes_casadi_v3_4_5/MHE_code/MHE_Robot_PS_mul_shooting_v2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541577509315, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.731947636378524}} {"text": "function result = ball_unit_14_3d ( func )\n\n%*****************************************************************************80\n%\n%% BALL_UNIT_14_3D approximates an integral inside the unit ball in 3D.\n%\n% Integration region:\n%\n% Points (X,Y,Z) such that:\n%\n% X**2 + Y**2 + Z**2 <= 1.\n%\n% Discussion:\n%\n% A 288 point 14-th degree formula is used, Stroud number S3:14-1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 25 November 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(X,Y,Z), of the form\n% function value = func ( x, y, z )\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n r = [ 0.968160240E+00, 0.836031107E+00, 0.613371433E+00, 0.324253423E+00 ];\n weight = [ 0.076181268E+00, 0.126263673E+00, 0.098048133E+00, 0.032840260E+00 ];\n xtab = [ ...\n -0.151108275E+00, 0.315838353E+00, 0.346307112E+00, ...\n -0.101808787E+00, -0.409228403E+00 ];\n ytab = [ ...\n 0.155240600E+00, 0.257049387E+00, 0.666277790E+00, ...\n 0.817386065E+00, 0.501547712E+00 ];\n ztab = [ ...\n 0.976251323E+00, 0.913330032E+00, 0.660412970E+00, ...\n 0.567022920E+00, 0.762221757E+00 ];\n\n quad = 0.0;\n\n for m = 1 : 4\n\n w1 = 125.0 * weight(m) / 3360.0;\n x = 0.525731112 * r(m);\n y = 0.850650808 * r(m);\n z = 0.0;\n\n for j = 1 : 2\n x = -x;\n for k = 1 : 2\n y = -y;\n for l = 1 : 3\n [ x, y, z ] = r8_swap3 ( x, y, z );\n quad = quad + w1 * feval ( func, x, y, z );\n end\n end\n end\n\n w2 = 143.0 * weight(m) / 3360.0;\n\n for n = 1 : 5\n\n x = xtab(n) * r(m);\n y = ytab(n) * r(m);\n z = ztab(n) * r(m);\n\n for i = 1 : 3\n\n temp = x;\n x = z;\n z = -y;\n y = -temp;\n\n for j = 1 : 3\n\n [ x, y, z ] = r8_swap3 ( x, y, z );\n\n quad = quad + w2 * feval ( func, x, y, z );\n\n end\n\n y = -y;\n z = -z;\n quad = quad + w2 * feval ( func, x, y, z );\n\n end\n\n end\n\n end\n\n volume = ball_unit_volume_3d ( );\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_unit_14_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7318356694184505}} {"text": "function theta = homogeneous_to_full_GLG( L, mu, sigma, alpha, beta, kappa )\n\n% Compute full parameter set from parameters from INLA\n% The homogeneus GLG model used in INLA only contains five parameters; this\n% function computes the remaining parameters in the 'full' GLG model.\n%\n% Syntax:\n% theta = homogeneus_to_full_GLG( L, mu, sigma, alpha, beta, kappa )\n%\n% Input:\n% L : The number of levels in the transform\n%\n% mu : Mean of root node\n%\n% sigma : Standard dev of root node\n%\n% alpha : Intercept of transitions\n%\n% beta : Slope of transitions\n%\n% kappa : Standard dev of transitions\n%\n% The dimension of the parameters determines the number of dimensions.\n% If a parameters is empty, a value is picked at random.\n%\n%\n% Output:\n% theta : A matrix with the full parameter set\n\n\n% ----------------------------------------------------------------------\n% Fill in empty parameters\n% ----------------------------------------------------------------------\n\nif nargin == 1\n [mu, sigma, alpha, beta, kappa] = deal( [] );\nend\n\nparameters = {mu, sigma, alpha, beta, kappa};\ndims = cellfun(@numel, parameters);\n\nmissing_vals = cellfun(@isempty, parameters);\n\n% The default number of dimensions is 3\nif all(missing_vals)\n D = 3;\nelse\n D = dims( find(dims, 1) );\nend\n\n% Simulate missing values\nfor j = find(missing_vals)\n switch j\n case {1, 3}\n parameters{j} = -1 + 2*rand(D, 1);\n \n case {2, 4, 5}\n parameters{j} = rand(D, 1);\n end\nend\n\n[mu, sigma, alpha, beta, kappa] = deal( parameters{:} );\n\n\n% ----------------------------------------------------------------------\n% Compute full theta\n% ----------------------------------------------------------------------\n\ntheta = zeros(L, 5, D);\n\ntheta(1, 1, :) = mu;\ntheta(1, 2, :) = sigma;\n\n% All alpha's, beta's and kappa's are the same\ntheta(2:end, 3, :) = repmat( reshape(alpha, [1 1 D]), [L-1 1 1] );\ntheta(2:end, 4, :) = repmat( reshape(beta, [1 1 D]), [L-1 1 1] );\ntheta(2:end, 5, :) = repmat( reshape(kappa, [1 1 D]), [L-1 1 1] );\n\n% Compute remaining mu's and sigma's\nfor l = 2:L\n for d = 1:D\n if beta(d) == 1\n theta(l,1,d) = alpha(d)*(l-1) + mu(d);\n \n sigma2 = kappa(d)^2*l + sigma(d)^2;\n theta(l,2,d) = sqrt( sigma2 );\n else\n theta(l,1,d) = alpha(d)*(beta(d)^(l-1)-1)/(beta(d)-1) + beta(d)^(l-1)*mu(d);\n \n sigma2 = kappa(d)^2*(beta(d)^(2*(l-1))-1)/(beta(d)^2-1) + beta(d)^(2*(l-1))*sigma(d)^2;\n theta(l,2,d) = sqrt( sigma2 );\n end\n end\nend\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/43417-gaussian-log-gaussian-modelling-of-wavelets/INLA/homogeneous_to_full_GLG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7318356644979227}} {"text": "function result=qn(x)\n\n%QN is a scale estimator which does not require an auxiliary location estimate.\n% Essentially it is the first quartile of all pairwise distances between\n% two data points. Its definition is given by \n% qn(x)= c_n 2.2219{|x_i - x_j|; i\n u = randn(dimensions_vec);% BM: replacing randn(m, n);\n u = u / norm(u(:), 'fro');% BM: replacing u / norm(u, 'fro');\n end\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(x) zeros(dimensions_vec);% BM: replacing zeros(m, n);\n \n M.transp = @(x1, x2, d) d;\n \n M.pairmean = @(x1, x2) .5*(x1+x2); % BM: okay.\n \n M.vec = @(x, u_mat) u_mat(:); % BM: okay.\n M.mat = @(x, u_vec) reshape(u_vec, dimensions_vec);% BM: replacing reshape(u_vec, [m, n]);\n M.vecmatareisometries = @() true;\n\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/manopt/manifolds/euclidean/euclideanfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7317056243658212}} {"text": "function B = Bspline(t,k,u,v,ForceSup)\n% :Usage:\n% ::\n%\n% Bspline(t,k,u[,v])\n%\n% Create B-Spline basis of order k, with knots u, evaluated at t.\n% If control verticies v are specified then then B is the spline\n% function instead of the basis.\n%\n% u must be at least length(k)+1 \n%\n% ..\n% $Id: Bspline.m,v 1.3 1998/11/09 00:55:06 nicholst Exp $\n% ..\n\nglobal iB\n\nif (nargin<3)\n help Bspline\n return\nend\n\nif (k+1>length(u))\n error('u must be at least length k+1')\nend\n\n% Silent flag for forcing the support to be defined between u(k)\n% and u(end-k+1)\nif (nargin<5)\n ForceSup = 1;\nend\n\nif ((nargin>3) & (length(v)+k ~= length(u)) & (ForceSup))\n error(sprintf('%d knots requires %d control verticies', ...\n\tlength(u), length(u)-k))\nend\n\n% columnize\nt=t(:);\nu=u(:);\n\nnBasis = length(u)-k;\nB = zeros(length(t),nBasis);\niB = zeros(1,nBasis);\n\nfor i=1:nBasis\n B(:,i) = recu(t,i,k,u);\n iB(i) = (u(i+k)-u(i))/k;\nend\n\n% zero outside of valid range, if there's enough\nif (length(u)>=2*k)\n if (ForceSup)\n B(t3)\n B = B*v(:);\nend\n\n\nreturn\n\n\nfunction B = recu(t,i,k,u)\n\nif (k==1)\n\n if (u(i)==u(i+1))\n B = zeros(size(t));\n else\n B = (u(i)<=t) & (t.\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/DetectionMatching/zncc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7315734916089957}} {"text": "function J=vl_imwhiten(I,alpha,cutoff)\n% VL_IMWHITEN Whiten image\n% J = VL_IMWHITEN(I,ALPHA) approximatively whitens the power spectrum\n% of the natural image I. The algorithm assumes that the modulus of\n% the spectrum decays as 1/f^ALPHA (f is the frequency).\n%\n% VL_IMWHITEN(I) uses ALPHA=1 (a typical value for natural images).\n%\n% VL_IMWHITEN(I,ALPHA,CUTOFF) also applies a low-pass filter with\n% cutoff frequency equal to CUTOFF x FN, where FN is the Nyquist\n% frequency (half of the sampling frequency).\n%\n% See also: VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\nif ~exist('alpha'), alpha = 1 ; end\nif ~exist('cutoff'), cutoff = [] ; end\n\n[M,N]=size(I) ;\n\n% Frequency domain\nfn = 0.5 ; % Nyquist freq (=1/2T, T=1)\nfx_range=linspace(-fn, fn, N) ;\nfy_range=linspace(-fn, fn, M) ;\n[fx fy]=meshgrid(fx_range, fy_range) ;\n\n% Whitening filter\nrho=sqrt(fx.*fx+fy.*fy);\nfilt=rho.^alpha ;\n\n% Low-pass filter\nif ~isempty(cutoff)\n fcut = cutoff * fn ;\n filt = filt .* exp(-(rho/fcut).^4);\n %filt = filt .* exp( - 0.5 * (rho / fcut) .^ 2);\nend\n\n% Apply filter\nJ = real(ifft2(fft2(I).*fftshift(filt))) ;\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/dependencies/vlfeat-0.9.16/toolbox/imop/vl_imwhiten.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7315734850908503}} {"text": "function [ n_data, mu, sigma, a, b, x, fx ] = ...\n truncated_normal_ab_pdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% TRUNCATED_NORMAL_AB_PDF_VALUES: values of the Truncated Normal AB PDF.\n%\n% Discussion:\n%\n% The Normal distribution, with mean Mu and standard deviation Sigma,\n% is truncated to the interval [A,B].\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% 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 A, B, the lower and upper truncation limits.\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 a_vec = [ ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0 ];\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.01543301171801836, ...\n 0.01588394472270638, ...\n 0.01624375997031919, ...\n 0.01650575046469259, ...\n 0.01666496869385951, ...\n 0.01671838200940538, ...\n 0.01666496869385951, ...\n 0.01650575046469259, ...\n 0.01624375997031919, ...\n 0.01588394472270638, ...\n 0.01543301171801836 ];\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 a = 0.0;\n b = 0.0;\n mu = 0.0;\n sigma = 0.0;\n x = 0.0;\n fx = 0.0;\n else\n a = a_vec(n_data);\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_ab_pdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7315570255378415}} {"text": "% Solution_Curve_ODE.\n% Copyright Springer 2013. Stephen Lynch.\n% See Figure 1.2.\ndeqn=@(t,c) .00713*(4-c)^2*(1-c/2);\n[t,ca]=ode45(deqn,[0 400],0);\nplot(t,ca(:,1));\naxis([0 400 0 3]);\nfsize=15;\nset(gca,'xtick',0:100:400,'FontSize',fsize);\nset(gca,'ytick',0:1:3,'FontSize',fsize);\nxlabel('t','FontSize',fsize);\nylabel('c(t)','FontSize',fsize);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/32919-applications-of-chaos-and-nonlinear-dynamics-in-engineering-vol-1/Solution_Curve_ODE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7315222608903648}} {"text": "function [lo, hi] = afb2D_A(x, af, d)\n\n% 2D Analysis Filter Bank\n% (along one dimension only)\n%\n% [lo, hi] = afb2D_A(x, af, d);\n% INPUT:\n% x - NxM matrix, where min(N,M) > 2*length(filter)\n% (N, M are even)\n% af - analysis filter for the columns\n% af(:, 1) - lowpass filter\n% af(:, 2) - highpass filter\n% d - dimension of filtering (d = 1 or 2)\n% OUTPUT:\n% lo, hi - lowpass, highpass subbands\n%\n% % Example\n% x = rand(32,64);\n% [af, sf] = farras;\n% [lo, hi] = afb2D_A(x, af, 1);\n% y = sfb2D_A(lo, hi, sf, 1);\n% err = x - y;\n% max(max(abs(err)))\n\nlpf = af(:, 1); % lowpass filter\nhpf = af(:, 2); % highpass filter\n\nif d == 2\n x = x';\nend\n\nN = size(x,1);\nL = size(af,1)/2;\nx = cshift2D(x,-L);\n\nlo = upfirdn(x, lpf, 1, 2);\nlo(1:L, :) = lo(1:L, :) + lo([1:L]+N/2, :);\nlo = lo(1:N/2, :);\n\nhi = upfirdn(x, hpf, 1, 2);\nhi(1:L, :) = hi(1:L, :) + hi([1:L]+N/2, :);\nhi = hi(1:N/2, :);\n\nif d == 2\n lo = lo';\n hi = hi';\nend\n\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_Proximal/Denoising/WaveletFunctions/afb2D_A.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7315222600804988}} {"text": "\nfunction fvsolver(N, method) \n% N = number of grid points\n\n% grid spacing on interval (-1,1)\ndx = 2./N; \n\n% location of cell centers \nx = linspace(-1+0.5*dx, 1-0.5*dx, N);\n\n% advection speed\nu = 1;\n\n% cfl condition + safety margin\ndt = 0.2*dx;\n\n% final time \nFinalTime = 2;\nNsteps = ceil(FinalTime/dt);\ndt = FinalTime/Nsteps;\n\n% initial condition\nq = fvexact(x); % q = 1*(abs(x)<=0.25);\n\n% time step\nfor n=1:Nsteps\n \n qp1 = [q(2:N),q(1)]; % q_{m+1}\n qm1 = [q(N),q(1:N-1)]; % q_{m-1}\n\n % compute slopes s_m based on limiter choice\n \n if(strcmp(method,'minmod'))\n s = minmod((q-qm1)/dx, (qp1-q)/dx);\n elseif(strcmp(method,'MC'))\n s = minmod( (qp1-qm1)/(2*dx), minmod(2*(q-qm1)/dx, 2*(qp1-q)/dx));\n elseif(strcmp(method,'Fromm'))\n s = (qp1-qm1)/(2*dx);\n elseif(strcmp(method,'BeamWarming'))\n s = (q-qm1)/(dx); % upwind\n elseif(strcmp(method,'LaxWendroff'))\n s = (qp1-q)/(dx); % downwind\n else\n s = zeros(size(q));\n end\n \n sm1 = [s(N),s(1:N-1)]; % s_{m-1}\n \n % update cell averages\n q = q - (u*dt/dx)*(q-qm1) - 0.5*(u*dt/dx)*(dx-u*dt)*(s-sm1); \n\n if(mod(n,40)==0)\n plot(x,q, '.'); pause(0.02);\n end\nend\n\nplot(x, q, 'b.'); \n% have gone one exact period\nhold on; plot(x, fvexact(x), 'r-'); hold off;\nxlabel('x'); \nlegend(sprintf('%s N=%d T=%f', method, N, FinalTime), 'Exact solution')\naxis([-1 1 -.5 1.5])", "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/fvsolver.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171238, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7315222570769052}} {"text": "function [r,xy,v,zp,dfe] = weighted_reg_old2(y,w,varz)\n% Calculate weighted average using weighted linear least squares\n%\n% :Model:\n%\n% z_i = 1*zpop + noise\n%\n% :Inputs:\n%\n% **Y:**\n% data matrix (nsub x T)\n%\n% **w:**\n% weights\n%\n% **varz:**\n% variance of data at each time point (nsub x T)\n%\n% :Outputs:\n%\n% **r:**\n% weighted correlation coeff across columns of y\n%\n% **xy:**\n% weighted covariance matrix\n%\n% **v:**\n% weighted variance estimates for each column of y\n%\n% **zp:**\n% weighted mean of each column of y\n%\n\n[m,n] = size(y);\n\n% computation stuff\ninvxwx = inv(X'*W*X);\npxw = invxwx * X' * W;\n\n\nW = diag(w); % Weight matrix\n\nX = repmat(1,m,1); % Design matrix - 1 column of all ones to calculate average \n\n\n\nzp = px*y; % weighted population mean\n\n\n\ne = y - repmat(zp,m,1); % residuals\n\n\n\ndfe_v = zeros(n,1); \n\nR = eye(m) - X*px; % residual inducing matrix\n\n\n\n% Calculate effective degrees of freedom\n\n\n\nfor i=1:n,\n\n\n\n V = diag(varz(:,i));\n\n dfe_v(i) = (trace(R*V)^2)/trace(R*V*R*V); % Satherwaite approximation\n\n \n\nend;\n\n\n\ndfe = mean(dfe_v); % Calculate average df over all time points. \n\n\n\n\n\nMSE = (e'*W*e)/dfe; % Mean square error\n\n\n\nxy = inv(X'*W*X)*MSE; % Covariance matrix for zp;\n\nxy = 0.5*(xy+xy'); % Remove rounding error\n\n\n\nv = diag(xy); % Variance for zp\n\nr = xy./sqrt(v*v'); % Correlation matrix for zp\n\n\n\n\n\nreturn\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/hewma_utility/weighted_reg_old2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7315222516437143}} {"text": "function [ stack, W_t ] = initialize_weights( eI )\n%INITIALIZE_WEIGHTS Random weight structures for a network architecture\n% eI describes an RNN via the fields layerSizes, inputDim and\n% temporalLayer\n% \n% This uses Xavier's weight initialization tricks for better backprop\n% See: X. Glorot, Y. Bengio. Understanding the difficulty of training \n% deep feedforward neural networks. AISTATS 2010.\n\n%% initialize hidden layers\nstack = cell(1, numel(eI.layerSizes));\nfor l = 1 : numel(eI.layerSizes)\n if l > 1\n prevSize = eI.layerSizes(l-1);\n else\n prevSize = eI.inputDim;\n end;\n curSize = eI.layerSizes(l);\n % Xaxier's scaling factor\n s = sqrt(6) / sqrt(prevSize + curSize);\n % Ilya suggests smaller scaling for recurrent layer\n if l == eI.temporalLayer\n s = sqrt(6) / sqrt(prevSize + 2*curSize);\n end;\n stack{l}.W = rand(curSize, prevSize)*2*s - s;\n stack{l}.b = zeros(curSize, 1);\nend\n%% weight tying\n% default weight tying to false\nif ~isfield(eI, 'tieWeights')\n eI.tieWeights = 0;\nend;\n% overwrite decoder layers for tied weights\nif eI.tieWeights\n decList = [(numel(eI.layerSizes)/2)+1 : numel(eI.layerSizes)-1];\n for l = 1:numel(decList)\n lDec = decList(l); \n lEnc = decList(1) - l;\n assert( norm(size(stack{lEnc}.W') - size(stack{lDec}.W)) == 0, ...\n 'Layersizes dont match for tied weights');\n stack{lDec}.W = stack{lEnc}.W';\n end;\nend;\n%% initialize temporal weights if they should exist\nW_t = [];\nif eI.temporalLayer \n % assuems temporal init type set\n if strcmpi(eI.temporalInit, 'zero')\n W_t = zeros(eI.layerSizes(eI.temporalLayer));\n elseif strcmpi(eI.temporalInit, 'rand')\n % Ilya's modification to Xavier's update rule\n s = sqrt(6) / sqrt(3*eI.layerSizes(eI.temporalLayer));\n W_t = rand(eI.layerSizes(eI.temporalLayer))*2*s - s;\n elseif strcmpi(eI.temporalInit, 'eye')\n W_t = eye(eI.layerSizes(eI.temporalLayer));\n else\n error('unrecognized temporal initialization: %s', eI.temporalInit);\n end; \nend;\n%% init short circuit connections\n% default short circuits to false\nif ~isfield(eI, 'shortCircuit')\n eI.shortCircuit = 0;\nend;\nif eI.shortCircuit\n %padSize = (eI.winSize-1) / 2;\n %stack{end}.W_ss = [zeros(eI.featDim, padSize*eI.featDim), eye(eI.featDim),...\n % zeros(eI.featDim, padSize*eI.featDim)];\n % use random init since input might contain noise estimate\n s = sqrt(6) / sqrt(eI.inputDim + eI.layerSizes(end));\n stack{end}.W_ss = rand(eI.inputDim, eI.layerSizes(end))*2*s - s;\nend;\n \n\n\n", "meta": {"author": "amaas", "repo": "rnn-speech-denoising", "sha": "55edd5bc4719f9747e390b9d57240aa5828c55d3", "save_path": "github-repos/MATLAB/amaas-rnn-speech-denoising", "path": "github-repos/MATLAB/amaas-rnn-speech-denoising/rnn-speech-denoising-55edd5bc4719f9747e390b9d57240aa5828c55d3/initialize_weights.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7315222485221858}} {"text": "function op = smooth_logLLogistic(y)\n% SMOOTH_LOGLLOGISTIC Log-likelihood function of a logistic: sum_i( y_i mu_i - log( 1+exp(mu_i) ) )\n% OP = SMOOTH_LOGLLOGISTIC( Y )\n% returns a function that computes the log-likelihood function\n% in a standard logistic regression model with independent entries. There\n% are two classes y_i = 0 and y_i = 1 with \n% \n% prob(y_i = 1) = exp(mu_i)/(1 + exp(mu_i)\n% \n% so that the log-likelihood is given by \n%\n% log-likelihood(mu) = sum_i ( y_i mu_i - log(1+ exp(mu_i)) ) \n%\n% where mu is the parameter of the distribution (this is unknown,\n% so it is the variable), and Y is a vector of observations.\n\nerror(nargchk(1,1,nargin));\nop = tfocs_smooth( @smooth_logLlogistic_impl);\n\nfunction [ v, g ] = smooth_logLlogistic_impl( mu )\n\n if length(mu) == 1, \n mu = mu * ones(size(y));\n elseif size(mu) ~= size(y),\n error('Parameters and data must be of the same size'),\n end\n \n aux = 1 + exp(-abs(mu));\n v = tfocs_dot(y-1,mu.*(mu > 0)) ...\n + tfocs_dot(y,mu.*(mu < 0)) ...\n - tfocs_dot(ones(size(y)), log(aux));\n if nargout > 1,\n g = y - ((mu > 0) + (mu <= 0).*exp(mu))./aux;\n end\nend\n\nend\n \n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/smooth_logLLogistic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.7315222477712875}} {"text": "function [y,coef,window,Cx,Ff] = lanczosfilter(x,varargin)\n%LANCZOSFILTER Filters a time series via Lanczos method (cosine filter). \n% [Y,coef,window,Cx,Ff] = LANCZOSFILTER(X,dT,Cf,M,pass) Filters the time\n% series via the Lanczos filter in the frequency space (FFT), where\n%\n% INPUTS:\n% X - Time series\n% dT - Sampling interval (default: 1)\n% Cf - Cut-off frequency (default: half Nyquist)\n% M - Number of coefficients (default: 100)\n% pass - Low or high-pass filter (default: 'low')\n%\n% OUTPUTS:\n% Y - Filtered time series\n% coef - Coefficients of the time window (cosine)\n% window - Frequency window (aprox. ones for Ff lower(greater) than Fc \n% if low(high)-pass filter and ceros otherwise)\n% Cx - Complex Fourier Transform of X for Ff frequencies\n% Ff - Fourier frequencies, from 0 to the Nyquist frequency.\n% \n% The program removes from the time series the frequencies greater than \n% the cut off frequency if \"pass\" is 'low', i.e., low-pass filter .\n% Otherwise, if pass is 'high', frequencies from zero to Cf are removed,\n% i.e., a high-pass filter. Units of the cut-off frequency, [Cf], must be\n% [dT]^{-1}. \n% \n% In consequence, when used as a low-pass the time series is smoothed \n% like a cosine filter in time space with M coefficients where greater is\n% better (see the reference). \n% \n% If any option is empty, defaults are used. \n%\n% Note: NaN's elements are replaced by the mean of the time series and\n% ignored. If you have a better idea, just let me know.\n% \n% Reference: \n% Emery, W. J. and R. E. Thomson. \"Data Analysis Methods in Physical \n% Oceanography\". Elsevier, 2d ed., 2004. On pages 533-539. \n% \n% Example:\n% dT = 30; % min \n% N = 7*24*60/dT; t = (0:N-1)*dT; % data for 7 days\n% pnoise = 0.30;\n% T1 = 12.4*60; T2 = 24*60; T3 = 15*24*60; Tc = 10*60; % min\n% xn = 5 + 3*cos(2*pi*t/T1) + 2*cos(2*pi*t/T2) + 1*cos(2*pi*t/T3);\n% xn = xn + pnoise*max(xn-mean(xn))*(0.5 - rand(size(xn))); \n% [xs,c,h,Cx,f] = lanczosfilter(xn,dT,1/Tc,[],'low'); \n% subplot(211), plot(t,xn,t,xs), legend('noisy','smooth'), axis tight\n% subplot(212), plot(f,h,f,abs(Cx)/max(abs(Cx)),...\n% [1 1]/Tc,[min(h) max(h)],'-.',...\n% [1/T1 1/T2 1/T3],([1/T1 1/T2 1/T3]<=1/Tc),'o'), axis tight \n% \n% See also FILTER, FFT, IFFT\n\n% Written by\n% Lic. on Physics Carlos Adrián Vargas Aguilera\n% Physical Oceanography MS candidate\n% UNIVERSIDAD DE GUADALAJARA \n% Mexico, 2004\n%\n% nubeobscura@hotmail.com\n\n% Check arguments:\nif nargin<1 || nargin>5\n error('Lanczosfilter:ArgumentNumber','Incorrect number of arguments.')\nelseif ~isvector(x) || ~isreal(x)\n error('Lanczosfilter:ArgumentType','Incorrect time series.')\nend\nif nargin<2 || isempty(varargin{1})\n dT = 1;\nelseif ~(numel(varargin{1})==1) || ~isreal(varargin{1})\n error('Lanczosfilter:ArgumentType','Incorrect time interval.')\nelse\n dT = varargin{1};\nend\nNf = 1/(2*dT); % Nyquist frequency\nif nargin<3 || isempty(varargin{2})\n Cf = Nf/2;\nelseif ~(numel(varargin{2})==1) || ~isreal(varargin{2}) || varargin{2}<=0 || varargin{2}>Nf \n error('Lanczosfilter:ArgumentType','Incorrect cut-off frequency.')\nelse\n Cf = varargin{2};\nend\nif nargin<4 || isempty(varargin{3})\n M = 100;\nelseif ~(numel(varargin{3})==1) || ~isreal(varargin{3}) || (varargin{3}==round(varargin{3}))\n error('Lanczosfilter:ArgumentType','Incorrect Number of coeffients.')\nelse\n M = varargin{3};\nend\nif nargin<5 || isempty(varargin{4})\n LoH = 'l';\nelseif ~ischar(varargin{4}) || isempty(strfind('lh',lower(varargin{4}(1))))\n error('Lanczosfilter:ArgumentType','Incorrect filter pass type.')\nelse\n LoH = varargin{4};\nend\nif strcmpi(LoH(1),'h')\n LoH = 2;\nelse\n LoH = 1;\nend\n\n% Normalize the cut off frequency with the Nyquist frequency:\nCf = Cf/Nf;\n\n% Lanczos cosine coeficients:\ncoef = lanczos_filter_coef(Cf,M); coef = coef(:,LoH);\n\n% Filter in frequency space:\n[window,Ff] = spectral_window(coef,length(x)); Ff = Ff*Nf;\n\n% Replace NaN's with the mean (ideas?):\ninan = isnan(x); \nxmean = mean(x(~inan)); \nx(inan) = xmean;\n\n% Filtering:\n[y,Cx] = spectral_filtering(x,window);\n\nfunction coef = lanczos_filter_coef(Cf,M)\n% Positive coeficients of Lanczos [low high]-pass.\nhkcs = lowpass_cosine_filter_coef(Cf,M);\nsigma = [1 sin(pi*(1:M)/M)./(pi*(1:M)/M)];\nhkB = hkcs.*sigma;\nhkA = -hkB; hkA(1) = hkA(1)+1;\ncoef = [hkB(:) hkA(:)];\n\nfunction coef = lowpass_cosine_filter_coef(Cf,M)\n% Positive coeficients of cosine filter low-pass.\ncoef = Cf*[1 sin(pi*(1:M)*Cf)./(pi*(1:M)*Cf)];\n\nfunction [window,Ff] = spectral_window(coef,N)\n% Window of cosine filter in frequency space.\nFf = 0:2/N:1; window = zeros(length(Ff),1);\nfor i = 1:length(Ff)\n window(i) = coef(1) + 2*sum(coef(2:end).*cos((1:length(coef)-1)'*pi*Ff(i)));\nend\n\nfunction [y,Cx] = spectral_filtering(x,window)\n% Filtering in frequency space is multiplication, (convolution in time \n% space).\nNx = length(x);\nCx = fft(x(:)); Cx = Cx(1:floor(Nx/2)+1);\nCxH = Cx.*window(:);\nCxH(length(CxH)+1:Nx) = conj(CxH(Nx-length(CxH)+1:-1:2)); \ny = real(ifft(CxH));\n\n\n% Carlos Adrián Vargas Aguilera. nubeobscura@hotmail.com", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/14041-lanczosfilter-m/lanczosfilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875223, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7314663966773483}} {"text": "function [rhsu] = HeatLDGRHS1D(u,time)\n\n% function [rhsu] = HeatLDGRHS1D(u,time,a,ax)\n% Purpose : Evaluate RHS flux in 1D heat equation using an LDG flux\n\nGlobals1D;\n\n% Define field differences at faces\ndu = zeros(Nfp*Nfaces,K); du(:) = (1.0+nx(:)).*(u(vmapM)-u(vmapP))/2.0;\n\n% impose boundary condition -- Dirichlet BC's\n%uin = -u(vmapI); du(mapI) = (1.0+nx(mapI)).*(u(vmapI)- uin)/2.0;\n%uout = -u(vmapO); du(mapO) = (1.0+nx(mapO)).*(u(vmapO)-uout)/2.0;\nuin = 0.1; du(mapI) = (1.0+nx(mapI)).*(u(vmapI)- uin)/2.0;\nuout = 0.1; du(mapO) = (1.0+nx(mapO)).*(u(vmapO)-uout)/2.0;\n\n% Compute q\nq = rx.*(Dr*u) - LIFT*(Fscale.*(nx.*du));\ndq = zeros(Nfp*Nfaces,K); dq(:) = (1.0-nx(:)).*(q(vmapM)-q(vmapP))/2.0;\n\n% impose boundary condition -- Neumann BC's\n%qin = q(vmapI); dq(mapI) = (1.0-nx(mapI)).*(q(vmapI)- qin)/2.0;\n%qout = q(vmapO); dq(mapO) = (1.0-nx(mapO)).*(q(vmapO)-qout)/2.0;\ndq(mapI)=0;\ndq(mapO)=0;\n\n% compute right hand sides of the semi-discrete PDE\nrhsu = rx.*(Dr*q) - LIFT*(Fscale.*(nx.*dq));\nreturn\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes1D/HeatLDGRHS1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388754, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7314223416250921}} {"text": "function alpha = meshDihedralAngles(vertices, edges, faces)\n%MESHDIHEDRALANGLES Dihedral at edges of a polyhedal mesh.\n%\n% ALPHA = meshDihedralAngles(V, E, F)\n% where V, E and F represent vertices, edges and faces of a mesh,\n% computes the dihedral angle between the two adjacent faces of each edge\n% in the mesh. ALPHA is a column array with as many rows as the number of\n% edges. The i-th element of ALPHA corresponds to the i-th edge.\n%\n% Note: the function assumes that the faces are correctly oriented. The\n% face vertices should be indexed counter-clockwise when considering the\n% supporting plane of the face, with the outer normal oriented outwards\n% of the mesh.\n%\n% Example\n% [v, e, f] = createCube;\n% rad2deg(meshDihedralAngles(v, e, f))\n% ans = \n% 90\n% 90\n% 90\n% 90\n% 90\n% 90\n% 90\n% 90\n% 90\n% 90\n% 90\n% 90\n%\n% See also\n% meshes3d, polyhedronMeanBreadth, trimeshMeanBreadth, dihedralAngle, meshEdgeFaces\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2010-10-04, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% compute normal of each face\nnormals = meshFaceNormals(vertices, faces);\n\n% indices of faces adjacent to each edge\nedgeFaces = meshEdgeFaces(vertices, edges, faces);\n\n% allocate memory for resulting angles\nNe = size(edges, 1);\nalpha = zeros(Ne, 1);\n\n% iterate over edges\nfor i = 1:Ne\n % indices of adjacent faces\n indFace1 = edgeFaces(i, 1);\n indFace2 = edgeFaces(i, 2);\n \n % normal vector of adjacent faces\n normal1 = normals(indFace1, :);\n normal2 = normals(indFace2, :);\n \n % compute dihedral angle of two vectors\n alpha(i) = vectorAngle3d(normal1, normal2);\nend\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/meshes3d/meshDihedralAngles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7314006701100256}} {"text": "function lattice_rule_test085 ( )\n\n%*****************************************************************************80\n%\n%% LATTICE_RULE_TEST085 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_TEST085\\n' );\n fprintf ( 1, ' LATTICE is a lattice rule for periodic functions.\\n' );\n fprintf ( 1, ' However, we apply it to a nonperiodic function\\n' );\n fprintf ( 1, ' just to see how it does.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The spatial dimension DIM_NUM = %d\\n', dim_num );\n\n a(1:dim_num) = 0.0;\n b(1:dim_num) = 1.0;\n\n exact = e_01_2d ( dim_num, a, b );\n\n z(1:dim_num) = [ 1, 2 ];\n i4vec_print ( dim_num, z, ' The lattice generator vector:' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' K M EXACT ESTIMATE ERROR\\n' );\n fprintf ( 1, '\\n' );\n\n for k = 3 : 18\n\n m = fibonacci ( k );\n\n quad = lattice ( dim_num, m, z, @f_01_2d );\n\n error = abs ( exact - quad );\n\n fprintf ( 1, ' %8d %8d %10.6f %10.6f %10.6e\\n', k, 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_test085.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7314006627094158}} {"text": "function [THD_U,THD_I,K_U,K_I,MaxHarm_I,MaxIHarm_I,MaxHFHarm_I,MaxHarm_U,MaxIHarm_U,MaxHFHarm_U,Order_Harm,Order_IHarm,Order_HFHarm] = IEC_Harmonics_final(f,Vn,Inom,U1,U2,U3,I1,I2,I3,U1_time,U2_time,U3_time,I1_time,I2_time,I3_time,figures)\n% This function will calculate the Harmonics spectrum values according to\n% the IEC 61000-4-7 Norm which spesify the need for 10 min Voltage and\n% current measured signals of the system under study and calulate the\n% Harmonics mean values every 10 Periods of the measured signal (In this case 50 Hz signal)\n% This Fucntion inputs are:\n% 1- The nominal values of the measured signal: Frequency,\n% Voltage, and the current. For example f = 50%Hz\n% Vn = 400%V (Phase to Phase Voltage of the grid)\n% Inom = 475%A (The nominal\n% current of the system under measurement)\n% 2- The measured Voltages and current signals with there time\n% measurement signals (U1,U2,U3,I1,I2,I3,U1_time,U2_time,U3_time,I1_time,I2_time,I3_time)\n% 3- figures is an input of 1 or 0 in order to activate showing the figures of the different harmonics spectrums figures calculated in this function.\n%PS: This function assume that you have the same sampling rate of the\n%different measured signals and that all measured signals has the same\n%length.\nFn = f;\nUn = Vn;\nIn = Inom;\nDelta_Time_Orginal = I1_time(2)-I1_time(1);\nF_Sample = abs(1/Delta_Time_Orginal);\n%------------------------------------------------------------------------------------------------------\n%---------------------- The Harmonics Spectrum of the complet input signal ----------------------------\n%------------------------------------------------------------------------------------------------------\nTp = length(I3_time);\nT_S = abs(Tp*Delta_Time_Orginal);\n[nyquist_number_I1,Bezugsfrequenz_I1,Signal_amp_I1] = Fast_Harmonics (I1,F_Sample,T_S);\n[nyquist_number_I2,Bezugsfrequenz_I2,Signal_amp_I2] = Fast_Harmonics (I2,F_Sample,T_S);\n[nyquist_number_I3,Bezugsfrequenz_I3,Signal_amp_I3] = Fast_Harmonics (I3,F_Sample,T_S);\n[nyquist_number_U1,Bezugsfrequenz_U1,Signal_amp_U1] = Fast_Harmonics (U1,F_Sample,T_S);\n[nyquist_number_U2,Bezugsfrequenz_U2,Signal_amp_U2] = Fast_Harmonics (U2,F_Sample,T_S);\n[nyquist_number_U3,Bezugsfrequenz_U3,Signal_amp_U3] = Fast_Harmonics (U3,F_Sample,T_S);\nif figures\n figure;\n subplot(2,1,1);\n plot([0:nyquist_number_I1]*Bezugsfrequenz_I1,Signal_amp_I1);ylabel('amplitude Currents [A]');title('Harmonic spectrom');hold on\n plot([0:nyquist_number_I2]*Bezugsfrequenz_I2,Signal_amp_I2,'-.r');hold on\n plot([0:nyquist_number_I3]*Bezugsfrequenz_I3,Signal_amp_I3,'--k');hold off\n subplot(2,1,2);\n plot([0:nyquist_number_U1]*Bezugsfrequenz_U1,Signal_amp_U1);xlabel('frequency [Hz]'),ylabel('amplitude Voltages [V]');hold on\n plot([0:nyquist_number_U2]*Bezugsfrequenz_U2,Signal_amp_U2,'-.r');hold on\n plot([0:nyquist_number_U3]*Bezugsfrequenz_U3,Signal_amp_U3,'.k','MarkerSize',0.1);hold off\nend\n%**********************************************************************\n%---------------------- Creating a grouping matrix --------------------\n%**********************************************************************\nSampling_Time = Delta_Time_Orginal;\nT_10_period = 10/Fn;\nF_Sample_Orginal = 1/Sampling_Time;\nif abs(F_Sample_Orginal) < 20000\n F_Sample_Complete_Data = 20000;\n [p, q] = rat(abs(Delta_Time_Orginal/(1/F_Sample_Complete_Data)));\n I1_Resampled = resample(I1,p,q);\n I2_Resampled = resample(I2,p,q);\n I3_Resampled = resample(I3,p,q);\n U1_Resampled = resample(U1,p,q);\n U2_Resampled = resample(U2,p,q);\n U3_Resampled = resample(U3,p,q);\n t_P = I1_time(1):((q/p)/F_Sample_Orginal):(I1_time(end)+((q/p)/F_Sample_Orginal));\n tt = length(t_P);\n if length(t_P) == length(I1_Resampled)\n I1_Resampled_time = t_P;\n I2_Resampled_time = t_P;\n I3_Resampled_time = t_P;\n U1_Resampled_time = t_P;\n U2_Resampled_time = t_P;\n U3_Resampled_time = t_P;\n else if length(t_P) < length(I1_Resampled)\n for kk = 1:abs(length(I1_Resampled)-length(t_P))\n t_P(tt+kk) = ((q/p)/F_Sample_Orginal)+t_P(tt+kk-1);\n end\n I1_Resampled_time = t_P;\n I2_Resampled_time = t_P;\n I3_Resampled_time = t_P;\n U1_Resampled_time = t_P;\n U2_Resampled_time = t_P;\n U3_Resampled_time = t_P;\n elseif length(t_P) > length(I1_Resampled)\n t_P = t_P(1:length(I1_Resample));\n I1_Resampled_time = t_P;\n I2_Resampled_time = t_P;\n I3_Resampled_time = t_P;\n U1_Resampled_time = t_P;\n U2_Resampled_time = t_P;\n U3_Resampled_time = t_P;\n end\n end\n Delta_Time_Complete_Data = 1/F_Sample_Complete_Data;\n Sampling_Time_New = Delta_Time_Complete_Data;\n Sampling_frq_New = (1/Sampling_Time_New)/1000;\n Sample_New = T_10_period*Sampling_frq_New*1000;\n ii= 1;\n Points = 2^ii;\n while Points < Sample_New\n Points = 2^ii;\n ii = ii+1;\n end\nelse if abs(F_Sample_Orginal) > 20000\n F_Sample_Complete_Data = 20000;\n [p, q] = rat(abs(Delta_Time_Orginal/(1/F_Sample_Complete_Data)));\n I1_Resampled = resample(I1,p,q);\n I2_Resampled = resample(I2,p,q);\n I3_Resampled = resample(I3,p,q);\n U1_Resampled = resample(U1,p,q);\n U2_Resampled = resample(U2,p,q);\n U3_Resampled = resample(U3,p,q);\n t_Q = I1_time(1):((q/p)/F_Sample):I1_time(end);\n I1_Resampled_time = t_Q;\n I2_Resampled_time = t_Q;\n I3_Resampled_time = t_Q;\n U1_Resampled_time = t_Q;\n U2_Resampled_time = t_Q;\n U3_Resampled_time = t_Q;\n Delta_Time_Complete_Data = 1/F_Sample_Complete_Data;\n %Sampling_Time_New = Delta_Time_Complete_Data;\n Sampling_frq_New = (1/Sampling_Time_Complete_Data)/1000;\n Sample_New = T_10_period*Sampling_frq_New*1000;\n ii= 1;\n Points = 2^ii;\n while Points < Sample_New\n Points = 2^ii;\n ii = ii+1;\n end\n else\n I1_Resampled = I1;\n I2_Resampled = I2;\n I3_Resampled = I3;\n U1_Resampled = U1;\n U2_Resampled = U2;\n U3_Resampled = U3;\n I1_Resampled_time = I1_time;\n I2_Resampled_time = I2_time;\n I3_Resampled_time = I3_time;\n U1_Resampled_time = U1_time;\n U2_Resampled_time = U2_time;\n U3_Resampled_time = U3_time;\n F_Sample_Complete_Data = 20000;\n Delta_Time_Complete_Data = I1_Resampled_time(2)-I1_Resampled_time(1);\n Sampling_frq = 1/Delta_Time_Complete_Data;\n T_10_period = 10/Fn;\n Sample = T_10_period*Sampling_frq;\n ii= 1;\n Points = 2^ii;\n while Points < Sample\n Points = 2^ii;\n ii = ii+1;\n end\n end\nend\n%----------------------------------------------------------------------\n%--------------- Zeros Results Array Definition -----------------------\n%----------------------------------------------------------------------\n%--------------- Try --------------------\nLOWPASS_CUTOFF = 100;% Filter cutoff frequency is 100 Hz\nLOWPASS_ORDER = 4;% Filter order is 4\n[b_bw, a_bw] = butter(LOWPASS_ORDER, LOWPASS_CUTOFF / (F_Sample_Complete_Data / 2), 'low');\nFilter = filter(b_bw, a_bw, U1_Resampled);\n%--------------- End --------------------\nnull_L1 = find(diff(Filter < 0));\nnull_L1_x = Zeros_finding(Filter,I1_Resampled_time');\nTp = length(U1_Resampled_time);\nlen = length(null_L1_x);\n%len_1_period = (1/Fn)/Delta_Time_Complete_Data;\n%len_10_period = (10*(1/Fn))/Delta_Time_Complete_Data;\nResults_U_H1 = zeros(50,length(0:20:len-30));\nResults_U_H2 = zeros(50,length(0:20:len-30));\nResults_U_H3 = zeros(50,length(0:20:len-30));\nResults_U_IH1 = zeros(39,length(0:20:len-30));\nResults_U_IH2 = zeros(39,length(0:20:len-30));\nResults_U_IH3 = zeros(39,length(0:20:len-30));\nResults_U_HF1 = zeros(35,length(0:20:len-30));\nResults_U_HF2 = zeros(35,length(0:20:len-30));\nResults_U_HF3 = zeros(35,length(0:20:len-30));\nResults_P = zeros(length(0:20:len-30));\nResults_Q = zeros(length(0:20:len-30));\n%----------------------------------------------------------------------\n%--------------------------- End --------------------------------------\n%----------------------------------------------------------------------\n%**********************************************************************\n%----------------------------------END---------------------------------\n%**********************************************************************\n%^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n%**********************************************************************\n%--------------------------- Gruoping ---------------------------------\n%**********************************************************************\nj = 0;\njj = 1;\nwhile j < len-30 % t < t2+0.1\n data_I1 = I1_Resampled(null_L1(j+3):null_L1(j+23)+1);\n data_I2 = I2_Resampled(null_L1(j+3):null_L1(j+23)+1);\n data_I3 = I3_Resampled(null_L1(j+3):null_L1(j+23)+1);\n data_U1 = U1_Resampled(null_L1(j+3):null_L1(j+23)+1);\n data_U2 = U2_Resampled(null_L1(j+3):null_L1(j+23)+1);\n data_U3 = U3_Resampled(null_L1(j+3):null_L1(j+23)+1);\n data_I1_time = I1_Resampled_time(null_L1(j+3):null_L1(j+23)+1);\n %------------------- Cut End --------------------------------------\n %------------------------------------------------------------------\n %--------- Data Resampling with the new Delta_10_Periods ----------\n %------------------------------------------------------------------\n delta = (null_L1_x(j+23)-null_L1_x(j+3))/Points;\n %Rampe = null_L1_x(j+3):delta:(((Points-1)*delta)+null_L1_x(j+3));\n iii=2;\n Rampe = zeros();\n Rampe(1) = null_L1_x(j+3);\n while iii <= Points\n Rampe(iii) = delta+Rampe(iii-1);\n iii = iii+1;\n end\n F_Sample_10_Periods = 1/delta;\n if abs(F_Sample_10_Periods) < F_Sample_Complete_Data\n F_Sample_New = F_Sample_10_Periods;\n [p, q] = rat(abs(Delta_Time/(1/F_Sample_New)));\n I1_Resampled_10_Period = resample(data_I1,p,q);\n I2_Resampled_10_Period = resample(data_I2,p,q);\n I3_Resampled_10_Period = resample(data_I3,p,q);\n U1_Resampled_10_Period = resample(data_U1,p,q);\n U2_Resampled_10_Period = resample(data_U2,p,q);\n U3_Resampled_10_Period = resample(data_U3,p,q);\n t_P = data_I1_time(1):(1/F_Sample_New):(data_I1_time(end)+(1/F_Sample_New));\n I1_Resampled_time_10_Period = t_P;\n I2_Resampled_time_10_Period = t_P;\n I3_Resampled_time_10_Period = t_P;\n U1_Resampled_time_10_Period = t_P;\n U2_Resampled_time_10_Period = t_P;\n U3_Resampled_time_10_Period = t_P;\n else if abs(F_Sample_10_Periods) > F_Sample_Complete_Data\n F_Sample_New = F_Sample_10_Periods;\n [p, q] = rat(abs(Delta_Time_Complete_Data/(1/F_Sample_New)));\n I1_Resampled_10_Period = resample(data_I1,p,q);\n I2_Resampled_10_Period = resample(data_I2,p,q);\n I3_Resampled_10_Period = resample(data_I3,p,q);\n U1_Resampled_10_Period = resample(data_U1,p,q);\n U2_Resampled_10_Period = resample(data_U2,p,q);\n U3_Resampled_10_Period = resample(data_U3,p,q);\n for kk=1:length(I1_Resampled_10_Period)-1\n I1_Resample_10_Period_Final(kk) = ((I1_Resampled_10_Period(kk)+I1_Resampled_10_Period(kk+1))/2);\n I2_Resample_10_Period_Final(kk) = ((I2_Resampled_10_Period(kk)+I2_Resampled_10_Period(kk+1))/2);\n I3_Resample_10_Period_Final(kk) = ((I3_Resampled_10_Period(kk)+I3_Resampled_10_Period(kk+1))/2);\n U1_Resample_10_Period_Final(kk) = ((U1_Resampled_10_Period(kk)+U1_Resampled_10_Period(kk+1))/2);\n U2_Resample_10_Period_Final(kk) = ((U2_Resampled_10_Period(kk)+U2_Resampled_10_Period(kk+1))/2);\n U3_Resample_10_Period_Final(kk) = ((U3_Resampled_10_Period(kk)+U3_Resampled_10_Period(kk+1))/2);\n end\n if length(I1_Resample_10_Period_Final) > length(Rampe)\n I1_Resample_10_Period_Final = I1_Resample_10_Period_Final(1:length(Rampe));\n I2_Resample_10_Period_Final = I2_Resample_10_Period_Final(1:length(Rampe));\n I3_Resample_10_Period_Final = I3_Resample_10_Period_Final(1:length(Rampe));\n else if length(I1_Resample_10_Period_Final) < length(Rampe)\n error('Please check the Resampled data something wrong there :(')\n end\n end\n t_Q = Rampe(1):((q/p)/F_Sample_Complete_Data):Rampe(end);\n if length(t_Q) == length(I1_Resampled_10_Period)\n I1_Resampled_time_10_Period = t_Q;\n I2_Resampled_time_10_Period = t_Q;\n I3_Resampled_time_10_Period = t_Q;\n U1_Resampled_time_10_Period = t_Q;\n U2_Resampled_time_10_Period = t_Q;\n U3_Resampled_time_10_Period = t_Q;\n else if length(t_Q) > length(I1_Resampled_10_Period)\n I1_Resampled_time_10_Period = t_Q(1:length(I1_Resampled_10_Period));\n I2_Resampled_time_10_Period = t_Q(1:length(I2_Resampled_10_Period));\n I3_Resampled_time_10_Period = t_Q(1:length(I3_Resampled_10_Period));\n U1_Resampled_time_10_Period = t_Q(1:length(U1_Resampled_10_Period));\n U2_Resampled_time_10_Period = t_Q(1:length(U2_Resampled_10_Period));\n U3_Resampled_time_10_Period = t_Q(1:length(U3_Resampled_10_Period));\n else if length(t_Q) < length(I1_Resampled_10_Period)\n I1_Resampled_time_10_Period = [t_Q t_Q(end)+((q/p)/F_Sample_Complete_Data)];\n I2_Resampled_time_10_Period = [t_Q t_Q(end)+((q/p)/F_Sample_Complete_Data)];\n I3_Resampled_time_10_Period = [t_Q t_Q(end)+((q/p)/F_Sample_Complete_Data)];\n U1_Resampled_time_10_Period = [t_Q t_Q(end)+((q/p)/F_Sample_Complete_Data)];\n U2_Resampled_time_10_Period = [t_Q t_Q(end)+((q/p)/F_Sample_Complete_Data)];\n U3_Resampled_time_10_Period = [t_Q t_Q(end)+((q/p)/F_Sample_Complete_Data)];\n end\n end\n end\n else\n error('Please check the Delta Value of the 10 Period signal')\n end\n end\n %------------------------------------------------------------------\n %---------------- Data Re-sampling End ----------------------------\n %------------------------------------------------------------------\n %----------------Spectrum Calculation------------------------------\n %------------------------------------------------------------------\n Tp_10_Period_Resampled = length(I1_Resampled_time_10_Period);\n Delta_Time_10_Period_Resampled = I1_Resampled_time_10_Period(2)-I1_Resampled_time_10_Period(3);\n F_Sample_10_Period_Resampled = abs(1/Delta_Time_10_Period_Resampled);\n T_S_10_Period_Resampled = abs(Tp*Delta_Time_10_Period_Resampled);\n %----------------------------------------------------------------------\n [nyquist_number_I1_Resampled_10_Period,Bezugsfrequenz_I1_Resampled_10_Period,Signal_amp_I1_Resampled_10_Period] = Fast_Harmonics_1 (I1_Resample_10_Period_Final,F_Sample_10_Period_Resampled,T_S_10_Period_Resampled);\n [nyquist_number_I2_Resampled_10_Period,Bezugsfrequenz_I2_Resampled_10_Period,Signal_amp_I2_Resampled_10_Period] = Fast_Harmonics_1 (I2_Resample_10_Period_Final,F_Sample_10_Period_Resampled,T_S_10_Period_Resampled);\n [nyquist_number_I3_Resampled_10_Period,Bezugsfrequenz_I3_Resampled_10_Period,Signal_amp_I3_Resampled_10_Period] = Fast_Harmonics_1 (I3_Resample_10_Period_Final,F_Sample_10_Period_Resampled,T_S_10_Period_Resampled);\n [nyquist_number_U1_Resampled_10_Period,Bezugsfrequenz_U1_Resampled_10_Period,Signal_amp_U1_Resampled_10_Period] = Fast_Harmonics_1 (U1_Resample_10_Period_Final,F_Sample_10_Period_Resampled,T_S_10_Period_Resampled);\n [nyquist_number_U2_Resampled_10_Period,Bezugsfrequenz_U2_Resampled_10_Period,Signal_amp_U2_Resampled_10_Period] = Fast_Harmonics_1 (U2_Resample_10_Period_Final,F_Sample_10_Period_Resampled,T_S_10_Period_Resampled);\n [nyquist_number_U3_Resampled_10_Period,Bezugsfrequenz_U3_Resampled_10_Period,Signal_amp_U3_Resampled_10_Period] = Fast_Harmonics_1 (U3_Resample_10_Period_Final,F_Sample_10_Period_Resampled,T_S_10_Period_Resampled);\n Figure_Show = 0;\n if Figure_Show == 1\n figure;\n subplot(2,1,1);\n plot([0:nyquist_number_data_I1]*Bezugsfrequenz_data_I1,Signal_amp_data_I1);ylabel('amplitude Currents [A]');title('Harmonic spectrom');hold on\n plot([0:nyquist_number_data_I2]*Bezugsfrequenz_data_I2,Signal_amp_data_I2,'-.r');hold on\n plot([0:nyquist_number_data_I3]*Bezugsfrequenz_data_I3,Signal_amp_data_I3,'--k');hold off\n subplot(2,1,2);\n plot([0:nyquist_number_data_U1]*Bezugsfrequenz_data_U1,Signal_amp_data_U1);xlabel('frequency [Hz]'),ylabel('amplitude Voltages [A]');hold on\n plot([0:nyquist_number_data_U2]*Bezugsfrequenz_data_U2,Signal_amp_data_U2,'-.r');hold on\n plot([0:nyquist_number_data_U3]*Bezugsfrequenz_data_U3,Signal_amp_data_U3,'.k','MarkerSize',0.1);hold off\n end\n % Grouping U1\n data_specM_x_H = [0:nyquist_number_U1_Resampled_10_Period]*Bezugsfrequenz_U1_Resampled_10_Period;\n deta_specM_x_V = data_specM_x_H';\n data_specM_Y_V = Signal_amp_U1_Resampled_10_Period';\n data_specM = data_specM_Y_V;\n i = 11;\n ii = 1;\n while i < 502\n harm_calc = sqrt(power(data_specM(i-1),2)+power(data_specM(i),2)+power(data_specM(i+1),2));\n iTxt = (i-1)/10;\n Results_U_H1(ii,jj) = harm_calc;\n if i < 392\n iharm_calc = sqrt(power(data_specM(i+2),2)+power(data_specM(i+3),2)+power(data_specM(i+4),2)+power(data_specM(i+5),2)+power(data_specM(i+6),2)+power(data_specM(i+7),2)+power(data_specM(i+8),2));\n Results_U_IH1(ii,jj) = iharm_calc;\n end\n if i <= 360\n j1 = (i-1)*4+360+1;\n j_end = j1+40;\n hfharm_calc = 0;\n while j1 <= j_end\n hfharm_calc = hfharm_calc+power(data_specM(j1),2);\n j1 =j1+1;\n end\n hfharm_calc = sqrt(hfharm_calc);\n j1 = 200*(i-1)/10+1900;\n Results_U_HF1(ii,jj) = hfharm_calc;\n end\n i = i+10;\n ii = ii+1;\n end\n % Grouping U2\n data_specM_x_H = [0:nyquist_number_U2_Resampled_10_Period]*Bezugsfrequenz_U2_Resampled_10_Period;\n deta_specM_x_V = data_specM_x_H';\n data_specM_Y_V = Signal_amp_U2_Resampled_10_Period';\n data_specM = data_specM_Y_V;\n i = 11;\n ii = 1;\n while i < 502\n harm_calc = sqrt(power(data_specM(i-1),2)+power(data_specM(i),2)+power(data_specM(i+1),2));\n iTxt = (i-1)/10;\n Results_U_H2(ii,jj) = harm_calc;\n if i < 392\n iharm_calc = sqrt(power(data_specM(i+2),2)+power(data_specM(i+3),2)+power(data_specM(i+4),2)+power(data_specM(i+5),2)+power(data_specM(i+6),2)+power(data_specM(i+7),2)+power(data_specM(i+8),2));\n Results_U_IH2(ii,jj) = iharm_calc;\n end\n if i <= 360\n j1 = (i-1)*4+360+1;\n j_end = j1+40;\n hfharm_calc = 0;\n while j1 <= j_end\n hfharm_calc = hfharm_calc+power(data_specM(j1),2);\n j1 =j1+1;\n end\n hfharm_calc = sqrt(hfharm_calc);\n j1 = 200*(i-1)/10+1900;\n Results_U_HF2(ii,jj) = hfharm_calc;\n end\n i = i+10;\n ii = ii+1;\n end\n % Grouping U3\n data_specM_x_H = [0:nyquist_number_U3_Resampled_10_Period]*Bezugsfrequenz_U3_Resampled_10_Period;\n deta_specM_x_V = data_specM_x_H';\n data_specM_Y_V = Signal_amp_U3_Resampled_10_Period';\n data_specM = data_specM_Y_V;\n i = 11;\n ii = 1;\n while i < 502\n harm_calc = sqrt(power(data_specM(i-1),2)+power(data_specM(i),2)+power(data_specM(i+1),2));\n iTxt = (i-1)/10;\n Results_U_H3(ii,jj) = harm_calc;\n if i < 392\n iharm_calc = sqrt(power(data_specM(i+2),2)+power(data_specM(i+3),2)+power(data_specM(i+4),2)+power(data_specM(i+5),2)+power(data_specM(i+6),2)+power(data_specM(i+7),2)+power(data_specM(i+8),2));\n Results_U_IH3(ii,jj) = iharm_calc;\n end\n if i <= 360\n j1 = (i-1)*4+360+1;\n j_end = j1+40;\n hfharm_calc = 0;\n while j1 <= j_end\n hfharm_calc = hfharm_calc+power(data_specM(j1),2);\n j1 =j1+1;\n end\n hfharm_calc = sqrt(hfharm_calc);\n j1 = 200*(i-1)/10+1900;\n Results_U_HF3(ii,jj) = hfharm_calc;\n end\n i = i+10;\n ii = ii+1;\n end\n % Grouping I1\n data_specM_x_H = [0:nyquist_number_I1_Resampled_10_Period]*Bezugsfrequenz_I1_Resampled_10_Period;\n %deta_specM_x_V = data_specM_x_H';\n data_specM_Y_V = Signal_amp_I1_Resampled_10_Period';\n data_specM = data_specM_Y_V;\n i = 11;\n ii = 1;\n while i < 502\n harm_calc = sqrt(power(data_specM(i-1),2)+power(data_specM(i),2)+power(data_specM(i+1),2));\n iTxt = (i-1)/10;\n Results_I_H1(ii,jj) = harm_calc;\n if i < 392\n iharm_calc = sqrt(power(data_specM(i+2),2)+power(data_specM(i+3),2)+power(data_specM(i+4),2)+power(data_specM(i+5),2)+power(data_specM(i+6),2)+power(data_specM(i+7),2)+power(data_specM(i+8),2));\n Results_I_IH1(ii,jj) = iharm_calc;\n end\n if i <= 360\n j1 = (i-1)*4+360+1;\n j_end = j1+40;\n hfharm_calc = 0;\n while j1 <= j_end\n hfharm_calc = hfharm_calc+power(data_specM(j1),2);\n j1 =j1+1;\n end\n hfharm_calc = sqrt(hfharm_calc);\n j1 = 200*(i-1)/10+1900;\n Results_I_HF1(ii,jj) = hfharm_calc;\n end\n i = i+10;\n ii = ii+1;\n end\n % Grouping I2\n data_specM_x_H = [0:nyquist_number_I2_Resampled_10_Period]*Bezugsfrequenz_I2_Resampled_10_Period;\n %deta_specM_x_V = data_specM_x_H';\n data_specM_Y_V = Signal_amp_I2_Resampled_10_Period';\n data_specM = data_specM_Y_V;\n i = 11;\n ii = 1;\n while i < 502\n harm_calc = sqrt(power(data_specM(i-1),2)+power(data_specM(i),2)+power(data_specM(i+1),2));\n iTxt = (i-1)/10;\n Results_I_H2(ii,jj) = harm_calc;\n if i < 392\n iharm_calc = sqrt(power(data_specM(i+2),2)+power(data_specM(i+3),2)+power(data_specM(i+4),2)+power(data_specM(i+5),2)+power(data_specM(i+6),2)+power(data_specM(i+7),2)+power(data_specM(i+8),2));\n Results_I_IH2(ii,jj) = iharm_calc;\n end\n if i <= 360\n j1 = (i-1)*4+360+1;\n j_end = j1+40;\n hfharm_calc = 0;\n while j1 <= j_end\n hfharm_calc = hfharm_calc+power(data_specM(j1),2);\n j1 =j1+1;\n end\n hfharm_calc = sqrt(hfharm_calc);\n j1 = 200*(i-1)/10+1900;\n Results_I_HF2(ii,jj) = hfharm_calc;\n end\n i = i+10;\n ii = ii+1;\n end\n % Grouping I3\n data_specM_x_H = [0:nyquist_number_I3_Resampled_10_Period]*Bezugsfrequenz_I3_Resampled_10_Period;\n %deta_specM_x_V = data_specM_x_H';\n data_specM_Y_V = Signal_amp_I3_Resampled_10_Period';\n data_specM = data_specM_Y_V;\n i = 11;\n ii = 1;\n while i < 502\n harm_calc = sqrt(power(data_specM(i-1),2)+power(data_specM(i),2)+power(data_specM(i+1),2));\n iTxt = (i-1)/10;\n Results_I_H3(ii,jj) = harm_calc;\n if i < 392\n iharm_calc = sqrt(power(data_specM(i+2),2)+power(data_specM(i+3),2)+power(data_specM(i+4),2)+power(data_specM(i+5),2)+power(data_specM(i+6),2)+power(data_specM(i+7),2)+power(data_specM(i+8),2));\n Results_I_IH3(ii,jj) = iharm_calc;\n end\n if i <= 360\n j1 = (i-1)*4+360+1;\n j_end = j1+40;\n hfharm_calc = 0;\n while j1 <= j_end\n hfharm_calc = hfharm_calc+power(data_specM(j1),2);\n j1 =j1+1;\n end\n hfharm_calc = sqrt(hfharm_calc);\n j1 = 200*(i-1)/10+1900;\n Results_I_HF3(ii,jj) = hfharm_calc;\n end\n i = i+10;\n ii = ii+1;\n end\n if 0 == 1\n v_alpha = sqrt(2)/3*(data_U1-0.5*data_U2-0.5*data_U3);\n v_beta = sqrt(2)/3*(sqrt(3)/2*data_U2-sqrt(3)/2*data_U3);\n I_alpha = sqrt(2)/3*(data_I1-0.5*data_I2-0.5*data_I3);\n I_beta = sqrt(2)/3*(sqrt(3)/2*data_I2-sqrt(3)/2*data_I3);\n P = 3*(v_alpha*I_alpha+v_beta*I_beta);\n Q = 3*(-v_alpha*I_beta+v_beta*I_alpha);\n Results_P(jj) = P;\n Results_Q(jj) = Q;\n end\n j = j+20; % Calculation every 10 Periods\n jj = jj+1;\nend\n%**********************************************************************\n%----------------------------------END---------------------------------\n%**********************************************************************\n%-------------------------- Normalization -----------------------------\n%**********************************************************************\nResults_U_H1_pu = Results_U_H1/sqrt(2)/Un;\nResults_U_H2_pu = Results_U_H2/sqrt(2)/Un;\nResults_U_H3_pu = Results_U_H3/sqrt(2)/Un;\nResults_I_H1_pu = Results_I_H1/sqrt(2)/In;\nResults_I_H2_pu = Results_I_H2/sqrt(2)/In;\nResults_I_H3_pu = Results_I_H3/sqrt(2)/In;\n%----------------------------------------------------------------------\nResults_U_IH1_pu = Results_U_IH1/sqrt(2)/Un;\nResults_U_IH2_pu = Results_U_IH2/sqrt(2)/Un;\nResults_U_IH3_pu = Results_U_IH3/sqrt(2)/Un;\nResults_I_IH1_pu = Results_I_IH1/sqrt(2)/In;\nResults_I_IH2_pu = Results_I_IH2/sqrt(2)/In;\nResults_I_IH3_pu = Results_I_IH3/sqrt(2)/In;\n%----------------------------------------------------------------------\nResults_U_HF1_pu = Results_U_HF1/sqrt(2)/Un;\nResults_U_HF2_pu = Results_U_HF2/sqrt(2)/Un;\nResults_U_HF3_pu = Results_U_HF3/sqrt(2)/Un;\nResults_I_HF1_pu = Results_I_HF1/sqrt(2)/In;\nResults_I_HF2_pu = Results_I_HF2/sqrt(2)/In;\nResults_I_HF3_pu = Results_I_HF3/sqrt(2)/In;\n%**********************************************************************\n%------------------------ End -----------------------------------------\n%**********************************************************************\n% ------------------- Mean and Max Value Calculation ------------------\n% *********************************************************************\n[~, colum] = size(Results_I_H1_pu);\nif colum > 1\nMeanHarm_U1 = mean(Results_U_H1_pu');\nMeanHarm_U2 = mean(Results_U_H2_pu');\nMeanHarm_U3 = mean(Results_U_H3_pu');\nMeanHarm_I1 = mean(Results_I_H1_pu');\nMeanHarm_I2 = mean(Results_I_H2_pu');\nMeanHarm_I3 = mean(Results_I_H3_pu');\n%----------------------------------------------------------------------\nMeanIHarm_U1 = mean(Results_U_IH1_pu');\nMeanIHarm_U2 = mean(Results_U_IH2_pu');\nMeanIHarm_U3 = mean(Results_U_IH3_pu');\nMeanIHarm_I1 = mean(Results_I_IH1_pu');\nMeanIHarm_I2 = mean(Results_I_IH2_pu');\nMeanIHarm_I3 = mean(Results_I_IH3_pu');\n%----------------------------------------------------------------------\nMeanHFHarm_U1 = mean(Results_U_HF1_pu');\nMeanHFHarm_U2 = mean(Results_U_HF2_pu');\nMeanHFHarm_U3 = mean(Results_U_HF3_pu');\nMeanHFHarm_I1 = mean(Results_I_HF1_pu');\nMeanHFHarm_I2 = mean(Results_I_HF2_pu');\nMeanHFHarm_I3 = mean(Results_I_HF3_pu');\n%----------------------------------------------------------------------\nMaxHarm_U = max(max(MeanHarm_U1,MeanHarm_U2),MeanHarm_U3);\nMaxHarm_I = max(max(MeanHarm_I1,MeanHarm_I2),MeanHarm_I3);\nMaxIHarm_U = max(max(MeanIHarm_U1,MeanIHarm_U2),MeanIHarm_U3);\nMaxIHarm_I = max(max(MeanIHarm_I1,MeanIHarm_I2),MeanIHarm_I3);\nMaxHFHarm_U = max(max(MeanHFHarm_U1,MeanHFHarm_U2),MeanHFHarm_U3);\nMaxHFHarm_I = max(max(MeanHFHarm_I1,MeanHFHarm_I2),MeanHFHarm_I3);\nelse\nMeanHarm_I1 = Results_I_H1_pu;\nMeanHarm_I2 = Results_I_H2_pu;\nMeanHarm_I3 = Results_I_H3_pu;\nMeanHarm_U1 = Results_U_H1_pu;\nMeanHarm_U2 = Results_U_H2_pu;\nMeanHarm_U3 = Results_U_H3_pu;\n%----------------------------------------------------------------------\nMeanIHarm_U1 = Results_U_IH1_pu;\nMeanIHarm_U2 = Results_U_IH2_pu;\nMeanIHarm_U3 = Results_U_IH3_pu;\nMeanIHarm_I1 = Results_I_IH1_pu;\nMeanIHarm_I2 = Results_I_IH2_pu;\nMeanIHarm_I3 = Results_I_IH3_pu;\n%----------------------------------------------------------------------\nMeanHFHarm_U1 = Results_U_HF1_pu;\nMeanHFHarm_U2 = Results_U_HF2_pu;\nMeanHFHarm_U3 = Results_U_HF3_pu;\nMeanHFHarm_I1 = Results_I_HF1_pu;\nMeanHFHarm_I2 = Results_I_HF2_pu;\nMeanHFHarm_I3 = Results_I_HF3_pu;\n%----------------------------------------------------------------------\nMaxHarm_U = max(max(MeanHarm_U1,MeanHarm_U2),MeanHarm_U3);\nMaxHarm_I = max(max(MeanHarm_I1,MeanHarm_I2),MeanHarm_I3);\nMaxIHarm_U = max(max(MeanIHarm_U1,MeanIHarm_U2),MeanIHarm_U3);\nMaxIHarm_I = max(max(MeanIHarm_I1,MeanIHarm_I2),MeanIHarm_I3);\nMaxHFHarm_U = max(max(MeanHFHarm_U1,MeanHFHarm_U2),MeanHFHarm_U3);\nMaxHFHarm_I = max(max(MeanHFHarm_I1,MeanHFHarm_I2),MeanHFHarm_I3);\nend\n%**********************************************************************\n%------------------------------- End ----------------------------------\n%**********************************************************************\n%--------------- Order (x-axie) Calculation and Ploting ---------------\n%**********************************************************************\nOrder_Harm = 1:1:50;\nOrder_IHarm = 1:1:39;\n%Order_HFHarm = 1:1:35;\n%Order_HFHarm = 2100:1:2134;\nOrder_HFHarm = 2100:200:8900;\nif figures\n figure;\n subplot(2,3,1)\n bar(Order_Harm,MaxHarm_I);xlabel('Order Number');ylabel('Current Hamonics Levels I/In in pu');title('Current Harmonics spectrom')\n subplot(2,3,2)\n bar(Order_IHarm,MaxIHarm_I);xlabel('Order Number');ylabel('Current Hamonics Levels I/In in pu');title('Current interharmonics spectrom')\n subplot(2,3,3)\n bar(Order_HFHarm,MaxHFHarm_I);xlabel('Frequency in Hz');ylabel('Current Hamonics Levels I/In in pu');title('Current Higher Frequencies spectrom')\n subplot(2,3,4)\n bar(Order_Harm,MaxHarm_U);xlabel('Order Number');ylabel('Voltage Hamonics Levels U/Un in pu');title('Voltage Harmonics spectrom')\n subplot(2,3,5)\n bar(Order_IHarm,MaxIHarm_U);xlabel('Order Number');ylabel('Voltage Hamonics Levels U/Un in pu');title('Voltage interharmonics spectrom')\n subplot(2,3,6)\n bar(Order_HFHarm,MaxHFHarm_U);xlabel('Frequency in Hz');ylabel('Voltage Hamonics Levels U/Un in pu');title('Voltage Higher Frequencies spectrom')\nend\n%**********************************************************************\n%------------------------------- End ----------------------------------\n%**********************************************************************\n%-------------------------- K, THD Factor ----------------------------\n%**********************************************************************\nTHD_U = sqrt(sum((MaxHarm_U(2:end).^2)'))/(MaxHarm_U(1));\nTHD_I = sqrt(sum((MaxHarm_I(2:end).^2)'))/(MaxHarm_I(1));\nK_U = sqrt(sum((MaxHarm_U(2:end).^2)')/(MaxHarm_U(1)+sum((MaxHarm_U(2:end).^2)')));\nK_I = sqrt(sum((MaxHarm_I(2:end).^2)')/(MaxHarm_I(1)+sum((MaxHarm_I(2:end).^2)')));\n%**********************************************************************\n%------------------------------- End ----------------------------------\n%**********************************************************************\n%------------------------ Saving Results ------------------------------\n%**********************************************************************\nsave('Harmonics','THD_U','THD_I','K_U','K_I','MaxHarm_I','MaxHarm_U','MaxIHarm_I','MaxIHarm_U','MaxHFHarm_I','MaxHFHarm_U','MaxHarm_I','Order_IHarm','Order_Harm','Order_HFHarm')\n%**********************************************************************\n%------------------------------- End ----------------------------------\n%**********************************************************************\nend\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/43496-iec-61000-4-7-for-harmonics-calculations/Harmonics_IEC/IEC_Harmonics_final.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7313160266393607}} {"text": "function [p2, R2] = SE3exp(j, dt)\nglobal uLINK\n% see Murray, Li, Sastry p.42\n\nnorm_w = norm(uLINK(j).w);\nif norm_w < eps\n p2 = uLINK(j).p + dt * uLINK(j).vo;\n R2 = uLINK(j).R;\nelse\n th = norm_w*dt;\n wn = uLINK(j).w/norm_w;\t\t% normarized vector\n vo = uLINK(j).vo/norm_w;\n \n w_wedge = [0 -wn(3) wn(2);wn(3) 0 -wn(1);-wn(2) wn(1) 0];\n drot = w_wedge * sin(th) + w_wedge^2 * (1-cos(th));\n rot = eye(3) + drot;\n \n p2 = rot * uLINK(j).p -drot*cross(wn, vo) + wn * wn' * vo * th; \n R2 = rot * uLINK(j).R;\nend\n", "meta": {"author": "s-kajita", "repo": "IntroductionToHumanoidRobotics", "sha": "55c46ce6902c97897596fda581f93555c426736c", "save_path": "github-repos/MATLAB/s-kajita-IntroductionToHumanoidRobotics", "path": "github-repos/MATLAB/s-kajita-IntroductionToHumanoidRobotics/IntroductionToHumanoidRobotics-55c46ce6902c97897596fda581f93555c426736c/SE3exp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.7312298885970304}} {"text": "% The OxyGEN proyect by Profoty.xyz\n% Together against the Covid-19\n% V4.0 rev.17/03/2020\n% \n% Website/blog: oxygen.protofy.xyz\n% Contact: oxygen@protofy.xyz\n\n\n%GEOMETRICAL PARAMETERS\n\nl0 = 30;\nh0 = 6.5;\n\nh1 = 10;\nh2 = 19;\n\nlm = 30;\nhm = 23;\n\nlb = l0 - 8.5;\n\n%Minimum radius of the camshaft\nv = hm - h2;\n\n%Y coordinate variation between min and max positions of the camshaft\ndv = h2 - h1;\n\n\n%BREATHING CYCLE PARAMETERS\n\n%Duration of the inhale cycle / duration of the whole cycle\nlambda1 = 0.50;\nlambda2 = 0.08;\n\n%Soft transition between inhale and exhale cycles\ndpsi21 = 0.12;\ndpsi12 = 0.15;\n\n%Adjust parameters of the inhale curve\nga1 = 4;\ngb1 = .85;\nff1 = 50;\n\n%Adjust parametes of the exhale curve\nga2 = 3.5;\ngb2 = .70;\nff2 = 55;\n\n\n%GENERATION OF THE CURVES AND THE CAMSHAFT\n\n%Time increment\ndt = 0.01;\n\n%time coordinate during the whole cycle\ntheta = 0:dt:2*pi;\n\n%Generation of the soft transition between inhale and exhale curves\npsi1 = [];\npsi2 = [];\n\nfor i = 1:numel(theta);\n \n if theta(i) < (lambda2-dpsi21/2)*2*pi;\n psi1(i) = 0;\n \n elseif theta(i) < (lambda2+dpsi21/2)*2*pi;\n psi1(i) = 0.5 + 0.5*cos((theta(i)-(lambda2+dpsi21/2)*2*pi)/(2*dpsi21));\n \n elseif theta(i) < (lambda1-dpsi12/2)*2*pi;\n psi1(i) = 1;\n \n elseif theta(i) < (lambda1+dpsi12/2)*2*pi;\n psi1(i) = 0.5 - 0.5*cos((theta(i)-(lambda1+dpsi12/2)*2*pi)/(2*dpsi12));\n \n else\n psi1(i) = 0;\n \n end;\n \n psi2(i) = 1 - psi1(i);\n \nend; \n\n\n%Generation of the complete breathing cycle rho(theta)\n\nrho = [];\nrho1 = [];\nrho2 = [];\nrho2next = [];\n\nrhomin = 1000;\nrhomax = 0;\n\nfor i = 1:numel(theta);\n \n %Inhale curve\n rho1(i) = ff1*gampdf(theta(i), ga1, gb1);\n \n %Exhale curve\n rho2(i) = ff2*gampdf(theta(i), ga2, gb2);\n rho2next(i) = ff2*gampdf(theta(i)+2*pi, ga2, gb2);\n \n if theta(i) < lambda1*pi \n rho(i) = psi1(i)*rho1(i) + psi2(i)*rho2next(i);\n \n else\n rho(i) = psi1(i)*rho1(i) + psi2(i)*rho2(i);\n \n end;\n \n %Capturing min and max in order to generate the normalized curve\n if rho(i) > rhomax\n rhomax = rho(i);\n end;\n \n if rho(i) < rhomin\n rhomin = rho(i);\n end;\n\nend;\n\n\n%Generation of a normalised curve and camshaft\n\nrhonorm = [];\nrhocam = [];\n\nfor i = 1:numel(theta);\n \n rhonorm(i) = (rho(i)-rhomin)/(rhomax-rhomin);\n \n rhocam(i) = v + rhonorm(i)*dv;\n \nend;\n\n\n%Generation of the first derivate of the camshaft geometry to analize and\n%validate the design\n\ndrho = [];\ndrhonorm = [];\ndrhocam = [];\n\na = v;\nb = 1/dt;\n\nfor i = 1 : numel(rho)-1;\n \n drho(i) = b*(rho(i+1)-rho(i));\n drhonorm(i) = b*(rhonorm(i+1)-rhonorm(i));\n drhocam(i) = b*(rhocam(i+1)-rhocam(i)) + a;\n \nend;\n\ndrho(numel(rho)) = b*(rho(1)-rho(numel(rho)));\ndrhonorm(numel(rhonorm)) = b*(rhonorm(1)-rhonorm(numel(rhonorm)));\ndrhocam(numel(rhocam)) = b*(rhocam(1)-rhocam(numel(rhocam))) + a;\n\n\n%X and Y coordinates during two cycles (for 2-cycle camshaft plot)\n\ntheta2 = [theta/2, (2*pi+theta)/2];\n\nrhocam2 = [rhocam, rhocam];\ndrhocam2 = [drho, drho];\n\n\n%X and Y coordinates during three cycles (for 3-cycle camshaft plot)\n\ntheta3 = [theta/3, (2*pi+theta)/3, (4*pi+theta)/3];\n\nrhocam3 = [rhocam, rhocam, rhocam];\ndrhocam3 = [drho, drho, drho];\n\n\n\n%GENERATION OF THE PLOTS\n\n%Trying to print it out in real size (FAIL)\n%set(gcf,'PaperUnits','centimeters'); \n%set(gcf,'PaperSize',[42 29.7]);\n\n%Plot of the breathing cycle interpolation by curves\n\nfcycle = figure('Name', 'Breath Cycle curves', 'Units', 'centimeters', 'NumberTitle', 'off');\n\nhold on\nplot(theta, psi1, '-k')\nplot(theta, psi2, '-k')\nplot(theta, rho1, '-g')\nplot(theta, rho2, '-g')\nplot(theta, rho2next, '-g')\n%plot(theta, drho, '-r')\nplot(theta, rho, '-b')\nhold off\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of the normalized breathing cycle and first derivate\n\nfnorm = figure('Name', 'Normalized Breath Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n\nhold on\nplot(theta, drhonorm, '-r')\nplot(theta, rhonorm, '-b')\nhold off\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of a 1-cycle camshaft\n\nfcam1 = figure('Name', '1-Cycle Camshaft', 'Units', 'centimeters', 'NumberTitle', 'off');\n\n%hold on\n%polar(theta, drhocam, '-r')\npolar(theta, rhocam, '-b')\n%hold off\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of a 2-cycle camshaft\n\nfcam2 = figure('Name', '2-Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n\n%hold on;\n%polar(theta, drhocam2, '-r')\npolar(theta2, rhocam2, '-b')\n%hold off;\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of a 3-cycle camshaft\n\nfcam3 = figure('Name', '3-Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n\n%hold on;\n%polar(theta,drhocam3)\npolar(theta3, rhocam3)\n%hold off;\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n% The OxyGEN proyect by Profoty.xyz\n% Together against the Covid-19\n% V4.0 rev.17/03/2020\n% \n% Website/blog: oxygen.protofy.xyz\n% Contact: oxygen@protofy.xyz", "meta": {"author": "ProtofyTeam", "repo": "OxyGEN", "sha": "8a2870695e01928c07af2cc73ed86e5e53d8f726", "save_path": "github-repos/MATLAB/ProtofyTeam-OxyGEN", "path": "github-repos/MATLAB/ProtofyTeam-OxyGEN/OxyGEN-8a2870695e01928c07af2cc73ed86e5e53d8f726/Matlab Files/V4/Respirador_V4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7312265874949967}} {"text": "function value = r8_exprel ( x )\n\n%*****************************************************************************80\n%\n%% R8_EXPREL evaluates the exponential relative error term of an R8 argument.\n%\n% Discussion:\n%\n% The relative error term is ( exp ( x ) - 1 ) / x.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 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 exponential relative error term\n% at X.\n%\n persistent nterms\n persistent xbnd\n\n if ( isempty ( nterms ) )\n alneps = log ( r8_mach ( 3 ) );\n xn = 3.72 - 0.3 * alneps;\n xln = log ( ( xn + 1.0 ) / 1.36 );\n nterms = r8_aint ( xn - ( xn * xln + alneps ) / ( xln + 1.36 ) + 1.5 );\n xbnd = r8_mach ( 3 );\n end\n\n absx = abs ( x );\n\n if ( absx < xbnd )\n value = 1.0;\n elseif ( absx <= 0.5 )\n value = 0.0;\n for i = 1 : nterms\n value = 1.0 + value * x / ( nterms + 2 - i );\n end\n else\n value = ( exp ( x ) - 1.0 ) / 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/fn/r8_exprel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.7312229817760394}} {"text": "function [xroot, froot] = brent (f, x1, x2, rtol)\n\n% solve for a single real root of a nonlinear equation\n\n% Brent's method\n\n% input\n\n% f = objective function coded as y = f(x)\n% x1 = lower bound of search interval\n% x2 = upper bound of search interval\n% rtol = algorithm convergence criterion\n\n% output\n\n% xroot = real root of f(x) = 0\n% froot = function value at f(x) = 0\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal iter;\n\n% machine epsilon\n\neps = 2.23e-16;\n\ne = 0;\n\na = x1;\nb = x2;\n\nfa = feval(f, a);\n\nfb = feval(f, b);\n\nfc = fb;\n\nfor iter = 1:1:50 \n \n if (fb * fc > 0)\n c = a;\n fc = fa;\n d = b - a;\n e = d;\n end\n\n if (abs(fc) < abs(fb))\n a = b;\n b = c;\n c = a;\n fa = fb;\n fb = fc;\n fc = fa;\n end\n\n tol1 = 2 * eps * abs(b) + 0.5 * rtol;\n\n xm = 0.5 * (c - b);\n\n if (abs(xm) <= tol1 || fb == 0)\n break;\n end\n\n if (abs(e) >= tol1 && abs(fa) > abs(fb))\n s = fb / fa;\n \n if (a == c)\n p = 2 * xm * s;\n q = 1 - s;\n else\n q = fa / fc;\n r = fb / fc;\n p = s * (2 * xm * q * (q - r) - (b - a) * (r - 1));\n q = (q - 1) * (r - 1) * (s - 1);\n end\n\n if (p > 0)\n q = -q;\n end\n\n p = abs(p);\n\n min = abs(e * q);\n \n tmp = 3 * xm * q - abs(tol1 * q);\n \n if (min < tmp)\n min = tmp;\n end\n\n if (2 * p < min)\n e = d;\n d = p / q;\n else\n d = xm;\n e = d;\n end\n else\n d = xm;\n e = d;\n end\n\n a = b;\n fa = fb;\n\n if (abs(d) > tol1)\n b = b + d;\n else\n b = b + sign(xm) * tol1;\n end\n\n fb = feval(f, b);\n\nend\n\nxroot = b;\nfroot = fb;\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/38942-the-hohmann-orbit-transfer/brent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888302, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.731189931876668}} {"text": "%SerialLink.JACOB0 Jacobian in world coordinates\n%\n% J0 = R.jacob0(Q, OPTIONS) is the Jacobian matrix (6xN) for the robot in\n% pose Q (1xN), and N is the number of robot joints. The manipulator\n% Jacobian matrix maps joint velocity to end-effector spatial velocity V =\n% J0*QD expressed in the world-coordinate frame.\n%\n% Options::\n% 'rpy' Compute analytical Jacobian with rotation rate in terms of \n% roll-pitch-yaw angles\n% 'eul' Compute analytical Jacobian with rotation rates in terms of \n% Euler angles\n% 'trans' Return translational submatrix of Jacobian\n% 'rot' Return rotational submatrix of Jacobian \n%\n% Note::\n% - The Jacobian is computed in the end-effector frame and transformed to\n% the world frame.\n% - The default Jacobian returned is often referred to as the geometric \n% Jacobian, as opposed to the analytical Jacobian.\n%\n% See also SerialLink.jacobn, jsingu, deltatr, tr2delta, jsingu.\n\n\n% Copyright (C) 1993-2015, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction J0 = jacob0(robot, q, varargin)\n\n opt.rpy = false;\n opt.eul = false;\n opt.trans = false;\n opt.rot = false;\n \n opt = tb_optparse(opt, varargin);\n \n\t%\n\t% dX_tn = Jn dq\n\t%\n\tJn = jacobn(robot, q);\t% Jacobian from joint to wrist space\n\n\t%\n\t% convert to Jacobian in base coordinates\n\t%\n\tTn = fkine(robot, q);\t% end-effector transformation\n\tR = t2r(Tn);\n\tJ0 = [R zeros(3,3); zeros(3,3) R] * Jn;\n\n if opt.rpy\n rpy = tr2rpy( fkine(robot, q) );\n B = rpy2jac(rpy);\n if rcond(B) < eps\n error('Representational singularity');\n end\n J0 = blkdiag( eye(3,3), inv(B) ) * J0;\n elseif opt.eul\n eul = tr2eul( fkine(robot, q) );\n B = eul2jac(eul);\n if rcond(B) < eps\n error('Representational singularity');\n end\n J0 = blkdiag( eye(3,3), inv(B) ) * J0;\n end\n \n if opt.trans\n J0 = J0(1:3,:);\n elseif opt.rot\n J0 = J0(4:6,:);\n end\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/@SerialLink/jacob0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.731070109321628}} {"text": "function pols = klegeypols ( x, y, n )\n\n%*****************************************************************************80\n%\n%% KLEGEYPOLS evaluates scaled Legendre polynomials.\n%\n% Discussion:\n%\n% This routine evaluate a sequence of scaled Legendre polynomials\n% P_n(x/y) y^n, with the parameter y in [0,1].\n%\n% Licensing:\n%\n% This code is distributed under the GNU GPL license.\n%\n% Modified:\n%\n% 13 June 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This 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, real X, the evaluation point.\n%\n% Input, real Y, the parameter.\n%\n% Input, integer N, the highest degree to be evaluated.\n%\n% Output, real POLS(N+1), the polynomial values.\n%\n pols = zeros(n+1,1);\n\n pkp1 = 1.0;\n pols(1) = pkp1;\n if ( n == 0 )\n return\n end\n\n pk = pkp1;\n pkp1 = x;\n pols(2) = pkp1;\n if ( n == 1 )\n return\n end\n\n for k = 1 : n - 1\n pkm1 = pk;\n pk = pkp1;\n pkp1 = ( ( 2.0 * k + 1.0 ) * x * pk ...\n - k * pkm1 * y * y ) / ( k + 1.0 );\n pols(k+2) = pkp1;\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/tetrahedron_arbq_rule/klegeypols.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422647, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.731018443383297}} {"text": "function meanRot=meanRotation(param1,w)\n%%MEANROTATION Perform a weighted or unweighted average of a set of\n% rotation matrices or unit quaternions (which represent\n% directions). The weights are scalar and the cost function\n% finds the rotation matrix REst to minimize the sum of \n% w(i)*norm(REst-R{i},'fro'), where R{i} is the ith rotation\n% matrix to be averaged (either given explicitly as a\n% rotation matrix or given as a quaternion).\n%\n%INPUTS: param1 A 3X3XN hypermatrix of N rotation matrices that are to be\n% averaged or a 4XN set of unit-quaternions that are to be\n% averaged. The function automatically detects whether\n% rotation matrices or quaternions were passed. The\n% handedness of the quaternions does not matter.\n% w An optional set of N weights for averaging the rotations.\n% If omitted, all of the rotation matrices/ unit quaternions\n% in param1 are equally weighted.\n%\n%OUTPUTS: meanRot The weighted mean 3X3 rotation matrix or 4X1 rotation\n% quaternion, depending on the data type passed in param1.\n%\n%The algorithm of [1] for performing a weighted average of quaternions or\n%rotation matrices is used. Note that the paper contains an additional\n%technique for averaging quaternions with non-scalar weights, which is not\n%implemented here.\n%\n%A quaternion can represent an orientation (rotation) in space as a 4X1\n%unit vector. However, one cannot simply take the weighted average of a\n%set of quaternions to get an average quaternion (that is then normalized)\n%to represent the average rotation, because the quaternion representation\n%is not unique. Thus, while q and -q represent the same rotation, they\n%affect such an average differently, which is bad. This is why the more\n%complicated algorithms of the above paper are used.\n%\n%REFERENCES:\n%[1] F. L. Markley, Y. Cheng, J. L. Crassidis, and Y. Oshman, \"Averaging\n% quaternions,\" Journal of Guidance, Control, and Dynamics, vol. 30,\n% no. 4, pp. 1193-1196, Jul. - Aug. 2007.\n%\n%September 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(size(param1,1)==3)\n usingQuaternions=false;\n RotMats=param1;\n \n numVals=size(param1,3);\nelse\n usingQuaternions=true;\n q=param1;\n \n numVals=size(param1,2);\nend\n\nif(nargin<2)\n w=ones(numVals,1); \nend\n\n%If quaternions are being averaged rather than rotation matrices.\nif(usingQuaternions)\n %Build M as in Equation 2 of [1].\n M=zeros(4,4);\n for curQuat=1:numVals\n M=M+w(curQuat)*(q(:,curQuat)*q(:,curQuat)');\n end\n\n %The solution to the cost function in Equation 13 is the eigenvector\n %corresponding to the largest eigenvalue in M.\n [V,D]=eig(M);\n %Get the indices of the sorted eigenvalues (and thus of the\n %corresponding eigenvectors).\n [~,idx]=sort(diag(D),'descend');\n %The rotation quaternion is the eigenvector associated with the\n %largest eigenvalue.\n meanRot=V(:,idx(1));%A quaternion\nelse%If rotation matrices are being averaged rather than quaternions.\n %Build B as in Equation 5 in [1].\n B=zeros(3,3);\n for curRot=1:numVals\n B=B+w(curRot)*RotMats(:,:,curRot); \n end\n\n %This solves the equivalent formulation of Wahba's problem for\n %Equation 4.\n meanRot=findTransParam(B,eye(3));%A rotation matrix.\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/meanRotation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7310184350741452}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% LMS Algorithm\n% Author : Arsal Butt\n% Contact information : \n% School of Electrical & Electronic Engineering,\n% University of Bradford,\n% Bradford, BD7 1DP,\n% United Kingdom .\n% email : a.butt7@bradford.ac.uk \n% Date : 03-8-2010\n% Version : 1.0.2\n% Reference : Statistical and Adaptive Signal Processing By Dimitris G. Manolakis, Vinay K. Ingle & Stephen M. Kogon. \n% Note : The author doesn't take any responsibility for any harm caused by\n% the use of this code;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Use N iterations of an adapting filter system to identify an unknown\n% Mth-order FIR filter.\nfunction lmsalgorithm = lms()\nsysorder = input('Enter the System Order? ')\nN = input('Enter the number of Itterations? ')\nif ((sysorder >= 2) && (N >= 2))\n x = randn(N,1); % Input to the filter \nb = fir1(sysorder-1,0.5); % FIR system to be identified \nn = 0.1*randn(N,1); % Uncorrelated noise signal \nd = filter(b,1,x)+n; % Desired signal = output of H + Uncorrelated noise signal\nw = zeros (sysorder, 1) ; % Initially filter weights are zero\nfor n = sysorder : N \n\tu = x(n:-1:n-sysorder+1) ;\n y(n)= w' * u; % output of the adaptive filter\n e(n) = d(n) - y(n) ; % error signal = desired signal - adaptive filter output\n mu=0.008;\n w = w + mu * u * e(n) ; % filter weights update\nend \nhold on\nplot(d,'g')\nplot(y,'r');\nsemilogy((abs(e)),'m') ;\ntitle('System output') ;\nxlabel('Samples')\nylabel('True and estimated output')\nlegend('Desired','Output','Error')\naxis([0 N -2 2.5])\nfigure\nplot(b', 'k+')\nhold on\nplot(w, 'r*')\nlegend('Actual weights','Estimated weights')\ntitle('Comparison of the actual weights and the estimated weights') ;\nelse ('System Order and numbers of Itterations should be greater than 1')\nend\n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28313-lms-algorithm-demonstration/lms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7310184330102972}} {"text": "function value = triangulation_area ( node_num, node_xy, element_order, ...\n element_num, element_node )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_AREA computes the area of a triangulation.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 December 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, real NODE_XY(NODE_NUM,2), the coordinates of the nodes.\n%\n% Input, integer ELEMENT_ORDER, the order of the triangles.\n%\n% Input, integer ELEMENT_NUM, the number of triangles.\n%\n% Input, integer ELEMENT_NODE(ELEMENT_NUM,ELEMENT_ORDER),\n% the nodes making up each triangle.\n%\n% Output, real VALUE, the area.\n%\n value = 0.0;\n\n for element = 1 : element_num\n\n element_xy(1:3,1:2) = node_xy(element_node(element,1:3),1:2);\n\n element_area = 0.5 * abs ( ...\n element_xy(1,1) * ( element_xy(2,2) - element_xy(3,2) ) ...\n + element_xy(2,1) * ( element_xy(3,2) - element_xy(1,2) ) ...\n + element_xy(3,1) * ( element_xy(1,2) - element_xy(2,2) ) );\n\n value = value + element_area;\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/shoreline/triangulation_area.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7309876982962854}} {"text": "internet = load('data/internet.dat')';\ny = internet(2, 2:end);\nfprintf(1, '\\n');\n\nP = 5;\nQ = 5;\n\n%% Model selection for complete series %%\nfprintf(1, 'AIC for ARMA(p, q) models on complete data:\\n');\nfprintf(1, ' '); for q = 0:Q, fprintf(1, '%-12d', q); end; fprintf(1, '\\n');\nlogL = zeros(P+1, Q+1);\nAIC = zeros(P+1, Q+1);\narma = cell(P+1, Q+1);\nfor p = 0 : P\n fprintf(1, '%-4d', p);\n for q = 0 : Q\n model = ssm_arma(p, q);\n [arma{p+1, q+1} logL(p+1, q+1) output] = estimate(y, model, [repmat(0.3, 1, model.w-1) 10], [], 'fmin', 'bfgs', 'disp', 'off');\n AIC(p+1, q+1) = output.AIC;\n fprintf(1, '%-12g', AIC(p+1, q+1));\n end\n fprintf(1, '\\n');\nend\n[m i] = min(AIC(:)); temp = AIC(i); AIC(i) = Inf;\nfprintf(1, 'ARMA(%d, %d) found to be the best model, ', mod(i-1, P+1), floor((i-1)/(P+1)));\n[m j] = min(AIC(:)); AIC(i) = temp;\nfprintf(1, 'ARMA(%d, %d) is the second best.\\n\\n', mod(j-1, P+1), floor((j-1)/(P+1)));\n\n%% Model selection for data with missing values %%\nymis = y; ymis([6 16 26 36 46 56 66 72 73 74 75 76 86 96]) = NaN;\nfprintf(1, 'AIC for ARMA(p, q) models on data w/ missing observations:\\n');\nfprintf(1, ' '); for q = 0:Q, fprintf(1, '%-12d', q); end; fprintf(1, '\\n');\nlogLmis = zeros(P+1, Q+1);\nAICmis = zeros(P+1, Q+1);\narmamis = cell(P+1, Q+1);\nfor p = 0 : P\n fprintf(1, '%-4d', p);\n for q = 0 : Q\n model = ssm_arma(p, q);\n [armamis{p+1, q+1} logLmis(p+1, q+1) output] = estimate(ymis, model, [repmat(-0.1, 1, model.w-1) 1], [], 'fmin', 'bfgs', 'disp', 'off');\n AICmis(p+1, q+1) = output.AIC;\n fprintf(1, '%-12g', AICmis(p+1, q+1));\n end\n fprintf(1, '\\n');\nend\n[m i] = min(AICmis(:)); temp = AICmis(i); AICmis(i) = Inf;\nfprintf(1, 'ARMA(%d, %d) found to be the best model, ', mod(i-1, P+1), floor((i-1)/(P+1)));\n[m j] = min(AICmis(:)); AICmis(i) = temp;\nfprintf(1, 'ARMA(%d, %d) is the second best.\\n\\n', mod(j-1, P+1), floor((j-1)/(P+1)));\n\n%% Forecast with ARMA(1, 1) on the complete data %%\n[armafore logL] = estimate(y, ssm_arma(1, 1), 0.1);\nyf = signal(kalman([y repmat(NaN, 1, 20)], armafore), armafore);\nfigure('Name', 'Internet series forecast');\nplot(yf, 'DisplayName', 'forecast'), hold all, scatter(1:length(y), y, 10, 'r', 's', 'filled', 'DisplayName', 'data'), hold off, ylim([-15 15]), legend('show');\nif ispc, set(gcf, 'WindowStyle', 'docked'); end\n\n%% Forecast with ARMA(1, 1) on the data w/ missing values %%\n[armafore logLmis] = estimate(ymis, ssm_arma(1, 1), 0.1);\nymisf = signal(kalman([ymis repmat(NaN, 1, 20)], armafore), armafore);\nfigure('Name', 'Internet series in-sample one-step and out-of-sample forecasts');\nplot(ymisf), hold all, scatter(1:length(ymis), ymis, 10, 'r', 's', 'filled'), hold off, ylim([-15 15]);\nif ispc, set(gcf, 'WindowStyle', 'docked'); end\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/SIFT-private/external/ssm-1.0.1/ssm-release/demos/demo_internet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7309876982239853}} {"text": "function [jac,invjac,phi,dphidx,dphidy] = deriv(s,t,xl,yl)\n%deriv evaluates derivatives of bilinear shape functions \n% [jac,invjac,phi,dphidx,dphidy] = deriv(s,t,xl,yl);\n% input\n% s reference element x coordinate \n% t reference element y coordinate\n% xl physical element x vertex coordinates \n% yl physical element y vertex coordinates \n% output\n% jac elementwise jacobian (evaluated at (s,t))\n% invjac elementwise inverse of jacobian\n% phi elementwise shape functions\n% dphidx x derivatives of phi\n% dphidy y derivatives of phi\n%\n% IFISS function: DJS; 4 March 2005.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage \n nel=length(xl(:,1));\n zero_v = zeros(nel,1);\n one_v = ones(nel,1);\n%\n% evaluate shape functions \n [phi_e,dphids,dphidt] = shape(s,t);\n%\n dxds = zero_v;\n dxdt = zero_v;\n dyds = zero_v;\n dydt = zero_v;\n\t jac = zero_v;\n invjac = zero_v; \n%\n for ivtx = 1:4\n dxds(:) = dxds(:) + xl(:,ivtx) .* one_v*dphids(ivtx);\n dxdt(:) = dxdt(:) + xl(:,ivtx) .* one_v*dphidt(ivtx);\n dyds(:) = dyds(:) + yl(:,ivtx) .* one_v*dphids(ivtx);\n dydt(:) = dydt(:) + yl(:,ivtx) .* one_v*dphidt(ivtx);\n end\n%\n jac(:) = dxds(:).*dydt(:) - dxdt(:).*dyds(:);\n%\n% check element Jacobian\n if any(jac < 1e-9)\n fprintf('Bad element warning ...\\n')\n if any(jac <= 0.0)\n error('singular Jacobian ... Aborted ...')\n end\n end\n invjac(:) = one_v ./ jac(:);\n%\n for ivtx = 1:4\n phi(:,ivtx) = phi_e(ivtx)*one_v;\n\t\t dphidx(:,ivtx) = ( dphids(:,ivtx).*dydt(:) - dphidt(:,ivtx).*dyds(:));\n dphidy(:,ivtx) = (-dphids(:,ivtx).*dxdt(:) + dphidt(:,ivtx).*dxds(:));\n end\n return\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms866/diffusion/deriv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7309876877575313}} {"text": "function dq = DQconj(dv,WHICHCONJ)\n\n% DQCONJ Dual quaternion conjugate\n%\n% DQ = DQCONJ(DV) returns the dual quaternion conjugate of the dual\n% quaternion DV. DV (resp. DQ) is a 8-vector representing a dual \n% quaternion or an array 8*N (column i represents dual quaternion i)\n% where N is the number of dual quaternions. The default type of \n% conjugate is 'point' (see below). DQ has the same size as DV.\n%\n% DQ = DQCONJ(DV,WHICHCONJ) returns the type of dual quaternion conjugate\n% corresponding to WHICHCONJ (DV = Q0+eps*Q1):\n% - 'point': mixed conjugate: dV* = Q0*-eps*Q1* (used for point\n% transformations).\n% - 'line': quaternion conjugate: dV* = Q0*+eps*Q1* (used for line\n% transformations).\n% - 'other': dual number conjugate: dV* = Q0-eps*Q1\n%\n% See also QCONJ, DQMULT\n\nif nargin < 2\n WHICHCONJ = 'point'; % default is 'mixed' conjugate' (point transformation)\nend\n\n\nsdv = size(dv);\nif sdv == [1 8], dv = dv'; sdv = size(dv); end\n\n% wrong size\nif sdv(1) ~= 8 \n error('DualQuaternion:DQconj:wrongsize',...\n '%d rows in array dv. It should be 8.',sdv(1));\nend\n\nn = sdv(2);\ndq = zeros(8,n);\nswitch WHICHCONJ\n case 'point' % % case of point transformation\n dq(1:4,:) = Qconj(dv(1:4,:));\n dq(5:8,:) = -Qconj(dv(5:8,:));\n case 'line' % case of line transformation\n dq(1:4,:) = Qconj(dv(1:4,:));\n dq(5:8,:) = Qconj(dv(5:8,:));\n case 'other' % dual number conjugate\n dq(1:4,:) = dv(1:4,:);\n dq(5:8,:) = -dv(5:8,:);\n otherwise\n error('DualQuaternion:DQconj:wrongsize',...\n 'WHICHCONJ must be ''point'', ''line'' or ''other'' ');\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/39288-dual-quaternion-toolbox/Dual quaternion toolbox v2/DQconj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7309876876852313}} {"text": "function z = compute_zeros(x,y)\n\n% compute_zeros - compute the location of zeros\n%\n% z = compute_zeros(x,y)\n%\n% find the roots z of f(z)=0 where f is sampled at y=f(x)\n%\n% Copyright (c) 2007 Gabriel Peyre\n\nI = find( y(1:end-1).*y(2:end) < 0);\n\nd = y(I+1)-y(I); \nJ = find(d==0); d(J) = 1;\nz = ( x(I).*y(I+1)-x(I+1).*y(I) )./d;\nz(J) = (x(I(J))+x(I(J)+1))/2;\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_misc/compute_zeros.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7309876837010894}} {"text": "% Fig. 8.13 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n%\n\nclear all;\n%close all;\nclf\n\nw=logspace(-1,2,100);\nl=length(w);\n\n% s-plane\nnum=5;\nden=[1 5];\n[magC,phaseC]=bode(num,den,w);\nsubplot(2,1,1),\nloglog(w,magC,'-')\naxis([.1 100 .01 1]);\nylabel('Magnitude')\n%xlabel('Frequency (rad/sec)')\ntitle('Fig. 8.13 (a) 100 rad/sec T=1/15 sec')\nnicegrid\nhold on\n\n% T = 1/15 sec\nT = 1/15;\n\n% MPZ\n\nnum=.143*[1 1];\nden=[1 -.715];\n[mag1,phase]=dbode(num,den,T,w);\n\n% MMPZ\n\nnum=.285;\nden=[1 -.715];\n[mag2,phase]=dbode(num,den,T,w);\n\n% Tustins\n\nnum=.143*[1 1];\nden=[1 -.713];\n[mag3,phase]=dbode(num,den,T,w);\n\nloglog(w,mag1,'--',w,mag2,'--',w,mag3,'-.')\nhold off\n\n% T = 1/3 sec\n\nsubplot(2,1,2),loglog(w,magC,'-')\nylabel('Magnitude')\nxlabel('Frequency (rad/sec)')\ntitle('(b) 20 rad/sec T=1/3 sec')\nnicegrid\nhold on\n\nT = 1/3;\n\n% MPZ\n\nnum=.405*[1 1];\nden=[1 -.189];\nwp=w;\nwp=wp(wp < 24);\n[mag1,phase]=dbode(num,den,T,wp);\n\n% MMPZ\n\nnum=.811;\nden=[1 -.189];\n[mag2,phase]=dbode(num,den,T,wp);\n\n% Tustins\n\nnum=.454*[1 1];\nden=[1 -.0914];\n[mag3,phase]=dbode(num,den,T,wp);\n\nloglog(wp,mag1,'--',wp,mag2,'--',wp,mag3,'-.')\n\nhold off\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig8_13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7309876729454348}} {"text": "function x = beta_binomial_cdf_inv ( cdf, a, b, c )\n\n%*****************************************************************************80\n%\n%% BETA_BINOMIAL_CDF_INV inverts the Beta Binomial CDF.\n%\n% Discussion:\n%\n% A simple discrete approach is used.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real CDF, the value of the CDF.\n%\n% Input, real A, B, parameters of the PDF.\n% 0.0D+00 < A,\n% 0.0D+00 < B.\n%\n% Input, integer C, a parameter of the PDF.\n% 0 <= C.\n%\n% Output, integer X, the smallest X whose cumulative density function\n% is greater than or equal to CDF.\n%\n if ( cdf <= 0.0 )\n\n x = 0;\n\n else\n\n cum = 0.0;\n\n for y = 0 : c\n\n pdf = beta ( a + y, b + c - y ) / ( ( c + 1 ) ...\n * beta ( y + 1, c - y + 1 ) * beta ( a, b ) );\n\n cum = cum + pdf;\n\n if ( cdf <= cum )\n x = y;\n return\n end\n\n end\n\n x = c;\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/beta_binomial_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7309599390607592}} {"text": "%DEMO_REGRESSION_MEANF Regression problem demonstration for GP model with a\n% mean function\n%\n% Description\n% The regression problem consist of a data with one input\n% variable and one output variable with Gaussian noise. The\n% problem is modelled with Full GP model with gaussian\n% likelihood and a specified mean function. The mean function m\n% is a weighted sum of some basis functions h, where\n%\n% m=h'*Beta\n%\n% and we have set a gaussian prior for the weights Beta\n%\n% Beta ~ N(b,B)\n%\n% Inference is done according to Rasmussen and Williams (2006)\n% p. 27-29.\n%\n% In this demonstration the data is from a function:\n%\n% y = 2 + x + x^2 + 4*cos(x)*sin(x) + epsilon\n%\n% and we define the base functions to be:\n%\n% h1(x)=x^2, h2(x)=x, h3(x)=2 \n%\n% References:\n% Rasmussen, C. E. and Williams, C. K. I. (2006). Gaussian\n% Processes for Machine Learning. The MIT Press.\n\n% Copyright (c) 2010 Tuomas Nikoskinen\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% Create the data\n x=[-2:0.6:2]';\n res=4*cos(x).*sin(x)+0.4*randn(size(sin(x)));\n y= 2 + x + x.^2 + res;\n%---------------\n \ngpcf = gpcf_sexp('lengthScale', [0.5], 'magnSigma2', .5);\nlik = lik_gaussian('sigma2', 0.4^2);\n\n% Initialize base functions for GP's mean function.\ngpmf1 = gpmf_constant('prior_mean',.3,'prior_cov',1);\ngpmf2 = gpmf_linear('prior_mean',.3,'prior_cov',1);\ngpmf3 = gpmf_squared('prior_mean',.3,'prior_cov',1);\n\n% Initialize gp structure\ngp = gp_set('lik', lik, 'cf', gpcf, 'meanf', {gpmf1,gpmf2,gpmf3});\n\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3,'DerivativeCheck','on');\n% Optimize with the scaled conjugate gradient method\ngp=gp_optim(gp,x,y,'opt',opt);\n\n% Predictions\nxt=[-3:0.1:3]';\n[Eft, Varft] = gp_pred(gp, x, y, xt);\n\n% PLOT THE DATA\n\nfigure\nm=plot(xt,Eft,'k','lineWidth',2);\nhold on\nplot(xt,Eft+2*sqrt(Varft),'k--')\nhold on\nm95=plot(xt,Eft-2*sqrt(Varft),'k--');\nhold on\nhav=plot(x,y, 'ro','markerSize',6,'MarkerFaceColor','r');\nhold on\nh=plot(xt,2+xt+xt.^2+4*cos(xt).*sin(xt),'b--','lineWidth',2);\nhold on\nmmmean=plot(xt,2+xt+xt.^2,'r--','lineWidth',1);\nlegend([m m95 h mmmean hav],'prediction','95%','f(x)','mean function','observations');\nxlabel('input x')\nylabel('output y')\ntitle('GP regression with a mean function')\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/gp/demo_regression_meanf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7309599270438721}} {"text": "function z = EulerToQuaternion(phi, theta, psi)\n%\n%\nsinPhi = sin(phi/2); cosPhi = cos(phi/2);\nsinTheta = sin(theta/2); cosTheta = cos(theta/2);\nsinPsi = sin(psi/2); cosPsi = cos(psi/2);\n\nz = [ cosPhi*cosTheta*cosPsi + sinPhi*sinTheta*sinPsi;\n sinPhi*cosTheta*cosPsi - cosPhi*sinTheta*sinPsi;\n cosPhi*sinTheta*cosPsi + sinPhi*cosTheta*sinPsi;\n cosPhi*cosTheta*sinPsi - sinPhi*sinTheta*cosPsi;\n ];", "meta": {"author": "philbooks", "repo": "Kalman-Filter-for-Beginners", "sha": "5190a723dcbf96eacda71ed56abddb3a11779a82", "save_path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners", "path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners/Kalman-Filter-for-Beginners-5190a723dcbf96eacda71ed56abddb3a11779a82/13.ARS/EulerToQuaternion.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924818279466, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.7309505787389353}} {"text": "function cdf = frechet_cdf ( x, alpha )\n\n%*****************************************************************************80\n%\n%% FRECHET_CDF evaluates the Frechet CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real ALPHA, the parameter.\n% It is required that 0.0 < ALPHA.\n%\n% Input, real X, the argument of the CDF.\n%\n% Output, real CDF, the value of the CDF.\n%\n if ( alpha <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FRECHET_CDF - Fatal error!\\n' );\n fprintf ( 1, ' ALPHA <= 0.0.\\n' );\n error ( 'FRECHET_CDF - Fatal error!' );\n end\n\n if ( x <= 0.0 )\n cdf = 0.0;\n else\n cdf = exp ( - 1.0 / x^alpha );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/frechet_cdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8128673201042493, "lm_q1q2_score": 0.7308663843898606}} {"text": "function [P,exitCode]=RiccatiPostNoClutter(H,F,R,Q,PD,RelTol,AbsTol,maxIter)\n%%RICCATIPOSTNOCLUTTER Solve the posterior Riccati equation that has been\n% modified for a probability of detection less\n% than or equal to 1. This provides the average \n% asymptotic covariance of a linear Kalman filter with\n% linear measurements just after a (possible with\n% probability PD) measurement update.\n%\n%INPUTS: 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 discrete-\n% time k+1 is modeled as F times the state at time k plus zero-\n% mean Gaussian process noise with covariance matrix Q.\n% R The zDim X zDim measurement covariance matrix.\n% Q The xDim X xDim process noise covariance matrix. This can not be\n% a singular matrix.\n% PD The optional detection probability of the target at each scan.\n% If omitted, PD is assumed to be one.\n% RelTol The maximum relative error tolerance allowed, a positive scalar.\n% This tolerance applies to all elements in the matrix and is only\n% needed if PD<1. If omitted or an empty matrix is passed, the\n% default value of 1e-13 is used.\n% AbsTol The absolute error tolerance allowed, a positive scalar. This\n% tolerance applies to all elements in the matrix and is only\n% needed if PD<1. If omitted or an empty matrix is passed, the\n% default value of 1e-10 is used.\n% maxIter An optional integer specifying the maximum number of iterations.\n% If omitted or an empty matrix is passed, the default is 5000.\n%\n%OUTPUTS: P The average asymptotic error covariance matrix of the linear\n% Kalman filter with a probability of detection of PD after a\n% (possible) measurement update.\n% exitCode This is zero if convergence is achieved and 1 if it is not\n% achieved.\n%\n%The notion of a Riccati equation with a detection probability less than\n%one is discussed in [1]. However, they do not explicitly write out the\n%posterior form. The posterior recursion goes from P_{k|k} to P_{k+1|k+1}.\n%This stands in contrast to the prior Riccati equation, which expresses the\n%transition from P_{k|k-1} to P_{k+1|k}.\n%\n%The posterior Riccati equation is\n%P=F*P*F'+Q-PD*(F*P*F'*H'+Q*H')*inv(H*F*P*F'*H'+H*Q*H'+R)*(F*P*F'*H'+Q*H')'\n%and is derived by substituting the prediction step into the measurement\n%update step of the linear Kalman filter with additive process noise and\n%additive measurement noise.\n%\n%EXAMPLE:\n% T=1;\n% F=FPolyKal(T,6,1);\n% q0=1;\n% Q=QPolyKal(T,6,1,q0);\n% R=diag([10;10;10]);\n% 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% P=RiccatiPostNoClutter(H,F,R,Q,PD)\n%\n%REFERENCES:\n%[1] Y. Boers and H. Driessen, \"Modified Riccati equation and its\n% application to target tracking,\" IEE Proceedings Radar, Sonar and\n% Navigation, vol. 153, no. 1, pp. 7-12, Feb. 2006.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<5||isempty(PD))\n PD=1; \nend\n\nif(nargin<6||isempty(AbsTol))\n AbsTol=1e-13;\nend\n\nif(nargin<7||isempty(RelTol))\n RelTol=1e-10;\nend\n\nif(nargin<8||isempty(maxIter))\n maxIter=5000; \nend\n\n%Get an initial estimate by solving the Riccati equation with PD=1.\nAD=F';\nBD=F'*H';\nSD=Q*H';\nRD=H*Q*H'+R;\nQD=Q;\nPPrev=RiccatiSolveD(AD,BD,QD,RD,SD);\nexitCode=0;\nif(PD~=1)\n %Now, iterate the Riccati equation with PD<1 until convergence of the\n %Frobenis norm or until a maximum number of iterations has occurred.\n curIter=0;\n while(curIter1,\n e = edgelist(K);ne = size(e,1); % get a sorted list of edges\nend\n\nif level==2 || level==4, % check each set of two edges of the convex hull (which obviously includes case '1' above)\n for i = 1:ne, % go through edge list\n va = xyz(e(i,1),:)-xyz(e(i,2),:);\n va = va/norm(va);\n for j = i+1:ne, % go through remaining edge list\n vb = xyz(e(j,1),:)-xyz(e(j,2),:);\n vb = vb - dot(va,vb)*va; % orthogonaylize second edge wrt first\n nv = cross(va,vb); % normal to plane formed by the two edges\n if sum(abs(nv))>0,\n vb = vb/norm(vb);nv = nv/norm(nv);\n [alp,bet,gam]=euler123(va,vb,nv);\n [d, rotmat, minmax] = checkbox(alp,bet,gam,xyz,metric,d,rotmat,minmax);\n end\n end\n end\nend\n\nif level==3 || level==4, % check edge as parallel to one edge of the bounding box\n for i = 1:ne, % go through edge list\n % calculate rhs with edge as one of the axes\n va = xyz(e(i,1),:)-xyz(e(i,2),:);\n vb = [va(2),-va(1),0];if sum(abs(vb))==0,vb = [va(3),0,-va(1)];end\n va = va/norm(va);vb = vb/norm(vb);\n nv = cross(va,vb);\n % check all combinations of possible rhs\n [alp,bet,gam]=euler123(va,vb,nv);\n [d, rotmat, minmax] = checkbox(alp,bet,gam,xyz,metric,d,rotmat,minmax);\n [alp,bet,gam]=euler123(vb,nv,va);\n [d, rotmat, minmax] = checkbox(alp,bet,gam,xyz,metric,d,rotmat,minmax);\n [alp,bet,gam]=euler123(nv,va,vb);\n [d, rotmat, minmax] = checkbox(alp,bet,gam,xyz,metric,d,rotmat,minmax);\n end\nend\n\n% get the output values\nh = [minmax(1,1),minmax(1,2),minmax(1,3); % xmin,ymin,zmin\n minmax(2,1),minmax(1,2),minmax(1,3); % xmax,ymin,zmin\n minmax(2,1),minmax(2,2),minmax(1,3); % xmax,ymax,zmin\n minmax(1,1),minmax(2,2),minmax(1,3); % xmin,ymax,zmin\n minmax(1,1),minmax(1,2),minmax(2,3); % xmin,ymin,zmax\n minmax(2,1),minmax(1,2),minmax(2,3); % xmax,ymin,zmax\n minmax(2,1),minmax(2,2),minmax(2,3); % xmax,ymax,zmax\n minmax(1,1),minmax(2,2),minmax(2,3); % xmin,ymax,zmax\n ];\n\ncornerpoints = h*inv(rotmat); % minimal boxes' cornerpoints\nh = minmax(2,:)-minmax(1,:);\nvolume = h(1)*h(2)*h(3);\nsurface = 2*(h(1)*h(2)+h(2)*h(3)+h(3)*h(1));\nedgelength = 4*sum(h);\n\n% all done\n\nend % mainline end\n\nfunction [alpha,beta,gamma]=euler123(v1,v2,nv)\n% calculate Euler angles for the x, y', z'' Euler sequence\n% see also\n% http://en.wikipedia.org/wiki/Euler_angles\n% http://de.wikipedia.org/wiki/Eulersche_Winkel\n\n% --> beta\nbeta = asin(sign(nv(:,1)).*min(1,abs(nv(:,1))));\n% --> alpha\nalpha=0*beta;\ni1 = find(nv(:,1)==1);i2 = setdiff(1:size(nv,1),i1);\nif ~isempty(i1), \n alpha(i1) = asin(sign(v2(i1,3)).*min(1,abs(v2(i1,3))));\nend\nif ~isempty(i2),\n alpha(i2) = acos(sign(nv(i2,3)./cos(beta(i2))).*min(1,abs(nv(i2,3)./cos(beta(i2)))));\n i3 = find(sign(nv(i2,2)) ~= sign(-sin(alpha(i2)).*cos(beta(i2))));\n alpha(i2(i3)) = -alpha(i2(i3));\nend\n% --> gamma\ngamma = 0*alpha;\nif ~isempty(i2),\n singamma = -v2(i2,1)./cos(beta(i2));\n i21 = find(v1(i2,1)>=0);i22=setdiff(1:length(i2),i21);\n gamma(i2(i21)) = asin(sign(singamma(i21)).*min(1,abs(singamma(i21))));\n gamma(i2(i22)) = -pi-asin(sign(singamma(i22)).*min(1,abs(singamma(i22))));\nend\n\nend % function euler123\n\nfunction [d, rotmat, minmax] = checkbox(alpha,beta,gamma,xyz,metric,d,rotmat,minmax)\n\n% will need a 3x3 rotation matrix through (Euler X, Y', Z'')-angles alpha, beta and gamma\nRmat = @(alpha,beta,gamma) [cos(beta)*cos(gamma) -cos(beta)*sin(gamma) sin(beta)\n sin(alpha)*sin(beta)*cos(gamma)+cos(alpha)*sin(gamma) -sin(alpha)*sin(beta)*sin(gamma)+cos(alpha)*cos(gamma) -sin(alpha)*cos(beta)\n -cos(alpha)*sin(beta)*cos(gamma)+sin(alpha)*sin(gamma) cos(alpha)*sin(beta)*sin(gamma)+sin(alpha)*cos(gamma) cos(alpha)*cos(beta)];\n\nrot = Rmat(alpha,beta,gamma);\nxyz_i = xyz*rot; % now the actual face is in the x-y plane\n\nx_i = xyz_i(:,1);y_i = xyz_i(:,2); % .. so take only the x and y values\nrot2 = minrect(x_i,y_i,metric); % find the optimal rotation around z-axis\nrot = rot*[[rot2,[0;0]];[0,0,1]]; % combine that with the formar rotation\nxyz_i = xyz*rot; % now again the xyz_i values, but in optimal axisparallel shape\n\nxyzmin = min(xyz_i,[],1);\nxyzmax = max(xyz_i,[],1);\nh = xyzmax-xyzmin;\n\nif metric == 'v', % smallest volume\n d_i = h(1)*h(2)*h(3);\nelseif metric == 's', % smallest surface\n d_i = h(1)*h(2)+h(2)*h(3)+h(3)*h(1);\nelse, % smallest sum of edges\n d_i = sum(h);\nend\n\nif d_i < d,\n d = d_i;\n rotmat = rot;\n minmax = [xyzmin;xyzmax];\nend\n\nend % function checkbox\n\nfunction rot = minrect(x,y,metric)\n% see comments from minboundrect of John d'Errico\n% i am only interested in the additional rotation matrix around [0,0,1]\nedges = convhull(x,y,{'Qt'});\nx = x(edges);y = y(edges);\nind = 1:length(x)-1;\nRmat = @(theta) [cos(theta) sin(theta);-sin(theta) cos(theta)];\nedgeangles = atan2(y(ind+1) - y(ind),x(ind+1) - x(ind));edgeangles = unique(mod(edgeangles,pi/2));\nnang = length(edgeangles);\narea = inf;perimeter = inf;met = inf;xy = [x,y];\nfor i = 1:nang\n rot_i = Rmat(-edgeangles(i));xyr = xy*rot_i;\n xymin = min(xyr,[],1);xymax = max(xyr,[],1);\n A_i = prod(xymax - xymin);P_i = 2*sum(xymax-xymin);\n if metric=='v', M_i = A_i;else, M_i = P_i;end\n if M_i' )\n ylabel ( '<--- T --->' );\n zlabel ( '<---U(X,T)--->' );\n filename = 'example2.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saved solution plot in file \"%s\"\\n', filename );\n%\n% Plot the initial condition, U at time 0.\n%\n figure ( 2 )\n plot ( xmesh, u(1,:), 'LineWidth', 3 );\n grid on\n title ( 'Example 2: Initial Condition', 'Fontsize', 16 );\n xlabel ( '<--- X --->' )\n ylabel ( '<--- U(X,T0) --->' );\n filename = 'example2_ic.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Saved initial condition plot in file \"%s\"\\n', filename );\n%\n% Plot the solution U at a fixed point, with time varying.\n%\n figure ( 3 )\n mid = 1 + floor ( 55 * ( nx - 1 ) / 100 );\n plot ( tspan, u(:,mid), 'LineWidth', 3 );\n grid on\n title ( 'Example 2: Time evolution of solution at X=5.0', 'Fontsize', 16 );\n xlabel ( '<--- T --->' )\n ylabel ( '<--- U(5.0,T) --->' );\n filename = 'example2_profile.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Saved time evolution plot in file \"%s\"\\n', filename );\n%\n% Animate the profile.\n% I wish I could also display the running value of time, but it\n% does not seem possible.\n%\n figure ( 4 )\n fig = plot ( xmesh, u(1,:), 'erase', 'xor' );\n title ( 'Profile animation', 'Fontsize', 16 );\n grid on\n for k = 2 : length ( tspan )\n set ( fig, 'xdata', xmesh, 'ydata', u(k,:) );\n pause ( 0.4 );\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EXAMPLE2:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction value = degwave ( x )\n\n%*****************************************************************************80\n%\n%% DEGWAVE determines the value of UBAR in the equation.\n%\n% Discussion:\n%\n% MATLAB's zero finder \"fzero()\" must be called in order to determine\n% the value of UBAR.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the spatial location.\n%\n% Output, real VALUE, the value of A(X).\n%\n if ( x < -35.0 )\n value = 1.0;\n elseif ( 2.0 < x )\n guess = 1.0 / x;\n value = fzero ( @f, guess, [], x );\n elseif ( -2.5 < x )\n guess = 0.6;\n value = fzero ( @f, guess, [], x );\n else\n guess = 1.0 - exp ( - 2.0 ) * exp ( x );\n value = fzero ( @f, guess, [], x );\n end\n\n return\nend\nfunction value = f ( u, x )\n\n%*****************************************************************************80\n%\n%% F evaluates a function, which should be zero if U = UBAR.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real U, the estimated solution value at X.\n%\n% Input, real X, the spatial location.\n%\n% Output, real VALUE, the function value.\n%\n value = ( 1.0 / u ) + log ( ( 1.0 - u ) / u ) - x;\n\n return\nend\nfunction [ c, f, s ] = pdefun ( x, t, u, dudx )\n\n%*****************************************************************************80\n%\n%% PDEFUN defines the components of the PDE.\n%\n% Discussion:\n%\n% The PDE has the form:\n%\n% c * du/dt = x^(-m) d/dx ( x^m f ) + s\n%\n% where m is 0, 1 or 2,\n% c, f and s are functions of x, t, u, and dudx, \n% and most typically, f = dudx.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the spatial location.\n%\n% Input, real T, the current time.\n%\n% Input, real U(:,1), the estimated solution at T and X.\n%\n% Input, real DUDX(:,1), the estimated spatial derivative of U at T and X.\n%\n% Output, real C(:,1), the coefficients of du/dt.\n%\n% Output, real F(:,1), the flux terms.\n%\n% Output, real S(:,1), the source terms.\n%\n c = 1.0;\n ubar = degwave ( x );\n f = dudx - ( 3.0 * ubar.^2 - 2.0 * ubar ) * u;\n s = 0.0;\n\n return\nend\nfunction u0 = icfun ( x )\n\n%*****************************************************************************80\n%\n%% ICFUN defines the initial conditions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the spatial location.\n%\n% Output, real U0(:,1), the value of the solution at the initial time, \n% and location X.\n%\n u0 = 1.0 / ( 1.0 + ( x - 5.0 ).^2 );\n\n return\nend\nfunction [ pl, ql, pr, qr ] = bcfun ( xl, ul, xr, ur, t )\n\n%*****************************************************************************80\n%\n%% BCFUN defines the boundary conditions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real XL, the spatial coordinate of the left boundary.\n%\n% Input, real UL(:,1), the solution estimate at the left boundary.\n%\n% Input, real XR, the spatial coordinate of the right boundary.\n%\n% Input, real UR(:,1), the solution estimate at the right boundary.\n%\n% Output, real PL(:,1), the Dirichlet portion of the left boundary condition.\n%\n% Output, real QL(:,1), the coefficient of the flux portion of the left \n% boundary condition.\n%\n% Output, real PR(:,1), the Dirichlet portion of the right boundary condition.\n%\n% Output, real QR(:,1), the coefficient of the flux portion of the right \n% boundary condition.\n%\n pl = ul;\n ql = 0.0;\n pr = ur;\n qr = 0.0;\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/pdepe/example2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7308222011958184}} {"text": "function i = mytsearch ( x, y, t, xi, yi, i )\n\n%*****************************************************************************80\n%\n%% MYTSEARCH: Find the enclosing triangle for points in a 2D plane.\n%\n% Discussion:\n%\n% The indices of the triangles enclosing the points in [XI,YI] are\n% returned. The triangulation T of [X,Y] must be convex. Points lying\n% outside the triangulation are assigned a NaN index.\n%\n% I is an optional initial guess for the indices. A full search is\n% done using the standard TSEARCH function for points with an invalid\n% initial guess.\n%\n% Author:\n%\n% Darren Engwirda\n%.\n\n% I/O and error checks\nif nargin<6\n i = [];\n if nargin<5\n error('Wrong number of inputs');\n end\nelseif nargin>6\n error('Wrong number of inputs');\nend\nif nargout>1\n error('Wrong number of outputs');\nend\nni = size(xi,1);\nif (numel(xi)~=ni) || (numel(yi)~=ni) || ...\n (numel(x)~=numel(y)) || (~isempty(i) && (numel(i)~=ni))\n error('Wrong input dimensions');\nend\n\n% Translate to the origin and scale the min xy range onto [-1,1]\n% This is absolutely critical to avoid precision issues for large problems!\nmaxxy = max([x,y]);\nminxy = min([x,y]);\nden = 0.5*min(maxxy-minxy);\n\nx = ( x-0.5*(minxy(1)+maxxy(1))) / den;\ny = ( y-0.5*(minxy(2)+maxxy(2))) / den;\nxi = (xi-0.5*(minxy(1)+maxxy(1))) / den;\nyi = (yi-0.5*(minxy(2)+maxxy(2))) / den;\n\n% Check initial guess\nif ( ~isempty(i) )\n k = find(i>0 & ~isnan(i));\n\n tri = i(k);\n\n n1 = t(tri,1);\n n2 = t(tri,2);\n n3 = t(tri,3);\n\n ok = sameside(x(n1),y(n1),x(n2),y(n2),xi(k),yi(k),x(n3),y(n3)) & ...\n sameside(x(n2),y(n2),x(n3),y(n3),xi(k),yi(k),x(n1),y(n1)) & ...\n sameside(x(n3),y(n3),x(n1),y(n1),xi(k),yi(k),x(n2),y(n2));\n\n j = true(ni,1);\n j(k(ok)) = false;\nelse\n j = true(ni,1);\nend\n%\n% Do a full search for points that failed\n%\nif any(j)\n i(j) = tsearch(x,y,t,xi(j),yi(j));\nend\n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction i = sameside(xa,ya,xb,yb,x1,y1,x2,y2)\n\n% Test if [x1(i),y1(i)] and [x2(i),y2(i)] lie on the same side of the line\n% AB(i).\n\n dx = xb-xa;\n dy = yb-ya;\n a1 = (x1-xa).*dy-(y1-ya).*dx;\n a2 = (x2-xa).*dy-(y2-ya).*dx;\n\n% If sign(a1)=sign(a2) the points lie on the same side\n i = false(length(xa),1);\n i(a1.*a2>=0.0) = true;\n\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/tsearch/mytsearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7308221900172669}} {"text": "function [ u, l ] = vand2_inverse_ul ( n, x )\n\n%*****************************************************************************80\n%\n%% VAND2_INVERSE_UL returns the UL factors of the VAND2 inverse matrix.\n%\n% Discussion:\n%\n% inverse ( A ) = U * L\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 November 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Richard Turner,\n% Inverse of the Vandermonde Matrix with Applications,\n% NASA Technical Note TN D-3547, 1966.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real X(N), the values that define A.\n%\n% Output, real U(N,N), L(N,N), the UL factors of inverse(A).\n%\n u = zeros ( n, n );\n\n for i = 1 : n\n u(i,i) = 1.0;\n if ( i == 1 )\n for j = i + 1 : n\n u(i,j) = - u(i,j-1) * x(j-1);\n end\n else\n for j = i + 1 : n\n u(i,j) = u(i-1,j-1) - u(i,j-1) * x(j-1);\n end\n end\n end\n \n l = zeros ( n, n );\n\n for i = 1 : n\n l(i,1:i) = 1.0; \n for j = 1 : i\n for k = 1 : i\n if ( j ~= k )\n l(i,j) = l(i,j) / ( x(j) - x(k) );\n end\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/vand2_inverse_ul.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7308134686581838}} {"text": "function elli = fitEllipse(varargin)\n%FITELLIPSE Fit an ellipse to a set of 2D points.\n%\n% ELLI = fitEllipse(PTS)\n%\n% Example\n% elli = [50 40 30 10 20];\n% pts = ellipseToPolygon(elli, 60) + randn(60,2);\n% figure; hold on; drawPoint(pts, 'ko');\n% axis equal; axis([0 100 0 100]);\n% ellFit = fitEllipse(pts);\n% drawEllipse(ellFit, 'b')\n% \n% This is a rewrite of an original function from the authors cited below.\n% Changes from original submission include:\n% * convert angle of result ellipse to degrees (to comply with MatGeom\n% convention)\n% * update comments\n%\n% Authors:\n% Andrew Fitzgibbon, Maurizio Pilu, Bob Fisher\n% Reference: \"Direct Least Squares Fitting of Ellipses\", IEEE T-PAMI, 1999\n%\n% https://fr.mathworks.com/matlabcentral/fileexchange/3215-fit_ellipse\n%\n% @Article{Fitzgibbon99,\n% author = \"Fitzgibbon, A.~W.and Pilu, M. and Fisher, R.~B.\",\n% title = \"Direct least-squares fitting of ellipses\",\n% journal = pami,\n% year = 1999,\n% volume = 21,\n% number = 5,\n% month = may,\n% pages = \"476--480\"\n% }\n%\n% See also \n% geom2d, ellipses2d, createEllipse, equivalentEllipse\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inrae.fr\n% Created: 2022-07-16, using Matlab 9.12.0.1884302 (R2022a)\n% Copyright 2022 INRAE - BIA Research Unit - BIBS Platform (Nantes)\n\n%% Process input arguments\n\nif nargin==1\n var = varargin{1};\n X = var(:,1);\n Y = var(:,2);\nelse\n X = varargin{1};\n Y = varargin{2};\nend\n\n%% Normalize data\n\n% recenter and reduce range\nmx = mean(X);\nmy = mean(Y);\nsx = (max(X) - min(X)) / 2;\nsy = (max(Y) - min(Y)) / 2; \nx = (X-mx) / sx;\ny = (Y-my) / sy;\n\n% Force to column vectors\nx = x(:);\ny = y(:);\n\n\n%% Main processing\n\n% Build design matrix\nD = [ x.*x x.*y y.*y x y ones(size(x)) ];\n\n% Build scatter matrix\nS = D' * D;\n\n% Build 6x6 constraint matrix\nC(6,6) = 0; \nC(1,3) = -2; \nC(2,2) = 1; \nC(3,1) = -2;\n\n% Solve eigensystem\n\n% Break into blocks\ntmpA = S(1:3,1:3);\ntmpB = S(1:3,4:6);\ntmpC = S(4:6,4:6);\ntmpD = C(1:3,1:3);\ntmpE = tmpC \\ tmpB';\n\n[evec_x, eval_x] = eig(tmpD \\ (tmpA - tmpB*tmpE));\n\n% Find the positive (as det(tmpD) < 0) eigenvalue\nI = real(diag(eval_x)) < 1e-8 & ~isinf(diag(eval_x));\n\n% Extract eigenvector corresponding to negative eigenvalue\nA = real(evec_x(:,I));\n\n% Recover the bottom half...\nevec_y = -tmpE * A;\nA = [A; evec_y];\n\n% re-calibrate\npar = [\n A(1)*sy*sy, ...\n A(2)*sx*sy, ...\n A(3)*sx*sx, ...\n -2*A(1)*sy*sy*mx - A(2)*sx*sy*my + A(4)*sx*sy*sy, ...\n -A(2)*sx*sy*mx - 2*A(3)*sx*sx*my + A(5)*sx*sx*sy, ...\n A(1)*sy*sy*mx*mx + A(2)*sx*sy*mx*my + A(3)*sx*sx*my*my ...\n - A(4)*sx*sy*sy*mx - A(5)*sx*sx*sy*my ...\n + A(6)*sx*sx*sy*sy ...\n ]';\n\n\n%% Identify parameters\n\n% rotation angle\ntheta = 0.5 * atan2(par(2), par(1) - par(3));\n\n% pre-comptute trigonometrics\ncost = cos(theta);\nsint = sin(theta);\nsin2 = sint .* sint;\ncos2 = cost .* cost;\ncos_sin = sint .* cost;\n\n%\nAo = par(6);\nAu = par(4) .* cost + par(5) .* sint;\nAv = -par(4) .* sint + par(5) .* cost;\nAuu = par(1) .* cos2 + par(3) .* sin2 + par(2) .* cos_sin;\nAvv = par(1) .* sin2 + par(3) .* cos2 - par(2) .* cos_sin;\n\n% ROTATED = [Ao Au Av Auu Avv]\n\ntuCentre = - Au./(2.*Auu);\ntvCentre = - Av./(2.*Avv);\nwCentre = Ao - Auu.*tuCentre.*tuCentre - Avv.*tvCentre.*tvCentre;\n\nuCentre = tuCentre .* cost - tvCentre .* sint;\nvCentre = tuCentre .* sint + tvCentre .* cost;\n\nRu = -wCentre ./ Auu;\nRv = -wCentre ./ Avv;\n\nRu = sqrt(abs(Ru)) .* sign(Ru);\nRv = sqrt(abs(Rv)) .* sign(Rv);\n\nelli = [uCentre, vCentre, Ru, Rv, rad2deg(theta)];\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/fitEllipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7308134686581838}} {"text": "function alpha = db2neper(alpha, y)\n%DB2NEPER Convert decibels to nepers.\n%\n% DESCRIPTION:\n% db2neper converts an attenuation coefficient in units of\n% dB/(MHz^y cm) to units of Nepers/((rad/s)^y m).\n%\n% USAGE:\n% alpha = db2neper(alpha)\n% alpha = db2neper(alpha, y)\n%\n% INPUTS:\n% alpha - attenuation in dB/(MHz^y cm)\n%\n% OPTIONAL INPUTS:\n% y - power law exponent (default = 1)\n%\n% OUTPUTS:\n% alpha - attenuation in Nepers/((rad/s)^y m)\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 27th March 2009\n% last update - 5th 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 neper2db\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\nif nargin == 1\n y = 1;\nend\nalpha = 100*alpha.*(1e-6/(2*pi)).^y./(20*log10(exp(1)));", "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/db2neper.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.73081346222789}} {"text": "function surfacedata = quarticssurface\n\nsurfacedata = struct('phi',@phi,'gradient', @gradient, 'unitoutnormal',...\n @unitoutnormal, 'project', @project, 'initmesh',@initmesh,...\n 'meancurvature', @meancurvature, 'u', @u, 'f', @f, 'gra_u',@gra_u);\n\n\nfunction [node, elem] = initmesh\nM = load('meshdata/quartics4528.mat');\nnode = M.node;\nelem = M.elem;\nend\n\n\nfunction z = phi(p)\n% level set function\nx = p(:,1); y = p(:,2); z = p(:,3);\nz = (x.^2 - 1).^2 + (y.^2 - 1).^2 + (z.^2 - 1).^2 - 1.05;\nend\n\n\nfunction n = unitoutnormal(p)\n% \nn = gradient(p);\nl = sqrt(sum(n.^2,2));\nn = n./repmat(l,1,3);\nend\n\nfunction n = gradient(p)\n% gradient of phi\nx = p(:,1); y = p(:,2); z = p(:,3);\nn = [4*(x.^2 - 1).*x,4*(y.^2 - 1).*y, 4*(z.^2 - 1).*z];\nend\n\nfunction [node,dist] = project(p)\n% projection function \n\ns = sign(phi(p));\n\nnode = p;\n\nnormalAtNode = gradient(node);\nvalueAtNode = phi(node);\nnode = node - valueAtNode*ones(1,3).*normalAtNode./(dot(normalAtNode,normalAtNode,2)*ones(1,3));\n\nvector = (-s)*ones(1,3).*(node - p);\n\nd = s.*sqrt(dot(vector,vector,2));\n\nnormalAtNode = gradient(node);\n\nnode = p - d*ones(1,3).*normalAtNode./(sqrt(dot(normalAtNode,normalAtNode,2))*ones(1,3));\n\nvalueAtNode = phi(node);\n\nnormalAtNode = gradient(node);\n\nvector = (-s)*ones(1,3).*(node - p);\n\nd = s.*sqrt(dot(vector,vector,2));\n\n\ne1 = normalAtNode./(sqrt(dot(normalAtNode, normalAtNode,2))*ones(1,3))-vector./(sqrt(dot(vector,vector,2))*ones(1,3));\nerror=sqrt(valueAtNode.^2./(dot(normalAtNode, normalAtNode,2))+dot(e1,e1,2));\n\nk=1;\nwhile max(abs(error)) > 1e-6 && k<200\n \n k=k+1;\n \n node = node - valueAtNode*ones(1,3).*normalAtNode./(dot(normalAtNode,normalAtNode,2)*ones(1,3));\n \n vector = -s*ones(1,3).*(node - p);\n d = s.*sqrt(dot(vector,vector,2));\n normalAtNode = gradient(node);\n \n node = p - d*ones(1,3).*normalAtNode./(sqrt(dot(normalAtNode,normalAtNode,2))*ones(1,3));\n \n valueAtNode = phi(node);\n \n normalAtNode = gradient(node);\n \n vector = (-s)*ones(1,3).*(node - p);\n \n d = s.*sqrt(dot(vector,vector,2));\n e1 = normalAtNode./(sqrt(dot(normalAtNode, normalAtNode,2))*ones(1,3))-vector./(sqrt(dot(vector,vector,2))*ones(1,3));\n error=sqrt(valueAtNode.^2./(dot(normalAtNode, normalAtNode,2))+dot(e1,e1,2)); \nend\n\nif nargout == 2\n dist = d;\nend\nend\n\nfunction mc = meancurvature(p)\nx = p(:,1); y = p(:,2); z = p(:,3);\ns = (x.^2-1).^2.*x.^2 + (y.^2-1).^2.*y.^2 + (z.^2-1).^2.*z.^2;\ns1 =(3 .* z .^ 2 - 2 + 3 .* y .^ 2) .* x .^ 6 + (-6 .* y .^ 2 - 6 .* z .^ 2 + 4) .* x .^ 4 ...\n + (-2 + 6 .* y .^ 2 + 3 .* z .^ 6 - 6 .* z .^ 4 - 6 .* y .^ 4 + 6 .* z .^ 2 + 3 .* y .^ 6) .* x .^ 2 ...\n+ (3 .* z .^ 2 - 2) .* y .^ 6 + (4 - 6 .* z .^ 2) .* y .^ 4 + ...\n (-2 + 6 .* z .^ 2 + 3 .* z .^ 6 - 6 .* z .^ 4) .* y .^ 2 - 2 .* z .^ 6 - 2 .* z .^ 2 + 4 .* z .^ 4;\n\nmc = 0.5 * s1 ./ (s.^(3/2));\nend\n\n\nfunction z = f(p)\np = project(p);\nx = p(:,1); y = p(:,2); z = p(:,3);\nx2 = x.^2; y2 = y.^2; z2 = z.^2;\nx4 = x2.^2; y4 = y2.^2; z4 = z2.^2;\n\nx31 = x2.*x - x;\ny31 = y2.*y - y;\nz31 = z2.*z - z;\n\nd1 = x31.^2 + y31.^2 + z31.^2;\nd2 = x31 + y31 + z31;\nt = exp(x+y+z);\n\nd3 = (z2 + y2 - 2/3).*x4.*(x2 - 2);\nd4 = (z4.*(z2-2) + 2*z2 + y4.*(y2 -2) + 2*y2 -2/3).*x2;\nd5 = (z2 - 2/3).*y4.*(y2 - 2);\nd6 = (z4.*(z2 -2) + 2*z2 - 2/3).*y2;\n\nz = -2*t.*((-(y31+z31).*x31 - z31.*y31 + d1).*d1 -1.5*(d3 + d4 + d5 + d6 - 2/3*z31.^2).*d2)./d1.^2;\nend\n\nfunction z = u(p) \n% exact solution\np = project(p);\nz = exp(sum(p,2));\nend\n\nfunction z = gra_u(p) \n\np = project(p);\nx = p(:,1); y = p(:,2); z = p(:,3);\nx2 = x.^2; y2 = y.^2; z2 = z.^2;\n\n\nx31 = x2.*x - x;\ny31 = y2.*y - y;\nz31 = z2.*z - z;\n\nd1 = x31.^2 + y31.^2 + z31.^2;\nt = exp(x+y+z);\nz1 = (y31+z31).*x31 - y31.^2 - z31.^2;\nz2 = (x31+z31).*y31 - x31.^2 - z31.^2;\nz3 = (x31+y31).*z31 - x31.^2 - y31.^2;\n\nz = -(t./d1)*ones(1,3).*[z1,z2,z3];\nend\n\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/mesh/surfacemesh/quarticssurface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8031737892899221, "lm_q1q2_score": 0.7308134540165875}} {"text": "function J = warp_jacobian(nx, ny, warp, transform)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%J = WARP_JACOBIAN(NX, NY, WARP, TRANSFORM)\n% This function computes the jacobian J of warp transform with respect \n% to parameters. In case of homography/euclidean transform, the jacobian depends on\n% the parameter values, while in affine/translation case is totally invariant.\n%\n% Input variables:\n% NX: the x-coordinate values of the horizontal side of ROI (i.e. [xmin:xmax]),\n% NY: the y-coordinate values of vertical side of ROI (i.e. [ymin:ymax]),\n% WARP: the warp transform (used only in homography and euclidean case),\n% TRANSFORM: the type of adopted transform\n% {'affine''homography','translation','euclidean'}\n% \n% Output:\n% J: The jacobian matrix J\n%--------------------------------------\n% $ Ver: 1.3, 13/5/2012, released by Georgios D. Evangelidis, INRIA, FRANCE\n% Email: georgios.evangelidis@inria.fr\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nsnx=length(nx);\nsny=length(ny);\n\nJx=nx(ones(1,sny),:);\nJy=ny(ones(1,snx),:)';\nJ0=0*Jx;\nJ1=J0+1;\n\n\nswitch lower(transform)\n case 'homography'\n\n xy=[Jx(:)';Jy(:)';ones(1,snx*sny)];\n\n\n %3x3 matrix transformation\n A = warp;\n A(3,3) = 1;\n\n % new coordinates\n xy_prime = A * xy;\n\n\n\n % division due to homogeneous coordinates\n xy_prime(1,:) = xy_prime(1,:)./xy_prime(3,:);\n xy_prime(2,:) = xy_prime(2,:)./xy_prime(3,:);\n\n den = xy_prime(3,:)';\n\n Jx(:) = Jx(:) ./ den;\n Jy(:) = Jy(:) ./ den;\n J1(:) = J1(:) ./ den;\n\n Jxx_prime = Jx;\n Jxx_prime(:) = Jxx_prime(:) .* xy_prime(1,:)';\n Jyx_prime = Jy;\n Jyx_prime(:) = Jyx_prime(:) .* xy_prime(1,:)';\n\n Jxy_prime = Jx;\n Jxy_prime(:) = Jxy_prime(:) .* xy_prime(2,:)';\n Jyy_prime = Jy;\n Jyy_prime(:) = Jyy_prime(:) .* xy_prime(2,:)';\n\n\n J = [Jx, J0, -Jxx_prime, Jy, J0, - Jyx_prime, J1, J0;...\n J0, Jx, -Jxy_prime, J0, Jy, -Jyy_prime, J0, J1];\n\n case 'affine'\n\n\n J = [Jx, J0, Jy, J0, J1, J0;... \n J0, Jx, J0, Jy, J0, J1];\n case 'translation'\n\n J = [J1, J0;...\n J0, J1];\n\n case 'euclidean'\n \n mycos = warp(1,1);\n mysin = warp(2,1);\n \n Jx_prime = -mysin*Jx - mycos*Jy;\n Jy_prime = mycos*Jx - mysin*Jy;\n\n J = [Jx_prime, J1, J0;...\n Jy_prime, J0, J1];\n \n otherwise\n error('function WARP_JACOBIAN: Unknown transform!');\nend\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/27253-ecc-image-alignment-algorithm-image-registration/warp_jacobian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7307962396807947}} {"text": "function v = std3(f)\n%STD3 Standard deviation of a CHEBFUN3.\n% V = STD3(F) computes the standard deviation of the CHEBFUN3 object F, \n% i.e.,\n% STD3(F)^2 = 1 / V*sum3(|F(x,y,z) - M|^2)\n%\n% where V is the volume of the domain of F and M is the mean of F.\n%\n% See also CHEBFUN3/MEAN, CHEBFUN3/MEAN2, CHEBFUN3/MEAN3, CHEBFUN3/STD and \n% CHEBFUN3/STD2.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nh = f - mean3(f);\nv = sqrt(mean3(h .* conj(h)));\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/std3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7306984655889298}} {"text": "function [xmin,fmin]=Trust_Region_Method(x0)\n\neta1=0.01;\neta2=0.75;\ngamma1=0.5;\ngamma2=2.0;\nDelta_bar=3;\nDelta0=1;\nepsilon=1e-6;\nk=0;\nxk=x0;\nDeltak=Delta0;\n\nwhile 1\n % stop criteria\n gk=gradient(xk);\n Bk=Hessian(xk);\n if norm(gk)<=epsilon\n xmin=xk;\n fmin=objective_fun(xmin);\n k\n return;\n end\n\n % solve subproblem\n % Cauchy displacement\n if gk'*Bk*gk<=0\n dk=-(Deltak/norm(gk))*gk;\n else\n dk=-min(norm(gk)^2/(gk'*Bk*gk),Deltak/norm(gk))*gk;\n end\n \n % Dogleg method\n% dku=-((norm(gk)^2)/(gk'*Bk*gk))*gk;\n% dkN=-inv(Bk)*gk;\n% if norm(dku)>=Deltak\n% dk=-(Deltak/norm(gk))*gk;\n% elseif norm(dku)=eta2 && (norm(dk)<=Deltak+epsilon && norm(dk)>=Deltak-epsilon)\n Deltak=min(gamma2*Deltak,Delta_bar);\n end\n \n % update iteration point\n if rhok>eta1\n xk=xk+dk;\n end\n k=k+1;\nend", "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/11_5Trust region method/Trust_Region_Method.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458253565792, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7306968460078341}} {"text": "function [ p2, dp2, p1 ] = legendre_recur ( x, n )\n\n%*****************************************************************************80\n%\n%% LEGENDRE_RECUR finds the value and derivative of a Legendre polynomial.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 October 2005\n%\n% Author:\n%\n% John Burkardt\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% Output, real P2, the value of P(N)(X).\n%\n% Output, real DP2, the value of P'(N)(X).\n%\n% Output, real P1, the value of P(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 = ( ( 2 * i - 1 ) * x * p1 ...\n + ( - i + 1 ) * p0 ) ...\n / ( i );\n\n dp2 = ( ( 2 * i - 1 ) * ( p1 + x * dp1 ) ...\n - ( i - 1 ) * dp0 ) ...\n / ( i );\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/legendre_recur.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7306967380667855}} {"text": "function variance = coupon_variance ( j, n )\n\n%*****************************************************************************80\n%\n%% COUPON_VARIANCE returns the variance of the Coupon PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer J, the number of distinct coupons to be collected.\n% J must be between 1 and N.\n%\n% Input, integer N, the number of distinct coupons.\n%\n% Output, real VARIANCE, the variance of the number of\n% coupons that must be collected in order to just get J distinct kinds.\n%\n if ( n < j )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'COUPON_VARIANCE - Fatal error!\\n' );\n fprintf ( 1, ' Number of distinct coupons desired must be no more\\n' );\n fprintf ( 1, ' than the total number of distinct coupons.\\n' );\n error ( 'COUPON_VARIANCE - Fatal error!' );\n end\n\n variance = 0.0;\n for i = 1 : j\n variance = variance + ( i - 1 ) / ( n - i + 1 )^2;\n end\n variance = variance * 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/prob/coupon_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7306894148031061}} {"text": "function x = spgridcc(levelseq, d)\n% SPGRIDCC Computes the Clenshaw-Curtis sparse grid points in\n% each coordinate direction. \n% X = SPGRIDCC(LEVELSEQ, D) Computes the sparse grid points for\n% the given sequence of index sets LEVELSEQ and dimension D. The\n% coordinate value of dimension i is stored in column i of the\n% matrix X. One row of matrix X represents one grid point.\n\t\n% Author : Andreas Klimke\n% Version: 1.1\n% Date : April 20, 2004\n\n% Change log:\n% V1.0 : July 30, 2003\n% Initial version\n% V1.1 : April 20, 2004\n% Altered function header and simplified code.\n\t\n% Get the number of levels\nnlevels = size(levelseq,1);\n\n% Compute number of points\ntotalpoints = spseqdimcc(levelseq,d);\n\n% index contains the index of the resulting array containing all\n% subdomains of the level.\nindex = 1;\n\nx = zeros(totalpoints,d);\n\nfor kl = 1:nlevels\n\tlevel = levelseq(kl,:);\n\tfor i = 1:d\n\t\t% compute the points, scaled to [0,1]\n\t\tif level(i) == 0\n\t\t\t% take the interval bounds if the level is zero\n\t\t\tc = 0.5;\n\t\telseif level(i) == 1\n\t\t\tc = [0; 1];\n\t\telse\n\t\t\tc = ( ( ( (1:2^(level(i)-1)) *2 ) -1).*2^(-level(i)))';\n\t\tend\n\t\t% Compute the number of grid points per dimension, store it\n\t\t% in repvec.\n\t\trepvec = ones(1,d);\n\t\tfor k = 1:d\n\t\t\tif level(k) == 0\n\t\t\t\t% repvec(k) = 1;\n\t\t\telseif level(k) < 3\n\t\t\t\trepvec(k) = 2;\n\t\t\telse\n\t\t\t\trepvec(k) = 2^(level(k)-1);\n\t\t\tend\n\t\tend\n\t\tnpoints = prod(repvec);\n\t\trepvec(i) = 1;\n\t\tc = repmat(shiftdim(c, 1-i), repvec);\n\t\tx(index:index+npoints-1,i) = c(:);\n\tend\n\tindex = index + npoints;\nend\n\n% -----------------------------------------------------------------\nfunction n = spseqdimcc(levelseq, d)\n% SPSEQDIMCC Compute number of grid points for given sequence of\n% index sets.\n\n% Author : Andreas Klimke\n% Version: 1.0\n% Date : April 20, 2004\n\nn = 0;\nfor k = 1:size(levelseq,1);\n\tntemp = 1;\n\tfor l = 1:d\n\t\tlev = levelseq(k,l);\n\t\tif lev == 0\n\t\t\tcontinue;\n\t\telseif lev <= 2\n\t\t\tntemp = ntemp * 2;\n\t\telse\n\t\t\tntemp = ntemp * 2^(lev-1);\n\t\tend\n\tend\n\tn = n + ntemp;\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms847/spgridcc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.7306894148031061}} {"text": "function op = proj_l2group( q,group_indices )\n%PROJ_L2GROUP Projection onto the intersection of scaled 2-norm balls.\n% OP = PROJ_L2GROUP( Q, GROUP_INDICES ) returns an operator implementing the \n% indicator function for the intersection of 2-norm ball of size q_k,\n% i.e. intersection_k B_k\n% where B_k = { X | norm( X(indK) ) <= q(k) }\n% and indK is indexed by group_indices. Group_indices keeps track\n% of the last index in each index set.\n% The index sets must be non-overlapping.\n% For example, if K=2, and ind1 = 1:10 and ind2 = 11:20,\n% then group_indices = [10,20].\n% Q must be a vector of length K or a vector of length N.\n%\n% With contributions from Joseph Salmon\n%\n% See also: proj_l2.m\n\nif isempty(q), q = 1; end\n% Make sure q is a column vector\nif size(q,1) == 1 && size(q,2) > 1, q = q.'; end\nq = expand_q(q,group_indices);\nop = @(varargin)proj_l2_q( q,group_indices, varargin{:} );\nend\n\nfunction [ v, x ] = proj_l2_q( q,group_indices, x, t )\nv = 0;\nnrm=group_norm(x,group_indices);\n\nswitch nargin,\n\tcase 3,\n\t\tif nargout == 2,\n\t\t\terror( 'This function is not differentiable.' );\n\t\telseif norm( nrm, 'inf') > q,\n\t\t\tv = Inf;\n\t\tend\n\tcase 4, \n x = x .* min(1,( q ./ nrm ));\n\totherwise,\n\t\terror( 'Not enough arguments.' );\nend\nend\n\n\nfunction y=group_norm(x,group_indices)\n% the groups are indexed by their end point\n K=length(group_indices);\n y=zeros(size(x));\n j=1; % start of the group\n for k=1:K\n end_point=group_indices(k);\n y(j:end_point)=norm(x(j:end_point));\n j=end_point+1;\n end\nend\n\nfunction Q = expand_q(q,group_indices)\n% If we have 2 groups, each of size 10\n% (group_indices = [10,20]), then q should\n% be a vector of size 20. But it's more convenient\n% for the user to pass in a vector of size 2, so this function\n% will convert it...\nn = group_indices(end);\nK = length(group_indices);\nif length(q) < n\n Q = ones(n,1);\n j=1; % start of the group\n for k=1:K\n end_point=group_indices(k);\n Q(j:end_point) = q(k);\n j=end_point+1;\n end\nelse\n Q = q;\nend\nend\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/proj_l2group.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7306532375099254}} {"text": "%The Gabor filter is basically a Gaussian (with variances sx and sy along x and y-axes respectively)\n%modulated by a complex sinusoid (with centre frequencies U and V along x and y-axes respectively) \n%described by the following equation\n%%\n% 1 -1 x ^ y ^\n%%% G(x,y) = ---------- * exp ([----{(----) 2+(----) 2}+2*pi*i*(Ux+Vy)])\n% 2*pi*sx*sy 2 sx sy\n\n%% But we use one dimentional gabor filter as below\n\n% 1 -1 x ^ \n%%% G(x) = ---------- * exp ([----(----) 2+2*pi*i*Ux])\n% 2*pi*sx 2 sx \n\n%And\n\n% 1 -1 y ^ \n%%% G(y) = ---------- * exp ([----(----) 2+2*pi*i*Uy])\n% 2*pi*sy 2 sy \n% By using these filters,reduces the filtering operations from O(M2N2) to O(MN2). \n\n%The output is\n%%% Iu(x,y) = Conv(I(x,y),g(y)); \n%%% Iv(x,y) = Conv(I(x,y),g(x));\n%%%Ifilt = sqrt(Iu^2+Iv^2);\n%% Where I is input image.\n\n\n%% Describtion :\n\n%% I : Input image\n%% Sx & Sy : Variances along x and y-axes respectively\n%% U & V : Centre frequencies along x and y-axes respectively\n\n%% Gx & Gy : The output filters as described above\n%% gabout : The output filtered image\n\n%% Author : Ahmad poursaberi e-mail : a.poursaberi@ece.ut.ac.ir\n%% Faulty of Engineering, Electrical&Computer Department,Tehran\n%% University,Iran,June 2004\n\nfunction [Gx,Gy,gabout] = gaborfilter1D(I,Sx,Sy,U,V);\n\nif isa(I,'double')~=1 \n I = double(I);\nend\nwarning off\nfor x = -fix(Sx):fix(Sx)\n for y = -fix(Sy):fix(Sy)\n Gx(fix(Sx)+x+1) = (1/(2*pi*Sx))*exp(-.5*((x/Sx)^2)+2*pi*i*U*x);\n Gy(fix(Sy)+y+1) = (1/(2*pi*Sy))*exp(-.5*((y/Sy)^2)+2*pi*i*V*y);\n \n end\nend\n\ngaboutu = conv2(I,double(Gy),'same');\ngaboutv = conv2(I,double(Gx),'same');\ngabout = uint8(sqrt(gaboutu.*gaboutu + gaboutv.*gaboutv));", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/5315-1d-gabor-filter/gaborfilter1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922388, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7305945238015078}} {"text": "% HOMOGRAPHY2D - computes 2D homography\n%\n% Usage: H = homography2d(x1, x2)\n% H = homography2d(x)\n%\n% Arguments:\n% x1 - 3xN set of homogeneous points\n% x2 - 3xN set of homogeneous points such that x1<->x2\n% \n% x - If a single argument is supplied it is assumed that it\n% is in the form x = [x1; x2]\n% Returns:\n% H - the 3x3 homography such that x2 = H*x1\n%\n% This code follows the normalised direct linear transformation \n% algorithm given by Hartley and Zisserman \"Multiple View Geometry in\n% Computer Vision\" p92.\n\n% Copyright (c) 2003-2005 Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk at csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, subject to the following conditions:\n% \n% The above copyright notice and this permission notice shall be included in \n% all copies or substantial portions of the Software.\n%\n% The Software is provided \"as is\", without warranty of any kind.\n\n% May 2003 - Original version.\n% Feb 2004 - Single argument allowed for to enable use with RANSAC.\n% Feb 2005 - SVD changed to 'Economy' decomposition (thanks to Paul O'Leary)\n\nfunction H = homography2d(varargin)\n \n [x1, x2] = checkargs(varargin(:));\n\n % Attempt to normalise each set of points so that the origin \n % is at centroid and mean distance from origin is sqrt(2).\n [x1, T1] = normalise2dpts(x1);\n [x2, T2] = normalise2dpts(x2);\n \n % Note that it may have not been possible to normalise\n % the points if one was at infinity so the following does not\n % assume that scale parameter w = 1.\n \n Npts = length(x1);\n A = zeros(3*Npts,9);\n \n O = [0 0 0];\n for n = 1:Npts\n\tX = x1(:,n)';\n\tx = x2(1,n); y = x2(2,n); w = x2(3,n);\n\tA(3*n-2,:) = [ O -w*X y*X];\n\tA(3*n-1,:) = [ w*X O -x*X];\n\tA(3*n ,:) = [-y*X x*X O ];\n end\n \n [U,D,V] = svd(A,0); % 'Economy' decomposition for speed\n \n % Extract homography\n H = reshape(V(:,9),3,3)';\n \n % Denormalise\n H = T2\\H*T1;\n \n\n%--------------------------------------------------------------------------\n% Function to check argument values and set defaults\n\nfunction [x1, x2] = checkargs(arg);\n \n if length(arg) == 2\n\tx1 = arg{1};\n\tx2 = arg{2};\n\tif ~all(size(x1)==size(x2))\n\t error('x1 and x2 must have the same size');\n\telseif size(x1,1) ~= 3\n\t error('x1 and x2 must be 3xN');\n\tend\n\t\n elseif length(arg) == 1\n\tif size(arg{1},1) ~= 6\n\t error('Single argument x must be 6xN');\n\telse\n\t x1 = arg{1}(1:3,:);\n\t x2 = arg{1}(4:6,:);\n\tend\n else\n\terror('Wrong number of arguments supplied');\n end\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/peter/homography2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7305621261863482}} {"text": "% the following script calculates and plots\n% the skin friction factors for smooth pipes for\n% laminar, turbulent and transitonal flows\n% for Reynnolds number up to 100000\n% CALLED FUNCTION: ffsmooth\n% ---------------------------------------------------------------\n% The MATLAB function was created by Tibor Balint, December 1998\n% TBoreal Research Corporation, Toronto, Ont. Canada \n% (tibor@netcom.ca) and also, University of Warwick, UK\n% ---------------------------------------------------------------\n\nclear\nformat long g; % set the format of the calculations\nn=2000; %number of points to be plotted\n\nRE=linspace(600,100000,n);\n\nfor i=1:n\n ffsm(i)=ffsmooth(RE(i)); %calculate the friction factors\nend\n\nfigure(1)\nh=get(0,'CurrentFigure');\nset(h,'Name','Friction Factor for Smooth Pipes','NumberTitle','off');\norient landscape;\nloglog(RE,ffsm)\n%plot(RE,ffsm)\nset(findobj('Type','line'),'Color','k','LineWidth',1.2); %set all the lines black, and the line width to 1.2 from 0.5 (default)\ngrid on;\naxis ([600 10^5 0.015 0.1]);\n%axis tight;\nxlabel('{\\bf Reynolds number} {\\it ( Re={UD_h}/\\nu )}');\nylabel('{\\bfFriction factor} {\\it f}');\ntitle ('{\\bf FRICTION FACTOR FOR SMOOTH PIPES}','FontSize',13);\nset(gca,'ytick',[0.015 0.02 0.025 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1]);\ntext(1.05*10^7,0.032,'\\it0.006','FontSize',7);\ntext(1000,0.0205,'{\\it To be used for laminar, transitional and turbulent flows,}','FontSize',8);\ntext(1000,0.0195,'{\\it in smooth pipes at Reynolds numbers below 100000}','FontSize',8);\ntext(0.99*10^3,0.06,'{\\it Laminar flow}','FontSize',8,'Rotation',-62);\ntext(1.05*10^4,0.0295,'{\\it Turbulent flow}','FontSize',8,'Rotation',-28);\ntext(2400,0.031,'{\\it Flow Transition}','FontSize',8,'Rotation',50);\ntext(4*10^4,0.013,'MATLAB script by Tibor Balint, April 1998','FontSize',6);\nreturn\n% -------------- end of the script ----------------------\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/237-pressuredrop/pressure_drop/plotffsm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.7305621206027778}} {"text": "function [gt,relres,iter]=gabfirtight(Lsupport,g,a,M,varargin)\n%GABFIRTIGHT Compute FIR tight window\n% Usage: gt=gabfirtight(Lsupport,g,a,M);\n% gt=gabfirtight(Lsupport,g,a,M, varagin);\n%\n% Input parameters:\n% Lsupport : Length of the tight window\n% g : Initial window function\n% a : Time shift\n% M : Number of Channels\n%\n% Output parameters:\n% gt : Tight window\n%\n% `gabfirtight(Lsupport,g,a,M)` computes an FIR window *gd* which is tight. \n% The FIR dual window will be supported on *Lsupport* samples.\n%\n% This function solve a convex optimization problem that can be written\n% as:\n%\n% .. gd = argmin_x || alpha x||_1 + || beta Fx||_1 \n%\n% .. + || omega (x -g_l) ||_2^2 + delta || x ||_S0\n%\n% .. + gamma || nabla F x ||_2^2 + mu || nabla x ||_2^2\n%\n% .. such that x is a tight FIR windows\n%\n% .. math:: \\begin{split} \\text{gd} = & \\text{arg} \\min_x \\| \\alpha x \\|_1 + \\| \\beta \\mathcal{F}x\\|_1 \\\\ & + \\| \\omega (x - g_l) \\|_2^2 \\\\ & \\delta \\| x \\|_{S0}+ \\mu \\| \\nabla x \\|_2^2 +\\gamma \\| \\nabla \\mathcal{F} x \\|_2^2 \\\\ & \\text{such that } x \\text{ is a tight FIR window} \\end{split}\n%\n% **Note**: This function require the unlocbox. You can download it at\n% ``_\n%\n% The function uses an iterative algorithm to compute the approximate\n% FIR tight windows. Warning The algorithm solve a non convex problem and\n% might be stack in bad local minima. The algorithm can be controlled by\n% the following flags: \n%\n% 'alpha',alpha Weight in time. If it is a scalar, it represent the\n% weights of the entire L1 function in time. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L1 norm (length: Ldual).\n% Default value is $\\alpha=0$.\n% **Warning**: this value should not be too big in order to\n% avoid the the L1 norm proximal operator kill the signal.\n% No L1-time constraint: $\\alpha=0$\n%\n% 'beta',beta Weight in frequency. If it is a scalar, it represent the\n% weights of the entire L1 function in frequency. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L1 norm in frequency. (length: Ldual).\n% Default value is $\\beta=0$.\n% **Warning**: this value should not be too big in order to\n% avoid the the L1 norm proximal operator kill the signal.\n% No L1-frequency constraint: $\\beta=0$\n%\n% 'omega',omega\n% Weight in time of the L2-norm. If it is a scalar,\n% it represent the\n% weights of the entire L2 function in time. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L2 norm (length: Ldual).\n% Default value is $\\omega=0$.\n% No L2-time constraint: $\\omega=0$\n%\n% 'glike',g_l $g_l$ is a windows in time. The algorithm try to shape\n% the dual window like $g_l$. Normalization of $g_l$ is done\n% automatically. To use option omega should be different\n% from 0. By default $g_d=0$.\n%\n% 'mu',mu Weight of the smooth constraint Default value is 1. \n% No smooth constraint: $\\mu=0$\n% \n% 'gamma',gamma Weight of the smooth constraint in frequency.\n% Default value is 1. No smooth constraint: $\\gamma=0$\n% \n% 'delta',delta Weight of the S0-norm. Default value is 0. \n% No S0-norm: $\\delta=0$\n%\n% 'dual' Look for a dual windows (default)\n%\n% 'painless' Construct a starting guess using a painless-case\n% approximation. This is the default\n%\n% 'zero' Choose a starting guess of zero.\n%\n% 'rand' Choose a random starting phase.\n%\n% 'tol',t Stop if relative residual error is less than the \n% specified tolerance. \n%\n% 'maxit',n Do at most n iterations. default 200\n%\n% 'print' Display the progress.\n%\n% 'debug' Display all the progresses.\n%\n% 'quiet' Don't print anything, this is the default.\n%\n% 'fast' Fast algorithm, this is the default.\n%\n% 'slow' Safer algorithm, you can try this if the fast algorithm\n% is not working. Before using this, try to iterate more.\n%\n% 'printstep',p If 'print' is specified, then print every p'th\n% iteration. Default value is p=10;\n%\n% 'hardconstraint' Force the projection at the end (default)\n%\n% 'softconstaint' Do not force the projection at the end\n%\n% See also: gaboptdual, gabdual, gabtight, gabfirdual, gabconvexopt\n \n\n% Author: Nathanael Perraudin\n% Date : 18 Feb 2014\n\nif nargin<4\n error('%s: Too few input parameters.',upper(mfilename));\nend;\n\n[gt,relres,iter]=gabconvexopt(g,a,M,varargin{:}, 'support',Lsupport,'tight');\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/gabor/gabfirtight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7305621133675888}} {"text": "% This m-file calculates the area of a circle,\n% and displays the result.\nradius = 2.5;\narea = pi * 2.5^2;\nstring = ['The area of the circle is ' num2str(area)];\ndisp(string);\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编程》源码/chap2/calc_area.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.730561275390143}} {"text": "function err ( )\n\n%*****************************************************************************80\n%\n%% ERR computes the L2 and H1 errors using a 2 point Gauss quadrature rule.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 April 2006\n%\n\n%\n% Set up the quadrature information.\n%\n [ xq, wq ] = gauss3pt ( ); \n\n el2 = 0.0;\n eh1 = 0.0;\n\n for it = 1 : nel \n\n for iq = 1 : nq\n ar = area(it) * wq(iq);\n x = xc(node(it,1)) + area(it) / 2.0 * ( xq(iq) + 1.0 );\n uh = 0.0;\n uhx = 0.0; \n for in = 1 : nnodes\n ip = node(it,in);\n [ bb, bx ] = quadbf ( x, it, in, xc, node );\n i = indx(ip);\n if ( i ~= 0 )\n uh = uh + bb * f(i);\n uhx = uhx + bx * f(i); \n end\n end\n [ uex, uexx ] = exact ( x );\n el2 = el2 + ar * ( uh - uex )^2; \n eh1 = eh1 + ar * ( uhx - uexx )^2 );\n end\n end\n\n el2 = sqrt ( el2 )\n eh1 = sqrt ( eh1 )\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/tumor/err.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331956, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7305612659262141}} {"text": "function expmat = MatrixLog6(T)\n% *** CHAPTER 3: RIGID-BODY MOTIONS ***\n% Takes a transformation matrix T in SE(3).\n% Returns the corresponding se(3) representation of exponential \n% coordinates.\n% Example Input:\n% \n% clear; clc;\n% T = [[1, 0, 0, 0]; [0, 0, -1, 0]; [0, 1, 0, 3]; [0, 0, 0, 1]];\n% expmat = MatrixLog6(T)\n% \n% Output:\n% expc6 =\n% 0 0 0 0\n% 0 0 -1.5708 2.3562\n% 0 1.5708 0 2.3562\n% 0 0 0 0\n\n[R, p] = TransToRp(T);\nomgmat = MatrixLog3(R);\nif isequal(omgmat, zeros(3))\n expmat = [zeros(3), T(1: 3, 4); 0, 0, 0, 0];\nelse\n theta = acos((trace(R) - 1) / 2);\n expmat = [omgmat, (eye(3) - omgmat / 2 ...\n + (1 / theta - cot(theta / 2) / 2) ...\n * omgmat * omgmat / theta) * p;\n 0, 0, 0, 0]; \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/MatrixLog6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.953275044028802, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7304886063517594}} {"text": "function jacobi_test01 ( )\n\n%*****************************************************************************80\n%\n%% JACOBI_TEST01 tests JACOBI1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 June 2011\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_TEST01:\\n' );\n\n it_num = 400;\n n = 20;\n\n x_exact = ( 1 : n )';\n a = dif2 ( n );\n b = a * x_exact;\n\n x = zeros ( n, 1 ); \n x_plot(1:n,1) = x;\n\n step = 1 : it_num + 1;\n r = nan ( it_num+1, 1 );\n xm = nan ( it_num+1, 1 );\n\n r(1,1) = ( norm ( a * x - b ) ).^2;\n\n for it = 1 : it_num\n\n x_new = jacobi1 ( n, a, b, x );\n% x_new = jacobi2 ( n, a, b, x );\n\n r(it+1,1) = ( norm ( a * x_new - b ) ).^2;\n x_plot(1:n,it+1) = x_new;\n%\n% Display the residual.\n%\n figure ( 1 )\n plot ( step, log ( r ), 'm-*' )\n title ( 'Log (Residual^2)' )\n xlabel ( 'Step' )\n ylabel ( 'Residual' )\n grid\n%\n% Display the motion.\n%\n xm(it,1) = sum ( ( x_new(:) - x(:) ).^2 ) / n;\n\n figure ( 2 )\n plot ( step, log ( xm ), 'm-*' )\n title ( 'Log (Average generator motion)' )\n xlabel ( 'Step' )\n ylabel ( 'Motion' )\n grid\n%\n% Update the solution\n%\n x = x_new;\n\n end\n%\n% Plot the evolution of the locations of the generators.\n%\n figure ( 3 )\n\n y = ( 0 : it_num );\n for k = 1 : n\n plot ( x_plot(k,1:it_num+1), y )\n hold on;\n end\n grid on\n hold off;\n\n title ( 'Generator evolution.' );\n xlabel ( 'Generator positions' );\n ylabel ( 'Iterations' ); \n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/jacobi/jacobi_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7303796079230007}} {"text": "function [b_value_ma, a_value_ma, b_error_ma] = ma(mag,cumnum)\n \n % compute the slope, intercept, and their errors using\n % \"Major Axis\" regression.\n % the inputs are two column vectors.\n % e.g. [b,a,e] = ma(X,Y) were X and Y are column vectors of the same length.\n % outputs are the b and a values and the standard error.\n \n report_this_filefun();\n \n X = [mag cumnum];\n m = mean(X);\n ssx = (X(:,1)-m(1))'*(X(:,1)-m(1));\n ssy = (X(:,2)-m(2))'*(X(:,2)-m(2));\n ssxy = (X(:,1)-m(1))'*(X(:,2)-m(2));\n \n % MAJOR AXIS REGRESSION\n [V,D] = eig(cov(X));\n % the slope of the line in the direction of max. variance\n b_value_ma = V(2,2)/V(1,2);\n a_value_ma = m(2) - (b_value_ma * m(1));\n \n % the standard error in the slopes\n r = ssxy/(sqrt(ssx.*ssy));\n b_error_ma = abs(b_value_ma)*sqrt((1-r^2)/length(X));\nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/src/ma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341987633821, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7303746835648282}} {"text": "function x = sample_paths_eigen ( n, n2, rhomax, rho0, correlation )\n\n%*****************************************************************************80\n%\n%% SAMPLE_PATHS_EIGEN: sample paths for stationary correlation functions.\n%\n% Discussion:\n%\n% This method uses the eigen-decomposition of the correlation matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points on each path.\n%\n% Input, integer N2, the number of paths.\n%\n% Input, real RHOMAX, the maximum value of RHO.\n%\n% Input, real RHO0, the correlation length.\n%\n% Input, @CORRELATION, a handle for a correlation function.\n%\n% Output, real X(N,N2), the sample paths.\n%\n\n%\n% Choose N equally spaced sample points from 0 to RHOMAX.\n%\n rho_vec = linspace ( 0.0, rhomax, n );\n%\n% Evaluate the correlation function.\n%\n cor_vec = correlation ( n, rho_vec, rho0 );\n\n cor = zeros ( n, n );\n%\n% Construct the correlation matrix;\n%\n% From the vector \n% [ C(0), C(1), C(2), ... C(N-1) ]\n% construct the vector\n% [ C(N-1), ..., C(2), C(1), C(0), C(1), C(2), ... C(N-1) ]\n% Every row of the correlation matrix can be constructed by a subvector\n% of this vector.\n%\n cor_vec = [ cor_vec(n:-1:2)', cor_vec(1:n)' ];\n for i = 1 : n\n cor(i,1:n) = cor_vec(n+1-i:2*n-i);\n end\n%\n% Get the eigendecomposition of COR:\n%\n% COR = V * D * V'.\n%\n% Because COR is symmetric, V is orthogonal.\n%\n [ v, d ] = eig ( cor );\n%\n% We assume COR is non-negative definite, and hence that there\n% are no negative eigenvalues. If this is not the case,\n% warn the user, hope the numbers are only slightly negative,\n% and reset them to 0.\n%\n dmin = min ( min ( d ) );\n\n if ( dmin < - sqrt ( eps ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SAMPLE_PATHS_EIGEN - Warning!\\n' );\n fprintf ( 1, ' Negative eigenvalues observed as low as %g\\n', dmin );\n end\n\n d = max ( d, 0.0 );\n%\n% Compute the eigenvalues of the factor C.\n%\n sqrt_d = sqrt ( d );\n%\n% Compute C, such that C' * C = COR.\n%\n c = v * sqrt_d * v';\n%\n% Compute N independent random normal values.\n%\n r(1:n,1:n2) = randn ( n, n2 );\n%\n% Get the variables X which have correlation COR.\n%\n x(1:n,1:n2) = c(1:n,1:n) * r(1:n,1:n2);\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/correlation/sample_paths_eigen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.7303469783488821}} {"text": "% By WangLin\n% 2015-11-5\n% wanglin193@hotmail.com\n\nclear all\n%close all\n%create a canvas\na = 32;\ncc = 255*rand(1,3);\nbb = 255*rand(1,3);\nfor i=1:3\n im(:,:,i) = [ cc(i)*ones(a,a),25+zeros(a,a);\n 25+zeros(a,a),cc(i)*ones(a,a)];\nend\n\nim = uint8(repmat(im,4,5));\n\n\n[imh,imw,imc] = size(im);\n\n%define landmarks\nps = [1,1;imw-0,1;imw-0,imh-0;1,imh-0;\n 0.4*imw,imh*3/8;\n 0.6*imw,imh*3/8; \n 0.4*imw,imh*5/8; \n 0.6*imw,imh*5/8];\npd = ps;\n%move some points\n% pd(5:8,:) = pd(5:8,:) + 15*[1,1;-1,1;1,-1;-1,-1];\npd(1:4,:) = pd(1:4,:) + 30*[1,1;-1,1;1,-1;-1,-1];\n%pd(5:8,:) = pd(5:8,:) + 30*[-1,1;-1,-1;1,1;1,-1];\n\n% ps=ps(5:end,:);\n% pd=pd(5:end,:);\n\nfigure\n\nsubplot(2,2,1)\nimshow(uint8(im))\ntitle('Orininal image with base landmarks');\nhold on\nplot( ps(:,1),ps(:,2),'r.' );\n plot( pd(:,1),pd(:,2),'g.' ); % added by Abdo\n \n%% Gaussian RBF function \n[imo1,mask1] = rbfwarp2d( im, ps, pd,'gau',imw*0.1 );\n[imo2,mask2] = rbfwarp2d( im, ps, pd,'gau',imw*0.5 );\n\nsubplot(2,2,2)\nimshow(uint8(imo1));\ntitle('RBF warping Rad = 0.1*imwidth');\nhold on\nplot( ps(:,1),ps(:,2),'r.' );\nplot( pd(:,1),pd(:,2),'g.' );\n\nsubplot(2,2,3)\nimshow(uint8(imo2));\ntitle('RBF warping Rad = 0.5*imwidth');\nhold on\nplot( ps(:,1),ps(:,2),'r.' );\nplot( pd(:,1),pd(:,2),'g.' );\n\n%% Thin plate warping\ntic\nfor i=1:150\n[imo1,mask1] = rbfwarp2d( im, ps, pd,'thin');\nend\ntoc\nsubplot(2,2,4)\nimshow(uint8(imo1));\ntitle('Thin-plate warping');\nhold on\nplot( ps(:,1),ps(:,2),'r.' );\nplot( pd(:,1),pd(:,2),'g.' );\n", "meta": {"author": "AbdoKamel", "repo": "sidd-ground-truth-image-estimation", "sha": "ede85b0c896dcadba8cc7c6f0f9bd516ad4e1ca2", "save_path": "github-repos/MATLAB/AbdoKamel-sidd-ground-truth-image-estimation", "path": "github-repos/MATLAB/AbdoKamel-sidd-ground-truth-image-estimation/sidd-ground-truth-image-estimation-ede85b0c896dcadba8cc7c6f0f9bd516ad4e1ca2/RBF_ThinPlate_image_warping/rbf_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7303469767004328}} {"text": "function [IDX,sep] = otsu(I,n)\n\n%OTSU Global image thresholding/segmentation using Otsu's method.\n% IDX = OTSU(I,N) segments the image I into N classes by means of Otsu's\n% N-thresholding method. OTSU returns an array IDX containing the cluster\n% indices (from 1 to N) of each point. Zero values are assigned to\n% non-finite (NaN or Inf) pixels.\n%\n% IDX = OTSU(I) uses two classes (N=2, default value).\n%\n% [IDX,sep] = OTSU(...) also returns the value (sep) of the separability\n% criterion within the range [0 1]. Zero is obtained only with data\n% having less than N values, whereas one (optimal value) is obtained only\n% with N-valued arrays.\n%\n% Notes:\n% -----\n% It should be noticed that the thresholds generally become less credible\n% as the number of classes (N) to be separated increases (see Otsu's\n% paper for more details).\n%\n% If I is an RGB image, a Karhunen-Loeve transform is first performed on\n% the three R,G,B channels. The segmentation is then carried out on the\n% image component that contains most of the energy.\n%\n% Example:\n% -------\n% load clown\n% subplot(221)\n% X = ind2rgb(X,map);\n% imshow(X)\n% title('Original','FontWeight','bold')\n% for n = 2:4\n% IDX = otsu(X,n);\n% subplot(2,2,n)\n% imagesc(IDX), axis image off\n% title(['n = ' int2str(n)],'FontWeight','bold')\n% end\n% colormap(gray)\n%\n% Reference:\n% ---------\n% Otsu N, A Threshold Selection Method from Gray-Level Histograms,\n% IEEE Trans. Syst. Man Cybern. 9:62-66;1979\n%\n% See also GRAYTHRESH, IM2BW\n%\n% -- Damien Garcia -- 2007/08, revised 2010/03\n% Visit my website for more details about OTSU\n\nerror(nargchk(1,2,nargin))\n\n% Check if is the input is an RGB image\nisRGB = isrgb(I);\n\nassert(isRGB | ndims(I)==2,...\n 'The input must be a 2-D array or an RGB image.')\n\n%% Checking n (number of classes)\nif nargin==1\n n = 2;\nelseif n==1;\n IDX = NaN(size(I));\n sep = 0;\n return\nelseif n~=abs(round(n)) || n==0\n error('MATLAB:otsu:WrongNValue',...\n 'n must be a strictly positive integer!')\nelseif n>255\n n = 255;\n warning('MATLAB:otsu:TooHighN',...\n 'n is too high. n value has been changed to 255.')\nend\n\nI = single(I);\n\n%% Perform a KLT if isRGB, and keep the component of highest energy\nif isRGB\n sizI = size(I);\n I = reshape(I,[],3);\n [V,D] = eig(cov(I));\n [tmp,c] = max(diag(D));\n I = reshape(I*V(:,c),sizI(1:2)); % component with the highest energy\nend\n\n%% Convert to 256 levels\nI = I-min(I(:));\nI = round(I/max(I(:))*255);\n\n%% Probability distribution\nunI = sort(unique(I));\nnbins = min(length(unI),256);\nif nbins==n\n IDX = ones(size(I));\n for i = 1:n, IDX(I==unI(i)) = i; end\n sep = 1;\n return\nelseif nbinspixval(k+1)) = 2;\n \n % separability criterion\n sep = maxsig/sum(((1:nbins)-mu(end)).^2.*P);\n \nelseif n==3\n w0 = w;\n w2 = fliplr(cumsum(fliplr(P)));\n [w0,w2] = ndgrid(w0,w2);\n \n mu0 = mu./w;\n mu2 = fliplr(cumsum(fliplr((1:nbins).*P))./cumsum(fliplr(P)));\n [mu0,mu2] = ndgrid(mu0,mu2);\n \n w1 = 1-w0-w2;\n w1(w1<=0) = NaN;\n \n sigma2B =...\n w0.*(mu0-mu(end)).^2 + w2.*(mu2-mu(end)).^2 +...\n (w0.*(mu0-mu(end)) + w2.*(mu2-mu(end))).^2./w1;\n sigma2B(isnan(sigma2B)) = 0; % zeroing if k1 >= k2\n \n [maxsig,k] = max(sigma2B(:));\n [k1,k2] = ind2sub([nbins nbins],k);\n \n % segmented image\n IDX = ones(size(I))*3;\n IDX(I<=pixval(k1)) = 1;\n IDX(I>pixval(k1) & I<=pixval(k2)) = 2;\n \n % separability criterion\n sep = maxsig/sum(((1:nbins)-mu(end)).^2.*P);\n \nelse\n k0 = linspace(0,1,n+1); k0 = k0(2:n);\n [k,y] = fminsearch(@sig_func,k0,optimset('TolX',1));\n k = round(k*(nbins-1)+1);\n \n % segmented image\n IDX = ones(size(I))*n;\n IDX(I<=pixval(k(1))) = 1;\n for i = 1:n-2\n IDX(I>pixval(k(i)) & I<=pixval(k(i+1))) = i+1;\n end\n \n % separability criterion\n sep = 1-y;\n \nend\n\nIDX(~isfinite(I)) = 0;\n\n%% Function to be minimized if n>=4\n function y = sig_func(k)\n \n muT = sum((1:nbins).*P);\n sigma2T = sum(((1:nbins)-muT).^2.*P);\n \n k = round(k*(nbins-1)+1);\n k = sort(k);\n if any(k<1 | k>nbins), y = 1; return, end\n \n k = [0 k nbins];\n sigma2B = 0;\n for j = 1:n\n wj = sum(P(k(j)+1:k(j+1)));\n if wj==0, y = 1; return, end\n muj = sum((k(j)+1:k(j+1)).*P(k(j)+1:k(j+1)))/wj;\n sigma2B = sigma2B + wj*(muj-muT)^2;\n end\n y = 1-sigma2B/sigma2T; % within the range [0 1]\n \n end\n\nend\n\nfunction isRGB = isrgb(A)\n% --- Do we have an RGB image?\n% RGB images can be only uint8, uint16, single, or double\nisRGB = ndims(A)==3 && (isfloat(A) || isa(A,'uint8') || isa(A,'uint16'));\n% ---- Adapted from the obsolete function ISRGB ----\nif isRGB && isfloat(A)\n % At first, just test a small chunk to get a possible quick negative\n mm = size(A,1);\n nn = size(A,2);\n chunk = A(1:min(mm,10),1:min(nn,10),:);\n isRGB = (min(chunk(:))>=0 && max(chunk(:))<=1);\n % If the chunk is an RGB image, test the whole image\n if isRGB, isRGB = (min(A(:))>=0 && max(A(:))<=1); end\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/26532-image-segmentation-using-otsu-thresholding/otsu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927838, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7303469604448136}} {"text": "function [aDeriv,aJacob,aHess,papt]=aCVRuv(x)\n%ACVRUV The drift function for a continuous-time motion model where the\n% the target state is given in monostatic range and u-v direction\n% cosine coordinates and the motion is constant-velocity in 3D\n% Cartesian coordinates.\n%\n%INPUTS: x The 6XN state vector of N targets in the order of\n% [r;u;;v;rDot;uDot;vDot], where r is monostatic range and u and v\n% are direction cosines. The target is assumed to always be in\n% front of the radar and not pass behind the radar.\n%\n%OUTPUTS: aDeriv The 6XN set of time-derivatives of the N state vectors\n% under the Cartesian linear motion model in r-u-v\n% coordinates.\n% aJacob The 6X6XN set of Jacobians of aDeriv, which can be useful\n% in extended Kalman filters. This is the derivative of each\n% component of aDeriv (selected by row) with respect to the\n% elements of the state [r,u,v,rDot,uDot,vDot] selected by\n% column.\n%\n%A full derivation of the dynamic model is provided in [1]. Summarizing it\n%here, let rVec be a position vector. We shall use the orthonormal basis\n%vectors:\n%uVec1=[u;v;sqrtw]\n%uVec2=[sqrt(w/(1-v2));0;-u/sqrt(1-v2)]\n%uVec3=[-u*v/sqrt(1-v2);sqrt(1-v2);-v*sqrt(w/(1-v2))];\n%Note that uVec2 is a normalized version of the derivative of uVec1 with\n%respect to u and uVec3 is cross(u1,u2). The time-derivatives of the basis\n%vectors can themselves be expressed as basis vectors:\n%uVec1Dot=c1*u2+c2*u3\n%uVec2Dot=c3*u1+c4*c3\n%uVec3Dot=c5*u1+c6*u2\n%The coefficients c1 through c6 are omitted for brevity but can be found\n%by taking the total derivative of each basis vector with respect to time\n%and then taking the dot products of the result with the orthonormal basis\n%vectors.\n%The vector rVec is written\n%rVec=r*u1\n%The velocity vector is the derivative of rVec. Using the chain rule and\n%substituting in the derivative parameters for the basis vectors,\n%rVecDot=rDot*uVec1+r*c1*uVec2+r*c2*uVec3\n%The decond derivative is more complicated, but simplifies to\n%rVecDDot=a1*uVec1+a2*uVec2+a3*uVec3\n%where two D's indicates two time-derivatives.\n%a1 is a radial acceleration and a3 and a3 are two other Cartesian\n%components of acceleration. The expressions for them are\n% a1=rDDot+r*(c1*c3+c2*c5);\n% a2=2*rDot*c1+r*(c1Dot+c2*c6);\n% a3=2*rDot*c2+r*(c2Dot+c1*c4);\n%The expression for the drift function comes from setting a1=a2=a3=0 and\n%solving for the second derivative terms. The second derivatives in u and v\n%arise through the derivatives of c1 and c2.\n%\n%EXAMPLE:\n%Here, we verify that integrating forward with this model is equivalent to\n%linear motion in Cartesian coordinates.\n% xInitCart=[400;920;1000;-100;20;64];\n% T=50;%The prediction time.\n% F=FPolyKal(T,6,1);\n% xInitRuv=stateCart2Ruv(xInitCart);\n% xEndCart=F*xInitCart;\n% RelTol=1e-10;\n% AbsTol=1e-13;\n% xStepsRuv=RKAdaptiveOverRange(xInitRuv,[0;T],@(x,t)aCVRuv(x),0.01,0,[],[],RelTol,AbsTol);\n% xEndRuvRK=xStepsRuv(:,end);\n% xEndRuvExact=stateCart2Ruv(xEndCart);\n% max(abs(xEndRuvRK-xEndRuvExact)./xEndRuvExact)\n%One will observe that the error is less than 1e-11, which is a good\n%agreement.\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"Basic Linear Dynamic Models in Local Coordinates,\"\n% Naval Research Laboratory, Washington, D.C., Tech. Rep.\n% NRL/MR/5344--19-9882, 24 Aug. 2019.\n%\n%August 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nr=x(1,:);\nu=x(2,:);\nv=x(3,:);\nrDot=x(4,:);\nuDot=x(5,:);\nvDot=x(6,:);\n\nu2=u.^2;\nv2=v.^2;\nr2=r.^2;\n\nw2=max(0,1-u2-v2);\nw=sqrt(w2);\n\ndiffV2=1-v2;\ndiffV=sqrt(diffV2);\n\ndiffU2=1-u2;\ndiffU=sqrt(diffU2);\n\nuDot2=uDot.*uDot;\nvDot2=vDot.*vDot;\nw3=w2.*w;\n\nrDDot=-(r*(-uDot2*diffV2-2*u*uDot*v*vDot-diffU2*vDot2))/w2;\nuDDot=-((2*rDot*uDot)/r)-u*(vDot2*diffU2+uDot2*diffV2+2*u*v*uDot*vDot)/w2;\nvDDot=-((2*rDot*vDot)/r)-v*(uDot2*diffV2+vDot2*diffU2+2*u*v*uDot*vDot)/w2;\n\naDeriv=[rDot;uDot;vDot;rDDot;uDDot;vDDot];\n\nif(nargout>1)\n N=size(x,2);\n if(N>1)\n error('Derivatives are only available for numPoints=1.')\n end\n\n w4=w2^2;\n\n ddrDDdr=-(-uDot2*diffV2-2*u*uDot*v*vDot-diffU2*vDot2)/w2;\n ddrDDdu=(2*r*(u*uDot+v*vDot)*(uDot-uDot*v2+u*v*vDot))/w4;\n ddrDDdv=-((2*r*(-u*uDot*v-diffU2*vDot)*(u*uDot+v*vDot))/w4);\n\n ddrDDduDot=((2*r*(uDot-uDot*v2+u*v*vDot))/w2);\n ddrDDdvDot=-(2*r*(-u*uDot*v-diffU2*vDot))/w2;\n\n dduDDdr=(2*rDot*uDot)/r2;\n dduDDdu=(-uDot2*(1+u2-v2)*diffV2-4*u*uDot*v*diffV2*vDot+(-1+v2-u2*(-2+u2+3*v2))*vDot2)/w4;\n dduDDdv=(2*u*(-u*uDot*v-diffU2*vDot)*(u*uDot+v*vDot))/w4;\n dduDDdrDot=-((2*uDot)/r);\n dduDDduDot=-((2*rDot)/r)-(2*u*(uDot-uDot*v2+u*v*vDot))/w2;\n dduDDdvDot=-(2*u*(u*uDot*v+vDot-u2*vDot))/w2;\n\n ddvDDdr=(2*rDot*vDot)/r2;\n ddvDDdu=-((2*v*(u*uDot+v*vDot)*(uDot-uDot*v2+u*v*vDot))/w4);\n ddvDDdv=(uDot2*(u2*(1-3*v2)-diffV2^2)-4*u*diffU2*uDot*v*vDot+diffU2*(-1+u2-v2)*vDot2)/w4;\n ddvDDdrDot=-((2*vDot)/r);\n ddvDDduDot=-(2*v*(uDot-uDot*v2+u*v*vDot))/w2;\n ddvDDdvDot=-((2*rDot)/r)-(2*v*(u*uDot*v+vDot-u2*vDot))/w2;\n\n aJacob=[0, 0, 0, 1, 0, 0;\n 0, 0, 0, 0, 1, 0;\n 0, 0, 0, 0, 0, 1;\n ddrDDdr, ddrDDdu, ddrDDdv, 0, ddrDDduDot, ddrDDdvDot;\n dduDDdr, dduDDdu, dduDDdv, dduDDdrDot, dduDDduDot, dduDDdvDot;\n ddvDDdr, ddvDDdu, ddvDDdv, ddvDDdrDot, ddvDDduDot, ddvDDdvDot];\n\n if(nargout>2)\n aHess=zeros(6,6,6);\n \n u4=u2*u2;\n v4=v2*v2;\n w6=w3*w3;\n diffU4=diffU2*diffU2;\n diffV4=diffV2*diffV2;\n\n ddrDDdrdr=0;\n ddrDDdudr=(2*(u*uDot+v*vDot)*(uDot-uDot*v2+u*v*vDot))/w4;\n ddrDDdvdr=-((2*(-u*uDot*v-diffU2*vDot)*(u*uDot+v*vDot))/w4);\n ddrDDduDotdr=((2*(uDot-uDot*v2+u*v*vDot))/w2);\n ddrDDdvDotdr=-(-2*u*uDot*v-2*diffU2*vDot)/w2;\n\n ddrDDdrdu=ddrDDdudr;\n ddrDDdudu=-(2*r*(-uDot2*(1+3*u2-v2)*diffV2-2*u*uDot*v*(3+u2-3*v2)*vDot+v2*(-1-3*u2+v2)*vDot2))/w6;\n ddrDDdvdu=(2*r*(uDot*(1+u2-v2)+2*u*v*vDot)*(2*u*uDot*v+vDot-u2*vDot+v2*vDot))/w6;\n ddrDDduDotdu=(-4*r*u*uDot*(-diffV2)+2*r*v*(1+u2-v2)*vDot)/w4;\n ddrDDdvDotdu=(2*r*v*(uDot*(1+u2-v2)+2*u*v*vDot))/w4;\n\n ddrDDdrdv=ddrDDdvdr;\n ddrDDdudv=ddrDDdvdu;\n ddrDDdvdv=-(2*r*(u2*uDot2*(-1+u2-3*v2)+2*u*uDot*v*(-3+3*u2-v2)*vDot+diffU2*(-1+u2-3*v2)*vDot2))/w6;\n ddrDDduDotdv=(2*r*u*(2*u*uDot*v+vDot-u2*vDot+v2*vDot))/w4;\n ddrDDdvDotdv=(2*r*u*uDot*(1-u2+v2)+4*r*diffU2*v*vDot)/w4;\n\n ddrDDdrdRDot=0;\n ddrDDdudRDot=0;\n ddrDDdvdRDot=0;\n ddrDDduDotdRDot=0;\n ddrDDdvDotdRDot=0;\n\n ddrDDdrduDot=ddrDDduDotdr;\n ddrDDduduDot=ddrDDduDotdu;\n ddrDDdvduDot=ddrDDduDotdv;\n ddrDDduDotduDot=(2*r*diffV2)/w2;\n ddrDDdvDotduDot=(2*r*u*v)/w2;\n\n ddrDDdrdvDot=ddrDDdvDotdr;\n ddrDDdudvDot=ddrDDdvDotdu;\n ddrDDdvdvDot=ddrDDdvDotdv;\n ddrDDduDotdvDot=ddrDDdvDotduDot;\n ddrDDdvDotdvDot=(2*r*diffU2)/w2;\n\n %%%\n dduDDdrdr=-((4*rDot*uDot)/r^3);\n dduDDdudr=0;\n dduDDdvdr=0;\n dduDDdrDotdr=(2*uDot)/r2;\n dduDDduDotdr=(2*rDot)/r2;\n dduDDdvDotdr=0;\n\n dduDDdrdu=dduDDdudr;\n dduDDdudu=-(2*u*uDot2*(3+u2-3*v2)*diffV2-4*uDot*v*diffV2*(-1-3*u2+v2)*vDot+2*u*v2*(3+u2-3*v2)*vDot2)/w6;\n dduDDdvdu=-(2*u2*uDot2*v*(3+u2-3*v2)+4*u*uDot*(1-v4+u2*(-1+3*v2))*vDot+2*v*(1-u4+(-1+3*u2)*v2)*vDot2)/w6;\n dduDDdrDotdu=0;\n dduDDduDotdu=-(2*diffV2*(uDot*(1+u2-v2)+2*u*v*vDot))/w4;\n dduDDdvDotdu=(-4*u*uDot*v*diffV2-2*(diffU4+(-1+3*u2)*v2)*vDot)/w4;\n\n dduDDdrdv=dduDDdvdr;\n dduDDdudv=dduDDdvdu;\n dduDDdvdv=-(2*u*(u2*uDot2*(1-u2+3*v2)+2*u*uDot*v*(3-3*u2+v2)*vDot-diffU2*(-1+u2-3*v2)*vDot2))/w6;\n dduDDdrDotdv=0;\n dduDDduDotdv=(2*u2*(-2*u*uDot*v+u2*vDot-(1+v2)*vDot))/w4;\n dduDDdvDotdv=(2*u*(u*uDot*(-1+u2-v2)-2*diffU2*v*vDot))/w4;\n\n dduDDdrdRDot=dduDDdrDotdr;\n dduDDdudRDot=dduDDdrDotdu;\n dduDDdvdRDot=dduDDdrDotdv;\n dduDDdrDotdRDot=0;\n dduDDduDotdRDot=-(2/r);\n dduDDdvDotdRDot=0;\n\n dduDDdrduDot=dduDDduDotdr;\n dduDDduduDot=dduDDduDotdu;\n dduDDdvduDot=dduDDduDotdv;\n dduDDdrDotduDot=dduDDduDotdRDot;\n dduDDduDotduDot=-((2*u*diffV2)/w2);\n dduDDdvDotduDot=-(2*u2*v)/w2;\n\n dduDDdrdvDot=dduDDdvDotdr;\n dduDDdudvDot=dduDDdvDotdu;\n dduDDdvdvDot=dduDDdvDotdv;\n dduDDdrDotdvDot=dduDDdvDotdRDot;\n dduDDduDotdvDot=dduDDdvDotduDot;\n dduDDdvDotdvDot=-(2*u*diffU2)/w2;\n\n %%%\n ddvDDdrdr=-((4*rDot*vDot)/r^3);\n ddvDDdudr=0;\n ddvDDdvdr=0;\n ddvDDdrDotdr=(2*vDot)/r2;\n ddvDDduDotdr=0;\n ddvDDdvDotdr=(2*rDot)/r2;\n\n ddvDDdrdu=ddvDDdudr;\n ddvDDdudu=-(2*v*(uDot2*(-1+v)*(1+v)*(-1-3*u2+v2)+2*u*uDot*v*(3+u2-3*v2)*vDot+v2*(1+3*u2-v2)*vDot2))/w6;\n ddvDDdvdu=-(2*u*uDot2*(1-v4+u2*(-1+3*v2))+4*uDot*v*(1-u4+(-1+3*u2)*v2)*vDot+2*u*v2*(3-3*u2+v2)*vDot2)/w6;\n ddvDDdrDotdu=0;\n ddvDDduDotdu=(2*v*(2*u*uDot*(-diffV2)+v*(-1-u2+v2)*vDot))/w4;\n ddvDDdvDotdu=-((2*v2*(uDot*(1+u2-v2)+2*u*v*vDot))/w4);\n\n ddvDDdrdv=ddvDDdvdr;\n ddvDDdudv=ddvDDdvdu;\n ddvDDdvdv=-(2*u2*uDot2*v*(3-3*u2+v2)-4*u*diffU2*uDot*(-1+u2-3*v2)*vDot+2*diffU2*v*(3-3*u2+v2)*vDot2)/w6;\n ddvDDdrDotdv=0;\n ddvDDduDotdv=(-2*uDot*(diffV4+u2*(-1+3*v2))-4*u*diffU2*v*vDot)/w4;\n ddvDDdvDotdv=(2*diffU2*(-2*u*uDot*v+u2*vDot-(1+v2)*vDot))/w4;\n\n ddvDDdrdRDot=ddvDDdrDotdr;\n ddvDDdudRDot=ddvDDdrDotdu;\n ddvDDdvdRDot=ddvDDdrDotdv;\n ddvDDdrDotdRDot=0;\n ddvDDduDotdRDot=0;\n ddvDDdvDotdRDot=-(2/r);\n\n ddvDDdrduDot=ddvDDduDotdr;\n ddvDDduduDot=ddvDDduDotdu;\n ddvDDdvduDot=ddvDDduDotdv;\n ddvDDdrDotduDot=ddvDDduDotdRDot;\n ddvDDduDotduDot=-((2*v*diffV2)/w2);\n ddvDDdvDotduDot=-(2*u*v2)/w2;\n\n ddvDDdrdvDot=ddvDDdvDotdr;\n ddvDDdudvDot=ddvDDdvDotdu;\n ddvDDdvdvDot=ddvDDdvDotdv;\n ddvDDdrDotdvDot=ddvDDdvDotdRDot;\n ddvDDduDotdvDot=ddvDDdvDotduDot;\n ddvDDdvDotdvDot=((2*(-1+u^2)*v)/w2);\n \n aHess(:,:,1)=[0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0;\n ddrDDdrdr, ddrDDdudr, ddrDDdvdr, 0, ddrDDduDotdr, ddrDDdvDotdr;\n dduDDdrdr, dduDDdudr, dduDDdvdr, dduDDdrDotdr, dduDDduDotdr, dduDDdvDotdr;\n ddvDDdrdr, ddvDDdudr, ddvDDdvdr, ddvDDdrDotdr, ddvDDduDotdr, ddvDDdvDotdr];\n aHess(:,:,2)=[0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0;\n ddrDDdrdu, ddrDDdudu, ddrDDdvdu, 0, ddrDDduDotdu, ddrDDdvDotdu;\n dduDDdrdu, dduDDdudu, dduDDdvdu, dduDDdrDotdu, dduDDduDotdu, dduDDdvDotdu;\n ddvDDdrdu, ddvDDdudu, ddvDDdvdu, ddvDDdrDotdu, ddvDDduDotdu, ddvDDdvDotdu];\n aHess(:,:,3)=[0, 0, 0, 0 0, 0;\n 0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0;\n ddrDDdrdv, ddrDDdudv, ddrDDdvdv, 0, ddrDDduDotdv, ddrDDdvDotdv;\n dduDDdrdv, dduDDdudv, dduDDdvdv, dduDDdrDotdv, dduDDduDotdv, dduDDdvDotdv;\n ddvDDdrdv, ddvDDdudv, ddvDDdvdv, ddvDDdrDotdv, ddvDDduDotdv, ddvDDdvDotdv];\n aHess(:,:,4)=[0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0;\n ddrDDdrdRDot, ddrDDdudRDot, ddrDDdvdRDot, 0, ddrDDduDotdRDot,ddrDDdvDotdRDot;\n dduDDdrdRDot, dduDDdudRDot, dduDDdvdRDot, dduDDdrDotdRDot,dduDDduDotdRDot,dduDDdvDotdRDot;\n ddvDDdrdRDot, ddvDDdudRDot, ddvDDdvdRDot, ddvDDdrDotdRDot,ddvDDduDotdRDot,ddvDDdvDotdRDot];\n aHess(:,:,5)=[0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0;\n ddrDDdrduDot, ddrDDduduDot, ddrDDdvduDot, 0, ddrDDduDotduDot,ddrDDdvDotduDot;\n dduDDdrduDot, dduDDduduDot, dduDDdvduDot, dduDDdrDotduDot,dduDDduDotduDot,dduDDdvDotduDot;\n ddvDDdrduDot, ddvDDduduDot, ddvDDdvduDot, ddvDDdrDotduDot,ddvDDduDotduDot,ddvDDdvDotduDot];\n aHess(:,:,6)=[0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0;\n 0, 0, 0, 0, 0, 0;\n ddrDDdrdvDot, ddrDDdudvDot, ddrDDdvdvDot, 0, ddrDDduDotdvDot,ddrDDdvDotdvDot;\n dduDDdrdvDot, dduDDdudvDot, dduDDdvdvDot, dduDDdrDotdvDot,dduDDduDotdvDot,dduDDdvDotdvDot;\n ddvDDdrdvDot, ddvDDdudvDot, ddvDDdvdvDot, ddvDDdrDotdvDot,ddvDDduDotdvDot,ddvDDdvDotdvDot];\n \n \n if(nargout>3) \n papt=zeros(6,1);\n end\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/Dynamic_Models/Continuous_Time/Non-Cartesian_Position/aCVRuv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119663, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7302837746584221}} {"text": "function degree = r8poly_degree ( na, a )\n\n%*****************************************************************************80\n%\n%% R8POLY_DEGREE returns the degree of a polynomial.\n%\n% Discussion:\n%\n% The degree of a polynomial is the index of the highest power\n% of X with a nonzero coefficient.\n%\n% The degree of a constant polynomial is 0. The degree of the\n% zero polynomial is debatable, but this routine returns the\n% degree as 0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NA, the dimension of A.\n%\n% Input, real A(NA+1), the coefficients of the polynomials.\n%\n% Output, integer DEGREE, the degree of A.\n%\n degree = na;\n\n while ( 0 < degree )\n\n if ( a(degree+1) ~= 0.0 )\n return\n end\n\n degree = degree - 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/hermite/r8poly_degree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8740772253241803, "lm_q1q2_score": 0.7302771247543461}} {"text": "function [H] = globalrescale(f);\n\n% GLOBALRESCALE creates the homogenous spatial transformation matrix\n% for a 7 parameter rigid-body transformation with global rescaling\n%\n% Use as\n% [H] = globalrescale(f)\n%\n% The transformation vector f should contain the \n% x-shift\n% y-shift\n% z-shift\n% followed by the\n% pitch (rotation around x-axis)\n% roll (rotation around y-axis)\n% yaw (rotation around z-axis)\n% followed by the\n% global rescaling factor\n\n% Copyright (C) 2000-2005, Robert Oostenveld\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\n% $Log: globalrescale.m,v $\n% Revision 1.1 2009/01/30 04:02:06 arno\n% *** empty log message ***\n%\n% Revision 1.3 2005/08/15 08:15:32 roboos\n% reimplemented the rotate function, which contained an error (the error is in the AIR technical reference)\n% changed all functions to be dependent on the rotate, translate and scale function\n% all functions now behave consistenly, which also means that they are not compleetly backward compatible w.r.t. the order of the rotations\n%\n% Revision 1.2 2004/05/19 09:57:07 roberto\n% added GPL copyright statement, added CVS log item\n%\n\n% compute the homogenous transformation matrix for the translation\nT = translate(f([1 2 3]));\n\n% compute the homogenous transformation matrix for the rotation\nR = rotate_new(f([4 5 6]));\n\n% compute the homogenous transformation matrix for the global scaling\nS = scale(f([7 7 7]));\n\n% compute the homogenous transformation matrix for the combination\nH = T*R*S;\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/eeglab13_4_4b/plugins/dipfit2.3/private/globalrescale.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.7302618404805589}} {"text": "function h = plot_gaussian_ellipsoid(m, C, sdwidth, npts, axh,alphaChannel,color)\n% PLOT_GAUSSIAN_ELLIPSOIDS plots 2-d and 3-d Gaussian distributions\n%\n% H = PLOT_GAUSSIAN_ELLIPSOIDS(M, C) plots the distribution specified by \n% mean M and covariance C. The distribution is plotted as an ellipse (in \n% 2-d) or an ellipsoid (in 3-d). By default, the distributions are \n% plotted in the current axes. H is the graphics handle to the plotted \n% ellipse or ellipsoid.\n%\n% PLOT_GAUSSIAN_ELLIPSOIDS(M, C, SD) uses SD as the standard deviation \n% along the major and minor axes (larger SD => larger ellipse). By \n% default, SD = 1. Note: \n% * For 2-d distributions, SD=1.0 and SD=2.0 cover ~ 39% and 86% \n% of the total probability mass, respectively. \n% * For 3-d distributions, SD=1.0 and SD=2.0 cover ~ 19% and 73%\n% of the total probability mass, respectively.\n% \n% PLOT_GAUSSIAN_ELLIPSOIDS(M, C, SD, NPTS) plots the ellipse or \n% ellipsoid with a resolution of NPTS (ellipsoids are generated \n% on an NPTS x NPTS mesh; see SPHERE for more details). By\n% default, NPTS = 50 for ellipses, and 20 for ellipsoids.\n%\n% PLOT_GAUSSIAN_ELLIPSOIDS(M, C, SD, NPTS, AX) adds the plot to the\n% axes specified by the axis handle AX.\n%\n% Examples: \n% -------------------------------------------\n% % Plot three 2-d Gaussians\n% figure; \n% h1 = plot_gaussian_ellipsoid([1 1], [1 0.5; 0.5 1]);\n% h2 = plot_gaussian_ellipsoid([2 1.5], [1 -0.7; -0.7 1]);\n% h3 = plot_gaussian_ellipsoid([0 0], [1 0; 0 1]);\n% set(h2,'color','r'); \n% set(h3,'color','g');\n% \n% % \"Contour map\" of a 2-d Gaussian\n% figure;\n% for sd = [0.3:0.4:4],\n% h = plot_gaussian_ellipsoid([0 0], [1 0.8; 0.8 1], sd);\n% end\n%\n% % Plot three 3-d Gaussians\n% figure;\n% h1 = plot_gaussian_ellipsoid([1 1 0], [1 0.5 0.2; 0.5 1 0.4; 0.2 0.4 1]);\n% h2 = plot_gaussian_ellipsoid([1.5 1 .5], [1 -0.7 0.6; -0.7 1 0; 0.6 0 1]);\n% h3 = plot_gaussian_ellipsoid([1 2 2], [0.5 0 0; 0 0.5 0; 0 0 0.5]);\n% set(h2,'facealpha',0.6);\n% view(129,36); set(gca,'proj','perspective'); grid on; \n% grid on; axis equal; axis tight;\n% -------------------------------------------\n% \n% Gautam Vallabha, Sep-23-2007, Gautam.Vallabha@mathworks.com\n\n% Revision 1.0, Sep-23-2007\n% - File created\n% Revision 1.1, 26-Sep-2007\n% - NARGOUT==0 check added.\n% - Help added on NPTS for ellipsoids\n\nif ~exist('sdwidth', 'var'), sdwidth = 1; end\nif ~exist('npts', 'var'), npts = []; end\nif ~exist('axh', 'var'), axh = gca; end\nif ~exist('alphaChannel','var'),alphaChannel=1;end\nif ~exist('color','var'),color=[0 0 1];end\n\nif numel(m) ~= length(m), \n error('M must be a vector'); \nend\nif ~( all(numel(m) == size(C)) )\n error('Dimensionality of M and C must match');\nend\nif ~(isscalar(axh) && ishandle(axh) && strcmp(get(axh,'type'), 'axes'))\n error('Invalid axes handle');\nend\n\nset(axh, 'nextplot', 'add');\n\nswitch numel(m)\n% case 2, if alphaChannel, h=show2d_noalpha(m(:),C,sdwidth,npts,axh,color); else h=show2d(m(:),C,sdwidth,npts,axh,alphaChannel,color); end\n case 2, h=show2d(m(:),C,sdwidth,npts,axh,alphaChannel,color);\n case 3, h=show3d(m(:),C,sdwidth,npts,axh);\n otherwise\n error('Unsupported dimensionality');\nend\n\nif nargout==0,\n clear h;\nend\n\n%-----------------------------\nfunction h = show2d(means, C, sdwidth, npts, axh,alphaChannel,color)\nif isempty(npts), npts=50; end\n% plot the gaussian fits\ntt=linspace(0,2*pi,npts)';\nx = cos(tt); y=sin(tt);\nap = [x(:) y(:)]';\n[v,d]=eig(C); \nd = sdwidth * sqrt(d); % convert variance to sdwidth*sd\nbp = (v*d*ap) + repmat(means, 1, size(ap,2));\n%if alphaChannel == 1\n%h = plot(bp(1,:), bp(2,:), '-', 'parent', axh);\n%set(h,'color',color);\n%else\nh = patchline(bp(1,:),bp(2,:),'linewidth',2,'linestyle','-','edgealpha',alphaChannel,'edgecolor',color,'LineSmoothing','on');\n%end\n\nfunction h = show2d_noalpha(means, C, sdwidth, npts, axh,color)\nif isempty(npts), npts=50; end\n% plot the gaussian fits\ntt=linspace(0,2*pi,npts)';\nx = cos(tt); y=sin(tt);\nap = [x(:) y(:)]';\n[v,d]=eig(C); \nd = sdwidth * sqrt(d); % convert variance to sdwidth*sd\nbp = (v*d*ap) + repmat(means, 1, size(ap,2));\nh = plot(bp(1,:), bp(2,:), '-', 'parent', axh);\nset(h,'color',color);\n\n\n\n%-----------------------------\nfunction h = show3d(means, C, sdwidth, npts, axh)\nif isempty(npts), npts=20; end\n[x,y,z] = sphere(npts);\nap = [x(:) y(:) z(:)]';\n[v,d]=eig(C); \nif any(d(:) < 0)\n fprintf('warning: negative eigenvalues\\n');\n d = max(d,0);\nend\nd = sdwidth * sqrt(d); % convert variance to sdwidth*sd\nbp = (v*d*ap) + repmat(means, 1, size(ap,2)); \nxp = reshape(bp(1,:), size(x));\nyp = reshape(bp(2,:), size(y));\nzp = reshape(bp(3,:), size(z));\nh = surf(axh, xp,yp,zp);\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_gaussian_ellipsoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7301694340314332}} {"text": "%RPY2R Roll-pitch-yaw angles to rotation matrix\n%\n% R = RPY2R(ROLL, PITCH, YAW, OPTIONS) is an SO(3) orthonornal rotation\n% matrix (3x3) equivalent to the specified roll, pitch, yaw angles angles.\n% These correspond to rotations about the X, Y, Z axes respectively. If\n% ROLL, PITCH, YAW are column vectors (Nx1) then they are assumed to\n% represent a trajectory and R is a three-dimensional matrix (3x3xN), where\n% the last index corresponds to rows of ROLL, PITCH, YAW.\n%\n% R = RPY2R(RPY, OPTIONS) as above but the roll, pitch, yaw angles angles\n% angles are taken from consecutive columns of the passed matrix RPY =\n% [ROLL, PITCH, YAW]. If RPY is a matrix (Nx3) then they are assumed to\n% represent a trajectory and R is a three-dimensional matrix (3x3xN), where\n% the last index corresponds to rows of RPY which are assumed to be [ROLL,\n% PITCH, YAW].\n%\n% Options::\n% 'deg' Compute angles in degrees (radians default)\n% 'zyx' Return solution for sequential rotations about Z, Y, X axes (Paul book)\n%\n% Note::\n% - In previous releases (<8) the angles corresponded to rotations about ZYX. Many \n% texts (Paul, Spong) use the rotation order ZYX. This old behaviour can be enabled \n% by passing the option 'zyx'\n%\n% See also TR2RPY, EUL2TR.\n\n\n\n% Copyright (C) 1993-2015, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction R = rpy2r(roll, varargin)\n opt.zyx = false;\n opt.deg = false;\n [opt,args] = tb_optparse(opt, varargin);\n\n % unpack the arguments\n if numcols(roll) == 3\n\t\tpitch = roll(:,2);\n\t\tyaw = roll(:,3);\n\t\troll = roll(:,1);\n\telseif nargin >= 3\n pitch = args{1};\n yaw = args{2};\n else\n error('RTB:rpy2r:badarg', 'bad arguments')\n end\n\n % optionally convert from degrees\n if opt.deg\n d2r = pi/180.0;\n roll = roll * d2r;\n pitch = pitch * d2r;\n yaw = yaw * d2r;\n end\n\n if ~opt.zyx\n % XYZ order\n if numrows(roll) == 1\n R = rotx(roll) * roty(pitch) * rotz(yaw);\n else\n R = zeros(3,3,numrows(roll));\n for i=1:numrows(roll)\n R(:,:,i) = rotx(roll(i)) * roty(pitch(i)) * rotz(yaw(i));\n end\n end\n else\n % old ZYX order (as per Paul book)\n if numrows(roll) == 1\n R = rotz(roll) * roty(pitch) * rotx(yaw);\n else\n R = zeros(3,3,numrows(roll));\n for i=1:numrows(roll)\n R(:,:,i) = rotz(roll(i)) * roty(pitch(i)) * rotx(yaw(i));\n end\n end\n end\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/rpy2r.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7301583751614809}} {"text": "function G = gaborPyramid(s, theta, sz);\n% Create a gabor wavelet pyramid.\n%\n% G = gaborPyramid(, , );\n%\n% BACKGROUND: this function creates a wavelet pyramid analogous to that\n% used by Kay et al (Nature 2000) to represent images for application to\n% fMRI activity patterns. This pyramid contains a series of Gabor wavelets,\n% each similar to the one described by Tai Sing Lee, \"Image Representation \n% Using 2D Gabor Wavelets\". \n% (IEEE Transactions 1996: online at www.cnbc.cmu.edu/~tai/papers/pami.pdf)\n%\n% \"Gabor\" wavelets (or \"Weyl-Heisenberg groups\" in physics) are a combined\n% harmonic and Gaussian function which the physicist Dennis Gabor showed\n% convey an optimal combination of spatial (or temporal) position localization \n% and frequency-domain localization. These functions serve as models of \n% receptive fields for early visual neurons, esp. simple cells. See the Lee \n% paper for more background. \n%\n% \"Pyramid\" refers to the fact that, for different spatial frequencies,\n% there will be a different number of channels, spanning the different\n% positions that can be localized. This code follows the Kay et al\n% convention of having spatial frequencies be powers of 2 in cycles per\n% image: for 2 cycles per image, there will be 2^2=4 possible positions;\n% for 4 cycles per image, there will be 4^2 possible positions.\n%\n%\n% INPUTS:\n% s: vector of spatial frequencies to use. s should be an integer, and specify \n% the log base 2 of the spatial frequency, in units of cycles / image. That is,\n% 2^s is the number of cycles in the image for a given channel. \n% E.g.: s=0 indicates a single cycle per image; s=1 indicates two cycles \n% per image. A DC offset is automatically added to the list of channels as well, \n% which has undefined spatial frequency (2^s = 0).\n%\n% theta: vector of orientations to use, in degrees counterclockwise from\n% the x0 axis. That is, 0=horizontal, 45 = increasing in x0/y0 direction, 90 =\n% vertical, 135 = increasing in x0 while decreasing in y0 direction. Note\n% that theta is cyclic with modulo 180 (theta=200 is the same as theta=20).\n%\n% sz: size [x y] of the resulting wavelets.\n%\n% OUTPUTS:\n% Return results in a structure G, with the following fields:\n%\todd: 3-D matrix of size [imgSize(1) imgSize(2) nChannels].\n%\t\todd-symmetric (sine) component channels.\n%\t\tThe # of channels depends on omega and theta (see above), and\n%\t\trepresents the even channels only in the complex function.\n%\teven: same size as odd, containing even-symmetric (cosine) component\n%\tchannels.\n%\tcyclesPerImage: vector of wavelengths corresponding to each channel.\n%\torientation: vector of orientations corresponding to each channel.\n%\tx0: vector of x0 position centers for each channel\n%\ty0: vector of y0 position centers for each channel.\n%\n% REFERENCES: We implement a version of the wavelet decomposition used in\n% Kay et al., Nature 2008. See also www.cnbc.cmu.edu/~tai/papers/pami.pdf.\n%\n% ras, 03/2008.\nif notDefined('s'),\t\t\ts = 0:2;\t\t\t\t\tend\nif notDefined('theta'),\t\ttheta = 22.5:22.5:180;\t\tend\nif notDefined('sz'),\t\tsz = [128 128];\t\t\t\tend\n\n%%%%% params / setup\n%% constants\nkappa = 2.5; % pi; % constrains the spat. freq. bandwith to be 1 octave\n\n%% parse inputs\nif length(sz)==1 % square image, only 1 size specified\n\tsz = [sz sz];\nend\n\n%% init empty struct\nG.odd = [];\nG.even = [];\nG.layer = [];\nG.cyclesPerImage = [];\nG.orientation = [];\nG.x0 = [];\nG.y0 = [];\n\n\n%%%%% (1) determine the number of channels\n% first, convert the spatial frequency param s into units of cycles per\n% image (cpi):\ncpi = 2 .^ s; \n\n% we add one channel for the DC component:\ncpi = [0 cpi];\n\n% for each # of cycles/image, we have a square grid of positions for that\n% frequency (see Kay et al, Sup Fig 2). \ntmp = sum( cpi .^ 2 ); % # of joint spatial-frequency/position combinations\n\n% for each layer except the first one, we have one channel for each\n% orientation. So, figure out the total # of channels:\nnChannels = tmp * length(theta) + 1;\nG.nChannels = nChannels;\n\n%%%%% (2) determine parameters for each channel\n% now, assign to each channel a unique combination of spatial frequency\n% (cyclesPerImage), orientation, and position (x0 and y0). We'll call the \n% set of channels corresponding to this spat. freq a \"layer\" in the pyramid:\nfor layer = 1:length(cpi)\n\t% the 0 cycles/image layer is a special case: only 1 DC channel\n\tif cpi(layer)==0\n\t\tG.layer = 1;\n\t\tG.cyclesPerImage = 0;\n\t\tG.orientation = 0; % could be NaN; this will help w/ plotting\n\t\tG.x0 = 0;\n\t\tG.y0 = 0;\n\t\t\n\telse\n\t\t% # positions along x/y axis for this layer\n\t\tnGrid = cpi(layer); \n\t\t\n\t\t% # channels in this layer\n\t\tn = length(theta) * nGrid ^ 2;\n\n\t\t% append cpi, orientation values\n\t\tG.layer = [G.layer repmat(layer, [1 n])];\t\t\n\t\tG.cyclesPerImage = [ G.cyclesPerImage, repmat(cpi(layer), [1 n]) ];\n\t\tG.orientation = [ G.orientation, repmat(theta, [1 nGrid^2]) ];\n\t\t\n\t\t% get a grid of (x0, y0) centers for each position for this layer\n\t\t% these positions are in pixels from the uppper left-hand corner of\n\t\t% the image:\n\t\tyRange = linspace(0, sz(1), nGrid+2); yRange = yRange(2:end-1);\n\t\txRange = linspace(0, sz(2), nGrid+2); xRange = xRange(2:end-1);\n\t\t[x0 y0] = meshgrid( xRange, yRange );\n\t\t\n\t\t% we tile the position space separately for each orientation\n\t\tx0 = repmat(x0(:)', [length(theta) 1]);\n\t\ty0 = repmat(y0(:)', [length(theta) 1]);\n\t\tG.x0 = [G.x0, x0(:)'];\n\t\tG.y0 = [G.y0, y0(:)'];\n\tend\nend\n\n\n%%%%% (3) create the channels\n% initialize the empty channels\nG.odd\t= zeros(sz(1), sz(2), nChannels);\nG.even\t= zeros(sz(1), sz(2), nChannels);\n\n% main loop\nfor n = 1:nChannels\n\t% get a map of (x,y) pixel positions relative to the center of the\n\t% Gabor function for this channel (x0, y0) across the image\n\t[x y] = meshgrid( [1:sz(2)] - G.x0(n), [1:sz(1)] - G.y0(n) );\n\t\n\t% express the orientation in radians\n\ttheta = G.orientation(n) * pi/180;\n\t\n\t% convert spatial frequency from units of cycles per image to units of\n\t% radians per unit distance: we take as the image size the larger of\n\t% the two edge lengths for the image:\n\tomega = 2*pi * G.cyclesPerImage(n)*2 / max(sz);\n\t\n\t% compute the wavelet\n\tphi = gaborWavelet(x, y, theta, omega, kappa);\n\n\t% grab the odd and even components\n\tG.even(:,:,n)\t= real(phi);\n\tG.odd(:,:,n)\t= imag(phi);\t\nend\n\n% to save memory, let's make everything single-precision\nfor f = fieldnames(G)'\n\tG.(f{1}) = single( G.(f{1}) );\nend\n\nreturn\n\n\n\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/mrBOLD/Analysis/retinotopyModel/GaborTools/gaborPyramid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650403, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7301268842511481}} {"text": "%% DEMO 9: Algorithms 04. Total Variation minimization algorithms\n%\n%\n% This demo presents the Total variation algorithms in TIGRE. Total\n% variation algorithms try to minimize the variation (gradient) of the\n% image, assuming its piecewise smooth, as most things in nature are (i.e.\n% human body). \n%\n% This set of algorithms is specially good performing when the noise is\n% very big or the number of projections is small, however, they require more\n% computational time and memory than the other algorithms to run.\n% \n%\n% This Demo is not fully complete, as several algorithms are not shown\n% here, yet are available in TIGRE, namely:\n%\n% - AwASD_POCS: Edge preserving ASD_POCS (Adaptative weigthed).\n% - OS_AwASD_POCS: OS-version of the previous algorithm\n% - PCSD: A version of ASD_POCS that heuristically select some of the\n% parameters, particularly epsilon (maxL2norm)\n% - AwPCSD: Edge preserving version of the previous algorithm\n% - OS_AwPCSD: block-wise version of the previous\n%\n% You can use these algorithms in a very similar manner as below examples.\n%--------------------------------------------------------------------------\n%--------------------------------------------------------------------------\n% This file is part of the TIGRE Toolbox\n% \n% Copyright (c) 2015, University of Bath and \n% CERN-European Organization for Nuclear Research\n% All rights reserved.\n%\n% License: Open Source under BSD. \n% See the full license at\n% https://github.com/CERN/TIGRE/blob/master/LICENSE\n%\n% Contact: tigre.toolbox@gmail.com\n% Codes: https://github.com/CERN/TIGRE/\n% Coded by: Ander Biguri \n%--------------------------------------------------------------------------\n%% Initialize\nclear;\nclose all;\n\n%% Define Geometry\ngeo=defaultGeometry('nVoxel',[128;128;128]); \n\n%% Load data and generate projections \n% see previous demo for explanation\nangles=linspace(0,2*pi-2*pi/30,30);\nhead=headPhantom(geo.nVoxel);\nprojections=Ax(head,geo,angles,'interpolated');\nnoise_projections=addCTnoise(projections);\n\n%% Lets create a OS-SART test for comparison\n[imgOSSART,errL2OSSART]=OS_SART(noise_projections,geo,angles,60);\n\n%% Total Variation algorithms\n%\n% ASD-POCS: Adaptative Steeppest Descent-Projection On Convex Subsets\n% Often called POCS-TV\n%==========================================================================\n%==========================================================================\n% ASD-POCS minimizes At-B and the TV norm separately in each iteration,\n% i.e. reconstructs the image first and then reduces the TV norm, every\n% iteration. As the other algorithms the mandatory inputs are projections,\n% geometry, angles and maximum iterations.\n%\n% ASD-POCS has a veriety of optional arguments, and some of them are crucial\n% to determine the behaviour of the algorithm. The advantage of ASD-POCS is\n% the power to create good images from bad data, but it needs a lot of\n% tunning. \n%\n% Optional parameters that are very relevant:\n% ----------------------------------------------\n% 'maxL2err' Maximum L2 error to accept an image as valid. This\n% parameter is crucial for the algorithm, determines at\n% what point an image should not be updated further.\n% Default is 20% of the FDK L2 norm.\n% \n% its called epsilon in the paper\nepsilon=im3Dnorm(Ax(FDK(noise_projections,geo,angles),geo,angles)-noise_projections,'L2')*0.15;\n% 'alpha': Defines the TV hyperparameter. default is 0.002. \n% However the paper mentions 0.2 as good choice\nalpha=0.002;\n\n% 'TViter': Defines the amount of TV iterations performed per SART\n% iteration. Default is 20\n\nng=25;\n\n% Other optional parameters\n% ----------------------------------------------\n% 'lambda': Sets the value of the hyperparameter for the SART iterations. \n% Default is 1\n%\n% 'lambdared': Reduction of lambda Every iteration\n% lambda=lambdared*lambda. Default is 0.99\n%\nlambda=1;\nlambdared=0.9999;\n\n\n% 'alpha_red': Defines the reduction rate of the TV hyperparameter\nalpha_red=0.95;\n\n% 'Ratio': The maximum allowed image/TV update ration. If the TV \n% update changes the image more than this, the parameter\n% will be reduced.default is 0.95\nratio=0.94;\n\n% 'Verbose' 1 or 0. Default is 1. Gives information about the\n% progress of the algorithm.\n\nverb=true;\n\nimgASDPOCS=ASD_POCS(noise_projections,geo,angles,50,...\n 'TViter',ng,'maxL2err',epsilon,'alpha',alpha,... % these are very important\n 'lambda',lambda,'lambda_red',lambdared,'Ratio',ratio,'Verbose',verb); % less important.\n\n\n\n \n% OS_ASD_POCS: Odered Subset-TV algorithm\n%==========================================================================\n%==========================================================================\n%\n% The logical next step to imporce ASD-POCS is substituting SART with a\n% faster algorithm, such as OS-SART\n%\n% The parameters are the same as in ASD-POCS, but also have 'BlockSize' and\n% @OrderStrategy', taken from OS-SART\n\nimgOSASDPOCS=OS_ASD_POCS(noise_projections,geo,angles,50,...\n 'TViter',ng,'maxL2err',epsilon,'alpha',alpha,... % these are very important\n 'lambda',lambda,'lambda_red',lambdared,'Ratio',ratio,'Verbose',verb,...% less important.\n 'BlockSize',size(angles,2)/10,'OrderStrategy','angularDistance'); %OSC options\n \n \n \n% B-ASD-POCS-beta \n%==========================================================================\n%==========================================================================\n% Is another version of ASD-POCS that has uses Bregman iteration, i.e.\n% updates the data vector every some ASD-POCS iteration, bringing closer\n% the data to the actual image. According to the original article, this\n% accelerates convergence rates, giving a better image in the same amount\n% of iteratiosn.\n%\n% It has all the inputs from ASD-POCS, and has 3 extra:\n% 'beta' hyperparameter controling the Bragman update. default=1\n% \n% 'beta_red' reduction of the beta hyperparameter. default =0.75\n% \n% 'bregman_iter' amount of global bregman iterations. This will define\n% how often the bregman iteration is executed. It has to\n% be smaller than the number of iterations.\n\n%Note that the number of iteration for TV has changed\n\nimgBASDPOCSbeta=B_ASD_POCS_beta(noise_projections,geo,angles,50,...\n 'TViter',40,'maxL2err',epsilon,'alpha',alpha,... % these are very important\n 'lambda',lambda,'lambda_red',lambdared,'Ratio',ratio,'Verbose',verb,... % less important.\n 'beta',0.5,'beta_red',0.7,'bregman_iter',10); % bregman options\n \n% SART-TV \n%==========================================================================\n%========================================================================== \n%\n% This implementation differs more from the others, as it minimizes the\n% ROF model, i.e. when minimizing the total variation of the image, it\n% also takes into account the information of the image. If only the total\n% variation minimization step was run in the rest of the algorithms, the\n% result would be a flat image (as that is the minimum total variation\n% image), altertatively, the ROF model enforces the image not to change too\n% much.\n% \n% This algirths performs better with more projections, but noisy data, by\n% enforncing the TV very little\n% \n% The optional parameters are for the total variatiot part of the image:\n%\n%\n% \n% 'TViter' amoutn of iteration in theTV step. Default 50\n% \n% 'TVlambda' hyperparameter in TV iteration. IT gives the ratio of\n% importance of the image vs the minimum total variation.\n% default is 15. Lower means more TV denoising.\n% \n \nimgSARTTV=SART_TV(noise_projections,geo,angles,50,'TViter',100,'TVlambda',50); \n\n\n% IRN_TV_CGLS\n%==========================================================================\n%========================================================================== \n% CGLS with TV regularization in an inner/outer iteration scheme\n%\n% 'lambda' hyperparameter in TV norm. It gives the ratio of\n% importance of the image vs the minimum total variation.\n% default is 15. Lower means less TV denoising.\n%\n% 'niter_outer' Number of outer iterations. Each outer iteration will\n% perform niter number of inner iterations, in the example\n% below, 20.Albeit this seems that it does many more\n% iterations than the other algorithms, this is an inherently\n% faster algorithm, both in convergence and time. \n\nimgIRN_TV_CGLS=IRN_TV_CGLS(noise_projections,geo,angles,20,'lambda',5,'niter_outer',2);\n% hybrid_fLSQR_TV\n%==========================================================================\n%========================================================================== \n% flexyble hybrod LSQR. Has TV regularization with reorthogonalization. \n%\n% 'lambda' hyperparameter in TV norm. It gives the ratio of\n% importance of the image vs the minimum total variation.\n% default is 15. Lower means less TV denoising.\n%\nimgflsqr=hybrid_fLSQR_TV(projections,geo,angles,20,'lambda',5);\n\n %% Lets visualize the results\n% Notice the smoother images due to TV regularization.\n%\n% head OS-SART ASD-POCS \n% \n% OS-ASD-POCS B-ASD-POCS-beta SART-TV\n%\n% IRN-TV-CGLS hybrid-fLSQR heads\n\nplotImg([imgIRN_TV_CGLS imgflsqr head;\n imgOSASDPOCS imgBASDPOCSbeta imgSARTTV;\n head, imgOSSART, imgASDPOCS ] ,'Dim','Z','Step',2,'clims',[0 1])\n % error\nplotImg(abs([head-imgIRN_TV_CGLS head-imgflsqr head-head;\n head-imgOSASDPOCS head-imgBASDPOCSbeta head-imgSARTTV;\n head-head, head-imgOSSART, head-imgASDPOCS ]) ,'Dim','Z','Slice',64,'clims',[0 0.1])\n\n%%\n% Obligatory XKCD reference: https://xkcd.com/833/\n\n\n\n", "meta": {"author": "CERN", "repo": "TIGRE", "sha": "8df632662228d1b1c52afd95c90d0f7a9f8dc4b3", "save_path": "github-repos/MATLAB/CERN-TIGRE", "path": "github-repos/MATLAB/CERN-TIGRE/TIGRE-8df632662228d1b1c52afd95c90d0f7a9f8dc4b3/MATLAB/Demos/d09_Algorithms04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.7301268839141728}} {"text": "function [r,s] = xytors(x,y)\n\n% function [r,s] = xytors(x, y)\n% Purpose : From (x,y) in equilateral triangle to (r,s) coordinates in standard triangle\n\nL1 = (sqrt(3.0)*y+1.0)/3.0;\nL2 = (-3.0*x - sqrt(3.0)*y + 2.0)/6.0;\nL3 = ( 3.0*x - sqrt(3.0)*y + 2.0)/6.0;\n\nr = -L2 + L3 - L1; s = -L2 - L3 + L1;\nreturn;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes2D/xytors.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9525741322079104, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7299515020790464}} {"text": "%SKEW Create skew-symmetric matrix\n%\n% S = SKEW(V) is a skew-symmetric matrix formed from V.\n% \n% If V (1x1) then S =\n%\n% | 0 -v |\n% | v 0 |\n%\n% and if V (1x3) then S =\n%\n% | 0 -vz vy |\n% | vz 0 -vx |\n% |-vy vx 0 |\n%\n%\n% Notes::\n% - This is the inverse of the function VEX().\n% - These are the generator matrices for the Lie algebras so(2) and so(3).\n%\n% References::\n% - Robotics, Vision & Control: Second Edition, Chap 2,\n% P. Corke, Springer 2016.\n%\n% See also SKEWA, VEX.\n\n% Copyright (C) 1993-2019 Peter I. Corke\n%\n% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n% of the Software, and to permit persons to whom the Software is furnished to do\n% so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%\n% https://github.com/petercorke/spatial-math\n\nfunction S = skew(v)\n if isvec(v,3)\n % SO(3) case\n S = [ 0 -v(3) v(2)\n v(3) 0 -v(1)\n -v(2) v(1) 0];\n elseif isvec(v,1)\n % SO(2) case\n S = [0 -v; v 0];\n else\n error('SMTB:skew:badarg', 'argument must be a 1- or 3-vector');\n end\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/skew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7299463025722294}} {"text": "function f = p37_f ( n, x )\n\n%*****************************************************************************80\n%\n%% P37_F evaluates the objective function for problem 37.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 January 2001\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Zbigniew Michalewicz,\n% Genetic Algorithms + Data Structures = Evolution Programs,\n% Third Edition,\n% Springer Verlag, 1996,\n% ISBN: 3-540-60676-9,\n% LC: QA76.618.M53.\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 arg = - ( x(1) - pi )^2 - ( x(2) - pi )^2;\n f = - cos ( x(1) ) * cos ( x(2) ) * exp ( arg );\n\n return\nend\n", "meta": {"author": "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/p37_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7299224430996945}} {"text": "function [ sa, seed ] = wshrt ( d, n, np, seed )\n\n%*****************************************************************************80\n%\n%% WSHRT returns a random Wishart variate.\n%\n% Discussion:\n%\n% This routine is a Wishart variate generator. \n%\n% On output, SA is an upper-triangular matrix of size NP * NP,\n% written in linear form, column ordered, whose elements have a \n% Wishart(N, SIGMA) distribution.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 April 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by William Smith, Ronald Hocking.\n% This MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% William Smith, Ronald Hocking,\n% Algorithm AS 53, Wishart Variate Generator,\n% Applied Statistics,\n% Volume 21, Number 3, pages 341-345, 1972.\n%\n% Parameters:\n%\n% Input, real D(NP*(NP+1)/2), the upper triangular array that\n% represents the Cholesky factor of the correlation matrix SIGMA.\n% D is stored in column-major form.\n%\n% Input, integer N, the number of degrees of freedom.\n% 1 <= N <= NP.\n%\n% Input, integer NP, the size of variables.\n%\n% Input/output, integer SEED, a seed for the random number generator.\n%\n% Output, real SA(NP*(NP+1)/2), a sample from the Wishart distribution.\n%\n k = 1;\n%\n% Load SB with independent normal (0, 1) variates.\n%\n nnp = floor ( ( np * ( np + 1 ) ) / 2 );\n sb = zeros ( nnp );\n\n while ( k <= nnp )\n\n [ u1, u2, seed ] = rnorm ( seed );\n\n sb(k) = u1;\n k = k + 1;\n\n if ( k <= nnp )\n sb(k) = u2;\n k = k + 1;\n end\n\n end\n%\n% Load diagonal elements with square root of chi-square variates.\n%\n sa = zeros ( nnp );\n\n ns = 0;\n\n for i = 1 : np\n%\n% The original text read \"DF = N - I + 1\".\n% This should read \"DF = NP - I + 1\".\n%\n df = np - i + 1;\n ns = ns + i;\n u1 = 2.0 / ( 9.0 * df );\n u2 = 1.0 - u1;\n u1 = sqrt ( u1 );\n%\n% Wilson-Hilferty formula for approximating chi-square variates:\n% The original code did not take the absolute value!\n%\n sb(ns) = sqrt ( df * abs ( ( u2 + sb(ns) * u1 ) ^ 3 ) );\n\n end\n\n rn = n;\n nr = 1;\n\n for i = 1 : np\n nr = nr + i - 1;\n for j = i : np\n ip = nr;\n nq = floor ( ( j * ( j - 1 ) ) / 2 ) + i - 1;\n c = 0.0;\n for k = i : j\n ip = ip + k - 1;\n nq = nq + 1;\n c = c + sb(ip) * d(nq);\n end\n sa(ip) = c;\n end\n end\n\n for i = 1 : np\n ii = np - i + 1;\n nq = nnp - np;\n for j = 1 : i\n ip = floor ( ( ii * ( ii - 1 ) ) / 2 );\n c = 0.0;\n for k = i : np\n ip = ip + 1;\n nq = nq + 1;\n c = c + sa(ip) * sa(nq);\n end\n sa(nq) = c / rn;\n nq = nq - 2 * np + i + j - 1;\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/asa053/wshrt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.729894572622152}} {"text": "%%DEMOGRAVCODENOCOMPILE This file demonstrates the functions for spherical\n% harmonic synthesis of gravitational and terrain\n% data. Unlike the function DemoGravCode, this\n% function does not make any plots, but does run fast\n% even when the mex files have not ben compiled. The\n% gravitational code library (that this function is\n% part of) must have been added to Matlab's search\n% path for this function to work.\n%\n%Rather than using advanced spherical harmonic models at high orders, this\n%function loads spherical harmonic coefficients only up to degree and order\n%50 for a simple ellipsoidal Earth model. The gravitational potential and\n%acceleration due to gravity from the ellipsoidal model as generated by the\n%coefficients are shown to match (within reasonable precision bounds) the\n%results obtained from closed-form functions.\n%\n%When run, the error in the potential should be 5.9474e-14% and the error\n%in the magnitude of the gravitational acceleration should be 3.3790e-12%.\n%\n%February 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nM=50;%The maximum degree and order of the model.\n%Generate coefficients for an ellipsoidal Earth model.\n[C,S,a,c]=ellipsGravCoeffs(M);\n\nlambda=-20*pi/180;%Longitude\ntheta=80*pi/180;%Ellipsoidal latitude\n%The zero altitude places the point on the reference ellipsoid.\npointEllips=[theta;lambda;0];\npointSpher=ellips2Sphere(pointEllips);%Convert to spherical coordinates.\n\n%Compute the potential and acceleration due to gravity.\n[V,gradV]=spherHarmonicEval(C,S,pointSpher,a,c);\n\n%Add in the centripetal effects of the Earth's rotation. The formulae for\n%the extra terms in the potential and acceleration due to gravity can be\n%found in Chapters 2.1 and 2.7 of\n%B. Hofmann-Wellenhof and H. Moritz, Physical Geodesy, 2nd ed. \n%SpringerWienNewYork, 2006.\nCartPoint=ellips2Cart(pointEllips);%Convert to Cartesian coordinates.\nomega=Constants.WGS84EarthRotationRate;\nU=V+0.5*omega^2*(CartPoint(1)^2+CartPoint(2)^2);%The gravity potential\n%Acceleration due to gravity with the Earth's rotation.\ng=gradV+omega^2*[CartPoint(1);CartPoint(2);0];\n\n%Get the exact values of U and g from explicit formulas for the ellipsoidal\n%Earth approximation.\n[U0,g0]=ellipsParam2Grav(CartPoint);\n\ndisp('The geodetic latitude and longitude of the point on the surface of')\ndisp('the WGS-84 reference ellipsoid where the values are computed are (in degrees)')\nlatitude=theta*(180/pi)\nlongitude=lambda*(180/pi)\n\ndisp('The gravity potential from the spherical harmonic solution is (in m^2/s^2)')\nU\n\ndisp('The gravitational acceleration vector (with centripetal acceleration)')\ndisp('from the spherical harmonic solution is (in m/s^2)')\ng\n\ndisp('The percent error in the potential from the spherical harmonic')\ndisp('approximation and from the explicit solution is')\npercentErrorPotential=100*(U-U0)/U0\n\ndisp('The percent error in the gravitational acceleration magnitude from')\ndisp('the spherical harmonic approximation and from the explicit solution is')\npercentErrorGravAccel=100*(norm(g)-norm(g0))/norm(g0)\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/Sample_Code/Gravitational_Models/DemoGravCodeNoCompile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7298945641661598}} {"text": "%==============================================================================\n% This code is part of the Matlab-based toolbox\n% FAIR - Flexible Algorithms for Image Registration. \n% For details see \n% - https://github.com/C4IR and\n% - http://www.siam.org/books/fa06/\n% ##2\n%==============================================================================\n%\n% Tutorial for FAIR: regulariztion\n%\n% given a certain force field f on a 2D domain, this tutorial \n% computes and visualizes the curvature regularized displacement u, such that \n%\n% B'*B u = f\n%\n% where B is the discrete curvature operator \n% see also getCurvatureMatrix\n%==============================================================================\n\nclear, close all, help(mfilename);\n\n % 2D example\nomega = [0,1,0,1]; % physical domain\nm = [16,12]; % number of discretization points\nn = prod(m); % number of cells, and staggered dimensions\nhd = prod((omega(2:2:end)-omega(1:2:end))./m);\nalpha = 10;\n\n% generate cell centered and nodal grids\n% note: computation is cell centered, others used for visualization\nxc = getCellCenteredGrid(omega,m);\nxn = getNodalGrid(omega,m);\n\n% build elasticity operator on a staggered grid and visualize\nB = getCurvatureMatrix(omega,m);\nFAIRfigure(1); clf; subplot(2,2,1); spy(B); title('B curcature on cell-centered grid')\n\n% create a force field o cell centered grid and visualize\nfc = [0*xc(1:n);-10*sin(pi*xc(1:n))];\n\n% compute the displacement from (B'*B)*us = fs\n% note B is derivative operator and has null space (constants)\n\n% remove constant parts: E'*(f-E*w) = 0\nE = [ones(n,1)*[1,0];ones(n,1)*[0,1]];\nfc = fc - E*((E'*E)\\(E'*fc));\n\n% solve for displacements\nwarning off % matrix is singular, but MATLAB doesn't care\nuc = hd*alpha*(B'*B)\\fc;\nwarning on\n\n% visualization on cell centered and nodal grids\nun = grid2grid(uc,m,'centered','nodal');\n\n% shortcuts for visualization, \nvecNorm = @(v) sqrt(sum(reshape(v,[],2).^2,2));\nviewField = @(v) viewImage2Dsc(vecNorm(v),omega,m); \nPG = @(x) plotGrid(x,omega,m);\n\n% visualize force field\nFAIRfigure(1); subplot(2,2,3);\nviewField(fc); hold on; colormap(gray); colorbar; PG(xn); \nqh = quiver(xc(1:n),xc(n+1:end),fc(1:n),fc(n+1:end),1);\nset(qh,'color','r','linewidth',1)\ntitle('a force field')\n\n% visualize displacement field\nFAIRfigure(1); subplot(2,2,4);\nviewField(uc); hold on; colormap(gray); colorbar; PG(xn);\nqh = quiver(xc(1:n),xc(n+1:end),uc(1:n),uc(n+1:end),1);\nset(qh,'color','g','linewidth',1)\ntitle('the displacement field')\n\n% visuaize the displaced grid\nFAIRfigure(1); subplot(2,2,2);\nxh = PG(xn); hold on; axis equal image; yh = PG(xn+un); \nset(xh,'linewidth',2); set(xh,'linewidth',2,'color','g');\ntitle('initial and displaced grids')\n\n%==============================================================================\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/examples/E8_forcesCurvature.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7298945599381638}} {"text": "function [trans,rot,scale,skew] = affineDecompose(A)\n%\n% [trans,rot,scale,skew] = affineDecompose(A)\n%\n% Decomposes an affine (orthogonal linear) transformation matrix into its\n% four componets: translations, rotations scales and skews.\n%\n% (See affineBuild for more info.)\n%\n% HISTORY:\n% 2004.03.12 RFD (bob@white.stanford.edu) shamelessly copied the core\n% algorithm from spm99's spm_imatrix.m.\n% 2005.07.08 ras (sayres at stanford edu) imported into mrVista 2.0\n\n% Translations and zooms\n%-----------------------------------------------------------------------\nR = A(1:3,1:3);\nC = chol(R'*R);\nP = [A(1:3,4)' 0 0 0 diag(C)' 0 0 0];\nif det(R)<0, P(7)=-P(7);end % Fix for -ve determinants\n\n% Shears\n%-----------------------------------------------------------------------\nC = diag(diag(C))\\C;\nP(10:12) = C([4 7 8]);\nR0 = affineBuild([0 0 0], [0 0 0], P(7:9), P(10:12));\nR0 = R0(1:3,1:3);\nR1 = R/R0;\n\n% This just leaves rotations in matrix R1\n%-----------------------------------------------------------------------\n%[ c5*c6, c5*s6, s5]\n%[-s4*s5*c6-c4*s6, -s4*s5*s6+c4*c6, s4*c5]\n%[-c4*s5*c6+s4*s6, -c4*s5*s6-s4*c6, c4*c5]\n\nP(5) = asin(rang(R1(1,3)));\nif (abs(P(5))-pi/2).^2 < 1e-9,\n\tP(4) = 0;\n\tP(6) = atan2(-rang(R1(2,1)), rang(-R1(3,1)/R1(1,3)));\nelse,\n\tc = cos(P(5));\n\tP(4) = atan2(rang(R1(2,3)/c), rang(R1(3,3)/c));\n\tP(6) = atan2(rang(R1(1,2)/c), rang(R1(1,1)/c));\nend;\ntrans = P(1:3);\nrot = P(4:6);\nscale = P(7:9);\nskew = P(10:12);\nreturn;\n\n% There may be slight rounding errors making b>1 or b<-1.\nfunction a = rang(b)\na = min(max(b, -1), 1);\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/RSVista/mrMethods/coords/affineDecompose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973295, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7298636059351862}} {"text": "function y = logSt(X, mu, sigma, v)\n% Compute log pdf of a Student's t distribution.\n% Input:\n% X: d x n data matrix\n% mu: mean\n% sigma: variance\n% v: degree of freedom\n% Output:\n% y: probability density in logrithm scale y=log p(x)\n% Written by mo Chen (sth4nth@gmail.com).\n[d,k] = size(mu);\n\nif size(sigma,1)==d && size(sigma,2)==d && k==1\n [R,p]= chol(sigma);\n if p ~= 0\n error('ERROR: sigma is not SPD.');\n end\n X = bsxfun(@minus,X,mu);\n Q = R'\\X;\n q = dot(Q,Q,1); % quadratic term (M distance)\n o = -log(1+q/v)*((v+d)/2);\n c = gammaln((v+d)/2)-gammaln(v/2)-(d*log(v*pi)+2*sum(log(diag(R))))/2;\n y = c+o;\nelseif size(sigma,1)==d && size(sigma,2)==k\n lambda = 1./sigma;\n ml = mu.*lambda;\n q = bsxfun(@plus,X'.^2*lambda-2*X'*ml,dot(mu,ml,1)); % M distance\n o = bsxfun(@times,log(1+bsxfun(@times,q,1./v)),-(v+d)/2);\n c = gammaln((v+d)/2)-gammaln(v/2)-(d*log(pi*v)+sum(log(sigma),1))/2;\n y = bsxfun(@plus,o,c);\nelseif size(sigma,1)==1 && size(sigma,2)==k\n X2 = repmat(dot(X,X,1)',1,k);\n D = bsxfun(@plus,X2-2*X'*mu,dot(mu,mu,1));\n q = bsxfun(@times,D,1./sigma); % M distance\n o = bsxfun(@times,log(1+bsxfun(@times,q,1./v)),-(v+d)/2);\n c = gammaln((v+d)/2)-gammaln(v/2)-d*log(pi*v.*sigma)/2;\n y = bsxfun(@plus,o,c);\nelse\n error('Parameters are mismatched.');\nend\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter02/logSt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7298604024003235}} {"text": "function P=ar1spectrum(ar1,period)\n%% AR1 power spectrum.\n%\n% power=ar1spectrum(ar1,period)\n%\n%\n% (c) Aslak Grinsted 2002-2014\n%\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\nfreq=1./period;\nP=(1-ar1.^2)./(abs(1-ar1.*exp(-2*pi*i*freq))).^2; %http://www.madsci.org/posts/archives/may97/864012045.Eg.r.html\n%fixed typo in numerical recipes\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/ar1spectrum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297807787538, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7298603939506891}} {"text": "function point_num = gp_se_size ( dim_num, level_max )\n\n%*****************************************************************************80\n%\n%% GP_SE_SIZE: Gauss Patterson Slow Exponential Growth.\n%\n% Discussion:\n%\n% The Gauss Patterson Slow Exponential Growth family assumes that, for the \n% underlying 1D rules, a precision of 2*L+1 is needed at level L. Therefore, \n% the lowest possible order Gauss-Patterson rule is chosen that will achieve\n% that precision. This retains a combination of the advantages of\n% nestedness and high accuracy.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 January 2010\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% Count the points in the 1D rule.\n%\n order_1d = zeros ( level_max+1, 1 );\n\n order_1d(0+1) = 1;\n for level = 1 : level_max\n p = 5;\n o = 3;\n while ( p < 2 * level + 1 )\n p = 2 * p + 1;\n o = 2 * o + 1;\n end\n order_1d(level+1) = o;\n end\n%\n% Count the new points in the 1D rule.\n%\n new_1d = zeros(level_max+1,1);\n\n new_1d(0+1) = 1;\n for level = 1 : level_max\n new_1d(level+1) = order_1d(level+1) - order_1d(level-1+1);\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 level_1d = [];\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_count/gp_se_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7298148494230888}} {"text": "function [ o, x, w ] = epn_glg_00_1 ( n, alpha )\n\n%*****************************************************************************80\n%\n%% EPN_GLG_00_1 implements the \"midpoint rule\" for region EPN_GLG.\n%\n% Discussion:\n%\n% The rule has order O = 1.\n%\n% The rule has precision P = 0.\n%\n% EPN_GLG is the N-dimensional positive space [0,+oo)^N with generalized\n% Laguerre weight function:\n%\n% w(alpha;x) = product ( 1 <= i <= n ) x(i)^alpha exp ( - x(i) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n%\n% Input, real ALPHA, the exponent of X in the weight function.\n% -1.0 < ALPHA.\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 if ( alpha <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EPN_GLG_00_1 - Fatal error!\\n' );\n fprintf ( 1, ' ALPHA <= -1.0\\n' );\n error ( 'EPN_GLG_00_1 - Fatal error!' );\n end\n\n expon = 0;\n volume = ep1_glg_monomial_integral ( expon, alpha );\n volume = volume ^ n;\n\n o = 1;\n\n x = zeros ( n, o );\n w = zeros ( o, 1 );\n\n k = 0;\n%\n% 1 point.\n%\n k = k + 1;\n x(1:n,k) = 1.0;\n w(k) = 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/epn_glg_00_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7298148295534201}} {"text": "function [ Pxx, Pyy, Pxy, coh, pha, freq ] = func_coherence( f1, f2, nfft, Fs, filt, n_overlap )\n\n%\n% Computing power spectrum, cross spectrum, coherence and phase\n%\n% All input parameters are equivalent to csd or the other spectrum \n% related function in MATLAB.\n%\n% This program use csd.m in Signal Processing Toolbox.\n%\n% Input\n%\tf1 and f2\tinput data\n%\tnfft\t\tnumber of data for FFT\n%\tFs\t\tsampling frequency\n%\tfilt\t\tfilter vector, hanning(nfft/2)\n%\tn_overlap\tnumber of overlap for smoothing\n%\n% Output\n%\tPxx\t\tspectrum of f1\n%\tPyy\t\tspectrum of f2\n%\tPxy\t\tcross spectrum between f1 and f2\n%\tcoh\t\tcoherence\n%\tpha\t\tphase\n%\tfreq\t\tfrequency vector\n%\n%======================================================================\n% Terms:\n%\n% Distributed under the terms of the terms of the BSD License\n%\n% Copyright:\n%\n% Nobuhito Mori\n% Disaster Prevention Research Institue\n% Kyoto University\n% mori@oceanwave.jp\n%\n%========================================================================\n\n[Pxx,freq] = csd( f1, f1, nfft, Fs, filt, n_overlap );\n[Pyy,freq] = csd( f2, f2, nfft, Fs, filt, n_overlap );\n[Pxy,freq] = csd( f1, f2, nfft, Fs, filt, n_overlap );\n\nKxy = real( Pxy );\nQxy = imag( Pxy );\ncoh = Pxy.*conj(Pxy)./(Pxx.*Pyy);\npha = atan2( Qxy, Kxy );\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/3194-funccoherence-m/func_coherence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.729778091832712}} {"text": "function [rootVals,exitCode]=polyRootsMultiDim(polyCoeffMats,maxDegIncreases,useMotzkinNull)\n%%POLYROOTSMULTIDIM Find the roots of a system of simultaneous multivariate\n% polynomials. Only the affine roots are found (which are\n% generally the only ones desired), not the roots at\n% infinity. The algorithm used transforms the\n% multivariate root finding problem into a generalized\n% eigenvalue problem involving the nullspace of a\n% Macaulay matrix. Due to finite precision errors and the\n% combinational complexity of the algorithm, it is\n% generally best if the maximum number of variables is\n% <=3 and the maximum degree of the polynomials is <=3.\n% Sparser polynomials are much easier than dense ones\n% (where all possible monomial coefficients are nonzero).\n% When dealing with dense polynomials, it is generally\n% best if the maximum number of variables is 2, where the\n% maximum degree can get as high as sixth order without\n% notable problems.\n%\n%INPUTS: polyCoeffMats An nX1 or 1Xn cell array containing n hypermatrices\n% of polynomial coefficients for a multivariate polynomial. A\n% hypermatrix of the coefficients for a multivariate\n% polynomial contains elements arranged such that\n% coeffs(a1,a2,a3...an) corresponds to the coefficient of an\n% x1^(a1-1)*x2^(a2-1)*x3^(a3-1)...xn^(an-1) term. Thus, the\n% number of indices coeffs takes is equal to the\n% dimensionality of x (not counting singleton dimensions at\n% the end of coeffs). Note that this ordering is the reverse\n% that used in the 1D polyval function that is built into\n% Matlab. The number of elements for each index in coeffs is\n% the maximum order of that dimension +1.\n% maxDegIncreases An optional parameter specifying the maximum number\n% of degree increases of the Motzkin matrix to use when\n% trying to solve the multivariate polynomial system. If\n% maxDegIncreases is too small, then the polynomial root\n% solver will fail. This parameter is provided as an option\n% to help identify when solving large systems would be very\n% slow. The default if this parameter is omitted or an empty\n% matrix is passed is 10*n. If one wishes there to be no\n% limit, then one can set maxDegIncreases to Inf and degree\n% increases will be allowed until Matlab runs out of memory.\n% useMotzkinNull A key step in the algorithm is the determination of\n% nullspaces. By defauly, the nullspace function is used.\n% However, if desired, the Motzkin algorithm described in [1]\n% can be used. The Motzkin algorithm is generally not as\n% numerically stable, but it can be useful if one wishes to\n% step through the code and compare the results to the values\n% in [1].\n%\n%OUTPUTS: rootVals An nXnumSol matrix of the numSol zeros of the polynomial\n% system found, or an empty matrix if exitCode does not\n% equal zero.\n% exitCode A parameter indicating how the algorithm terminated.\n% Possible values:\n% 0 The algorithm was a success; the roots were found.\n% 1 The maximum number of degree increases elapsed.\n% 2 A finite precision error occured either causing the\n% nullity of the Macaulay matrix to change after\n% stabilization, or to decrease when the degree was\n% increased.\n%\n%This function implements Algorithm 3 of [1], an affine null space based\n%root finding method for multivariate poylnomials. The polynomials in\n%polyCoeffMats are converted into term matrices. The degree negative\n%lexicographic ordering in the paper, for a fixed degree, coincides with\n%the ordering of the terms provided by unrankTComposition with\n%firstElMostSig=true. Thus, ranking and unranking of compositions is used\n%to keep track of the monomials in the columns of the Macaulay matrix.\n%\n%The algorithm requires that a \"shift function\" be chosen (g(x) in [1]).\n%The shift function was arbitrarily chosen to be the sum_{i=1}^n i*xi,\n%where xi is the ith unknown variable. That is, the sum of all first degree\n%terms multiplied by their position.\n%\n%The use of the Motzkin algorithm for finding the nullspace computation\n%(Sections 3.2.1, 3.2.2 and 6.2.5 of [1]) allows one to avoid computation\n%of degree-augmented Macaulay matrices, and provides a basis for the\n%nullspace havign the nice sparse structure as used in [1]. However,\n%Section 6.2.3 demonstrated that the choice of basis for the nullspace does\n%not change the final solution. Thus, the option to use the (possibly more\n%stable) null command (which uses singular value decomposition) is offered,\n%though it does require keeping track of the entire Macaulay matrix.\n%\n%Though the Macaulay matrix has a sparse quasi-Toeplitz structure, the\n%sparsity was not taken advantage of in the implementation of this\n%algorithm.\n%\n%Roots at infinity are not \"true\" solutions to the problem; they only arise\n%when the system of polynomials has been homogenized (all monomial terms in\n%each equation made to have the same total degree) through the introduction\n%of an additional variable. Section 2.3 of [1] discusses what they are.\n%This algorithm does not find them.\n%\n%EXAMPLE 1:\n%An example is the third-order polynomial system on page 94 of [1]. The\n%equations are\n%0=x1^2+5*x1*x2+4*x2*x3-10\n%0=x2^3+3*x1^2*x2-12\n%0=x3^3+4*x1*x2*x3-8\n%Thus, the solution is \n% p=zeros(4,4,4);%First Equation\n% p(2+1,0+1,0+1)=1;\n% p(1+1,1+1,0+1)=5;\n% p(0+1,1+1,1+1)=4;\n% p(0+1,0+1,0+1)=-10;\n% \n% q=zeros(4,4,4);%Second Equation\n% q(0+1,3+1,0+1)=1;\n% q(2+1,1+1,0+1)=3;\n% q(0+1,0+1,0+1)=-12;\n% \n% k=zeros(4,4,4);%Third Equation\n% k(0+1,0+1,3+1)=1;\n% k(1+1,1+1,1+1)=4;\n% k(0+1,0+1,0+1)=-8;\n% \n% polyCoeffMats=cell(3,1);\n% polyCoeffMats{1}=p;\n% polyCoeffMats{2}=q;\n% polyCoeffMats{3}=k;\n% rootVals=polyRootsMultiDim(polyCoeffMats)\n%Where 18 solutions are found. Two are real; the rest complex.\n%\n%EXAMPLE 2:\n%This is the system of equations used as an example in Section 2.1. of [1].\n%0=-x1^2+2*x1*x2+x2^2+5*x1-3*x2-4\n%0=x1^2+2*x1*x2+x2^2-1\n%Thus, the solution is \n% p=zeros(2+1,2+1);\n% p(0+1,0+1)=-4;\n% p(2+1,0+1)=-1;\n% p(1+1,1+1)=2;\n% p(0+1,2+1)=1;\n% p(1+1,0+1)=5;\n% p(0+1,1+1)=-3;\n% \n% q=zeros(3+1,3+1);\n% q(0+1,0+1)=-1;\n% q(2+1,0+1)=1;\n% q(1+1,1+1)=2;\n% q(0+1,2+1)=1;\n% polyCoeffMats=cell(2,1);\n% polyCoeffMats{1}=p;\n% polyCoeffMats{2}=q;\n% rootVals=polyRootsMultiDim(polyCoeffMats)\n%In this instance, all four roots of the system are real. The solutions are\n%(4,-5), (1,0), (3,-2), (0,-1).\n%\n%REFERENCES:\n%[1] P. Dreesen, \"Back to the roots: Polynomial system solving using linear\n% algebra,\" Ph.D. dissertation, Katholieke Universiteit Leuven, Leuven,\n% Flanders, Belgium, Sep. 2013.\n%\n%January 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%The number polynomials and the number of variables.\nn=length(polyCoeffMats);\n\nif(nargin<2||isempty(maxDegIncreases))\n maxDegIncreases=10*n;\nend\n\nif(nargin<3||isempty(useMotzkinNull))\n useMotzkinNull=false;\nend\n\n%Determine the number of variables. Not all polynomials have to have all of\n%the same variables, so \ntermMats=cell(n,1);\n\n%Holds the degrees of each polynomial.\nd=zeros(n,1);\n\n%Convert the polynomial hypermatrices to term matrices. The order of the\n%monomials in the term matrix does not matter here (though the ordering of\n%the monomials when added to the Motzkin matrix is important).\nfor curPoly=1:n\n termMat=multiDimPolyMat2Terms(polyCoeffMats{curPoly},2,n);\n \n %Normalize the equation so that the highest coefficient has magnitude\n %one. This helps reduce finite precision problems.\n maxVal=max(abs(termMat(1,:)));\n termMat(1,:)=termMat(1,:)/maxVal;\n\n termMats{curPoly}=termMat;\n \n %The total degree of the current polynomial.\n d(curPoly)=max(sum(termMat(2:end,:),1));\nend\n\n%The maximum total degree of all of the polynomials.\nd0=max(d);\n\n%This keeps track of the number of columns of the Macaulay matrix before\n%the first column containing a certain degree monomial term (the\n%number of monomial terms before the first monomial term of the given\n%degree. The array numBeforeDeg is extended each time another degree block\n%is added to the Macaulay matrix. numBeforeDeg(i+1) is the number of items\n%before degree i, starting with degree 0, where numBeforeDeg(0+1)=0.\nnumBeforeDeg=getNumElsBeforeDeg(n,d0);\n\n%Construct the initial Macaulay matrix of degree d0, which is the highest\n%total degree of all of the polynomials going in.\n[N,numBeforeDeg]=buildInitialMacaulayMat(termMats,d,d0,numBeforeDeg);\np=size(N,1);\nq=size(N,2);\n\n%Compute the inital basis for the nullspace\nif(useMotzkinNull)\n Z=MotzkinMatrix(N);\nelse\n Z=nullspace(N);\nend\nN=[];%N is no longer needed.\n\n%We keep track of the nullity to determine when the size of the nullspace\n%has stabilized. Only after it has stabilized do we consider whether we can\n%identify where any solutions at infinity are (so as to eliminate them).\nnullity=size(Z,2);\n\ndG=[];\ndCur=d0;\n\nnullityStabilized=false;\nfor curDegIncrease=1:maxDegIncreases\n %Get the new rows that would have to be augmented.\n [NRows,numBeforeDeg]=newRows4MacaulayMatrix(p,numBeforeDeg,termMats,d,dCur);\n qNew=size(NRows,2);\n \n %Compute the augmented nullspace for the Macaulay matrix using\n %Motzkin's algorithm (Algorithm 4). This used the block method of\n %Section 6.2.5 to expand the nullspace.\n N1=NRows(:,1:q);\n N2=NRows(:,(q+1):qNew);\n if(useMotzkinNull)\n XY=MotzkinMatrix([N1*Z,N2]);\n else\n XY=nullspace([N1*Z,N2]);\n end\n numZPrev=size(Z,2);\n X=XY(1:numZPrev,:);\n Y=XY((numZPrev+1):end,:);\n Z=[Z*X;Y];\n\n nullityNew=size(Z,2);\n\n dCur=dCur+1;\n p=size(N,1);\n q=qNew;\n \n %If we have found the degree for which the nullity no longer increases.\n if(nullityNew==nullity)\n nullityStabilized=true;\n \n %Check whether we are at dG -the degree where we can detect the\n %affine basis set (and thus know that there are ma solutions).\n [isAtdG,ma,degOfGap]=checkFordG(Z,numBeforeDeg,dCur);\n \n if(isAtdG)\n dG=dCur;\n break;\n end\n elseif(nullityStabilized==true||nullityNew=0. The lexicographic rank of\n%a composition (starting from 0) is the offset within graded lexicographic\n%ordering of a value with a particular fixed degree. We are going to have\n%to keep track of these offsets to be able to index vectors.\n\nnumBeforeDeg=zeros(dMax+1,1);\nnumBeforeDeg(0+1)=0;\nnumBeforeDeg(1+1)=1;\nfor degree=1:dMax\n %The number of compositions of degree into n parts, where the parts can\n %be zero. We are including d0 as the function checkFordG will need it\n %even though this function only needs it up to degree d0-1.\n numCompositionsInDeg=binomial(degree+n-1,n-1);\n \n numBeforeDeg(degree+2)=numBeforeDeg(degree+1)+numCompositionsInDeg;\nend\n\nend\n\nfunction [M,numBeforeDeg]=buildInitialMacaulayMat(termMats,d,d0,numBeforeDeg)\n%%BUILDINITIASLMACAULAYMAT Construct the minimum-sized Macaulay matrix for\n% the system given. The degree of the matrix is the maximum\n% total degree of all of the polynomials. The Macaulay matrix\n% is defined in Section 5.1.2. This function is also used as a\n% convenience function to construct Sg.\n\ns=length(termMats);%The number of polynomials\nn=size(termMats{1},1)-1;%The number of variables\n\n%Initially a Macaulay matrix of degree d0 is constructed. The number of\n%rows p and columns q of the matrix are given \n[p,q]=MacaulayMatrixSize(d0,d);\n\n%Allocate space for the d0th order Macaulay matrix.\nM=zeros(p,q);\n\n%Now, fill in the Macaulay matrix of order d0. Here, each polynomial is\n%multiplied by all monomials of degree <=d0-d(i) and added. This includes\n%the zeroth-degree, which contains\ncurRow=1;\nfor i=1:s%Going through all the polynomials\n termMat=termMats{i};%The current polynomial being manipulated.\n \n %First, add the zeroth-order term (the polynomial itself.\n numTerms=size(termMat,2);\n for curTerm=1:numTerms\n %The degree of the term to add.\n deg=sum(termMat(2:end,curTerm));\n offset=numBeforeDeg(deg+1);\n \n idx=rankTComposition(termMat(2:end,curTerm)+1,true)+offset+1;\n M(curRow,idx)=termMat(1,curTerm);\n end\n curRow=curRow+1;\n \n %Now, add all other terms associated with this polynomial.\n for degree=1:(d0-d(i))%All the orders for the current polynomial.\n %For each order, all possible monomials are given by all\n %compositions of degree into n parts (as n is the number of\n %variables). Of course, these compositions are defined such that \n %the minimum value in each element is 1 and we want it to be zero,\n %so we have to adjust for that\n \n numMonomials=binomial(degree+n-1,n-1);\n for j=0:(numMonomials-1)\n curMonomial=unrankTComposition(j,n,degree+n,true)-1;\n \n %Add the polynomial multiplied by the current monomial.\n for curTerm=1:numTerms\n monomial2Add=curMonomial+termMat(2:end,curTerm);\n \n %The degree of the term to add.\n deg=sum(monomial2Add);\n offset=numBeforeDeg(deg+1);\n \n idx=rankTComposition(monomial2Add+1,true)+offset+1;\n M(curRow,idx)=termMat(1,curTerm);\n end\n curRow=curRow+1;\n end\n end\nend\nend\n\nfunction [p,q]=MacaulayMatrixSize(d0,d)\n%%%MACAULAYMATRIXSIZE The size of a d0th order Macaulay matrix when the\n% polynomials have degree d(i). This implements Lemma 5.8\n% in Section 5.2.1 of [1].\n\n%The number of polynomials.\nn=length(d);\n\nq=binomial(n+d0,d0);\n\np=0;\nfor i=1:n\n p=p+binomial(n+d0-d(i),d0-d(i)); \nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Polynomials/Generic_Multivariate_Polynomials/polyRootsMultiDim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7297780835769693}} {"text": "function [u,c]=getEllipsHarmAxes(pointHarmon,E)\n%%GETELLIPSHARMAXES Find the Cartesian unit vectors corresponding to the\n% normalized gradients of the components of a point in\n% ellipsoidal harmonic coordinates. Also, get the\n% magnitudes of the gradients.\n%\n%INPUTS: pointHarmon A point given in terms of ellipsoidal harmonic reduced\n% latitude and longitude in radians and a semi-major\n% axis in meters.\n% E The linear eccentricity defining the ellipsoidal\n% harmonic coordinate system. If this parameter is\n% omitted, then the linear eccentricity of the WGS84\n% reference ellipsoid is used.\n%\n%OUTPUTS: u u(:,1), u(:,2) and u(:,3) are the unit vectors in the\n% respective directions of the respective gradients of reduced\n% latitude, longitude and the semi-major axis.\n% c c(1), c(2) and c(3) are the respective magnitudes of the\n% derivative of the Cartesian position with respect to reduced\n% latitude, longitude and the semi-major axis.\n%\n%The ellipsoidal harmonic coordinate system is described in Chapter 1.15\n%of [1] and is an orthogonal coordinate system.\n%\n%REFERENCES:\n%[1] B. Hofmann-Wellenhof and H. Moritz, Physical Geodesy, 2nd ed. \n% SpringerWienNewYork, 2006.\n%\n%January 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<2||isempty(E))\n a=Constants.WGS84SemiMajorAxis;\n f=Constants.WGS84Flattening;\n b=a*(1 - f);\n E=sqrt(a^2-b^2);\nend\n\n beta=pointHarmon(1);\n lambda=pointHarmon(2);\n u=pointHarmon(3);\n \ndBeta=[-sqrt(E^2+u^2)*sin(beta)*cos(lambda);\n -sqrt(E^2+u^2)*sin(beta)*sin(lambda);\n u*cos(beta)];\nc1=norm(dBeta);\ndBeta=dBeta/c1;\n \ndu=[u*cos(beta)*cos(lambda)/sqrt(E^2+u^2);\n u*cos(beta)*sin(lambda)/sqrt(E^2+u^2);\n sin(beta)];\nc3=norm(du);\ndu=du/c3;\n\ndLambda=[-sqrt(E^2+u^2)*cos(beta)*sin(lambda);\n sqrt(E^2+u^2)*cos(beta)*cos(lambda);\n 0];\nc2=norm(dLambda);\n\n%If the point is too close to the poles, then it is possible that c2 is\n%nearly equal to zero. However, a normalized dLambda can just be found by\n%orthogonality: it is orthogonal to dBeta and du.\ndLambda=cross(dBeta,du);\n\nu=[dBeta,dLambda,du];\nc=[c1;c2;c3];\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/getEllipsHarmAxes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.729707175074736}} {"text": "function R = functionRlocalscattering3D(M_H, M_V, d_H, d_V, varphi, stdphi, theta, stdtheta, dist)\n%Generate the spatial correlation matrix for the 3D local scattering model,\n%defined in (7.17) for different angular distributions.\n%\n%INPUT:\n% M_H = Number of antennas per horizontal row, i.e., # of columns\n% M_V = Number of horizontal rows\n% d_H = Horizontal antenna spacing in multiples of wavelength\n% d_V = Vertical antenna spacing in multiples of wavelength\n% varphi = Azimuth angle in radians\n% stdphi = Azimuth angular spread (standard deviation or limit)\n% theta = Elevation angle in radians\n% stdtheta = Elevation angular spread (standard deviation or limit)\n% dist = 'Gaussian' or 'Laplace' or 'Uniform'\n%\n%OUTPUT:\n% R = M x M channel covariance matrix, where M = M_H x M_V\n%\n%\n%This Matlab function was developed to generate simulation results to:\n%\n%Emil Bjornson, Jakob Hoydis and Luca Sanguinetti (2017), \n%\"Massive MIMO Networks: Spectral, Energy, and Hardware Efficiency\", \n%Foundations and Trends in Signal Processing: Vol. 11, No. 3-4, \n%pp. 154-655. DOI: 10.1561/2000000093.\n%\n%For further information, visit: https://www.massivemimobook.com\n%\n%This is version 1.0 (Last edited: 2017-11-04)\n%\n%License: This code is licensed under the GPLv2 license. If you in any way\n%use this code for research that results in publications, please cite our\n%monograph as described above.\n\n\n% Index mapping functions\ni = @(m) mod(m-1, M_H);\nj = @(m) floor((m-1)/M_H);\n\n%Create the correlation matrix\nM = M_H*M_V;\nR = zeros(M);\n\n% Define angle distributions as functions\nif (strcmp(dist,'Laplace'))\n f1 = @(x) exp(-sqrt(2)*abs(x-varphi)/stdphi)/(sqrt(2)*stdphi);\n f2 = @(x) exp(-sqrt(2)*abs(x-theta)/stdtheta)/(sqrt(2)*stdtheta);\nelseif (strcmp(dist,'Gaussian'))\n f1 = @(x) exp(-(x-varphi).^2/(2*stdphi^2))/(sqrt(2*pi)*stdphi);\n f2 = @(x) exp(-(x-theta).^2/(2*stdtheta^2))/(sqrt(2*pi)*stdtheta);\nelseif (strcmp(dist,'Uniform'))\n f1 = @(x)1/(2*stdphi);\n f2 = @(x) 1/(2*stdtheta);\nelse\n error('Please provide a valid angle distribution')\nend\n\n%% Compute correlation matrix\nLOOKUP = zeros(2*M_H-1,M_V); %Define a lookup table to speedup the computation process\nfor m = 1:M\n for l = 1:m\n indi = i(l)-i(m) + M_H;\n indj = j(l)-j(m) + M_V;\n if (LOOKUP(indi,indj)==0)\n integrand = @(p,t) exp(1j*2*pi*d_V*(j(l)-j(m)).*sin(t)) .* exp(1j*2*pi*d_H*(i(l)-i(m)).*cos(t).*sin(p)) .* f1(p) .* f2(t);\n if (strcmp(dist,'Uniform'))\n LOOKUP(indi,indj) = integral2(integrand, varphi-stdphi, varphi+stdphi, theta-stdtheta, theta+stdtheta);\n else\n LOOKUP(indi,indj) = integral2(integrand, varphi-20*stdphi, varphi+20*stdphi, theta-20*stdtheta, theta+20*stdtheta);\n end\n end\n R(m,l) = LOOKUP(indi,indj);\n R(l,m) = R(m,l)';\n end\nend\n", "meta": {"author": "emilbjornson", "repo": "massivemimobook", "sha": "4e429497dea72d52172972f3f686b34d1d047013", "save_path": "github-repos/MATLAB/emilbjornson-massivemimobook", "path": "github-repos/MATLAB/emilbjornson-massivemimobook/massivemimobook-4e429497dea72d52172972f3f686b34d1d047013/Code/functionRlocalscattering3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7297071576562641}} {"text": "% Chapter 10 - Limit Cycles.\n% Programs_10b - Phase Portrait (Fig. 10.2).\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% Limit cycle of a van der Pol system.\n% IMPORTANT - Programs_10a.m is vectorfield.m.\nclear\nhold on\n% sys=inline('[x(2);-x(1)-5*x(2)*((x(1))^2-1)]','t', 'x');\nsys = @(t,x) [x(2);-x(1)-5*x(2)*((x(1))^2-1)]; \nvectorfield(sys,-3:.3:3,-10:1.3:10);\n[t,xs] = ode45(sys,[0 30],[2 1]);\nplot(xs(:,1),xs(:,2)) \nhold off\naxis([-3 3 -10 10])\nfsize=15;\nset(gca,'XTick',-3:1:3,'FontSize',fsize)\nset(gca,'YTick',-10:5:10,'FontSize',fsize)\nxlabel('x(t)','FontSize',fsize)\nylabel('y(t)','FontSize',fsize)\nhold off\n\n% End of Programs_10b.", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2374-dynamical-systems-with-applications-using-matlab/MATLAB files 20013a/Programs_10b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.7905303137346444, "lm_q1q2_score": 0.7296904434938374}} {"text": "%OUTEROP calculate an outer operation on two vectors\n% function y=outerop(A,B,OPERATOR)\n% \n% Calculates resultant matrix when the OPERATOR is applied \n% to all combinations of the elements of vector A and the \n% elements of vector B e.g. the outer product of A and B \n% is outerop(A,B,'*'), the outer sum of A and B \n% is outerop(A,B,'+') \n%\n% If OPERATOR is omitted '+' is assumed\n%\n% This function is equivalent to the \n% APL language's circle.dot operation. e.g. \n% in APL Ao.*B is the outer product \n% of A and B % and Ao.+B is the outer sum.\n% Ideally it would work on matrices but in practice\n% I've only ever needed to use it with vectors.\n%\n% Copyright Murphy O'Brien 2005\n% all rights unreserved\n%\nfunction y=outerop(a,b,operator)\n\nif nargin<3\n operator='+'; % for only two arguments assume outerproduct \nend \n\nif isequal(operator,'*') % common operator \n y=a(:)*b(:)';\nelse \n outera=a(:)*ones(1,length(b)); % these are the matrices that \n outerb=ones(length(a),1)*b(:).'; % meshgrid(A,B) would generate \n functionHandle=str2func(operator); % new R14 functionality\n y=functionHandle(outera,outerb); % allows faster/neater method\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/8370-outer-operation/outerop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7295742937490245}} {"text": "function out = SY_Trend(y)\n% SY_Trend Quantifies various measures of trend in a time series.\n%\n%---INPUT:\n% y, the input time series.\n%\n%---OUTPUTS:\n% Linearly detrends the time series using detrend, and returns the ratio of\n% standard deviations before and after the linear detrending. If a strong linear\n% trend is present in the time series, this operation should output a low value.\n%\n% Also fits a line and gives parameters from that fit, as well as statistics on\n% a cumulative sum of the time series.\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\nif ~BF_iszscored(y)\n warning('The input time series should be z-scored')\nend\n\nN = length(y);\n\n% Ratio of std before and after linear detrending:\nout.stdRatio = std(detrend(y)) / std(y);\n\n% Linear fit:\n[out.gradient,out.intercept] = LinearFit(1:N,y);\n\n% Stats on the cumulative sum:\nyC = cumsum(y);\nout.meanYC = mean(yC);\nout.stdYC = std(yC);\n[out.gradientYC,out.interceptYC] = LinearFit(1:N,yC);\n\n% Mean cumsum in first and second half of the time series:\nout.meanYC12 = mean(yC(1:floor(N/2)));\nout.meanYC22 = mean(yC(floor(N/2)+1:end));\n\n% ------------------------------------------------------------------------------\nfunction [m,b] = LinearFit(xData,yData)\n if size(xData,1) ~= size(yData,1);\n yData = yData';\n end\n coeff = polyfit(xData,yData,1);\n m = coeff(1); b = coeff(2);\nend\n% ------------------------------------------------------------------------------\n\nend\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Operations/SY_Trend.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.729461445626263}} {"text": "function M = spherefactory(n, m)\n% Returns a manifold struct to optimize over unit-norm vectors or matrices.\n%\n% function M = spherefactory(n)\n% function M = spherefactory(n, m)\n%\n% Manifold of n-by-m real matrices of unit Frobenius norm.\n% By default, m = 1, which corresponds to the unit sphere in R^n. The\n% metric is such that the sphere is a Riemannian submanifold of the space\n% of nxm matrices with the usual trace inner product, i.e., the usual\n% metric.\n% \n% See also: obliquefactory spherecomplexfactory\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 \n if ~exist('m', 'var')\n m = 1;\n end\n\n if m == 1\n M.name = @() sprintf('Sphere S^%d', n-1);\n else\n M.name = @() sprintf('Unit F-norm %dx%d matrices', n, m);\n end\n \n M.dim = @() n*m-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) real(acos(x(:).'*y(:)));\n \n M.typicaldist = @() pi;\n \n M.proj = @(x, d) d - x*(x(:).'*d(:));\n \n M.tangent = M.proj;\n\t\n % For Riemannian submanifolds, converting a Euclidean gradient into a\n % Riemannian gradient amounts to an orthogonal projection.\n\tM.egrad2rgrad = M.proj;\n\t\n\tM.ehess2rhess = @ehess2rhess;\n\tfunction rhess = ehess2rhess(x, egrad, ehess, u)\n rhess = M.proj(x, ehess) - (x(:)'*egrad(:))*u;\n\tend\n \n M.exp = @exponential;\n \n M.retr = @retraction;\n\n M.log = @logarithm;\n function v = logarithm(x1, x2)\n v = M.proj(x1, x2 - x1);\n di = M.dist(x1, x2);\n % If the two points are \"far apart\", correct the norm.\n if di > 1e-6\n nv = norm(v, 'fro');\n v = v * (di / nv);\n end\n end\n \n M.hash = @(x) ['z' hashmd5(x(:))];\n \n M.rand = @() random(n, m);\n \n M.randvec = @(x) randomvec(n, m, x);\n \n M.lincomb = @matrixlincomb;\n \n M.zerovec = @(x) zeros(n, m);\n \n M.transp = @(x1, x2, d) M.proj(x2, d);\n \n M.pairmean = @pairmean;\n function y = pairmean(x1, x2)\n y = x1+x2;\n y = y / norm(y, 'fro');\n end\n\n M.vec = @(x, u_mat) u_mat(:);\n M.mat = @(x, u_vec) reshape(u_vec, [n, m]);\n M.vecmatareisometries = @() true;\n\nend\n\n% Exponential on the sphere\nfunction y = exponential(x, d, t)\n\n if nargin == 2\n t = 1;\n end\n \n td = t*d;\n \n nrm_td = norm(td, 'fro');\n \n if nrm_td > 4.5e-8\n y = x*cos(nrm_td) + td*(sin(nrm_td)/nrm_td);\n else\n % If the step is too small to accurately evaluate sin(x)/x,\n % then sin(x)/x is almost indistinguishable from 1.\n y = x + td;\n y = y / norm(y, 'fro');\n end\n\nend\n\n% Retraction on the sphere\nfunction y = retraction(x, d, t)\n\n if nargin == 2\n t = 1;\n end\n \n y = x + t*d;\n y = y / norm(y, 'fro');\n\nend\n\n% Uniform random sampling on the sphere.\nfunction x = random(n, m)\n\n x = randn(n, m);\n x = x/norm(x, 'fro');\n\nend\n\n% Random normalized tangent vector at x.\nfunction d = randomvec(n, m, x)\n\n d = randn(n, m);\n d = d - x*(x(:).'*d(:));\n d = d / norm(d, 'fro');\n\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/manopt/manifolds/sphere/spherefactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7294614436178729}} {"text": "%% Quiver calculations\n% These are calculations for the quiver dimensions as implemented in MATLAB\n% (HG1) as in the |quiver.m| function.\n%\n% For HG2 and Octave, the situation might be different.\n%\n% A single quiver is defined as:\n%\n% C\n% \\\n% \\\n% A ----------------- B \n% /\n% /\n% D\n%\n% To know the dimensions of the arrow head, MATLAB defines the quantities\n% alpha = beta = 0.33 that determine the coordinates of C and D as given below.\n\nclc; \nclear variables;\nclose all;\n\n%% Parameters\ntry\n syms x y z u v w alpha beta epsilon real\ncatch\n warning('Symbolic toolbox not found. Interpret the values with care!');\n x = randn(); y = randn(); z = randn();\n u = randn(); v = randn(); w = randn();\nend\nalpha = 0.33;\nbeta = alpha;\nepsilon = 0;\nis2D = true;\n\n%% Coordinates as defined in MATLAB\n% Note that in 3D, the arrow head is oriented in a weird way. Let' just ignore\n% that and only focus on 2D and use the same in 3D. Due to the lack\n% of [u,v,w]-symmetry in those equations, the angle is bound to depend on the\n% length of |delta|, i.e. something we don't know beforehand.\nA = [x y z].';\ndelta = [u v w].';\nB = A + delta;\nC = B - alpha*[u+beta*(v+epsilon);\n v-beta*(u+epsilon)\n w];\nD = B - alpha*[u-beta*(v+epsilon);\n v+beta*(u+epsilon)\n w];\n\nif is2D\n A = A(1:2);\n B = B(1:2);\n C = C(1:2);\n D = D(1:2);\n delta = delta(1:2);\nend\n\n%% Calculating the angle of the arrowhead\n% Calculate the cos(angle) using the inner product\nunitVector = @(v) v/norm(v);\ncosAngleBetween = @(a,b,c) unitVector(a-b).' * unitVector(c-b);\n\ncosTwiceTheta = cosAngleBetween(C,B,D);\nif isa(cosTwiceTheta, 'sym')\n cosTwiceTheta = simplify(cosTwiceTheta);\nend\n\ntheta = acos(cosTwiceTheta) / 2\n\nradToDeg = @(rads) (rads * 180 / pi);\n\nthetaVal = radToDeg(theta)\ntry\n thetaVal = double(thetaVal)\nend\n\n% For the MATLAB parameters alpha=beta=0.33, we get theta = 18.263 degrees.\n\n", "meta": {"author": "matlab2tikz", "repo": "matlab2tikz", "sha": "806c97d99f87f8a1e99a7c54e853c25c82aac301", "save_path": "github-repos/MATLAB/matlab2tikz-matlab2tikz", "path": "github-repos/MATLAB/matlab2tikz-matlab2tikz/matlab2tikz-806c97d99f87f8a1e99a7c54e853c25c82aac301/test/examples/example_quivers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.729461441609483}} {"text": "function s=phon2sone(p)\n%PHON2SONE convert PHON loudness values to SONEs s=(p)\n%Inputs: p is a matrix of phon values\n%\n%Outputs: s is a matrix, the same size as p, of sone values\n%\n% The phon scale measures perceived loudness in dB; at 1 kHz it is identical to dB SPL\n% relative to 20e-6 Pa sound pressure. The sone scale is proportional to apparent loudness\n% and, by definition, equals 1 at 40 phon. The form of the loudness curve is taken from [1].\n% The hearing threshold at 1 kHz for 18 to 25 year olds with normal hearing is taken from [2].\n%\n% Refs: [1]\tJ. Lochner and J. Burger. Form of the loudness function in the presence of masking noise.\n% The Journal of the Acoustical Society of America, 33: 1705, 1961.\n% [2]\tISO/TC43. Acoustics – normal equal-loudness-level contours.\n% Standard ISO 226:2003, Aug. 2003.\n\n\n% Copyright (C) Mike Brookes 2012-2013\n% Version: $Id: phon2sone.m 3295 2013-08-02 14:03:11Z 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 d\nif isempty(a)\n b=log(10)*0.1*0.27; % 0.27 is the exponent from [1] and [2]\n d=exp(b*2.4); % 2.4 dB is teh hearing threshold from [2]\n a=1/(exp(b*40)-d); % scale factor to make p=40 give s=1\nend\nif nargout>0\n s=a*(exp(b*p)-d);\nelse\n if nargin<1 || isempty(p)\n pp=linspace(5,90,100)'; % phon values\n else\n pp=p;\n end\n semilogy(pp,phon2sone(pp));\n axisenlarge(-1);\n yticksi;\n xlabel('phon = dB SPL @ 1 kHz');\n ylabel('sone');\nend\n", "meta": {"author": "covarep", "repo": "covarep", "sha": "5a2be5d6b776f14a0b275c69fde90eb13849e60d", "save_path": "github-repos/MATLAB/covarep-covarep", "path": "github-repos/MATLAB/covarep-covarep/covarep-5a2be5d6b776f14a0b275c69fde90eb13849e60d/external/voicebox/phon2sone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.729449976474793}} {"text": "function d = Point2LineDistance(P, A, B)\n\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% This function is written by Annibale Panichella\n\n d = zeros(size(P,1),1);\n for i = 1:size(P,1)\n pa = P(i,:) - A;\n ba = B - A;\n t = dot(pa, ba)/dot(ba, ba);\n d(i,1) = norm(pa - t * ba,2);\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/Algorithms/Multi-objective optimization/AGE-MOEA-II/Point2LineDistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7294499724646455}} {"text": "function [xVals,tVals,dxdtVals,exitCode,nextStepSize]=RKAdaptiveOverRange(xStart,tSpan,f,initStepSize,numRefinedSteps,order,solutionChoice,RelTol,AbsTol,maxSteps)\n%%RKADAPTIVEOVERRANGE Perform explicit Runge-Kutta integration over a\n% given range of values using an adaptive step size.\n% Runge-Kutta methods are derivative-free techniques\n% for solving ordinary differential equations. That is,\n% integrating dx/dt=f(x,t) given initial conditions\n% (xStart,tSpan(1)). More information on available\n% algorithms for the steps is given in the comments to\n% the function RungeKStep.\n%\n%INPUTS: xStart The NX1 state vector at time tSpan(1).\n% tSpan A 2X1 or 1X2 vector where tSpan(1) is the starting time and\n% tSpan2 is the desired stopping time for the integration.\n% f The function handle for f(x,t)=dxdt over which integration\n% is to be performed. The output is NX1-dimensional.\n% initStepSize An optional initial step size (in t) to use for the\n% integration. If omitted or an empty matrix is passed, an\n% ad-hoc method described below is used to find an initial\n% step size.\n% numRefinedSteps An optional parameter specifying the number of steps to\n% interpolate between each normal step. With high-order\n% formulas, the steps produced might not be very nice to\n% use for plotting, so setting this to a value above 0 adds\n% more intermediate values (using the polynomial returned by\n% the RKInterpPolys function) so that plotted data can look\n% nicer. If omitted or an empty matrix is passed, the default\n% value of 0 (no extra/ interpolated steps) is used.\n% Interpolation is done at the main order of the Runge-Kutta\n% method.\n% order,solutionChoice A pair of optional parameters that specify the\n% highest order of the embedded Runge-Kutta pair to use as\n% well as the specific algorithm to use. Details are given in\n% the comments to the RungeKStep function. If omitted or\n% empty matrices are passed, the default order of 5 is used\n% and the default solutionChoice of 0 is used.\n% RelTol The maximum relative error tolerance allowed, a\n% positive scalar (its use is explained in more detail\n% below). If omitted or an empty matrix is passed, the\n% default value of 1e-3 is used.\n% AbsTol The absolute error tolerance allowed, a positive scalar, of\n% the same for all components of x, or a positive NX1 vector.\n% If omitted or an empty matrix is passed, the default value\n% of 1e-6 is used.\n% maxSteps The maximum allowable number of steps to perform the\n% integration. If omitted, the default of 1024 is used.\n%\n%OUTPUTS: xVals The NXnumSteps set of values of x along the path.\n% xVals(:,1) is xStart and xVals(:,end) is the value at final\n% time tSpan(2). If the Runge-Kutta integration failed, e.g.\n% due to encountering a NaN or being unable to get a\n% sufficient step size, an empty matrix is returned.\n% tVals A numStepsX1 vector of values of t corresponding to the\n% values of x in xVals. tVals(1) is equal to tSpan(1) and\n% tVals(end) is equal to tSpan(2). If integration fails, an\n% empty matrix is returned.\n% dxdtVals A numStepsXN array containing derivatives of x evaluated at\n% the times in tVals. The derivatives are just the result of\n% evaluating f(x,t) at each point in (xVals,tVals). This\n% combined with xVals and tVals could be used in functions to\n% perform Hermite interpolation. If integration fails, an\n% empty matrix is returned.\n% exitCode A code indicating how the algorithm terminated. Possible\n% values are\n% 0: Integration was successful.\n% 1: Unable to get a small enough step size.\n% 2: Maximum number of steps reached without completion.\n% 3: Non-finite number encountered.\n% nextStepSize The step size (in t) that would be used for the next\n% integration step. If empty, then the integration ended\n% because the step size was too small.\n%\n%The basic idea behind adaptive stepsize control can be ascertained from\n%Chapter 5.2 of [3]. However, the implementation here has a number of\n%changes. For example, unlike the basic algorithm of [3], depending on the\n%user's choice of order and solutionChoice, the main Runge-Kutta formula,\n%which is the one whose result is saved, might have a higher or lower order\n%than the subsidiary formula, which is only used to check the error to\n%determine how the stepsize should change. The smallest order of the two is\n%the order that is used in formulae for adaptively changing the step size.\n%\n%The algorithm needs an initial stepsize to start. If the user does not\n%provide an intial stepsize, then the initial stepsize is just set to the\n%width of the integration region in t divided by the maximum number of\n%steps. That is, initStepSize = (tSpan(2)-tSpan(1))/maxSteps;\n%\n%Once an initial stepsize has been determined, the function RungeKStep is\n%used to perform a single step of the Runge-Kutta algorithm. Then one must\n%determine whether the stepsize was small enough. If the stepsize is small\n%enough, then the stepsize should still be adaptively changed for the nest\n%step. The procedure for updating the stepsize is essentially the procedure\n%for non-stiff equations from [2], Equation 2.3). The method has been\n%slightly modified in that the error being adjusted is not just the\n%absolute error, as explained below. Also, the maximum stepsize is limited\n%to 1/5 the integration region and increases in the stepsize are limited\n%so as not to be too large.\n%\n%We would like the error in each step to be less than the absolute and the\n%relative error tolerances. For an absolute error tolerance, this means\n%that\n%abs(xPredMain-xPredSubsid)tEnd*deltaTSign)\n deltaTMag=abs(tEnd-tCur);\n deltaT=deltaTMag*deltaTSign;\n %Allow the last step to be very small.\n deltaTMinMag=min(deltaTMinMag,deltaTMag);\n end\n \n [deltaTNew,xNew,tNew,k,dxdtCur,exitCode]=performOneAdaptiveRKStep(xCur,tCur,f,deltaT,deltaTMinMag,deltaTMaxMag,dxdtCur,order,solutionChoice,AbsTol,RelTol);\n\n %If an error occurred, then just return.\n if(exitCode~=0)\n xVals=[];\n tVals=[];\n dxdtVals=[];\n nextStepSize=abs(deltaTNew);\n return\n end\n \n dxdtVals(:,lastStep)=dxdtCur;\n\n if(numRefinedSteps~=0)\n %If extra interpolation between the steps is to be performed.\n %Get a Hermite interpolating polynomial over the step. \n [interpPolyA,interpPolyC]=RKInterpPolys(xCur,tCur,xNew,tNew,f,order,solutionChoice,k);\n %The interpolating polynomials take stapes parameterized by\n %a value between zero and 1 representing the distance from\n %tCur to tNew.\n deltaTTaken=tNew-tCur;\n \n deltaFraction=1/(numRefinedSteps+1);\n curStepFrac=deltaFraction;\n for curRStep=1:numRefinedSteps\n lastStep=lastStep+1;\n tVals(lastStep)=tVals(lastStep-1)+deltaFraction*deltaTTaken;\n\n xVals(:,lastStep)=polyValNewton(curStepFrac,interpPolyA,interpPolyC);\n dxdtVals(:,lastStep)=f(xVals(:,lastStep),tVals(lastStep));\n curStepFrac=curStepFrac+deltaFraction;\n end\n end\n \n lastStep=lastStep+1;\n xVals(:,lastStep)=xNew;\n tVals(lastStep)=tNew;\n dxdtVals(:,lastStep)=dxdtCur;\n deltaT=deltaTNew;\n\n if(tVals(lastStep)==tEnd)\n %If integration completed, reshape the outputs to match the actual\n %number of steps.\n xVals=xVals(:,1:lastStep);\n tVals=tVals(1:lastStep);\n dxdtVals=dxdtVals(:,1:lastStep);\n exitCode=0;\n nextStepSize=deltaTMag;\n return\n end\nend\n\n%If we get here, then the maximum number of iterations was reached without\n%reaching the end.\nxVals=[];\ndxdtVals=[];\ntVals=[];\nexitCode=2;\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Differential_Equations/RKAdaptiveOverRange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7294499685991611}} {"text": "function R = quatToMat(b, c, d, qx, qy, qz, qfac, pixdim)\n%\n% R = quatToMat(qb, qc, qd, qx, qy, qz, qfac, pixdim)\n%\n% Convert a quaternion to a 4x4 rotation/scaling/translation matrix. Based on the\n% nifti1 spec implemented in nifti1_io.c.\n%\n% 2008.10.01 RFD: wrote it.\n%\n\nif(isstruct(b))\n c = b.quatern_c;\n d = b.quatern_d;\n qx = b.quatern_x;\n qy = b.quatern_y;\n qz = b.quatern_z;\n qfac = b.qfac;\n pixdim = [b.dx b.dy b.dz];\n b = b.quatern_b;\nend\n\nR = zeros(4);\n\nR(4,:) = [0 0 0 1];\n\n% compute a from b,c,d\na = 1.0 - (b*b + c*c + d*d);\nif( a < 1.e-7 ) % special case\n a = 1.0 / sqrt(b*b+c*c+d*d);\n b = b*a; c = c*a; d = d*a; % normalize (b,c,d) vector\n a = 0.0; % a = 0 ==> 180 degree rotation\nelse\n a = sqrt(a); % angle = 2*arccos(a)\nend\n\n% build rotation matrix, including scaling factors for voxel sizes\nif length(pixdim) == 3 \n xd = pixdim(1); yd = pixdim(2); zd = pixdim(3);\nelse\n xd = pixdim(1); yd = pixdim(2); zd = 1;\nend\nif(xd<=0.0), xd = 1.0; end\nif(yd<=0.0), yd = 1.0; end\nif(zd<=0.0), zd = 1.0; end\n\nif(qfac < 0.0), zd = -zd; end % left handedness?\n\nR(1,1) = (a*a+b*b-c*c-d*d) * xd ;\nR(1,2) = 2.0 * (b*c-a*d ) * yd ;\nR(1,3) = 2.0 * (b*d+a*c ) * zd ;\nR(2,1) = 2.0 * (b*c+a*d ) * xd ;\nR(2,2) = (a*a+c*c-b*b-d*d) * yd ;\nR(2,3) = 2.0 * (c*d-a*b ) * zd ;\nR(3,1) = 2.0 * (b*d-a*c ) * xd ;\nR(3,2) = 2.0 * (c*d+a*b ) * yd ;\nR(3,3) = (a*a+d*d-c*c-b*b) * zd ;\n\n% load offsets\n\nR(1:3,4) = [qx;qy;qz];\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/fileFilters/nifti/quatToMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7293739529549301}} {"text": "% TRIMMED_GRASSMANN_AVERAGE Robustly estimate average subspace spanned by data by element-wise trimmed averages.\n%\n% TRIMMED_GRASSMANN_AVERAGE(X, P) returns a basis vector for the \n% average one-dimensional subspace spanned by the data X. This is\n% a N-by-D matrix containing N observations in R^D. Robustness is\n% achieved by element-wise trimming at P percent.\n%\n% TRIMMED_GRASSMANN_AVERAGE(X, P, K) returns a D-by-K matrix of\n% orthogonal basis vectors spanning a K-dimensional average subspace.\n%\n% Reference:\n% \"Grassmann Averages for Scalable Robust PCA\".\n% S. Hauberg, A. Feragen and M.J. Black. In CVPR 2014.\n% http://ps.is.tue.mpg.de/project/Robust_PCA\n\n% Grassmann Averages\n% Copyright (C) 2014 Søren Hauberg\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\nfunction vectors = trimmed_grassmann_average(X, percent, K)\n \n %% Check input\n if (nargin < 2)\n error ('trimmed_grassmann_average: not enough input arguments');\n end % if\n if (nargin < 3)\n K = 1;\n end % if\n if (percent < 0 || percent > 50)\n error('trimmed_grassmann_average: trimming percentage must be between 0 and 50');\n end % if\n \n %% Initialisation\n [N, D] = size(X);\n vectors = NaN(D, K, class(X));\n \n %% Options\n epsilon = 1e-5;\n \n %% Create output structure\n for k = 1:K\n %% Compute k'th principal component\n mu = rand(D, 1) - 0.5;\n mu = mu / norm(mu);\n \n %% Initialize using a few EM iterations\n for iter = 1:3\n dots = X * mu; % Nx1\n mu = dots.' * X; % 1xD\n mu = mu(:) / norm(mu); % Dx1\n end % for\n dots = []; % clear up memory\n \n %% Now the Grassmann average\n for iter = 1:N\n prev_mu = mu;\n\n %% Compute angles and flip\n dot_signs = sign(X * mu); % Nx1\n \n %% Compute weighted Grassmannian mean\n mu = trimmed_mean(bsxfun(@times, X, dot_signs), percent); % 1xD\n mu = mu(:) / norm(mu); % Dx1\n\n %% Check for convergence\n if (max(abs(mu - prev_mu)) < epsilon)\n iter\n break;\n end % if\n end % for\n dot_signs = []; % clear up memory\n prev_mu = []; % clear up memory\n \n %% Store the estimated vector (and possibly subtract it from data, and perform reorthonormalisation)\n if (k == 1)\n vectors(:, k) = mu;\n X = X - (X * mu) * mu.';\n elseif (k < K)\n mu = reorth(vectors(:, 1:k-1), mu, 1);\n mu = mu / norm(mu);\n vectors(:, k) = mu;\n\n X = X - (X * mu) * mu.';\n else % k == K\n mu = reorth(vectors(:, 1:k-1), mu, 1);\n mu = mu / norm(mu);\n vectors(:, k) = mu;\n end % if\n end % for\nend % function\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/rpca/TGA/trimmed_grassmann_average.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7293087424038712}} {"text": "function [model, L] = mlpReg(X, y, k, lambda)\n% Train a multilayer perceptron neural network for regression with backpropagation\n% tanh activation function is used\n% Input:\n% X: d x n data matrix\n% y: 1 x n real value response vector\n% k: T x 1 vector to specify number of hidden nodes in each layer\n% lambda: regularization parameter\n% Ouput:\n% model: model structure\n% L: (regularized least square) loss\n% Written by Mo Chen (sth4nth@gmail.com).\nif nargin < 4\n lambda = 1e-2;\nend\neta = 1e-5;\ntol = 1e-5;\nmaxiter = 50000;\nL = inf(1,maxiter);\n\nk = [size(X,1);k(:);size(y,1)];\nT = numel(k)-1;\nW = cell(T,1);\nb = cell(T,1);\nfor t = 1:T\n W{t} = randn(k(t),k(t+1));\n b{t} = randn(k(t+1),1);\nend\nR = cell(T,1);\nZ = cell(T+1,1);\nZ{1} = X;\nfor iter = 2:maxiter\n% forward\n for t = 1:T-1\n Z{t+1} = tanh(W{t}'*Z{t}+b{t}); % 5.10 5.113\n end\n Z{T+1} = W{T}'*Z{T}+b{T}; % 5.114\n\n% loss\n E = Z{T+1}-y; \n Wn = cellfun(@(x) dot(x(:),x(:)),W); % |W|^2\n L(iter) = dot(E(:),E(:))+lambda*sum(Wn);\n if abs(L(iter)-L(iter-1)) < tol*L(iter-1); break; end\n \n% backward\n R{T} = E; \n for t = T-1:-1:1\n df = 1-Z{t+1}.^2; % h'(a)\n R{t} = df.*(W{t+1}*R{t+1}); % 5.66\n end\n \n% gradient descent\n for t=1:T\n dW = Z{t}*R{t}'+lambda*W{t}; % 5.67\n db = sum(R{t},2);\n W{t} = W{t}-eta*dW; % 5.43\n b{t} = b{t}-eta*db;\n end\nend\nL = L(2:iter);\nmodel.W = W;\nmodel.b = b;\n", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter05/mlpReg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7292845213622202}} {"text": "% This is a sample code from Appendix A.4 of the following book:\n%\n% Zhuang Jiao, YangQuan Chen, Igor Podlubny, \n% Distributed-Order Dynamic Systems: Stability, Simulation, \n% Applications and Perspectives (Springer, London, 2012),\n% ISBN ISBN 978-1-4471-2851-9,\n% http://www.springer.com/engineering/control/book/978-1-4471-2851-9\n%\n% (C) Igor Podlubny, 2011\n\nclear all\n\n% Check if the FEX package 36574 is on your MATLAB path, \n% and if not, then suggest downloading the FEX submission #36574 \n% \"Demos for investigating distributed-order linear time-invariant systems\"\n% by Zhuang Jiao, which contains the Matlab code from Appendices 1-3\n% of the same book\nExplanation = ['You may be interested in downloading ' ...\n'Zhuang Jiao''s FEX submission #36574' sprintf('\\n')...\n'(Demos for investigating distributed-order linear ' ... \n'time-invariant systems)', sprintf('\\n')...\n'which contains the Matlab code from Appendices 1-3 to the same book.' ];\nif ~(exist('stabbound_dods', 'file') == 2)\n P = suggestFEXpackage(36574, Explanation); \nend\n\n% Check if the FEX package 22071 is on your MATLAB path, \n% and if it is not there, then require the FEX packages \n% 31069 (\"requireFEXpackage\") and 22071 (\"Matrix approach \n% to discretization of ODEs and PDEs of arbitrary real order\"):\nif ~(exist('ban', 'file') == 2 && exist('fan', 'file') == 2 && exist('eliminator', 'file') == 2)\n P = requireFEXpackage(31069); % \"requireFEXpackage\" \n P = requireFEXpackage(22071); % \"Matrix approach...\"\nend\n\n\n% (1) Prepare constants and nodes \n% (this is the longest part of the script):\nh = 0.01; % step of discretization \nt = 0:h:5; % discretization nodes\nN = length(t) + 1; % number of nodes\nB = 0.1; % coefficient of the equation \nf = '0 + 0*t'; % right-hand-side\nM = zeros(N,N); % pre-allocate matrix M for the system\n\n% (2) Write the discretization matrix:\nM = doban('6*alf.*(1-alf)', [0 1], 0.01, N-1, h) + B*eye(N-1,N-1);\n\n% (3) Compute the right-hand side at discretization nodes:\nF = eval ([f '-B'], t)';\n\n% (4) Utilize zero initial condition:\nM = eliminator(N-1,[1])*M*eliminator(N-1, [1])';\nF = eliminator(N-1,[1])*F;\n\n% (5) And solve the system MY=F:\nY = M\\F;\n\n% (6) Pre-pend the zero initial value \nY0 = [0; Y];\n\n% and plot the solution:\nU = Y0 + 1;\nplot(t, U, 'k')\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/36570-matrix-approach-to-distributed-order-odes-and-pdes/mfcdo-20120509/dorelaxation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.7292296640080621}} {"text": "function trans = localToGlobal3d(varargin)\n%LOCALTOGLOBAL3D Transformation matrix from local to global coordinate system\n%\n% TRANS = localToGlobal3d(CENTER, THETA, PHI, PSI)\n% Compute the transformation matrix from a local (or modelling)\n% coordinate system to the global (or world) coordinate system.\n% This is a low-level function, used by several drawing functions.\n%\n% The transform is defined by:\n% - CENTER: the position of the local origin into the World coordinate\n% system\n% - THETA: colatitude, defined as the angle with the Oz axis (between 0\n% and 180 degrees), positive in the direction of the of Oy axis.\n% - PHI: azimut, defined as the angle of the normal with the Ox axis,\n% between 0 and 360 degrees\n% - PSI: intrinsic rotation, corresponding to the rotation of the object\n% around the direction vector, between 0 and 360 degrees\n%\n% The resulting transform is obtained by applying (in that order):\n% - Rotation by PSI around he Z-axis\n% - Rotation by THETA around the Y-axis\n% - Rotation by PHI around the Z-axis\n% - Translation by vector CENTER\n% This corresponds to Euler ZYZ rotation, using angles PHI, THETA and\n% PSI.\n%\n% The 'eulerAnglesToRotation3d' function may better suit your needs as\n% it is more 'natural'.\n%\n% Example\n% localToGlobal3d\n%\n% See also\n% transforms3d, createEulerAnglesRotation\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2009-06-19, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009 INRA - Cepia Software Platform.\n\n% HISTORY\n% 19/08/2009 fix bug in parsing center with 4 args\n% 2011-06-21 use degrees\n\n% extract the components of the transform\nif nargin == 1\n % all components are bundled in the first argument\n var = varargin{1};\n center = var(1:3);\n theta = var(4);\n phi = var(5);\n psi = 0;\n if length(var) > 5\n psi = var(6);\n end\n \nelseif nargin == 4\n % arguments = center, then the 3 angles\n center = varargin{1};\n theta = varargin{2};\n phi = varargin{3};\n psi = varargin{4}; \n \nelseif nargin > 4\n % center is given in 3 arguments, then 3 angles\n center = [varargin{1} varargin{2} varargin{3}];\n theta = varargin{4};\n phi = varargin{5};\n psi = 0;\n if nargin > 5\n psi = varargin{6}; \n end\nend\n \n% conversion from degrees to radians\nk = pi / 180;\n\n% rotation around normal vector axis\nrot1 = createRotationOz(psi * k);\n\n% colatitude\nrot2 = createRotationOy(theta * k);\n\n% longitude\nrot3 = createRotationOz(phi * k);\n\n% shift center\ntr = createTranslation3d(center);\n\n% create final transform by concatenating transforms\ntrans = tr * rot3 * rot2 * rot1;\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom3d/private/localToGlobal3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7292296523733799}} {"text": "function c = l1nn_cholesky ( n, h )\n\n%*****************************************************************************80\n%\n%% L1NN_CHOLESKY computes the Cholesky factor of the 1D NN Laplacian.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 October 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n% N must be at least 3.\n%\n% Input, real H, the spacing between points.\n%\n% Output, real C(N,N), the Cholesky factor.\n%\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'L1NN_CHOLESKY - Fatal error!\\n' );\n fprintf ( 1, ' N < 3.\\n' );\n error ( 'L1NN_CHOLESKY - Fatal error!' );\n end\n\n c = zeros ( n, n );\n\n for i = 1 : n - 1\n c(i,i) = + 1.0;\n c(i,i+1) = - 1.0;\n end\n\n c(1:n,1:n) = c(1:n,1:n) / h;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/laplacian/l1nn_cholesky.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7292296354997262}} {"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%\nv=sigmoid(X*theta);\nfor i=1:m\n\tif v(i,1)>=0.5\n\t\tp(i,1)=1;\n\telse\n\t\tp(i,1)=0;\nend\n\n\n\n\n\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "loserChen", "repo": "Coursera-MachineLearning", "sha": "ce2360516c36805e8bd4fb3c796d7820f320cc78", "save_path": "github-repos/MATLAB/loserChen-Coursera-MachineLearning", "path": "github-repos/MATLAB/loserChen-Coursera-MachineLearning/Coursera-MachineLearning-ce2360516c36805e8bd4fb3c796d7820f320cc78/machine-learning-ex2/ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.85391273808085, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7291669785424477}} {"text": "function sparse_grid_open_test05 ( dim_num, level_max )\n\n%*****************************************************************************80\n%\n%% TEST05 tests LEVELS_OPEN_INDEX to make a Gauss Patterson grid.\n%\n% Discussion:\n%\n% This routine gets the sparse grid indices and determines the \n% corresponding sparse grid abscissas for a Gauss Patterson scheme.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 April 2007\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST05:\\n' );\n fprintf ( 1, ' Make a sparse Gauss Patterson grid.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEVELS_OPEN_INDEX returns all grid indexes\\n' );\n fprintf ( 1, ' whose level value satisfies\\n' );\n fprintf ( 1, ' 0 <= LEVEL <= LEVEL_MAX.\\n' );\n fprintf ( 1, ' Here, LEVEL is the sum of the levels of the 1D rules,\\n' );\n fprintf ( 1, ' and the order of the rule is 2^(LEVEL+1) - 1.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Now we demonstrate how to convert grid indices\\n' );\n fprintf ( 1, ' into physical grid points. In this case, we\\n' );\n fprintf ( 1, ' want points on [-1,+1]^DIM_NUM.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEVEL_MAX = %d\\n', level_max );\n fprintf ( 1, ' Spatial dimension DIM_NUM = %d\\n', dim_num );\n\n point_num = sparse_grid_ofn_size ( dim_num, level_max );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of unique points in the grid = %d\\n', point_num );\n%\n% Compute the orders and points.\n%\n grid_index = levels_open_index ( dim_num, level_max, point_num );\n%\n% Now we're done. Print the merged grid data.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Grid index:\\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : point_num\n fprintf ( 1, ' %4d', j );\n for dim = 1 : dim_num\n fprintf ( 1, '%6d', grid_index(dim,j) );\n end\n fprintf ( 1, '\\n' );\n end\n%\n% Convert index information to physical information.\n%\n grid_point = zeros ( dim_num, point_num );\n\n order_max = 2^( level_max + 1 ) - 1;\n\n for j = 1 : point_num\n for dim = 1 : dim_num\n grid_point(dim,j) = gp_abscissa ( order_max, grid_index(dim,j) );\n end\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Grid points:\\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : point_num\n fprintf ( 1, ' %4d', j );\n for dim = 1 : dim_num\n fprintf ( 1, '%10f', grid_point(dim,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/sparse_grid_open/sparse_grid_open_test05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7291447891607415}} {"text": "function edge_length = triangle_edge_length_2d ( t )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_EDGE_LENGTH_2D returns edge lengths of a triangle in 2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(2,3), the triangle vertices.\n%\n% Output, real EDGE_LENGTH(3,1), the length of the edges.\n%\n for j1 = 1 : 3\n j2 = i4_wrap ( j1 + 1, 1, 3 );\n edge_length(j1,1) = sqrt ( ( t(1,j2) - t(1,j1) )^2 ...\n + ( t(2,j2) - t(2,j1) )^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/geometry/triangle_edge_length_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8175744761936438, "lm_q1q2_score": 0.7291219483376212}} {"text": "function value = c8_sqrt ( c )\n\n%*****************************************************************************80\n%\n%% C8_SQRT returns the principal square root of a C8.\n%\n% Discussion:\n%\n% A C8 is a complex double precision value.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 April 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, complex double precision C, the number whose square root is desired.\n%\n% Output, complex double precision VALUE, the square root of X.\n%\n argument = c8_arg ( c );\n magnitude = c8_mag ( c );\n\n if ( magnitude == 0.0 )\n\n value = 0.0;\n\n else\n\n value = sqrt ( magnitude ) ...\n * ( cos ( argument / 2.0 ) + i * sin ( argument / 2.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/c8lib/c8_sqrt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8175744673038222, "lm_q1q2_score": 0.7291219404095801}} {"text": "function d=sqdist(a,b)\n% SQDIST - computes squared Euclidean distance matrix\n% computes a rectangular matrix of pairwise distances\n% between points in A (given in columns) and points in B\n\n% NB: very fast implementation taken from Roland Bunschoten\n\naa = sum(a.*a,1); bb = sum(b.*b,1); ab = a'*b; \nd = abs(repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab);\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/sqdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8175744673038221, "lm_q1q2_score": 0.7291219357077903}} {"text": "function A_xyz = computeVelCoeffsMtx(sectorOrder)\n%COMPUTEVELCOEFFSMTX Compute the generating matrices of products of\n%beampatterns with dipoles\n%\n% This routine computes the matrices that generate the coefficients of\n% the beampattern of order (sectorOrder+1) that is essentially the \n% product of a pattern of order=sectorOrder and a dipole. It is used in \n% beamWeightsVelocityPatterns.m. For the derivation of the matrices see:\n%\n% Politis, A. and Pulkki, V., 2016. \n% Acoustic intensity, energy-density and diffuseness estimation in a directionally-constrained region. \n% arXiv preprint arXiv:1609.03409.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% COMPUTEVELCOEFFSMTX.M - 7/06/2015\n% Archontis Politis, archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% orders of sector and resulting velocity patterns\nNs = sectorOrder;\nNxyz = Ns+1;\n\n% Complex SH coefficients of velocity x,y,z\n% X = cos\\phi sin\\theta\n% Y = sin\\phi sin\\theta\n% Z = cos\\theta\n% q = 1 -> Yq = Y_{1(-1)}\n% q = 2 -> Yq = Y_{10}\n% q = 3 -> Yq = Y_{11}\n% x_q != 0 only for q=1,3\n% y_q != 0 only for q=1,3\n% z_q != 0 only for q=2\nx1 = sqrt(2*pi/3);\nx3 = -sqrt(2*pi/3);\ny1 = 1i*sqrt(2*pi/3);\ny3 = 1i*sqrt(2*pi/3);\nz2 = sqrt(4*pi/3);\n\nA_xyz = zeros((Nxyz+1)^2, (Ns+1)^2, 3);\n\nG_mtx = gaunt_mtx(Ns, 1, Nxyz);\n\nfor ii=1:(Nxyz+1)^2\n for jj=1:(Ns+1)^2\n \n A_xyz(ii,jj,1) = x1*G_mtx(jj,2,ii) + x3*G_mtx(jj,4,ii);\n A_xyz(ii,jj,2) = y1*G_mtx(jj,2,ii) + y3*G_mtx(jj,4,ii);\n A_xyz(ii,jj,3) = z2*G_mtx(jj,3,ii);\n end\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/computeVelCoeffsMtx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7290874007572569}} {"text": "function [ cc_est, r_min, r_max ] = cube_random_centralize ( m, n, oc, cc, cr )\n\n%*****************************************************************************80\n%\n%% CUBE_RANDOM_CENTRALIZE centralizes random data from a cube surface.\n%\n% Discussion:\n%\n% We generate N points uniformly at random on the surface of the\n% M dimensional cube, of center CC and radius R.\n%\n% The cube is aligned with the coordinate axes.\n%\n% We seek to estimate the value of CC.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of random points to generate.\n%\n% Input, real OC(M,1), the observation point.\n%\n% Input, real CC(M,1), the center of the cube.\n%\n% Input, real CR, the radius of the cube.\n%\n% Output, real CC_EST(M,1), the estimated cube center.\n%\n% Output, real R_MIN, R_MAX, the minimum and maximum distances\n% between the observation point and sample points on the cube surface.\n%\n\n%\n% Destroy all row vectors!\n%\n cc = cc(:);\n oc = oc(:);\n%\n% Compute sample points on the cube surface.\n%\n x = cube_surface_sample ( m, n, cc, cr );\n%\n% The center estimate is simply the average.\n%\n cc_est(1:m,1) = sum ( x, 2 ) / n;\n%\n% For each point on the cube surface, the \"radius\" ROC is the norm of X - OC.\n%\n roc = x - repmat ( oc, 1, n );\n roc = roc.^2;\n roc = sum ( roc, 1 );\n roc = sqrt ( roc );\n%\n% Return the minimum and maximum radiuses.\n%\n r_min = min ( roc );\n r_max = max ( roc );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/centralize/cube_random_centralize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7290781678998682}} {"text": "function r = sobol_dataset ( m, n, skip )\n\n%*****************************************************************************80\n%\n%% SOBOL_DATASET generates a Sobol dataset and writes it to a file.\n%\n% Usage:\n%\n% r = sobol_dataset ( m, n, skip )\n%\n% where\n%\n% * M, the spatial dimension,\n% * N, the number of points to generate,\n% * SKIP, the number of initial values to skip.\n% * R is the M by N array created.\n%\n% creates an M by N Sobol dataset and writes it to the\n% file \"sobol_M_N.txt\".\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 December 2009\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SOBOL_DATASET\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Generate a Sobol dataset.\\n' );\n%\n% Get the spatial dimension.\n%\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n m = input ( ' Enter the spatial dimension M: ' );\n else\n m = str2num ( m );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension M = %d\\n', m );\n%\n% Get the number of points.\n%\n if ( nargin < 2 )\n fprintf ( 1, '\\n' );\n n = input ( ' Enter the number of points N: ' );\n else\n n = str2num ( n );\n end\n\n fprintf ( 1, ' Number of points N = %d\\n', n );\n%\n% Get SKIP.\n%\n if ( nargin < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' SKIP is the number of points to skip.\\n' );\n fprintf ( 1, ' 0 is a common choice.\\n' );\n fprintf ( 1, ' Another is the least power of 2 greater than or equal to N.\\n' );\n skip = input ( ' Enter SKIP: ' );\n else\n skip = str2num ( skip );\n end\n\n fprintf ( 1, ' SKIP = %d\\n', skip );\n%\n% Compute the data.\n%\n r = i4_sobol_generate ( m, n, skip );\n%\n% Write it to a file.\n%\n output_filename = ...\n strcat ( 'sobol_', num2str ( m ), '_', num2str ( n ), '.txt' );\n\n r8mat_write ( output_filename, m, n, r );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The data was written to the file \"%s\".\\n', ...\n output_filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SOBOL_DATASET:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction bit = i4_bit_hi1 ( n )\n\n%*****************************************************************************80\n%\n%% I4_BIT_HI1 returns the position of the high 1 bit base 2 in an integer.\n%\n% Example:\n%\n% N Binary BIT\n% ---- -------- ----\n% 0 0 0\n% 1 1 1\n% 2 10 2\n% 3 11 2 \n% 4 100 3\n% 5 101 3\n% 6 110 3\n% 7 111 3\n% 8 1000 4\n% 9 1001 4\n% 10 1010 4\n% 11 1011 4\n% 12 1100 4\n% 13 1101 4\n% 14 1110 4\n% 15 1111 4\n% 16 10000 5\n% 17 10001 5\n% 1023 1111111111 10\n% 1024 10000000000 11\n% 1025 10000000001 11\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the integer to be measured.\n% N should be nonnegative. If N is nonpositive, the value will always be 0.\n%\n% Output, integer BIT, the number of bits base 2.\n%\n i = floor ( n );\n bit = 0;\n\n while ( 1 )\n\n if ( i <= 0 )\n break;\n end\n\n bit = bit + 1;\n i = floor ( i / 2 );\n\n end\n\n return\nend\n\nfunction bit = i4_bit_lo0 ( n )\n\n%*****************************************************************************80\n%\n%% I4_BIT_LO0 returns the position of the low 0 bit base 2 in an integer.\n%\n% Example:\n%\n% N Binary BIT\n% ---- -------- ----\n% 0 0 1\n% 1 1 2\n% 2 10 1\n% 3 11 3 \n% 4 100 1\n% 5 101 2\n% 6 110 1\n% 7 111 4\n% 8 1000 1\n% 9 1001 2\n% 10 1010 1\n% 11 1011 3\n% 12 1100 1\n% 13 1101 2\n% 14 1110 1\n% 15 1111 5\n% 16 10000 1\n% 17 10001 2\n% 1023 1111111111 1\n% 1024 10000000000 1\n% 1025 10000000001 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the integer to be measured.\n% N should be nonnegative.\n%\n% Output, integer BIT, the position of the low 1 bit.\n%\n bit = 0;\n i = floor ( n );\n\n while ( 1 )\n\n bit = bit + 1;\n i2 = floor ( i / 2 );\n\n if ( i == 2 * i2 )\n break;\n end\n\n i = i2;\n\n end\n\n return\nend\nfunction [ quasi, seed ] = i4_sobol ( dim_num, seed )\n\n%*****************************************************************************80\n%\n%% I4_SOBOL generates a new quasirandom Sobol vector with each call.\n%\n% Discussion:\n%\n% The routine adapts the ideas of Antonov and Saleev.\n%\n% Thanks to Francis Dalaudier for pointing out that the range of allowed\n% values of DIM_NUM should start at 1, not 2! 17 February 2009.\n%\n% This function was modified to use PERSISTENT variables rather than\n% GLOBAL variables, 13 December 2009.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Bennett Fox.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Antonov, Saleev,\n% USSR Computational Mathematics and Mathematical Physics,\n% Volume 19, 1980, pages 252 - 256.\n%\n% Paul Bratley, Bennett Fox,\n% Algorithm 659:\n% Implementing Sobol's Quasirandom Sequence Generator,\n% ACM Transactions on Mathematical Software,\n% Volume 14, Number 1, pages 88-100, 1988.\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% Ilya Sobol,\n% USSR Computational Mathematics and Mathematical Physics,\n% Volume 16, pages 236-242, 1977.\n%\n% Ilya Sobol, Levitan, \n% The Production of Points Uniformly Distributed in a Multidimensional \n% Cube (in Russian),\n% Preprint IPM Akad. Nauk SSSR, \n% Number 40, Moscow 1976.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the number of spatial dimensions.\n% DIM_NUM must satisfy 1 <= DIM_NUM <= 40.\n%\n% Input/output, integer SEED, the \"seed\" for the sequence.\n% This is essentially the index in the sequence of the quasirandom\n% value to be generated. On output, SEED has been set to the\n% appropriate next value, usually simply SEED+1.\n% If SEED is less than 0 on input, it is treated as though it were 0.\n% An input value of 0 requests the first (0-th) element of the sequence.\n%\n% Output, real QUASI(DIM_NUM), the next quasirandom vector.\n%\n persistent atmost;\n persistent dim_max;\n persistent dim_num_save;\n persistent initialized;\n persistent lastq;\n persistent log_max;\n persistent maxcol;\n persistent poly;\n persistent recipd;\n persistent seed_save;\n persistent v;\n\n if ( isempty ( initialized ) )\n initialized = 0;\n dim_num_save = -1;\n end\n\n if ( ~initialized | dim_num ~= dim_num_save )\n\n initialized = 1;\n\n dim_max = 40;\n dim_num_save = -1;\n log_max = 30;\n seed_save = -1;\n%\n% Initialize (part of) V.\n%\n v(1:dim_max,1:log_max) = zeros(dim_max,log_max);\n\n v(1:40,1) = [ ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]';\n\n v(3:40,2) = [ ...\n 1, 3, 1, 3, 1, 3, 3, 1, ...\n 3, 1, 3, 1, 3, 1, 1, 3, 1, 3, ...\n 1, 3, 1, 3, 3, 1, 3, 1, 3, 1, ...\n 3, 1, 1, 3, 1, 3, 1, 3, 1, 3 ]';\n\n v(4:40,3) = [ ...\n 7, 5, 1, 3, 3, 7, 5, ...\n 5, 7, 7, 1, 3, 3, 7, 5, 1, 1, ...\n 5, 3, 3, 1, 7, 5, 1, 3, 3, 7, ...\n 5, 1, 1, 5, 7, 7, 5, 1, 3, 3 ]';\n\n v(6:40,4) = [ ...\n 1, 7, 9,13,11, ...\n 1, 3, 7, 9, 5,13,13,11, 3,15, ...\n 5, 3,15, 7, 9,13, 9, 1,11, 7, ...\n 5,15, 1,15,11, 5, 3, 1, 7, 9 ]';\n \n v(8:40,5) = [ ...\n 9, 3,27, ...\n 15,29,21,23,19,11,25, 7,13,17, ...\n 1,25,29, 3,31,11, 5,23,27,19, ...\n 21, 5, 1,17,13, 7,15, 9,31, 9 ]';\n\n v(14:40,6) = [ ...\n 37,33, 7, 5,11,39,63, ...\n 27,17,15,23,29, 3,21,13,31,25, ...\n 9,49,33,19,29,11,19,27,15,25 ]';\n\n v(20:40,7) = [ ...\n 13, ...\n 33,115, 41, 79, 17, 29,119, 75, 73,105, ...\n 7, 59, 65, 21, 3,113, 61, 89, 45,107 ]';\n\n v(38:40,8) = [ ...\n 7, 23, 39 ]';\n%\n% Set POLY.\n%\n poly(1:40)= [ ...\n 1, 3, 7, 11, 13, 19, 25, 37, 59, 47, ...\n 61, 55, 41, 67, 97, 91, 109, 103, 115, 131, ...\n 193, 137, 145, 143, 241, 157, 185, 167, 229, 171, ...\n 213, 191, 253, 203, 211, 239, 247, 285, 369, 299 ];\n\n atmost = 2^log_max - 1;\n%\n% Find the number of bits in ATMOST.\n%\n maxcol = i4_bit_hi1 ( atmost );\n%\n% Initialize row 1 of V.\n%\n v(1,1:maxcol) = 1;\n\n end\n%\n% Things to do only if the dimension changed.\n%\n if ( dim_num ~= dim_num_save )\n%\n% Check parameters.\n%\n if ( dim_num < 1 | dim_max < dim_num )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_SOBOL - Fatal error!\\n' );\n fprintf ( 1, ' The spatial dimension DIM_NUM should satisfy:\\n' );\n fprintf ( 1, ' 1 <= DIM_NUM <= %d\\n', dim_max );\n fprintf ( 1, ' But this input value is DIM_NUM = %d\\n', dim_num );\n return\n end\n\n dim_num_save = dim_num;\n%\n% Initialize the remaining rows of V.\n%\n for i = 2 : dim_num\n%\n% The bits of the integer POLY(I) gives the form of polynomial I.\n%\n% Find the degree of polynomial I from binary encoding.\n%\n j = poly(i);\n m = 0;\n\n while ( 1 )\n\n j = floor ( j / 2 );\n\n if ( j <= 0 )\n break;\n end\n\n m = m + 1;\n\n end\n%\n% Expand this bit pattern to separate components of the logical array INCLUD.\n%\n j = poly(i);\n for k = m : -1 : 1\n j2 = floor ( j / 2 );\n includ(k) = ( j ~= 2 * j2 );\n j = j2;\n end\n%\n% Calculate the remaining elements of row I as explained\n% in Bratley and Fox, section 2.\n%\n for j = m + 1 : maxcol \n newv = v(i,j-m);\n l = 1;\n for k = 1 : m\n l = 2 * l;\n if ( includ(k) )\n newv = bitxor ( newv, l * v(i,j-k) );\n end\n end\n v(i,j) = newv;\n end\n end\n%\n% Multiply columns of V by appropriate power of 2.\n%\n l = 1;\n for j = maxcol-1 : -1 : 1\n l = 2 * l;\n v(1:dim_num,j) = v(1:dim_num,j) * l;\n end\n%\n% RECIPD is 1/(common denominator of the elements in V).\n%\n recipd = 1.0 / ( 2 * l );\n\n lastq(1:dim_num) = 0;\n\n end\n\n seed = floor ( seed );\n\n if ( seed < 0 )\n seed = 0;\n end\n\n if ( seed == 0 )\n\n l = 1;\n lastq(1:dim_num) = 0;\n\n elseif ( seed == seed_save + 1 )\n%\n% Find the position of the right-hand zero in SEED.\n%\n l = i4_bit_lo0 ( seed );\n\n elseif ( seed <= seed_save )\n\n seed_save = 0;\n l = 1;\n lastq(1:dim_num) = 0;\n\n for seed_temp = seed_save : seed - 1\n l = i4_bit_lo0 ( seed_temp );\n for i = 1 : dim_num\n lastq(i) = bitxor ( lastq(i), v(i,l) );\n end\n end\n\n l = i4_bit_lo0 ( seed );\n\n elseif ( seed_save + 1 < seed )\n\n for seed_temp = seed_save + 1 : seed - 1\n l = i4_bit_lo0 ( seed_temp );\n for i = 1 : dim_num\n lastq(i) = bitxor ( lastq(i), v(i,l) );\n end\n end\n\n l = i4_bit_lo0 ( seed );\n\n end\n%\n% Check that the user is not calling too many times!\n%\n if ( maxcol < l )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_SOBOL - Fatal error!\\n' );\n fprintf ( 1, ' Too many calls!\\n' );\n fprintf ( 1, ' MAXCOL = %d\\n', maxcol );\n fprintf ( 1, ' L = %d\\n', l );\n return\n end\n%\n% Calculate the new components of QUASI.\n%\n for i = 1 : dim_num\n quasi(i) = lastq(i) * recipd;\n lastq(i) = bitxor ( lastq(i), v(i,l) );\n end\n\n seed_save = seed;\n seed = seed + 1;\n\n return\nend\nfunction r = i4_sobol_generate ( m, n, skip )\n\n%*****************************************************************************80\n%\n%% I4_SOBOL_GENERATE generates a Sobol dataset.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 December 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points to generate.\n%\n% Input, integer SKIP, the number of initial points to skip.\n%\n% Output, real R(M,N), the points.\n%\n seed = skip;\n\n for j = 1 : n\n [ r(1:m,j), seed ] = i4_sobol ( m, seed );\n end\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Discussion:\n%\n% An R8MAT is an array of R8's.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 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, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n return;\n end\n%\n% Write the data.\n%\n% For smaller data files, and less precision, try:\n%\n% fprintf ( output_unit, ' %14.6f', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %24.16f', table(i,j) );\n end\n fprintf ( output_unit, '\\n' );\n end\n%\n% Close the file.\n%\n fclose ( output_unit );\n\n return\nend\nfunction timestamp ( )\n\n%*****************************************************************************80\n%\n%% TIMESTAMP prints the current YMDHMS date as a timestamp.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 February 2003\n%\n% Author:\n%\n% John Burkardt\n%\n t = now;\n c = datevec ( t );\n s = datestr ( c, 0 );\n fprintf ( 1, '%s\\n', s );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sobol_dataset/sobol_dataset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7290781659311113}} {"text": "function [A,B,C,D]=era(h,n,N,Ts,def);\n\n% Eigensystem Realization Algorithm (ERA)\n%\n% Author: Samuel da Silva - UNICAMP\n% e-mail: samsilva@fem.unicamp.br\n% Date: 2006/10/20\n% \n% [A,B,C,D]=era(h,n,N,Ts,def);\n% \n% Inputs:\n% h: discrete-time impulse response\n% n: order of the system\n% N: number of samples to assembly the Hankel matrix\n% Ts: sample time\n% def: if = 1: the output will be the discrete-time state-space model\n% if = 2: the output will be the continuous-time state-space model\n% \n% Otputs:\n% [A,B,C,D]: state-space model\n% \n% Note: For now, it works to SISO systems and it is necessary the control toolbox\n%\n% References: Juang, J. N. and Phan, M. Q. \"Identification and Control of\n% Mechanical Systems\", Cambridge University Press, 2001\n\n% Hankel matrix\nH0 = hankel(h(2:N+1)); % k = 0\nH1 = hankel(h(3:N+2)); % k = 1;\n\n% Factorization of the Hankel matrix by use of SVD\n[R,Sigma,S] = svd(H0); \n% R and S are orthonormal and Sigma is a rectangular matrix\n\nSigman = Sigma(1:n,1:n); \n\nWo = R(:,1:n)*Sigman^0.5; % observability matrix\nCo = Sigman^.5*S(:,1:n)'; % controllability matrix\n\n% The identified system matrix are:\nA = Sigman^-.5*R(:,1:n)'*H1*S(:,1:n)*Sigman^-.5; % dynamic matrix\nB = Co(:,1); % input matrix\nC = Wo(1,:); % output matrix\nD = h(1); % direct-transmission matrix\n\nsysdisc = ss(A,B,C,D,Ts); % discrete-time system\n\nif def == 2 \n syscont = d2c(sysdisc,'zoh'); % Conversion of discrete LTI models to continuous time\n [A,B,C,D]=ssdata(syscont); % continuous system\nend\n\n%--------------------------------------------------------------------------\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/12848-eigensystem-realization-algorithm/era.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7290207594772864}} {"text": "function [ c ] = get_bpsk_cap( snr_db )\n% assumes e[x^2] = 1;\n\nx_vec = [-1, 1];\nn_0 = 1/2*10^(-snr_db/10);\ndelta_y = sqrt(n_0) * 0.001;\nmax_value = min(10000, max(x_vec) + 3 + 3*sqrt(n_0));\ny_vec = -max_value: delta_y : max_value;\np_y = zeros(length(y_vec), 1);\nfor y_index = 1 : length(y_vec)\n y = y_vec(y_index);\n for x_index = 1 : length(x_vec) \n x = x_vec(x_index);\n p_y(y_index) = p_y(y_index) + exp(-(y - x).^2/2/n_0)/sqrt(2*pi*n_0) * 0.5;\n end\nend\n\np_y = p_y / (sum(p_y)*delta_y);\n\nh = 0;\nfor y_index = 1 : length(y_vec)\n if p_y(y_index) > 0\n h = h + (-log2(p_y(y_index))) * p_y(y_index) * delta_y;\n end\nend\nc = h - 0.5 * (1 + log(2*pi*n_0))/log(2) ;\n\n\n", "meta": {"author": "tavildar", "repo": "Polar", "sha": "75f13c43d550d4ce1c84eab0b86d0fe537c312b1", "save_path": "github-repos/MATLAB/tavildar-Polar", "path": "github-repos/MATLAB/tavildar-Polar/Polar-75f13c43d550d4ce1c84eab0b86d0fe537c312b1/PolarM/CapacityHelper/get_bpsk_cap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7290207579882058}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% inhomo_iso.m demonstrates Edge-preserving non-linear\n% inhomogeneous linear isotropic filtering for denoising\n%\n% Copyright (c) Ritwik Kumar, Harvard University 2010\n% www.seas.harvard.edu/~rkkumar\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclear;\n%read the image\nim = image_read('synimgn2');\nw = double(im);\n\n% set up finite difference parameters\nalpha =0.5;\nk = 1;\nh = 1;\n\nlambda = (alpha^2)*(k/(h^2));\n\n[m n] = size(w);\n% stick image into a vector\nw_vec = reshape(w,n*n,1);\nw_old = w_vec;\nw_new = w_vec;\n\n%smooth the image using Gaussian filtering\nim_smth = filter_function(w,3);\n\n%required of g() calculation\n[dx_im_smth dy_im_smth] = gradient(im_smth);\ngr_im_smth = dx_im_smth.^2 + dy_im_smth.^2;\n\n% element by element g() calculation\n[mmm nnn] = size(gr_im_smth);\nfor i=1:mmm\n for j=1:nnn\n g(i,j) = 1/(1+(gr_im_smth(i,j)/36));\n end\nend\ng = g';\njj=1;\n\nfigure;\nfor k=1:200 % for each iteration \n for i=1:n*n % solve using JAcobi iteration scheme\n row = ceil(i/n); %compute what row this pixel belongs to in original image\n col = i - (row-1) * n; % compute the column similarly\n\n %different if conditions handles pixels at different location in\n %the image as depending on their location they may or may not have\n %all their neighbor pixels which will be required for finite\n %differences\n \n if((col > 1) && (col < n) && (row > 1) && (row < n))\n xx = [(lambda * (-g(row,col) + g(row,col+1) + g(row+1,col) -g(row+1,col+1))) * ...\n (- w_old(i) + w_old(i+1) - w_old(i+n) + w_old(i+n+1))];\n \n s = [-(lambda * g(row,col)) * (w_old(i+1) + w_old(i-1) + w_old(i+n) + w_old(i-n))] ...\n + xx;\n w_new(i) = (-s + w_old(i))/(1+4*lambda*g(row,col));\n elseif((row == 1) && (col > 1) && (col < n))\n xx = [(lambda * (-g(row,col) + g(row,col+1) + g(row+1,col) -g(row+1,col+1))) * ...\n (- w_old(i) + w_old(i+1) - w_old(i+n) + w_old(i+n+1))];\n \n s = [-(lambda * g(row,col)) * (w_old(i+1) + w_old(i-1) + w_old(i+n))] ...\n + xx;\n \n w_new(i) = (-s + w_old(i))/(1+4*lambda);\n elseif((row == n) && (col > 1) && (col < n))\n xx = [(lambda * (-g(row,col) + g(row,col+1))) * ...\n (- w_old(i) + w_old(i+1))];\n \n s = [-(lambda * g(row,col)) * (w_old(i+1) + w_old(i-1) + w_old(i-n))] ...\n + xx;\n \n w_new(i) = (-s + w_old(i))/(1+4*lambda);\n elseif((col == 1) && (row > 1) && (row < n))\n xx = [(lambda * (-g(row,col) + g(row,col+1) + g(row+1,col) -g(row+1,col+1))) * ...\n (- w_old(i) + w_old(i+1) - w_old(i+n) + w_old(i+n+1))];\n \n s = [-(lambda * g(row,col)) * (w_old(i+1) + w_old(i+n) + w_old(i-n))] ...\n + xx;\n \n %s = -(lambda) * (w_old(i+1) + w_old(i+n) + w_old(i-n));\n w_new(i) = (-s + w_old(i))/(1+4*lambda);\n elseif((col == n) && (row > 1) && (row < n))\n xx = [(lambda * (-g(row,col) + g(row+1,col) )) * ...\n (- w_old(i) - w_old(i+n))];\n \n s = [-(lambda * g(row,col)) * ( w_old(i-1) + w_old(i+n) + w_old(i-n))] ...\n + xx;\n \n w_new(i) = (-s + w_old(i))/(1+4*lambda);\n elseif((col==1) && (row==1))\n xx = [(lambda * (-g(row,col) + g(row,col+1) + g(row+1,col) -g(row+1,col+1))) * ...\n (- w_old(i) + w_old(i+1) - w_old(i+n) + w_old(i+n+1))];\n \n s = [-(lambda * g(row,col)) * (w_old(i+1) + w_old(i+n))] ...\n + xx;\n \n w_new(i) = (-s + w_old(i))/(1+4*lambda);\n elseif((col==n) && (row==1))\n xx = [(lambda * (-g(row,col) + g(row+1,col))) * ...\n (- w_old(i) - w_old(i+n) )];\n\n s = [-(lambda * g(row,col)) * (w_old(i-1) + w_old(i+n))] ...\n + xx;\n\n w_new(i) = (-s + w_old(i))/(1+4*lambda);\n elseif((col==1) && (row==n))\n xx = [(lambda * (-g(row,col) + g(row,col+1) )) * ...\n (- w_old(i) + w_old(i+1) )];\n\n s = [-(lambda * g(row,col)) * (w_old(i+1) + w_old(i-n))] ...\n + xx;\n\n w_new(i) = (-s + w_old(i))/(1+4*lambda);\n elseif((col==n) && (row==n))\n xx = [(lambda * (-g(row,col) )) * ...\n (- w_old(i) )];\n\n s = [-(lambda * g(row,col)) * ( w_old(i-1) + w_old(i-n))] ...\n + xx;\n\n w_new(i) = (-s + w_old(i))/(1+4*lambda);\n end\n end\n w_old = w_new;\n if((k==10)||(k==50)||(k==100)||(k==200)) % outputting the values at different iterations\n subplot(2,2,jj)\n imshow(uint8(reshape(w_new,n,n)));\n imwrite(uint8(reshape(w_new,n,n)),strcat('iso-synimgn2',int2str(jj),'.bmp')); \n title('Linear Inhomogeneous Isotropic Filtering (Implicit Euler Method)');\n xlabel(strcat('Lenna at t=',int2str(k),', Alpha=0.5')); \n \n\n jj=jj+1;\n end\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/28112-diffusion-filtering-for-image-denoising/ImageDenoising/inhomo_iso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7290207547553003}} {"text": "function [C, status] = parfileCondition(parfiles, nFrames);\n%\n% [C, status] = parfileCondition(parfiles, );\n%\n% Estimate the condition number of an experimental paradigm\n% specified by parfiles. This condition number determines\n% whether or not time courses can be successfully deconvolved\n% for data with this paradigm.\n% \n% parfiles: cell of parfile paths.\n% \n% nFrames: optional argument specifying # of frames to take from\n% each parfile. If omitted, just takes max # of frames set by the\n% parfiles.\n%\n% C: condition number, equal to sum(X' * X), where X is the\n% design matrix constructed from the parfiles.\n%\n% status: 1 if time courses can be deconvolved, 0 if not. \n% Basically, status just tests whether C is less than 10 million.\n%\n%\n%\n% ras 02/2006. \nstatus = 0;\n\nparams = er_defaultParams;\nparams.glmHRF = 0;\n\n% create Toeplitz matrix for deconvolution from the parfiles\nS = delta_function_from_parfile(parfiles);\nX = glm_deconvolution_matrix(S, -4:17);\n\n% This part I've empirically determined from er_selxavg, but\n% hope to understand soon:\n% iteratively sum the matrix X' * W * X \n% (where W is a whitening matrix which we basically always\n% set to the identitiy matrix, so I'm only concerned with that\n% case).\nnFrames = size(X, 1);\nnPred = size(X, 2);\nnRuns = size(X, 3);\nXtX = zeros(nPred, nPred);\nfor i = 1:nRuns\n XtX = XtX + [X(:,:,i)' * X(:,:,i)];\nend\n\nC = cond(XtX);\nstatus = (C < 10^7);\n\nif status==0\n disp('Paradigm is ill-conditioned.')\nend\n\nreturn", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrBOLD/EventRelated/parfileCondition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7290207487989775}} {"text": "function [xc,Vi] = canonical_autocorrelation(TR,n,varargin)\n% [xc,Vi] = canonical_autocorrelation(TR,n,[a])\n% Tor Wager, 2 / 23 / 04\n%\n% exponential autocorrelation function of the form xc = e ^ (-ax)\n% Optional input \"a\" is an exponent; higher = more white noise, low =\n% colored\n%\n% TR = sampling rate (time per data point)\n% n = number of samples in timeseries\n%\n% xc = vector containing autocorrelation coefficients\n% Vi = autocorrelation matrix\n\nf = inline('A * exp(-a * x)','A','a','x'); % exponential function\nxa = 0:TR:60;\n\nif length(varargin) > 0\n xc = f(1,varargin{1},xa); \nelse\n xc = f(.9475,.5323,xa); % params at 3T from vnl experiment, n = 10\n xc = xc ./ max(xc);\nend\n\n% autocorrelation\nVi = getV('make',xc,n);\n\nreturn\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/GA3/canonical_autocorrelation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.729020748289489}} {"text": "% Program for Bus Power Injections, Line & Power flows (p.u)...\n\n%function [Pi Qi Pg Qg Pl Ql] = loadflow(nb,V,del,BMva)\nfunction [Load_Flow_M Line_Flow_M] = loadflow(nb,V,del,BMva,Line_Data,Bus_Data)\n\nY = ybusppg(nb,Line_Data); % Calling Ybus program..\n%lined = linedatas(nb); % Get linedats.\nlined = Line_Data;\nbusd = Bus_Data;\n%busd = busdatas(nb); % Get busdatas..\n\nVm = pol2rect(V,del); % Converting polar to rectangular..\nDel = 180/pi*del; % Bus Voltage Angles in Degree...\nfb = lined(:,1); % From bus number...\ntb = lined(:,2); % To bus number...\nnl = length(fb); % No. of Branches..\nPl = busd(:,7); % PLi..\nQl = busd(:,8); % QLi..\n\nIij = zeros(nb,nb);\nSij = zeros(nb,nb);\nSi = zeros(nb,1);\n\n% Bus Current Injections..\n I = Y*Vm;\n Im = abs(I);\n Ia = angle(I);\n \n%Line Current Flows..\nfor m = 1:nl\n p = fb(m); q = tb(m);\n Iij(p,q) = -(Vm(p) - Vm(q))*Y(p,q); % Y(m,n) = -y(m,n)..\n Iij(q,p) = -Iij(p,q);\nend\nIij = sparse(Iij);\nIijm = abs(Iij);\nIija = angle(Iij);\n\n% Line Power Flows..\nfor m = 1:nb\n for n = 1:nb\n if m ~= n\n Sij(m,n) = Vm(m)*conj(Iij(m,n))*BMva;\n end\n end\nend\nSij = sparse(Sij);\nPij = real(Sij);\nQij = imag(Sij);\n \n% Line Losses..\nLij = zeros(nl,1);\nfor m = 1:nl\n p = fb(m); q = tb(m);\n Lij(m) = Sij(p,q) + Sij(q,p);\nend\nLpij = real(Lij);\nLqij = imag(Lij);\n\n% Bus Power Injections..\nfor i = 1:nb\n for k = 1:nb\n Si(i) = Si(i) + conj(Vm(i))* Vm(k)*Y(i,k)*BMva;\n end\nend\nPi = real(Si);\nQi = -imag(Si);\nPg = Pi+Pl;\nQg = Qi+Ql;\n\nLoad_Flow_M = zeros(nb+1,9);\n\nfor m = 1:nb\n Load_Flow_M(m,1) = m;\n Load_Flow_M(m,2) = V(m);\n Load_Flow_M(m,3) = Del(m);\n Load_Flow_M(m,4) = Pi(m); \n Load_Flow_M(m,5) = Qi(m); \n Load_Flow_M(m,6) = Pg(m);\n Load_Flow_M(m,7) = Qg(m); \n Load_Flow_M(m,8) = Pl(m);\n Load_Flow_M(m,9) = Ql(m);\nend\nm = m + 1;\n Load_Flow_M(m,1) = NaN;\n Load_Flow_M(m,2) = NaN;\n Load_Flow_M(m,3) = NaN;\n Load_Flow_M(m,4) = sum(Pi); \n Load_Flow_M(m,5) = sum(Qi); \n Load_Flow_M(m,6) = sum(Pi+Pl);\n Load_Flow_M(m,7) = sum(Qi+Ql); \n Load_Flow_M(m,8) = sum(Pl);\n Load_Flow_M(m,9) = sum(Ql);\n \nLine_Flow_M = zeros(nl+1,10);\n\nfor m = 1:nl\n p = fb(m); q = tb(m);\n Line_Flow_M(m,1) = full(p); \n Line_Flow_M(m,2) = full(q); \n Line_Flow_M(m,3) = full(Pij(p,q));\n Line_Flow_M(m,4) = full(Qij(p,q));\n Line_Flow_M(m,5) = full(q);\n Line_Flow_M(m,6) = full(p);\n Line_Flow_M(m,7) = full(Pij(q,p));\n Line_Flow_M(m,8) = full(Qij(q,p));\n Line_Flow_M(m,9) = Lpij(m);\n Line_Flow_M(m,10) = Lqij(m);\nend\nm = m+1;\n Line_Flow_M(m,1) = NaN; \n Line_Flow_M(m,2) = NaN; \n Line_Flow_M(m,3) = NaN;\n Line_Flow_M(m,4) = NaN;\n Line_Flow_M(m,5) = NaN;\n Line_Flow_M(m,6) = NaN;\n Line_Flow_M(m,7) = NaN;\n Line_Flow_M(m,8) = NaN;\n Line_Flow_M(m,9) = sum(Lpij);\n Line_Flow_M(m,10) = sum(Lqij);\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/30069-excel-based-power-flow-program/Excel_Powerflow Solver/loadflow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.7290175539266589}} {"text": "function fem1d_bvp_quadratic_test06 ( )\n\n%*****************************************************************************80\n%\n%% FEM1D_BVP_QUADRATIC_TEST06 does an error analysis.\n%\n% Discussion:\n%\n% Use A6, C6, F6, EXACT6, EXACT_UX6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM1D_BVP_QUADRATIC_TEST06\\n' );\n fprintf ( 1, ' Solve -( A(x) U''(x) )'' + C(x) U(x) = F(x)\\n' );\n fprintf ( 1, ' for 0 < x < 1, with U(0) = U(1) = 0.\\n' );\n fprintf ( 1, ' A6(X) = 1.0\\n' );\n fprintf ( 1, ' C6(X) = 0.0\\n' );\n fprintf ( 1, ' F6(X) = pi*pi*sin(pi*X)\\n' );\n fprintf ( 1, ' U6(X) = sin(pi*x)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Compute L2 norm and seminorm of error for various N.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N L1 error L2 error Seminorm error\\n' );\n fprintf ( 1, '\\n' );\n\n n = 11;\n for i = 0 : 4\n%\n% Geometry definitions.\n%\n x_first = 0.0;\n x_last = 1.0;\n x = linspace ( x_first, x_last, n );\n x = x(:);\n\n u = fem1d_bvp_quadratic ( n, @a6, @c6, @f6, x );\n\n e1 = l1_error ( n, x, u, @exact6 );\n e2 = l2_error_quadratic ( n, x, u, @exact6 );\n h1s = h1s_error_quadratic ( n, x, u, @exact_ux6 );\n\n fprintf ( 1, ' %4d %14f %14f %14f\\n', n, e1, e2, h1s );\n\n n = 2 * ( n - 1 ) + 1;\n\n end\n\n return\nend\nfunction value = a6 ( x )\n\n%*****************************************************************************80\n%\n%% A6 evaluates A function #6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of A(X).\n%\n value = 1.0;\n\n return\nend\nfunction value = c6 ( x )\n\n%*****************************************************************************80\n%\n%% C6 evaluates C function #6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of C(X).\n%\n value = 0.0;\n\n return\nend\nfunction value = exact6 ( x )\n\n%*****************************************************************************80\n%\n%% EXACT6 returns exact solution #6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of U(X).\n%\n value = sin ( pi * x );\n\n return\nend\nfunction value = exact_ux6 ( x )\n\n%*****************************************************************************80\n%\n%% EXACT_UX6 evaluates the derivative of exact solution #6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of dUdX(X).\n%\n value = pi * cos ( pi * x );\n\n return\nend\nfunction value = f6 ( x )\n\n%*****************************************************************************80\n%\n%% F6 evaluates right hand side function #6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of F(X).\n%\n value = pi * pi * sin ( pi * x );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem1d_bvp_quadratic/fem1d_bvp_quadratic_test06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7289671516087397}} {"text": "function ou_euler_maruyama ( theta, mu, sigma, x0, tmax, n, r, seed )\n\n%*****************************************************************************80\n%\n%% OU_EULER_MARUYAMA applies Euler-Maruyama to the Ornstein-Uhlenbeck SDE.\n%\n% Discussion:\n%\n% The stochastic differential equation (SDE) is:\n%\n% dx = theta * ( mu - x(t) ) dt + sigma dW, \n% x(0) = x0,\n%\n% The discretized Brownian path uses a constant stepsize.\n%\n% A \"large\" time step DT_LARGE is used for the smooth portion of the\n% equation, while a smaller time step DT_SMALL is used for the\n% discretized Brownian path. We take R small steps to equal one \n% large step, so that:\n%\n% dt_large = r * dt_small = tmax / n\n%\n% For an SDE of the form:\n%\n% dx = f(x(t)) dt + g(x(t)) dW(t)\n%\n% the Euler-Maruyama method has the form:\n%\n% x(j) = x(j-1) + f(X(j-1)) * dt_large + g(X(j-1)) * dW(j-1)\n%\n% where dW(j-1) is approximated by the sum of R normal random values\n% multiplied by the square root of DT_SMALL.\n%\n% Note that if SIGMA is zero, the problem becomes deterministic,\n% with solution\n%\n% x(t) = mu + ( x0 - mu ) * exp ( - theta * t )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 January 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Desmond Higham,\n% An Algorithmic Introduction to Numerical Simulation of\n% Stochastic Differential Equations,\n% SIAM Review,\n% Volume 43, Number 3, September 2001, pages 525-546\n%\n% Parameters:\n%\n% Input, real THETA, MU, SIGMA, the value of problem parameters.\n%\n% Input, real X0, the initial condition. When studying many\n% realizations of this problem, it is usual for X0 to be chosen\n% from a normal distribution.\n%\n% Input, real TMAX, the final time.\n%\n% Input, integer N, the number of large scale time steps.\n%\n% Input, integer R, the number of small scale time steps per single\n% large scale time step.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'OU_EULER_MARUYAMA:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Use an Euler-Maruyama method to approximate the solution of\\n' );\n fprintf ( 1, ' the Ornstein-Uhlenbeck stochastic differential equation:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' d x(t) = theta * ( mu - x(t) ) dt + sigma dW\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' with initial condition x(0) = x0.\\n' );\n\n if ( nargin < 1 )\n theta = 2.0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using default decay rate THETA = %g\\n', theta );\n end\n\n if ( nargin < 2 )\n mu = 1.0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using default mean MU = %g\\n', mu );\n end\n\n if ( nargin < 3 )\n sigma = 0.15;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using default variance SIGMA = %g\\n', sigma );\n end\n\n if ( nargin < 4 )\n x0 = 2.0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using default initial value X0 = %g\\n', x0 );\n end\n\n if ( nargin < 5 )\n tmax = 3.0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using default final time TMAX = %g\\n', tmax );\n end \n\n if ( nargin < 6 )\n n = 10000;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using default number of large timesteps N = %d\\n', n );\n end\n\n if ( nargin < 7 )\n r = 8;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using default ratio of small to large timesteps R = %d\\n', r );\n end\n\n if ( nargin < 8 )\n seed = 123456789;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using default value of random SEED = %d\\n', seed );\n end\n%\n% Initialize the random number generator.\n% The following way to initialize the random number generator \n% may not be available in older versions of MATLAB.\n%\n rng ( seed )\n%\n% Set time steps.\n%\n dt_large = tmax / n;\n dt_small = tmax / n / r;\n%\n% Carry out the Euler-Maruyama approximate integration process.\n%\n t = linspace ( 0, tmax, n + 1 );\n x = zeros ( 1, n + 1 );\n\n x(1) = x0;\n for j = 1 : n\n dw = sqrt ( dt_small ) * randn ( 1, r );\n x(j+1) = x(j) + dt_large * theta * ( mu - x(j) ) + sigma * sum ( dw(1:r) );\n end\n%\n% Plot the approximate solution.\n%\n plot ( t, x, 'r-', 'LineWidth', 3 )\n xlabel ( 't', 'FontSize', 16 )\n ylabel ( 'X(t)', 'FontSize', 16, 'Rotation', 0, 'HorizontalAlignment', 'right' )\n title ( 'Euler-Maruyama solution of Ornstein-Uhlenbeck SDE', 'FontSize', 16 )\n grid on\n\n filename = 'ou_euler_maruyama.png';\n print ( '-dpng', filename )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Plot saved 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/ornstein_uhlenbeck/ou_euler_maruyama.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7289671490679648}} {"text": "function d = edge_degree ( n_node, n_edge, t )\n\n%*****************************************************************************80\n%\n%% EDGE_DEGREE returns the degree of the nodes of a graph stored by edges.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 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_NODE, the number of nodes in the graph.\n% N_NODE must be positive.\n%\n% Input, integer N_EDGE, the number of edges in the graph.\n% N_EDGE must be positive.\n%\n% Input, integer T(2,N_EDGE), describes the edges of the tree\n% as pairs of nodes.\n%\n% Output, integer D(N_NODE), the degree of each node.\n%\n\n%\n% Check.\n%\n ierror = edge_check ( n_node, n_edge, t );\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'EDGE_DEGREE - Fatal error!\\n' );\n fprintf ( 1, ' The input array is illegal.\\n' );\n fprintf ( 1, ' IERROR = %d\\n', ierror );\n error ( 'EDGE_DEGREE - Fatal error!' );\n end\n%\n% Compute the degree of each node.\n%\n d(1:n_node) = 0;\n\n for j = 1 : n_edge\n d(t(1,j)) = d(t(1,j)) + 1;\n d(t(2,j)) = d(t(2,j)) + 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/combo/edge_degree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.8479677564567912, "lm_q1q2_score": 0.7289671357295389}} {"text": "%% \"Spirograph\" Code\n% Jonathan Jamieson - September 2013\n% unigamer@gmail.com\n% www.jonathanjamieson.com\n\n% This is the main script. Run it in Matlab and then mess around with\n% the \"User Configurable Parameters\". By default arm at the bottom\n% is arm \"a\" and the left arm is arm \"b\". The \"c\" coordinates denote\n% the position of the rotating platform.\n\n%% User Configurable Parameters -------------------------------------------\n% a - arm a parameters\n% b - arm b parameters\n% c - parameters of the rotating disc where the paper would be\n\n% Time-span\nt=1:0.01:900;\n\n% The positions of the local coordinate systems in the global one\nxa = 18; \nya = 2.5;\n\nxb = 6.5;\nyb = 12;\n\nxc = 18;\nyc = 12;\n\n% The positions of where the arms are mounted to the rotating discs\nA_x_local =-1.8;\nA_y_local = 0.2;\n\nB_x_local = 3;\nB_y_local = 1;\n\n% The angular speeds of the rotating discs\nA_omega = -3*5;\nB_omega = 1*5;\nC_omega = 0.22*5;\n\n% The lengths of the arms\nLa = 8;\nLb = 13;\n\n% The distance between where the two rods join and the pen\nextension = 1; \n\n% Radii of the discs\nra = 2; % The \"r\" parameters are only\nrb = 4; % used for the purpose of\nrc = 6; % visualisation, not calculation\n\n% End of User Configurable Parameters -------------------------------------\n\n%% Graphical Stuff\nscrsz = get(0,'ScreenSize'); % Get screen size\nfigure('Name','The drawing','Position',[scrsz(1)+scrsz(3)/4 scrsz(2)+scrsz(4)/6 scrsz(3)/2 scrsz(4)/1.5]);\nhold on\ntitle('The Plot');\naxis equal\n \nfield_size = 30;\nxlim(gca, [0 field_size]);\nylim(gca, [0 field_size]);\n\nL1_handle = line([0 0],[0 0],'Color','red','LineWidth',2);\nL2_handle = line([0 0],[0 0],'Color','red','LineWidth',2);\nP_handle = line([0 0],[0 0],'Color','red','LineWidth',2);\n\nPlotCircle(xa,ya,ra);\nPlotCircle(xb,yb,rb);\nPlotCircle(xc,yc,rc);\n\npen_log = zeros(numel(t),2); % Pre-allocate the matrix, this speeds stuff up and is good practice.\n\n%% Main Loop\n% This loop is executed for each time-step\n\ntry\n for loop_counter=1:1:numel(t)\n \n %% Calculate the position of the pen at the current time-step\n current_time=t(loop_counter);\n [A_x_global,A_y_global] = Local2Global(A_x_local,A_y_local,xa,ya,current_time*A_omega);\n [B_x_global,B_y_global] = Local2Global(B_x_local,B_y_local,xb,yb,current_time*B_omega);\n [C_x_global,C_y_global] = Calculate_Point_C(A_x_global,B_x_global,A_y_global,B_y_global,La,Lb); % This is the intersection of two circles\n [P_x_global,P_y_global ] = CalculatePenPosition(A_x_global,A_y_global,C_x_global,C_y_global,extension);\n [C_x_local,C_y_local] = Global2Local(P_x_global,P_y_global,xc,yc,current_time*C_omega); \n \n pen_log((loop_counter),:) = [C_x_local,C_y_local]; % Update the pen_log with the new pen position\n \n %% Create a temporary matrix with the global position of each pen point generated so far\n % at the current time. Since the local coordinate system is rotating a new set of temporary coordinates need to be generated each time step.\n pen_log_temp = zeros(loop_counter,2);\n \n for loop_plot=1:1:loop_counter;\n \n [temp_x temp_y] = Local2Global(pen_log(loop_plot,1),pen_log(loop_plot,2),xc,yc,current_time*C_omega);\n\n pen_log_temp(loop_plot,:) = [temp_x temp_y];\n end\n \n if loop_counter ~= 1; % Don't try and delete on the first iteration because nothing will have been plotted yet\n delete(h_plot);\n end\n \n %% Redraw everything for the current time-step\n h_plot = plot(pen_log_temp(:,1),pen_log_temp(:,2),'Color','magenta');\n\n set(L1_handle,'XData',[A_x_global C_x_global],'YData',[A_y_global C_y_global]);\n set(L2_handle,'XData',[B_x_global C_x_global],'YData',[B_y_global C_y_global]);\n set(P_handle,'XData',[C_x_global P_x_global],'YData',[C_y_global P_y_global]);\n\n refresh\n pause(0.000001);\n \n end\n\n %% Check figure hasn't been closed\n catch E\n if ~strcmp(E.identifier, 'MATLAB:class:InvalidHandle')\n pen_log = pen_log(any(pen_log,2),:); % Delete unused pen_log entries\n x = pen_log(:,1); % Make a vector from the first column\n y = pen_log(:,2); % Make a vector from the second column\n clearvars -except x y % Delete all variables except the coordinates generated in the drawing process. Uncomment this if you wish to debug something.\n break\n \n end\nend\n\n% comet(x,y) % Uncomment this function if you want an animated plot at the end of the drawing\n% plot (x,y) % Uncomment this function if you want a plot at the end of the drawing\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/38828-rotordraw/RotorDraw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7289100301591859}} {"text": "function w = dualtree(x, J, Faf, af)\n\n% Dual-tree Complex Discrete Wavelet Transform\n%\n% USAGE:\n% w = dualtree(x, J, Faf, af)\n% INPUT:\n% x - N-point vector\n% 1) N is divisible by 2^J\n% 2) N >= 2^(J-1)*length(af)\n% J - number of stages\n% Faf - filters for the first stage \n% af - filters for the remaining stages\n% OUTPUT:\n% w - DWT coefficients\n% w{j}{1}, j = 1..J - real part \n% w{j}{2}, j = 1..J - imaginary part \n% w{J+1}{d} - lowpass coefficients, d = 1,2\n% EXAMPLE:\n% x = rand(1, 512);\n% J = 4;\n% [Faf, Fsf] = FSfarras;\n% [af, sf] = dualfilt1;\n% w = dualtree(x, J, Faf, af);\n% y = idualtree(w, J, Fsf, sf);\n% err = x - y;\n% max(abs(err))\n%\n% WAVELET SOFTWARE AT POLYTECHNIC UNIVERSITY, BROOKLYN, NY\n% http://taco.poly.edu/WaveletSoftware/\n\n% normalization\nx = x/sqrt(2);\n\n% Tree 1\n[x1 w{1}{1}] = afb(x, Faf{1});\nfor j = 2:J\n [x1 w{j}{1}] = afb(x1, af{1});\nend\nw{J+1}{1} = x1;\n\n% Tree 2\n[x2 w{1}{2}] = afb(x, Faf{2});\nfor j = 2:J\n [x2 w{j}{2}] = afb(x2, af{2});\nend\nw{J+1}{2} = x2;\n\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/DTCWT/dualtree.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.7289100257202232}} {"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% Discussion:\n%\n% The L2 norm can be defined here as:\n%\n% C8_NORM2(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% 04 February 2004\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/linplus/c8_le_l2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7288567260896701}} {"text": "function a = oto ( m, n )\n\n%*****************************************************************************80\n%\n%% OTO returns the OTO matrix.\n%\n% Example:\n%\n% N = 5\n%\n% 2 1 . . .\n% 1 2 1 . .\n% . 1 2 1 .\n% . . 1 2 1\n% . . . 1 2\n%\n% Properties:\n%\n% A is banded, with bandwidth 3.\n%\n% A is tridiagonal.\n%\n% Because A is tridiagonal, it has property A (bipartite).\n%\n% A is integral: int ( A ) = A.\n%\n% A is Toeplitz: constant along diagonals.\n%\n% A is symmetric: A' = A.\n%\n% Because A is symmetric, it is normal.\n%\n% Because A is normal, it is diagonalizable.\n%\n% A is persymmetric: A(I,J) = A(N+1-J,N+1-I).\n%\n% A is weakly diagonally dominant, but not strictly diagonally dominant.\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 November 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns of A.\n%\n% Output, real A(M,N), the matrix.\n%\n a = zeros ( m, n );\n\n for i = 1 : m\n for j = 1 : n\n\n if ( j == i - 1 )\n a(i,j) = 1.0;\n elseif ( j == i )\n a(i,j) = 2.0;\n elseif ( j == i + 1 )\n a(i,j) = 1.0;\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/oto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7288318792979454}} {"text": "function [TCER, TCER_rand] = gsp_learn_tcer(G, X, params)\n%GSP_LEARN_TCER Learn the Total Cumulative Energy Residual\n% Usage: TCER = gsp_learn_tcer(G, X);\n% TCER = gsp_learn_tcer(G, X, params);\n% [TCER, TCER_rand] = gsp_learn_tcer(...);\n% \n% Input parameters:\n% G : the graph\n% X : a data matrix\n% Output parameters: \n% TCER : the computed total commulative energy residual for G \n% TCER_rand : the computed total commulative energy residual for a random basis \n% \n% Total Cumulative Energy Residual (TCER): This is a number from [0 to 1]\n% describing how well a graph fits a given data matrix X, or\n% distribution.\n%\n% Optional parameters\n% -------------------\n%\n% * *params.s* : s = svd(X);\n% * *params.verbose*: 0 = nothing, 1 = plot cum energy, 2 = plot against\n% random basis as a baseline (default 0)\n% * *params.sort* : sort basis columns to get the minimum residual\n% possible (default 0)\n% \n% See also: gsp_good_graph_index, gsp_stationarity_ratio\n% \n\n\n% Author : Andreas Loukas, Vassilis Kalofolias\n% Date : 15 Nov 2016\n\n% Handle input\nif nargin < 3, params = struct(); end\nif not(isfield(params, 'verbose')); params.verbose = 0; end;\nif not(isfield(params, 'sort')); params.sort = 0; end;\nif not(isfield(params, 's')); params.s = svd(full(X)); end;\n\ns = params.s;\n\nif numel(s)< G.N\n s = [s; zeros(G.N-numel(s),1)];\nend\n\nif not(isfield(G, 'U'))\n G = gsp_compute_fourier_basis(G);\nend\n\n% frobenius norm of X\nnorm_X_fro = norm(s);\n\n% sorting already done by svd.\n% var_cumsum_svd = cumsum(sort(s.^2, 'descend')) ./ norm_X_fro^2;\nvar_cumsum_svd = cumsum(s.^2) ./ norm_X_fro^2;\n\n% frobenius norm of X\nnorm_X_fro = norm(X, 'fro');\n\n% for the graph\nif params.sort\n var_cumsum_s_G = cumsum(sort(sum(abs(G.U' * X).^2, 2) ./ norm_X_fro^2, 'descend'));\nelse\n var_cumsum_s_G = cumsum(sum(abs(G.U' * X).^2, 2) ./ norm_X_fro^2);\nend\n\n% area under the curve\nAUC_SVD = sum(var_cumsum_svd);\nAUC_G = sum(var_cumsum_s_G);\nTCER = 1 - AUC_G/AUC_SVD;\n\n% compute also the result for a random basis \nAUC_RB = sum(linspace(1/G.N, 1, G.N));\nTCER_rand = (AUC_SVD - AUC_RB)/(AUC_SVD);\n\nif params.verbose >= 1\n \n figure; hold on;\n\n plot(var_cumsum_svd)\n plot(var_cumsum_s_G)\n [Urand, ~] = qr(randn(G.N)); % random basis\n var_cumsum_s_rand = cumsum(sum(abs(Urand' * X).^2, 2) ./ norm_X_fro^2);\n plot(var_cumsum_s_rand)\n\n xlabel('k (number of basis vectors used)');\n ylabel('cumulative variance');\n legend('svd', 'G', 'random basis') \nend\n\n% plot good quality residual figure\nif params.verbose >= 2\n figure; \n plot(var_cumsum_svd);\n hold on;\n % plot(cum_energy_graph);\n plot(var_cumsum_s_G, 'color', [0.8500 0.3250 0.0980]);\n n_nodes = length(var_cumsum_svd);\n xf = [1:n_nodes, fliplr(1:n_nodes)];\n yf = [zeros(n_nodes,1); flipud(var_cumsum_svd)];\n fill(xf, yf, [ 0 0.4470 0.7410],'facealpha', .2);\n\n xf = [1:n_nodes, fliplr(1:n_nodes)];\n yf = [zeros(n_nodes,1); flipud(var_cumsum_s_G)];\n fill(xf, yf, [0.8500 0.3250 0.0980],'facealpha', .2);\n\n plot(var_cumsum_s_G, 'color', [0.8500 0.3250 0.0980]);\n plot(var_cumsum_svd, 'color', [ 0 0.4470 0.7410]);\n legend('Ground truth covariance', 'Graph', 'Ground truth total C.E.', 'Graph total C.E.','location', 'se')\n% title(['graph from ', num2str(k), ' samples'])\n ylabel('Expected cumulative energy');\n text(n_nodes/2, .5, ['Residual: ', num2str(100*TCER, 3), '%']);\n xlabel('k');\n ylim([0,1]);\nend", "meta": {"author": "epfl-lts2", "repo": "gspbox", "sha": "a7d9aac5e239f1bcb37a9bb09998cc161be2732f", "save_path": "github-repos/MATLAB/epfl-lts2-gspbox", "path": "github-repos/MATLAB/epfl-lts2-gspbox/gspbox-a7d9aac5e239f1bcb37a9bb09998cc161be2732f/learn_graph/gsp_learn_tcer.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7288318683923259}} {"text": "function [uout, tout] = spin2(varargin)\n%SPIN2 Solve stiff PDEs in 2D periodic domains, Fourier spectral method and \n%exponential integrators.\n%\n% UOUT = SPIN2(PDECHAR) solves the PDE specified by the string PDECHAR, and\n% plays a movie of the solution. Possible strings include 'GL' and 'GS' for \n% the Ginzburg-Landau and Gray-Scott equations. Other PDEs are available, see \n% Remark 1 and Examples 1-4. The output UOUT is a CHEBFUN2 corresponding to \n% the solution at the final time (a CHEBMATRIX for systems of equations, each \n% row representing one variable).\n%\n% UOUT = SPIN2(S, N, DT) solves the PDE specified by the SPINOP2 S with N grid\n% points in each direction and time-step DT, and plays a movie of the solution. \n% See HELP/SPINOP2 and Example 5.\n%\n% [UOUT, TOUT] = SPIN2(...) also returns the times chunks TOUT at which UOUT\n% was computed.\n%\n% Users of SPIN2 will quickly find they want to vary aspects of the plotting.\n% The fully general syntax for this involves using preferences specified by\n% a SPINPREF2 object PREF. See HELP/SPINPREF2 and Example 6. However for many \n% purposes it is most convenient to use the syntax\n%\n% UOUT = SPIN2(..., 'PREF1', VALUE1, 'PREF2', VALUE2, ...)\n%\n% For example:\n%\n% UOUT = SPIN2(..., 'Clim', [a b]) changes colorbar limits to [a b] \n% UOUT = SPIN2(..., 'colormap', 'jet') changes the colormap to 'jet'\n% UOUT = SPIN2(..., 'dataplot', 'abs') plots absolute value\n% UOUT = SPIN2(..., 'iterplot', 4) plots only every 4th time step \n% UOUT = SPIN2(..., 'Nplot', 256) plays a movie at 256x256 resolution\n% UOUT = SPIN2(..., 'plot', 'off') for no movie\n% UOUT = SPIN2(..., 'view', [a b]) changes the view angle to [a b]\n%\n% Remark 1: List of PDEs (case-insensitive)\n%\n% - 'GL' for the Ginzburg-Landau equation,\n% - 'GS' for the Gray-Scott equations (stripes),\n% - 'GSspots' for the Gray-Scott equations (spots),\n% - 'SCHNAK' for the Schnakenberg equations,\n% - 'SH' for the Swift-Hohenberg equation.\n%\n% Example 1: Ginzburg-Landau equation (spiral waves)\n%\n% u = spin2('GL');\n%\n% solves the Ginzburg-Landau equation\n%\n% u_t = laplacian(u) + u - (1+1.5i)*u*|u|^2,\n%\n% on [0 100]^2 from t=0 to t=100, with a RANDNFUN2 initial condition. \n% The movie shows the real part of u. For a movie of the absolute\n% value of u rather than the real part, execute\n%\n% S = spinop2('GL');\n% u = spin2(S, 128, 1e-1, 'dataplot', 'abs');\n%\n% Example 2: Gray-Scott equations (pattern formation - stripes)\n%\n% u = spin2('GS');\n%\n% solves the Gray-Scott equations\n%\n% u_t = 2e-5*laplacian(u) + F*(1-u) - u*v^2,\n% v_t = 1e-5*laplacian(v) - (F+K)*v + u*v^2,\n%\n% on [0 1]^2 from t=0 to t=5000, with initial condition\n%\n% u0(x,y) = 1 - exp(-100*((x-1/2.05)^2 + (y-1/2.05)^2)),\n% v0(x,y) = exp(-100*((x-1/2)^2 + 2*(y-1/2)^2)),\n%\n% with F=0.030 and K=0.057.\n% \n% Example 2 (bis): Gray-Scott equations (pattern formation - spots)\n%\n% u = spin2('GSspots');\n%\n% solves the Gray-Scott equations\n%\n% u_t = 2e-5*laplacian(u) + F*(1-u) - u*v^2,\n% v_t = 1e-5*laplacian(v) - (F+K)*v + u*v^2,\n%\n% on [0 1]^2 from t=0 to t=5000, with initial condition\n%\n% u0(x,y) = 1 - exp(-100*((x-1/2.05)^2 + (y-1/2.05)^2)),\n% v0(x,y) = exp(-100*((x-1/2)^2 + 2*(y-1/2)^2)), \n%\n% with F=0.026 and K=0.059.\n%\n% Example 3: Schnakenberg equations (pattern formation - spots)\n%\n% u = spin2('SCHNAK');\n%\n% solves the Schnakenberg equations\n%\n% u_t = laplacian(u) + 3*(a - u + u^2*v),\n% v_t = 10*laplacian(v) + 3*(b - u^2*v),\n%\n% on [0 50]^2 from t=0 to t=500, with initial condition\n%\n% u0(x,y) = (a+b) - exp(-2*((x-G/2.15)^2 + (y-G/2.15)^2)),\n% v0(x,y) = b/(a+b)^2 + exp(-2*((x-G/2)^2 + 2*(y-G/2)^2)),\n% with G=50, a=0.1 and b=0.9.\n%\n% Example 4: Swift-Hohenberg equation (Rayleigh-Benard convection rolls)\n%\n% u = spin2('SH');\n%\n% solves the Swift-Hohenberg equation\n%\n% u_t = -2*laplacian(u) - biharmonic(u) - .9*u - u^3,\n%\n% on [0 50]^2 from t=0 to t=800, with a RANDNFUN2 initial condition.\n%\n% Example 5: PDE specified by a SPINOP2\n%\n% dom = [0 100 0 100]; tspan = [0 100];\n% S = spinop2(dom, tspan);\n% S.lin = @(u) lap(u);\n% S.nonlin = @(u) u - (1 + 1.5i)*u.*(abs(u).^2);\n% S.init = randnfun2(4, dom, 'trig');\n% S.init = S.init/norm(S.init, inf);\n% u = spin2(S, 128, 1e-1);\n%\n% is equivalent to u = spin2('GL');\n%\n% Example 6: Using preferences\n%\n% pref = spinpref2('plot', 'off', 'scheme', 'pecec433');\n% S = spinop2('SH');\n% u = spin2(S, 128, 5e-1, pref);\n% or simply,\n% u = spin2(S, 128, 5e-1, 'plot', 'off', 'scheme', 'pecec433');\n%\n% solves the Swift-Hohenberg equation using N=128 grid points in each\n% direction, a time-step dt=5e-1, doesn't play any movie and uses the\n% time-stepping scheme PECEC433.\n%\n% See also SPINOP2, SPINPREF2, EXPINTEG.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% We are going to parse the inputs and call SOLVEPDE in the following ways,\n%\n% SPINOPERATOR.SOLVEPDE(S, N, dt)\n% or\n% SPINOPERATOR.SOLVEPDE(S, N, dt, pref)\n%\n% where S is a SPINOP2 object, N is the number of grid points in each direction, \n% DT is the time-step and PREF is a SPINPREF2 oject.\n\n% CASE 1. U = SPIN2('GL'):\nif ( nargin == 1 ) \n \n try spinop2(varargin{1});\n catch\n error('Unrecognized PDE. See HELP/SPINSPHERE for the list of PDEs.')\n end\n [S, N, dt, pref] = parseInputs(varargin{1});\n varargin{1} = S;\n varargin{2} = N;\n varargin{3} = dt;\n varargin{4} = pref;\n \n% CASE 2. U = SPIN2('GL', 'PREF1', VALUE1) or U = SPINSPHERE(S, N, DT):\nelseif ( nargin == 3 ) \n \n % CASE 2.1. U = SPIN2('GL', 'PREF1', VALUE1):\n if ( isa(varargin{1}, 'char') == 1 && isa(varargin{2}, 'char') == 1 )\n [S, N, dt, pref] = parseInputs(varargin{1});\n pref.(varargin{2}) = varargin{3};\n varargin{1} = S;\n varargin{2} = N;\n varargin{3} = dt;\n varargin{4} = pref;\n \n % CASE 2.2. U = SPIN2(S, N, DT):\n else\n % Nothing to do here.\n end\n \n% CASE 3. U = SPIN2(S, N, DT, PREF)\nelseif ( nargin == 4 ) \n % Nothing to do here.\n \n% CASE 4. \nelseif ( nargin >= 5 )\n \n % CASE 4.1. U = SPIN2('GL', 'PREF1', VALUE1, 'PREF2', VALUE2, ...)\n if ( isa(varargin{1}, 'char') == 1 && isa(varargin{2}, 'char') == 1 )\n [S, N, dt, pref] = parseInputs(varargin{1});\n j = 2;\n while j < nargin\n pref.(varargin{j}) = varargin{j+1};\n varargin{j} = [];\n varargin{j+1} = [];\n j = j + 2;\n end\n varargin{1} = S;\n varargin{2} = N;\n varargin{3} = dt;\n varargin{4} = pref;\n varargin = varargin(~cellfun(@isempty, varargin));\n \n % CASE 4.2. U = SPIN2(S, N, DT, 'PREF1', VALUE1, 'PREF2', VALUE2, ...)\n else\n pref = spinpref2();\n j = 4;\n while j < nargin\n pref.(varargin{j}) = varargin{j+1};\n varargin{j} = [];\n varargin{j+1} = [];\n j = j + 2;\n end\n varargin{4} = pref;\n varargin = varargin(~cellfun(@isempty, varargin));\n end\n \nend\n\n% SPIN2 is a wrapper for SOLVPDE:\n[uout, tout] = spinoperator.solvepde(varargin{:});\n\nend\n\nfunction [S, N, dt, pref] = parseInputs(pdechar)\n%PARSEINPUTS Parse the inputs.\n\npref = spinpref2();\nS = spinop2(pdechar);\nif ( strcmpi(pdechar, 'GL') == 1 )\n dt = 1e-1;\n N = 128;\n pref.Clim = [-1 1];\n pref.iterplot = 2;\n pref.Nplot = 256;\nelseif ( strcmpi(pdechar, 'GS') == 1 )\n dt = 5;\n N = 64;\n pref.Clim = [.25 .8 0 .35];\n pref.iterplot = 10;\n pref.Nplot = 128;\nelseif ( strcmpi(pdechar, 'GSspots') == 1 )\n dt = 2;\n N = 64;\n pref.Clim = [.25 .85 0 .35];\n pref.iterplot = 25;\n pref.Nplot = 128;\nelseif ( strcmpi(pdechar, 'SCHNAK') == 1 )\n dt = 5e-1;\n N = 64;\n pref.Clim = [.7 1.7 .65 1.05];\n pref.iterplot = 10;\n pref.Nplot = 128;\nelseif ( strcmpi(pdechar, 'SH') == 1 )\n dt = 1;\n N = 128;\n pref.Clim = [-.4 .5];\n pref.iterplot = 4;\n pref.Nplot = 256;\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/spin2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.8723473746782093, "lm_q1q2_score": 0.728831855885276}} {"text": "%% compute predicted travel times for infrasound waves based on GPS coords & wind\n%% also add lat, lon, distance and backaz fields to waveform objects\ndisp('Predicting travel times based on GPS coordinates and wind vector...')\nfout = fopen(fullfile(figureOutDirectory, 'predictedTravelTimes.txt'), 'w');\nfprintf(fout,'\\n_______________________________________________\\n');\nfprintf(fout,'PREDICTED TRAVEL TIME BASED ON:\\n');\nfprintf(fout,' sound speed(c) %.1fm/s\\n', speed_of_sound);\nfprintf(fout,' wind speed %.1fm/s\\n', wind_speed);\nfprintf(fout,' wind direction %.1f degrees\\n', wind_direction);\nfprintf(fout,'------\\t--------\\t-----------\\t----------\\t-----------\\n');\nfprintf(fout,'Channel\\tDistance\\tBackAzimuth\\tTravelTime\\tc_effective\\n');\nfprintf(fout,'------\\t--------\\t-----------\\t----------\\t-----------\\n');\nfor c=1:length(lat)\n [arclen(c), backaz(c)] = distance(lat(c), lon(c), source.lat, source.lon, 'degrees');\n arclen(c) = deg2km(arclen(c))*1000;\n effective_speed(c) = speed_of_sound + wind_speed * cos(deg2rad( (180+backaz(c)) - wind_direction) );\n predicted_traveltime_seconds(c) = arclen(c)/effective_speed(c);\n fprintf(fout,'%s\\t%.1fm\\t\\t%.1f degrees\\t%.3fs\\t\\t%.1fm/s\\n',get(w(c),'channel'), arclen(c), backaz(c), predicted_traveltime_seconds(c),effective_speed(c));\n w(c) = addfield(w(c), 'lat', lat(c));\n w(c) = addfield(w(c), 'lon', lon(c));\n w(c) = addfield(w(c), 'distance', arclen(c));\n w(c) = addfield(w(c), 'backaz', backaz(c));\nend\nfprintf(fout,'_______________________________________________\\n');\nfprintf(fout,'Program name: %s\\n',mfilename('fullpath'));\nfclose(fout);", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/applications/rockets/infrasoundgt/predictedTravelTimes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.7288215789814215}} {"text": "function f = erfz(zz)\n%ERFZ Error function for complex inputs\n% f = erfz(z) is the error function for the elements of z.\n% Z may be complex and of any size.\n% Accuracy is better than 12 significant digits.\n%\n% Usage: f = erfz(z)\n%\n% Ref: Abramowitz & Stegun section 7.1\n% equations 7.1.9, 7.1.23, and 7.1.29\n%\n% Tested under version 5.3.1\n%\n% See also erf, erfc, erfcx, erfinc, erfcore\n\n% Main author Paul Godfrey \n% Small changes by Peter J. Acklam \n% 09-26-01\n\n error(nargchk(1, 1, nargin));\n \n % quick exit for empty input\n if isempty(zz)\n f = zz;\n return;\n end\n \n twopi = 2*pi;\n sqrtpi=1.772453850905516027298;\n\n f = zeros(size(zz));\n ff=f;\n\n az=abs(zz);\n p1=find(az<=8);\n p2=find(az> 8);\n\nif ~isempty(p1)\n z=zz(p1);\n\n nn = 32;\n\n x = real(z);\n y = imag(z);\n k1 = 2 / pi * exp(-x.*x);\n k2 = exp(-i*2*x.*y);\n\n s1 = erf(x);\n\n s2 = zeros(size(x));\n k = x ~= 0; % when x is non-zero\n s2(k) = k1(k) ./ (4*x(k)) .* (1 - k2(k));\n k = ~k; % when x is zero\n s2(k) = i / pi * y(k);\n\n f = s1 + s2;\n\n k = y ~= 0; % when y is non-zero\n xk = x(k);\n yk = y(k);\n\n s5 = 0;\n for n = 1 : nn\n s3 = exp(-n*n/4) ./ (n*n + 4*xk.*xk);\n s4 = 2*xk - k2(k).*(2*xk.*cosh(n*yk) - i*n*sinh(n*yk));\n s5 = s5 + s3.*s4;\n end\n s6 = k1(k) .* s5;\n f(k) = f(k) + s6;\n ff(p1)=f;\nend\n\nif ~isempty(p2)\n z=zz(p2);\n pn=find(real(z)<0);\n\n if ~isempty(pn)\n z(pn)=-z(pn); \n end\n\n nmax=193;\n s=1;\n y=2*z.*z;\n for n=nmax:-2:1\n s=1-n.*(s./y);\n end\n\n f=1.0-s.*exp(-z.*z)./(sqrtpi*z);\n\n if ~isempty(pn)\n f(pn)=-f(pn);\n end\n\n pa=find(real(z)==0);\n% fix along i axis problem\n if ~isempty(pa)\n f(pa)=f(pa)-1;\n end\n\n ff(p2)=f;\nend\n\nf=ff;\n\nreturn\n\n %a demo of this function is\n x = -4:0.125:4;\n y = x;\n [X, Y] = meshgrid(x,y);\n z = complex(X, Y);\n f = erfz(z);\n af = abs(f);\n %let's truncate for visibility\n p = find(af > 5);\n af(p) = 5;\n mesh(x, y, af);\n view(-70, 40);\n rotate3d on;\n\n return\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/3574-erfz/erfz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.728815601291225}} {"text": "function x = gumbel_cdf_inv ( cdf )\n\n%*****************************************************************************80\n%\n%% GUMBEL_CDF_INV inverts the Gumbel CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 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 of the CDF.\n%\n if ( cdf < 0.0 | 1.0 < cdf )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GUMBEL_CDF_INV - Fatal error!\\n' );\n fprintf ( 1, ' CDF < 0 or 1 < CDF.\\n' );\n error ( 'GUMBEL_CDF_INV - Fatal error!' );\n end\n\n x = - log ( - log ( 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/gumbel_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.728812536266526}} {"text": "function Vpolicy = mdp_eval_policy_matrix(P, R, discount, policy)\n\n\n% mdp_eval_policy_matrix Evaluation of the value function of a policy\n% Arguments -------------------------------------------------------------\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 matrix (SxS) possibly sparse\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% policy(S) = a policy\n% Evaluation -------------------------------------------------------------\n% Vpolicy(S) = value function of the policy\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 iscell(P); S = size(P{1},1); else S = size(P,1); end;\nif discount <= 0 || discount >= 1\n disp('--------------------------------------------------------')\n disp('MDP Toolbox ERROR: Discount rate must be in ]0; 1[')\n disp('--------------------------------------------------------')\nelseif size(policy,1)~=S || any(mod(policy,1)) || any(policy<1) || any(policy>S)\n disp('--------------------------------------------------------')\n disp('MDP Toolbox ERROR: policy must be a (1xS) vector with integer from 1 to S')\n disp('--------------------------------------------------------')\nelse\n \n [Ppolicy, PRpolicy] = mdp_computePpolicyPRpolicy(P, R, policy);\n \n % V = PR + gPV => (I-gP)V = PR => V = inv(I-gP)*PR\n Vpolicy = (speye(S,S) - discount*Ppolicy) \\ PRpolicy;\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/25786-markov-decision-processes-mdp-toolbox/MDPtoolbox/mdp_eval_policy_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7288125342280002}} {"text": "function fx = p04_fun ( option, nvar, x )\n\n%*****************************************************************************80\n%\n%% P04_FUN evaluates the function for problem 4.\n%\n% Title:\n%\n% The Broyden function\n%\n% Description:\n%\n% The function F is derived via homotopy from a simpler function G:\n%\n% F(X(1),X(2),X(3)) = g(X(1),X(2)) + (X(3)-1) * G(Y1,Y2).\n%\n% with\n%\n% (Y1,Y2) some starting point,\n%\n% and\n%\n% G(1) = 0.5*sin(X(1)*X(2)) - X(2)/PI - X(1)\n% G(2) = (1-1/(4*PI))*(exp(2*X(1))-E) + E*X(2)/PI- 2*E*X(1)\n%\n% where \"E\" = exp(1).\n%\n% Options:\n%\n% The only option starts with (0.4, 3, 0), and seeks the target\n% solution whose third component is 1. The correct value of the\n% target solution is\n%\n% ( -0.2207014, 0.8207467, 1.0D+00 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Charles Broyden,\n% A New Method of Solving Nonlinear Simultaneous Equations,\n% The Computer Journal,\n% Volume 12, 1969, pages 94-99.\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 function.\n%\n% Output, real FX(NVAR-1), the value of the function at X.\n%\n\n%\n% Get the starting point.\n%\n y = p04_start ( option, nvar );\n%\n% Get the function value at the starting point and at the\n% current point.\n%\n gy = p04_gx ( y );\n gx = p04_gx ( x );\n%\n% Use X3 to compute a homotopy.\n%\n for i = 1 : nvar-1\n fx(i) = gx(i) + ( x(3) - 1.0 ) * gy(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/test_con/p04_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7288125216755901}} {"text": "% p23 例5 埃特金逐步插值\nclear;\nformat long;\nx = 0.3 :0.1 : 0.7;\ny = [0.29850, 0.39646, 0.49311, 0.58813, 0.68122];\nxx = 0.462; % 插值点\nfij(:,1) = y;\nfor i = 1 : 3\n for j = i+1 : 5\n fij(j,i+1) = fij(i,i)*(xx-x(j))/(x(i)-x(j)) + fij(j,i)*(xx-x(i))/(x(j)-x(i)) % 显示中间结果,体现迭代\n end\nend\nfij", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第二章 插值方法/example_2_5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7288125215838032}} {"text": "function svd_snowfall_test04 ( x )\n\n%*****************************************************************************80\n%\n%% SVD_SNOWFALL_TEST04 looks at the first 6 modes in the U matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X(8,123), the snowfall data.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SVD_SNOWFALL_TEST04\\n' );\n fprintf ( 1, ' Look at the first 6 modes in the U matrix.\\n' );\n fprintf ( 1, ' Each of these represents a pattern for snowfall over a year.\\n' );\n fprintf ( 1, ' The first mode is the pattern that is strongest in the data.\\n' );\n%\n% Compute the SVD.\n%\n [ u, s, v ] = svd ( x );\n%\n% Normalize the patterns so that each column has maximum entry 1.\n%\n us = r8col_normalize_li ( 8, 8, u );\n%\n% Plot the modes.\n%\n t = 1 : 8;\n\n figure ( 4 )\n\n subplot ( 2, 3, 1 )\n hold on\n plot ( [1,8], [0,0], 'r-' )\n plot ( t, us(:,1), 'b-', 'Linewidth', 3 )\n axis ( [1,8,-1.0,+1.0] )\n grid on\n title ( 'U Mode #1' )\n hold off\n\n subplot ( 2, 3, 2 )\n hold on\n plot ( [1,8], [0,0], 'r-' )\n plot ( t, us(:,2), 'b-', 'Linewidth', 3 )\n axis ( [1,8,-1.0,+1.0] )\n grid on\n title ( 'U Mode #2' )\n hold off\n\n subplot ( 2, 3, 3 )\n hold on\n plot ( [1,8], [0,0], 'r-' )\n plot ( t, us(:,3), 'b-', 'Linewidth', 3 )\n axis ( [1,8,-1.0,+1.0] )\n grid on\n title ( 'U Mode #3' )\n hold off\n\n subplot ( 2, 3, 4 )\n hold on\n plot ( [1,8], [0,0], 'r-' )\n plot ( t, us(:,4), 'b-', 'Linewidth', 3 )\n axis ( [1,8,-1.0,+1.0] )\n grid on\n title ( 'U Mode #4' )\n hold off\n\n subplot ( 2, 3, 5 )\n hold on\n plot ( [1,8], [0,0], 'r-' )\n plot ( t, us(:,5), 'b-', 'Linewidth', 3 )\n axis ( [1,8,-1.0,+1.0] )\n grid on\n title ( 'U Mode #5' )\n hold off\n\n subplot ( 2, 3, 6 )\n hold on\n plot ( [1,8], [0,0], 'r-' )\n plot ( t, us(:,6), 'b-', 'Linewidth', 3 )\n axis ( [1,8,-1.0,+1.0] )\n grid on\n title ( 'U Mode #6' )\n hold off\n\n print ( '-dpng', 'u_modes.png' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Plotted U modes 1 to 6 in \"u_modes.png\".\\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/svd_snowfall/svd_snowfall_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7288117353891882}} {"text": "function [ pl, pld ] = p12_legendre_val ( t, dtdx, npolys )\n\n%*****************************************************************************80\n%\n%% P12_LEGENDRE_VAL evaluates the Legendre polynomials and derivatives.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 September 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T, the argument of the Legendre polynomials, in\n% the normalized interval [-1,1].\n%\n% Input, real DTDX, the value of the quantity dTdX at the point\n% X. In the most common case, this is simply the relationship\n% between the width of the normalized T interval (2), and the\n% width of the X interval to which the Legendre polynomial\n% arguments have been mapped. DTDX is needed so that the\n% computed values PLD can be converted from dPL/dT to dPL/dX.\n%\n% Input, integer NPOLYS, the number of Legendre polynomials to\n% evaluate. If NPOLYS is 1, then only the constant polynomial\n% is evaluated, NPOLYS = 2 means the constant and linear, and so on.\n%\n% Output, real PL(NPOLYS), PLD(NPOLYS), the values of PL(X)\n% and dPL(X)/dX at the point X which has normalized coordinate T.\n%\n if ( 1 <= npolys )\n pl(1) = 1.0;\n pld(1) = 0.0;\n end\n\n if ( 2 <= npolys )\n pl(2) = t;\n pld(2) = 1.0;\n end\n\n a = 0.0;\n for i = 3 : npolys\n\n a = a + 1.0;\n\n pl(i) = ( ( 2.0 * a + 1.0 ) * t * pl(i-1) - a * pl(i-2) ) / ( a + 1.0 );\n\n pld(i) = ( ( 2.0 * a + 1.0 ) * ( t * pld(i-1) + pl(i-1) ) ...\n - a * pld(i-2) ) / ( a + 1.0 );\n\n end\n\n pld(1:npolys) = dtdx * pld(1:npolys);\n\n return\nend\n", "meta": {"author": "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/p12_legendre_val.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8615382165412808, "lm_q1q2_score": 0.7288117320430142}} {"text": "function SStar=covMatEstShrinkage(x,centerData,algorithm)\n%%COVMATESTSHRINKAGE When estimating a covariance matrix from a small\n% number of samples, it can occur that the resultng estimate is\n% poorly conditioned. This function estimates the covariance\n% matrix from samples using one of two shrinkage estimators that\n% are mean to avoid poor conditioning and that can produce more\n% accurate (in terms of the squared Frobenius norm) estimates\n% than one can obtain from the sample covariance matrix.\n%\n%INPUTS: x A pXn matrix of n samples of a p-dimensional distribution.\n% centerData If the samples in x are zero mean or the mean has been\n% subtracted from them, then centerData can be false. Otherwise,\n% centerData should be true to center the data (subtract the\n% sample mean). The algorithmic choices assume that the true mean\n% has been subtracted, so subtracting the sample mean might affect\n% the performance. The default if omitted or an empty matrix is\n% passd is true.\n% algorithm An optional parameter selecting the algorithm to use. Possible\n% values are:\n% 0 (The default if omitted or an empty matrix is passed) Use the\n% Ledoit-Wolf algorithm of [1].\n% 1 Use the empirical Bayesian estimator (the Hanff estimator),\n% which is also described in [1].\n%\n%OUTPUTS: SStar The pXp covariance matrix estimate.\n%\n%Note that the algorithms are not unbiased. However, the Ledoit-Wolf\n%algorithm is shown in [1] to be asymptotically unbiased (as n gets large\n%keeping p/n fixed).\n%\n%EXAMPLE:\n%Here, we look at the performance when considering random diagonal\n%covariance matrices whose elements are drawn from the log-normal\n%distribution. We look at the percentage relative improvement in average\n%loss (PRIAL) criterion, which is essentially the relative improvement in\n%the squared Frobenius norm of the error of the sample covariance matrix\n%versus the Ledoit-Wolf covariance matrix esitmate.\n% numRuns=10000;\n% p=20;\n% n=40;\n% %Parameters for the log-normal distribution from which the covariance\n% %matrix is drawn.\n% mu=1;\n% Sigma=1;\n% centerData=false;\n%\n% SSigmaFro2=0;\n% SStarSigmaFro2=0;\n% for curRun=1:numRuns\n% x=LogNormalD.rand(p,mu,Sigma);\n% X=diag(x);%The current covariance matrix.\n% SX=cholSemiDef(X,'lower');\n% x=SX*randn(p,n);%Zero mean.\n% \n% S=(1/n)*(x*x');%Sample covariance matrix.\n% SStar=covMatEstShrinkage(x,centerData);\n% \n% SSigmaFro2=SSigmaFro2+norm(S-Sigma,'fro')^2;\n% SStarSigmaFro2=SStarSigmaFro2+norm(SStar-Sigma,'fro')^2;\n% end\n% SSigmaFro2=SSigmaFro2/numRuns;\n% SStarSigmaFro2=SStarSigmaFro2/numRuns;\n% PRIAL=(SSigmaFro2-SStarSigmaFro2)/SSigmaFro2\n%One will typically see that the PRIAL is positive, around 0.08, indicating\n%that the Ledoit-Wolf covariance matrix esitmate is 8% better than the\n%sample covariance estimate. It was empirically noticed that setting\n%centerData=true will further improve the performance on this example even\n%though the samples generated are already zero-mean.\n%\n%REFERENCES:\n%[1] O. Ledoit and M. Wolf \"A Well-conditioned estimator for large-\n% dimensional covariance matrices,\" Journal of Multivariate Analysis,\n% vol. 88, no. 2, pp. 365-411, 2004.\n%\n%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(algorithm))\n algorithm=0;\nend\n\nif(nargin<2||isempty(centerData))\n centerData=true;\nend\n\nif(centerData)\n x=bsxfun(@minus,x,mean(x,2)); \nend\n\np=size(x,1);\nn=size(x,2);\n%The sample covariance matrix.\nS=(1/n)*(x*x');\n\nswitch(algorithm)\n case 0%The Ledoit-Wolf covariance estimator.\n %Lemma 3.2\n m=trace(S)/p;\n\n %Lemma 3.3\n d2=norm(S-diag(m),'fro')^2;\n\n %Lemma 3.4\n b2Bar=0;\n for k=1:n\n b2Bar=b2Bar+norm(x(:,k)*x(:,k)'-S,'fro')^2;\n end\n b2Bar=(1/n^2)*b2Bar;\n b2=min(b2Bar,d2);\n\n %Lemma 3.5\n a2=d2-b2;\n\n %Equation 14\n SStar=(b2/d2)*diag(m)+(a2/d2)*S;\n case 1%The empirical Bayesian estimator (Haff estimator).\n mEB=det(S)^(1/p);\n if(mEB<=0||~isreal(mEB))\n mEB=trace(S)/p;\n end\n\n SStar=((p*n-2*n-2)/(p*n^2))*diag(mEB)+(n/(n+1))*S;\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/Statistics/covMatEstShrinkage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.7288117310474168}} {"text": "function [F,J] = bananaobj(x)\n% Evaluate the vector function and the Jacobian matrix for \n% the system of nonlinear equations derived from the general \n% n-dimensional Rosenbrock function.\n% Get the problem size\nn = length(x); \nif n == 0, error('Input vector, x, is empty.'); end\nif mod(n,2) ~= 0, \n error('Input vector, x, must have an even number of components.'); \nend\n% Evaluate the vector function\nodds = 1:2:n;\nevens = 2:2:n;\nF=x(:);\n% F = zeros(n,1);\nF(odds,1) = 1-x(odds);\nF(evens,1) = 10.*(x(evens)-x(odds).^2); \n% Evaluate the Jacobian matrix if nargout > 1\nif nargout > 1\n c = -ones(n/2,1); C = sparse(odds,odds,c,n,n);\n d = 10*ones(n/2,1); D = sparse(evens,evens,d,n,n);\n e = -20.*x(odds); E = sparse(evens,odds,e,n,n);\n J = C + D + E;\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/18171-lsqnonlincsd/bananaobj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7288071704169303}} {"text": "function [xm xcov] = UT(Xi, W, noiseCov) \n%\n%\n[n, kmax] = size(Xi);\n\nxm = 0;\nfor k=1:kmax\n xm = xm + W(k)*Xi(:, k);\nend\n\nxcov = zeros(n, n);\nfor k=1:kmax\n xcov = xcov + W(k)*(Xi(:, k) - xm)*(Xi(:, k) - xm)';\nend\nxcov = xcov + noiseCov;", "meta": {"author": "philbooks", "repo": "Kalman-Filter-for-Beginners", "sha": "5190a723dcbf96eacda71ed56abddb3a11779a82", "save_path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners", "path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners/Kalman-Filter-for-Beginners-5190a723dcbf96eacda71ed56abddb3a11779a82/15.UKF/RadarUKF/UT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7288071653293228}} {"text": "function [out] = ReedSolomon(random,codeRS,Tx);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% %\n%% Name: ReedSolomon.m %\n%% %\n%% Description: The Reed-Solomon encoder is realized according to %\n%% the standard. %\n%% %\n%% Parameters: %\n%% Sequence of bits to endoe with the algorithm. %\n%% %\n%% Result: It gives back the encoded bits according to the need %\n%% and also following the modulation. %\n%% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n m = 8; % Number of bits per symbol\n n = codeRS(1); % Length of the codeword\n k = codeRS(2); % Number of information symbols\n \n % To realize the Reed-Solomon code, the information is needed in decimal.\n\n random = reshape(random,8,length(random)/8)';\n random = bi2de(random,'left-msb');\n \nif Tx==1 \n % 36 bytes are needed with a stuffed zero at the end of the vector:\n yk=[random' 0];\n \n % The Galois vector is generated, the generating polynomial of the\n % code. Then the symbols are encoded with Reed-Solomon.\n msg = gf([yk],m); \n if n==k % bypass for BPSK\n codeRS = msg; \n elseif n~=k\n codeRS = rsenc(msg,n,k);\n end\n out = codeRS.x;\n \nelseif Tx==0\n yk = random; % In the receiver, nothing needs to be completed.\n \n msg = gf([yk],m); % In this case, the encoding is undone.\n if n==k\n codeRS = yk;\n elseif n~=k\n codeRS = rsdec(msg',n,k);\n codeRS = codeRS.x;\n end\n out = codeRS(1:end-1);\nend\n\n% The binary data to continue working:\n out = double (out);\n out = de2bi (out,8,'left-msb');\n\n% Serial the data for the next step.\n out = reshape (out', 1, length(out)*8);\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/21494-a-802-16d-system-comments-on-english/ReedSolomon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768651485395, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.728756774174981}} {"text": "function [out] = phenology_2(p1,p2,p3,t,tmax,dt)\n%phenology_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: Phenology-based maximum interception capacity (returns store size [mm])\n% Constraints: Implicit assumption: 0 <= p2 <= 1\n% @(Inputs): p1 - mean interception capacity [mm]\n% p2 - seasonal change as fraction of the mean [-]\n% p3 - time of maximum store size [d]\n% t - current time step [-]\n% tmax - seasonal length [d]\n% dt - time step size [d]\n\nout = p1*(1+p2*sin(2*pi*(t*dt-p3)/tmax));\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/phenology_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9441768557238083, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7287567718558133}} {"text": "%CREATETREFOILKNOT Create a 3D mesh around a trefoild curve\n%\n% [X, Y, Z] = createTrefoilKnot;\n% [X, Y, Z] = createTrefoilKnot(NPTS);\n%\n% Example\n% createTrefoilKnot\n%\n% See also\n%\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2015-01-07, using Matlab 8.4.0.150421 (R2014b)\n% Copyright 2015 INRA - Cepia Software Platform.\n\n%% Constants\n\n% number of vertices of trefoil curve\nnPoints = 200;\n\n% thickness of the 3D mesh\nthickness = .5;\n\n% number of corners around each curve vertex\nnCorners = 16;\n\n\n%% Create trefoil curve\n\n% parameterisation variable\nt = linspace(0, 2*pi, nPoints + 1);\nt(end) = [];\n\n% trefoil curve coordinates\ncurve(:,1) = sin(t) + 2 * sin(2 * t);\ncurve(:,2) = cos(t) - 2 * cos(2 * t);\ncurve(:,3) = -sin(3 * t);\n\n% display curve\nfigure; \ndrawPolyline3d(curve, 'LineWidth', 4, 'color', 'b');\naxis equal; view(3);\naxis([-4 4 -4 4 -2 2]);\n\n\n%% Create surrounding mesh\n\n% compute mesh\n[v2, f2] = curveToMesh(curve, thickness, nCorners);\n\n% display mesh\ndrawMesh(v2, f2, 'FaceAlpha', 0.5);", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/demos/meshes3d/createTrefoilKnot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7287189169935672}} {"text": "function [ fea, out ] = ex_diffusion2( varargin )\n%EX_DIFFUSION2 1D Time dependent diffusion equation examples.\n%\n% [ FEA, OUT ] = EX_DIFFUSION2( VARARGIN ) 1D time dependent diffusion equation on\n% a line with exact solutions. Accepts the following property/value pairs.\n%\n% Input Value/{Default} Description\n% -----------------------------------------------------------------------------------\n% nu scalar {1e-1} Diffusion coefficient\n% icase scalar {2} Test case\n% hmax scalar {1/25} Max grid cell size\n% dt scalar {0.1} Time step size\n% ischeme scalar {3} Time stepping scheme\n% sfun string {sflag1} Shape function\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 = { ...\n 'nu', 1e-1; ...\n 'icase', 2; ...\n 'hmax', 1/25; ...\n 'dt' 0.1; ...\n 'ischeme' 3; ...\n 'sfun', 'sflag1'; ...\n 'iplot', 1; ...\n 'tol', 1e-2; ...\n 'fid', 1 };\n[got,opt] = parseopt(cOptDef,varargin{:});\nfid = opt.fid;\n\n\ntmax = 1;\nswitch( opt.icase )\n case 1\n refsol = '(1-x)*2.2+x*3.3';\n case 2\n n = 1;\n refsol = ['exp(-',num2str(opt.nu*n^2*pi^2),'*t)*sin(',num2str(n*pi),'*x)'];\nend\n\n\n% Grid generation.\nfea.grid = linegrid( 1/opt.hmax, 0, 1 );\n\n\n% Problem definition.\nfea.sdim = { 'x' };\nfea = addphys( fea, @convectiondiffusion );\nfea.phys.cd.sfun = { opt.sfun };\nfea.phys.cd.eqn.coef{2,4} = { opt.nu };\nfea = parsephys(fea);\n\n\n% Parse and solve problem.\nx = fea.grid.p';\nn = length(x);\nif( strcmp( opt.sfun,'sflag2' ) )\n x = [ x; (x(2:end)+x(1:end-1))/2 ];\nend\nt = 0;\nu0 = eval( refsol );\nfea = parseprob( fea );\nif( opt.ischeme>0 )\n\n fea.bdr.d{1} = refsol;\n fea.bdr.d{2} = refsol;\n fea.bdr.n = cell(1,2);\n [fea.sol.u,tlist] = solvetime( fea, 'fid', fid, 'init', u0, 'ischeme', opt.ischeme, 'tstep', opt.dt, 'tmax', tmax, 'nstbwe', 0, 'tstop', 0, 'imass', 2 );\n\nelse\n\n [M,A,f] = assembleprob( fea, 'f_m', 1, 'imass', 1, 'f_a', 1, 'f_f', 1, 'f_sparse', 1 );\n M = spdiags( full(sum(M')'), 0, size(M,1), size(M,1) );\n fea.sol.u = u0;\n dt = opt.dt;\n it = 0;\n tlist = 0;\n if( opt.ischeme==-1 ) % Crank-Nicolson.\n C = [ M + dt/2*A ];\n elseif( opt.ischeme==-2 ) % Backward Euler.\n C = [ M + dt*A ];\n end\n C(1,:) = 0;\n C(1,1) = 1;\n C(n,:) = 0;\n C(n,n) = 1;\n while 1\n t = t + dt;\n it = it + 1;\n\n u_r = eval( refsol );\n if( opt.ischeme==-1 ) % Crank-Nicolson.\n b = [ [ M - dt/2*A ]*u0 + dt*f ];\n elseif( opt.ischeme==-2 ) % Backward Euler.\n b = [ M*u0 + dt*f ];\n end\n b(1) = u_r(1);\n b(n) = u_r(n);\n\n u1 = C\\b;\n\n if( t>=tmax )\n break\n end\n\n err = norm( u1 - u_r )/norm( u_r );\n errnm(it) = err;\n if( ~isempty(fid) )\n fprintf( fid, 'Time = %f, error norm = %d\\n', t, err );\n end\n\n fea.sol.u = [ fea.sol.u u1 ];\n tlist = [ tlist t ];\n u0 = u1;\n end\n\nend\n\n\n% Postprocessing.\nif( opt.iplot>0 )\n figure;\n if( opt.iplot>1 )\n i_sol_list = 1:numel(tlist);\n else\n i_sol_list = numel(tlist);\n end\n [~,ix] = sort( x );\n for i_sol=i_sol_list\n t = tlist(i_sol);\n clf\n postplot( fea, 'surfexpr', 'c', 'solnum', i_sol );\n hold on\n u_r = eval( refsol );\n plot( sort(x), u_r(ix), 'r--' );\n title( ['Solution at time ',num2str(t)])\n xlabel( 'x' )\n drawnow\n end\nend\n\n\n% Error checking.\nfor i_sol=1:numel(tlist)\n u_i = fea.sol.u(:,i_sol);\n t = tlist(i_sol);\n u_r = eval( refsol );\n errnm(i_sol) = norm( u_i - u_r )/norm( u_r );\nend\nout.err = errnm;\nout.pass = all( errnm 1e-10\n error('Something went wrong')\nend\n\nfor indx_sho = 1 : N\n FEVD(:,indx_sho) = out_.var_(:,indx_sho)./out_.all_var_*100; \n\nend\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/bvartools/fevd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.8006920116079208, "lm_q1q2_score": 0.728555267128432}} {"text": "function [W, funcVal] = Least_NCFGLassoF2(X, Y, lambda, beta, opts)\n% Non-Convex Fused Group Lasso with Least Squares Loss (Formulation 2). \n% By Jiayu Zhou (jiayu.zhou@asu.edu) Dec. 2011\n\n% Objective (Non-Convex):\n% argmin_W { \\sum_{i=1}^t (0.5 * norm (Y{i} - X{i}' * W(:, i))^2)\n% + lambda * \\sum_{i=1}^d \\sqrt{ \\|R * W(i, :)\\|_1 + beta * \\|W(i, :)\\|_1}\n% }\n%\n% t - task number \n% d - dimension\n% n - sample size\n%\n% lambda: joint feature selection\n% beta: Lasso sparsity.\n% R encodes fused structure relationship [1 -1 0 ...; 0 1 -1 ...; ...]\n% R=zeros(t,t-1);R(1:(t+1):end)=1;R(2:(t+1):end)=-1;\n\n%%% input\n% X: {d * n} * t - input matrix\n% Y: {n * 1} * t - output matrix\n% lambda: 1 - joint feature selection\n% beta: 1 - Lasso sparsity.\n\nif nargin <5\n opts = [];\nend\n\nif isfield(opts, 'max_iter')\n max_iter = opts.max_iter;\nelse\n max_iter = 20;\nend\n\nif isfield(opts, 'tol_funcVal')\n tol_funcVal = opts.tol_funcVal;\nelse\n tol_funcVal = 10^-6;\nend\n\ntask_num = length (X);\ndimension = size(X{1}, 1);\n\n% Relation\nR=zeros(task_num,task_num-1);\nR(1:(task_num+1):end)=1;\nR(2:(task_num+1):end)=-1;\nR = R';\n\n\nif isfield(opts, 'starting_point')\n %fprintf('Least_NCFGLassoF2: Init model used\\n');\n W0 = opts.starting_point;\nelse\n %W0 = rand(dimension, task_num);\n [W0] = Least_FGLasso(X, Y, lambda*beta, lambda);\nend\n\nepsilon = 10e-12; % should be slight larger than machine error.\n\nfuncVal = funcVal_eval (W0);\n\ninner_iteration_opts.max_iter = 100;\ninner_iteration_opts.tol_funcVal = 10^-7;\n\niter = 0;\nwhile iter < max_iter\n % reweigting vector.\n \n rho1 = zeros(dimension, 1); % weighted Lasso \n rho2 = zeros(dimension, 1); % weighted Fused Lasso\n for t = 1: dimension\n rho2(t) = lambda / (2 * sqrt(norm(W0(t, :),1) + norm(R * W0(t, :)', 1) + epsilon));\n rho1(t) = rho2(t) * beta; \n end\n \n [W, sub_funcVal] = Least_Weight2FGLasso(X, Y, rho1, rho2, inner_iteration_opts);\n \n funcVal = cat(1, funcVal, funcVal_eval (W));\n \n % test stop condition.\n if length(funcVal)> 1 &&...\n (abs(funcVal(end-1) - funcVal(end))/ funcVal(end))<=tol_funcVal\n break;\n end\n \n iter = iter + 1;\n W0 = W;\n \nend\n\n function [funcVal] = funcVal_eval (W)\n funcVal = 0;\n for i = 1: task_num\n funcVal = funcVal + 0.5 * norm (Y{i} - X{i}' * W(:, i))^2;\n end\n % non-smooth part\n for i = 1 : size(W, 1) % dimension \n w = W(i, :);\n funcVal = funcVal ...\n + lambda * sqrt(norm(R * w', 1) + beta * norm(w, 1));\n end\n end\n\nend", "meta": {"author": "jiayuzhou", "repo": "MALSAR", "sha": "fb9751594983df020ddc4f7e4a40520ee7c37989", "save_path": "github-repos/MATLAB/jiayuzhou-MALSAR", "path": "github-repos/MATLAB/jiayuzhou-MALSAR/MALSAR-fb9751594983df020ddc4f7e4a40520ee7c37989/MALSAR/functions/progression_model/nFSGL/Least_NCFGLassoF2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.728555266713243}} {"text": "function pers=categorical_persistence(S)\n% CATEGORICAL_PERSISTENCE computes the persistence of an unordered multilayer partition\n%\n% Version: 2.2.0\n% Date: Thu 11 Jul 2019 12:25:42 CEST\n%\n% pers = categorical_PERSISTENCE(S) with a single multilayer partition or a\n% cell of multilayer partitions S (with S{i} the ith multilayer partition of\n% cell S) computes the \"persistence\" of multilayer partitions. The output pers\n% is a vector such that pers(i) is the persistence of multilayer partition\n% S{i} (stored as an N*T matrix where N is the number of nodes in each layer\n% and T is the number of layers). For a multilayer network with unordered\n% layers, the value of persistence is the sum over all pairs of layers of\n% the number of nodes that do not change community assignments. Categorical\n% persistence varies between 0 and 1. Categorical persistence is related to\n% the multilayer quality function developed in Mucha et al. 2010 when one\n% uses categorical interlayer coupling.\n%\n% References:\n%\n% Mucha, Peter J., Thomas Richardson, Kevin Macon, Mason A. Porter, and\n% Jukka-Pekka Onnela. \"Community Structure in Time-Dependent,\n% Multiscale, and Multiplex Networks,\" Science 328, 876-878 (2010).\n%\n% Bazzi, Marya, Mason A. Porter, Stacy Williams, Mark McDonald, Daniel\n% J. Fenn, and Sam D. Howison. \"Community Detection in Temporal\n% Multilayer Networks, with an Application to Correlation Networks\",\n% MMS: A SIAM Interdisciplinary Journal 14, 1-41 (2016). \n\nif ~iscell(S)\n S={S};\nend\n\n[N,T]=size(S{1});\nall2all = N*[(-T+1):-1,1:(T-1)];\nA=spdiags(ones(N*T,2*T-2),all2all,N*T,N*T);\npers=zeros(length(S),1);\nfor i=1:length(S)\n\n G=sparse(1:length(S{i}(:)),S{i}(:),1);\n pers(i)=trace(G'*A*G)/(N*T*(T-1));\nend\n\nend\n", "meta": {"author": "GenLouvain", "repo": "GenLouvain", "sha": "5688f219baa726988a2faa19cf00d63159fa4ff9", "save_path": "github-repos/MATLAB/GenLouvain-GenLouvain", "path": "github-repos/MATLAB/GenLouvain-GenLouvain/GenLouvain-5688f219baa726988a2faa19cf00d63159fa4ff9/HelperFunctions/categorical_persistence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7285334502295233}} {"text": "%--------------------------------------------------------------------------\n% [yn,ref_dn,W,en] = lms2(xn,dn,M,mu)\n%--------------------------------------------------------------------------\n% 功能:\n% LMS自适应滤波器 带通道时延\n%--------------------------------------------------------------------------\n% 输入:\n% xn 输入信号的序列 列向量\n% dn 所期望的响应序列 列向量\n% M 滤波器阶数\n% mu 收敛因子(步长)\n% 输出:\n% W 滤波器的权值矩阵 大小为M * iter\n% en 误差序列(itr * 1) 列向量\n% yn 实际输出序列 列向量\n%--------------------------------------------------------------------------\n% 例子:\n% 暂无\n%--------------------------------------------------------------------------\nfunction [yn,ref_dn,W,en] = lms2(xn,dn,M,mu)\nif rem(M,2)==0\n disp('请将滤波器阶数为奇数')\n return\nend\n\nw_ref = [zeros((M-1)/2,1);1;zeros((M-1)/2,1)]; %正常延迟信号 延迟(M-1)/2个点\nxn = xn(:);\ndn =conv(w_ref,dn(:)); %正常信号延迟\nref_dn = dn;\nitr = length(xn);\nen = zeros(itr,1); %误差序列,en(k)表示第k次迭代时预期输出与实际输出的误差\nW = zeros(M,itr); %滤波器的权值矩阵(矩阵)\n%--------------------------------------------------------------------------\n% 迭代计算\n%--------------------------------------------------------------------------\nfor idx = M:itr %第k次迭代\n x = xn(idx:-1:idx-M+1); %滤波器M个抽头的输入\n y = W(:,idx-1).'*x; %滤波器的输出\n en(idx) = dn(idx) - y; %第k次迭代的误差\n %----------------------------------------------------------------------\n % 滤波器权值计算的迭代式\n %----------------------------------------------------------------------\n W(:,idx) = W(:,idx-1) + 2*mu*en(idx)*x;\nend\n\n%--------------------------------------------------------------------------\n% 求最优时滤波器的输出序列,r如果没有yn的返回参数可以不要下面的\n%--------------------------------------------------------------------------\nyn = conv(W(:,end),xn);", "meta": {"author": "qwe14789cn", "repo": "SP", "sha": "4134ad2e50a446a3d496517720358a808da2f059", "save_path": "github-repos/MATLAB/qwe14789cn-SP", "path": "github-repos/MATLAB/qwe14789cn-SP/SP-4134ad2e50a446a3d496517720358a808da2f059/+sp/lms2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7285334439139116}} {"text": "function [masks,keepLocs] = maskGaussians( siz, M, width, offset, show )\n% Divides a volume into softly overlapping gaussian windows.\n%\n% Return M^nd masks each of size siz. Each mask represents a symmetric\n% gaussian window, the locations are evenly spaced throughout the array of\n% size siz. For example, if M=2, then along each dimension d the location\n% of each mask is either 1/4 or 3/4 of siz(d) and likewise if M=3 that mask\n% is at 1/6,3/6, or 5/6 of siz(d). For higher M the locations are:\n% 1/2M,3/2M,...,M-1/2M. See examples below to visualize the masks.\n%\n% The std of each gaussian is set to be equal to the spacing between two\n% adjacent masks multiplied by width. Reducing the widths of the gaussians\n% causes there to be less overlap between masks, but if the width is\n% reduced too far certain pixels in between masks receive very little\n% weight. A desired property of the masks is that their coverage (the\n% total weight placed on the pixel by all the masks) is approximately\n% constant. Typically, we settle for having the coverage be monotonically\n% decreasing as we move away from the center. (In reality the coverage\n% oscilates as we move past peaks, it's just that the oscillations tend to\n% be small). The default value of the width is .6, which minimizes overlap\n% while still providing good overall coverage. Values lower tend to produce\n% noticeable oscillations in coverage. offset in (-.5,1) controls the\n% spacing of the locations. Essentially, a positive offset moves the\n% locations away from the center of the array and a negative offset moves\n% the windows away from the center. Using a positive offset gives better\n% coverage to areas near the borders.\n%\n% USAGE\n% [masks,keepLocs] = maskGaussians( siz, M, [width], [offset], [show] )\n% \n% INPUTS\n% siz - dimensions of each mask\n% M - # mask locations along each dim [either scalar or vector]\n% width - [.6] widths of the gaussians\n% offset - [.1] spacing of mask centers; in (-.5,1)\n% [show] - [0] figure to use for display (no display if==0) (nd<=3)\n%\n% OUTPUTS\n% masks - [see above] array of size [siz x M^nd]\n% keepLocs - logical array of all locs where masks is nonzero\n%\n% EXAMPLE\n% masks = maskGaussians( 100, 10, .6, -.1, 1 ); %1D\n% masks = maskGaussians( [35 35], 3, .6, .1, 1 ); %2D\n% masks = maskGaussians( [35 35 35], [2 2 4], .6, .1, 1 ); %3D\n%\n% See also HISTCIMLOC, MASKCIRCLE\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\nnd = length(siz);\nif( nargin<3 || isempty(width)); width = .6; end; \nif( nargin<4 || isempty(offset)); offset = .1; end;\nif( nargin<5 || isempty(show) || nd>3 ); show = 0; end;\n\n%%% uses a cache since this is slow but often called with same inputs.\npersistent cache; if( isempty(cache) ); cache=simpleCache('init'); end;\nkey = [nd siz M width offset];\n[found,val] = simpleCache( 'get', cache, key ); \nif( found ) %%% get masks and keepLocs from cache\n [masks,keepLocs] = deal(val{:});\nelse %%% create masks and keepLocs\n [M,er] = checkNumArgs( M, [1 nd], 0, 2 ); error(er);\n inds = {':'}; inds = inds(:,ones(1,nd)); \n if( offset<=-.5 || offset>=1 ); error('offset must be in (-.5,1)'); end;\n\n %%% the covariance of each window\n spacing = (siz*(1+2*offset))./M;\n sigmas = spacing * width;\n C = diag(sigmas.^2);\n \n %%% create each mask\n masks = zeros( [siz,prod(M)] );\n for c=1:prod(M) \n sub = ind2sub2( M, c );\n mus = (sub-.5).* spacing + .5-offset*siz;\n masks(inds{:},c) = filterGauss( siz, mus, C );\n end\n keepLocs = masks>1e-7;\n\n %%% place into cache\n cache = simpleCache( 'put', cache, key, {masks,keepLocs} );\nend;\n\n%%% optionally display\nif( show )\n if( nd==1 )\n figure(show); clf; plot( masks );\n figure(show+1); clf; plot(sum( masks,nd+1 ));\n a=axis; a(3)=0; axis(a);\n title('coverage');\n elseif( nd==2)\n figure(show); clf; montage2( masks ); \n figure(show+1); clf; im(sum( masks,nd+1));\n title('coverage');\n elseif( nd==3)\n figure(show); clf; montage2( masks ); \n figure(show+1); clf; montage2(sum( masks,nd+1) );\n title('coverage');\n end\nend;\n \n", "meta": {"author": "pdollar", "repo": "toolbox", "sha": "e87332637bbe8e8b92dd487c87567d9628404523", "save_path": "github-repos/MATLAB/pdollar-toolbox", "path": "github-repos/MATLAB/pdollar-toolbox/toolbox-e87332637bbe8e8b92dd487c87567d9628404523/images/maskGaussians.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7285334436928339}} {"text": "function nMC=grMinVerCover(E,d)\n% Function nMC=grMinVerCover(E,d) solve the minimal vertex cover problem.\n% Input parameters: \n% E(m,2) - the edges of graph;\n% 1st and 2nd elements of each row is numbers of vertexes;\n% m - number of edges.\n% d(n) (optional) - the weights of vertexes,\n% n - number of vertexes.\n% If we have only 1st parameter E, then all d=1.\n% Output parameter:\n% nMC - the list of the numbers of vertexes included \n% in the minimal (weighted) vertex cover.\n% Uses the reduction to integer LP-problem.\n% Required the Optimization Toolbox v.3.0.1 or over.\n% Author: Sergiy Iglin\n% e-mail: siglin@yandex.ru\n% personal page: http://iglin.exponenta.ru\n\n% ============= Input data validation ==================\nif nargin<1,\n error('There are no input data!')\nend\n[m,n,E] = grValidation(E); % E data validation\nif nargin<2, % we may only 1st parameter\n d=ones(n,1); % all weights =1\nelse\n d=d(:); % reshape to vector-column\n if length(d) 0} rpepresents the exterior domain of the interface. \n% \n% Definition\n% Interface element: the element whose vertices are not in the same side\n% of the interface.\n%\n% Interface node: the vertices of all the interface elements. Split the\n% set of interface nodes into two parts: interior interface nodes (phi(p)<=0) and\n% exterior interface nodes (phi(p)>=0);\n%\n% Example\n% clear all; close all;\n% node = [-1 -1; 1 -1; 1 1; -1 1];\n% elem = [2 3 1; 4 1 3];\n% [node,elem] = interfacemesh(node,elem,@ellipse);\n%\n% See also bisect, circle, ellipse.\n%\n% Reference: H. Wei, L. Chen, Y. Huang and B. Zheng. Adaptive Mesh\n% Refinement and Superconvergence for Two Dimensional Interface Problems.\n% SIAM Journal on Scientific Computing, 2014.\n%\n% Add by Huayi Wei. Based on discussion with Long Chen.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\noldNodeIdx = [];\noldNode = [];\noldElemIdx = [];\noldElem = [];\n\n%% Step 1: Refine mesh such that the set of interface elements is non-empty\nN0 = size(node,1);\nphiValue = phi(node);\n\nif all(phiValue<0)\n error('The initial mesh is in the interior of the domain the interface surrounds, please use a mesh which can cover the interface!')\nend\n\n% uniform bisect the mesh, to make sure there exist at least one mesh node\n% which is inside of the interface, namely, phi(p)<0.\nwhile all(phiValue>0)\n [node,elem] = uniformbisect(node,elem);\n N1 = size(node,1);\n phiValue(N0+1:N1) = phi(node(N0+1:N1,:)); % append the phi value\n N0 = N1;\nend\n\ndisplay('Finish Step 1: uniform bisect all elements');\n\n%% Step 2: estimate the discrete curvature, then bisect elements with big curvature\n% find interface elements, which are elements crossed by the interface and\n% restrict the computation to the interface elements\n[interfaceElemIdx, ~, isInterfaceElem] = markinterface(elem,phiValue);\ninterfaceElem = elem(interfaceElemIdx,:);\nisInterfaceNode = false(size(node,1),1);\nisInterfaceNode(interfaceElem(:))=true;\ninterfaceNT = size(interfaceElem,1);\nT = auxstructure(interfaceElem);\nedge = double(T.edge);\nedge2elem = T.edge2elem;\nclear T;\n\n% case: Fig 2(a) in p6 \ntmpAngle = ones(interfaceNT,1)*[90,45,45];\nangle = accumarray(interfaceElem(:),tmpAngle(:),[size(node,1) 1]);\nis360 = (angle == 360);\n\n% case: Fig 2(b) in p6\nisInterfaceBEdge = (edge2elem(:,1) == edge2elem(:,2));\ninterfaceBEdge = edge(isInterfaceBEdge,:);\nv2vI = sparse(interfaceBEdge,interfaceBEdge(:,[2,1]),1,size(node,1),size(node,1));\nisLinkNode = (v2vI*isInterfaceNode >= 3);\n\n% case: Fig 2(c) in p6\nisInteriorNode = phiValue < 0;\nturnAngle = zeros(size(node,1),1);\nisIn = isInterfaceNode & isInteriorNode & ~is360 & ~isLinkNode;\nturnAngle(isIn) = 180 - (360 - angle(isIn));\nisOut = isInterfaceNode & ~isInteriorNode & ~is360 & ~isLinkNode;\nturnAngle(isOut ) = (360 - angle(isOut)) -180;\nv2v = sparse(edge,edge(:,[2,1]),1,size(node,1),size(node,1));\nturnAngleTotal = v2v*turnAngle+turnAngle;\n\n% case: size of interface elements should be small enough\nve = node(elem(:,3),:) - node(elem(:,2),:);\nL = sqrt(sum(ve.^2,2));\nmL = max(L);\nisBigSizeElem = ((L > mL*mL) & isInterfaceElem);\n% mark nodes for refinement\nisBigCurvNode = (is360 | isLinkNode |(abs(turnAngleTotal)> 170));\n\nif any(isBigCurvNode) || any(isBigSizeElem)\n \n bigCurvElem = interfaceElemIdx(max(isBigCurvNode(interfaceElem),[],2));\n bigSizeElem = find(isBigSizeElem); \n\n count = 0;\n while count < 100\n % bisect marked elements\n [node,elem] = bisect(node,elem,[bigCurvElem; bigSizeElem]);\n \n N1 = size(node,1);\n phiValue(N0+1:N1) = phi(node(N0+1:N1,:));\n N0 = N1;\n \n % find interface elements and nodes\n interfaceElemIdx = markinterface(elem,phiValue);\n interfaceElem = elem(interfaceElemIdx,:);\n isInterfaceNode = false(size(node,1),1);\n isInterfaceNode(interfaceElem(:))=true;\n T = auxstructure(interfaceElem);\n edge = double(T.edge);\n edge2elem = T.edge2elem;\n clear T;\n \n % find triangles containing curves with high curvature\n % case: Fig 2(a) in p6 \n interfaceNT = size(interfaceElem,1);\n tmpAngle = ones(interfaceNT,1)*[90,45,45]; \n angle = accumarray(interfaceElem(:),tmpAngle(:),[size(node,1) 1]);\n is360 = angle == 360;\n \n % case: Fig 2(b) in p6\n isInterfaceBEdge = edge2elem(:,1) == edge2elem(:,2);\n interfaceBEdge = edge(isInterfaceBEdge,:);\n v2vI = sparse(interfaceBEdge,interfaceBEdge(:,[2,1]),1,size(node,1),size(node,1));\n isLinkNode = (v2vI*isInterfaceNode >= 3);\n\n % case: Fig 2(c) in p6\n isInteriorNode = (phiValue < 0);\n turnAngle = zeros(size(node,1),1);\n isIn = isInterfaceNode & isInteriorNode & ~is360 & ~isLinkNode;\n turnAngle(isIn) = 180 - (360 - angle(isIn));\n isOut = isInterfaceNode & ~isInteriorNode & ~is360 & ~isLinkNode;\n turnAngle(isOut ) = (360 - angle(isOut)) -180;\n v2v = sparse(edge,edge(:,[2,1]),1,size(node,1),size(node,1));\n turnAngleTotal = v2v*turnAngle+turnAngle;\n \n % control size of interface elements\n ve = node(interfaceElem(:,3),:) - node(interfaceElem(:,2),:);\n L = sqrt(sum(ve.^2,2));\n bigSizeElem = interfaceElemIdx(L > mL^2);\n \n isBigCurvNode = is360 | isLinkNode |(abs(turnAngleTotal)> 170);\n if ~any(isBigCurvNode) && ~any(isBigSizeElem)\n break;\n end\n \n bigCurvElem = interfaceElemIdx(max(isBigCurvNode(interfaceElem),[],2));\n end\nend\n\ndisplay('Finish Step 2: bisect interface with big curvature!');\n\n%% Step 3: Update the type of interface triangles\n% Two types of triangles in the bisection grids\n% Type A: two edges parallel to coordinates; see Fig 2.6\n% Type B: the longest edge parallel to x or y coordinate; see Fig 2.7\n\nve = node(elem(:,3),:) - node(elem(:,2),:);\nelemType = (abs(ve(:,1)) > eps & abs(ve(:,2)) > eps); \n[interfaceElemIdx, ~,isInterfaceElem] = markinterface(elem,phiValue);\nT = auxstructure(elem);\nneighbor = T.neighbor;\nclear T;\nisMark = false(size(elem,1),1);\nisMark(interfaceElemIdx) = true;\nisMark(neighbor(interfaceElemIdx,1)) = true;\n\nt = cumsum(ones(size(elem,1),1));\ntt = neighbor(:,1);\nisTransitionTypeBElem = isInterfaceElem & isInterfaceElem(tt) & neighbor(tt,1) ~= t & ~elemType;\n\n%% Deal with the transition Type B elements, see Fig 2.7 (c) and (d) and conditions (C1) and (C2)\n% \n% case 1: a Type B interface element whose second neighbor is a interface\n% and Type A element.\nidx2 = find(isTransitionTypeBElem & isInterfaceElem(neighbor(:,2)) ...\n & elemType(neighbor(:,2)));\nif ~isempty(idx2)\n p1 = node(elem(idx2,1),:);\n p2 = node(elem(idx2,2),:);\n p3 = node(elem(idx2,3),:);\n p4 = node(elem(neighbor(idx2,2),1),:);\n m14 = (p1 + p4)/2;\n m34 = (p3 + p4)/2;\n m23 = (p2 + p3)/2;\n m1 = (m23 + p3)/2;\n m2 = (m23 + p2)/2;\n isNotTB = ((phiValue(elem(idx2,3)) .* phi(m1)) > 0 & ...\n (phi(m14) .* phi(m34) < 0)) | phi(m1).*phi(m2) < 0;\n isTransitionTypeBElem(idx2(isNotTB)) = false;\nend\n\n% case 2: a Type B interface element whose third neighbor is a interface\n% and Type A element.\nidx3 = find(isTransitionTypeBElem & isInterfaceElem(neighbor(:,3)) ...\n & elemType(neighbor(:,3)));\nif ~isempty(idx3)\n p1 = node(elem(idx3,1),:);\n p2 = node(elem(idx3,2),:);\n p3 = node(elem(idx3,3),:);\n p4 = node(elem(neighbor(idx3,3),1),:);\n m14 = (p1 + p4)/2;\n m24 = (p2 + p4)/2;\n m23 = (p2 + p3)/2;\n m1 = (m23 + p3)/2;\n m2 = (m23 + p2)/2;\n isNotTB = ((phiValue(elem(idx3,2)).*phi(m2)) > 0 & ...\n (phi(m14).*phi(m24) < 0)) | phi(m1).*phi(m2) < 0;\n isTransitionTypeBElem(idx3(isNotTB)) = false;\nend\n\n% case 3: a Type B interface element whose third neighbor is a interface\n% and Type B element.\nidx4 = find(isTransitionTypeBElem & isInterfaceElem(neighbor(:,2)) ...\n & ~elemType(neighbor(:,2)));\nif ~isempty(idx4)\n p2 = node(elem(idx4,2),:);\n p3 = node(elem(idx4,3),:);\n m23 = (p2 + p3)/2;\n m1 = (m23 + p3)/2;\n m2 = (m23 + p2)/2;\n isNotTB = phi(m1).*phi(m2) < 0;\n isTransitionTypeBElem(idx4(isNotTB)) = false;\nend\n\n% case 4: a Type B interface element whose third neighbor is a interface\n% and Type B element.\nidx5 = find(isTransitionTypeBElem & isInterfaceElem(neighbor(:,3)) ...\n & ~elemType(neighbor(:,3)));\nif ~isempty(idx5)\n p2 = node(elem(idx5,2),:);\n p3 = node(elem(idx5,3),:);\n m23 = (p2 + p3)/2;\n m1 = (m23 + p3)/2;\n m2 = (m23 + p2)/2;\n isNotTB = phi(m1).*phi(m2) < 0;\n isTransitionTypeBElem(idx5(isNotTB)) = false;\nend\ntypeB = (isMark & ~elemType & ~isTransitionTypeBElem);\n\n% bisect some transition type B elements to type A\nwhile any(typeB)\n \n [node,elem,~, ~,tree] = bisect(node,elem,typeB);\n N1 = size(node,1);\n phiValue(N0+1:N1) = phi(node(N0+1:N1,:));\n N0 = N1;\n \n elemType = updatetype(elemType,tree(:,[2,3]));\n \n [interfaceElemIdx, ~,isInterfaceElem] = markinterface(elem,phiValue);\n \n T = auxstructure(elem);\n neighbor = T.neighbor;\n clear T;\n isMark = false(size(elem,1),1);\n isMark(interfaceElemIdx) = true;\n isMark(neighbor(interfaceElemIdx,1)) = true;\n \n t = cumsum(ones(size(elem,1),1));\n tt = neighbor(:,1);\n isTransitionTypeBElem = isInterfaceElem & isInterfaceElem(tt) & ...\n neighbor(tt,1) ~= t & ~elemType;\n \n % case 1: a Type B interface element whose second neighbor is a interface\n % and Type A element.\n idx2 = find(isTransitionTypeBElem & isInterfaceElem(neighbor(:,2)) & ...\n elemType(neighbor(:,2)));\n if ~isempty(idx2)\n p1 = node(elem(idx2,1),:);\n p2 = node(elem(idx2,2),:);\n p3 = node(elem(idx2,3),:);\n p4 = node(elem(neighbor(idx2,2),1),:);\n m14 = (p1 + p4)/2;\n m34 = (p3 + p4)/2;\n m23 = (p2 + p3)/2;\n m1 = (m23 + p3)/2;\n m2 = (m23 + p2)/2;\n isNotTB = ((phiValue(elem(idx2,3)) .* phi(m1)) > 0 & ...\n (phi(m14) .* phi(m34) < 0)) | phi(m1).*phi(m2) < 0;\n isTransitionTypeBElem(idx2(isNotTB)) = false;\n end\n % case 2: a Type B interface element whose third neighbor is a interface\n % and Type A element.\n idx3 = find(isTransitionTypeBElem & isInterfaceElem(neighbor(:,3)) & ...\n elemType(neighbor(:,3)));\n if ~isempty(idx3)\n p1 = node(elem(idx3,1),:);\n p2 = node(elem(idx3,2),:);\n p3 = node(elem(idx3,3),:);\n p4 = node(elem(neighbor(idx3,3),1),:);\n m14 = (p1 + p4)/2;\n m24 = (p2 + p4)/2;\n m23 = (p2 + p3)/2;\n m1 = (m23 + p3)/2;\n m2 = (m23 + p2)/2;\n isNotTB = ((phiValue(elem(idx3,2)).*phi(m2)) > 0 & ...\n (phi(m14).*phi(m24) < 0)) | phi(m1).*phi(m2) < 0;\n isTransitionTypeBElem(idx3(isNotTB)) = false;\n end\n \n % case 3: a Type B interface element whose second neighbor is a interface\n % and Type B element.\n idx4 = find(isTransitionTypeBElem & isInterfaceElem(neighbor(:,2)) & ...\n ~elemType(neighbor(:,2)));\n if ~isempty(idx4) \n p2 = node(elem(idx4,2),:);\n p3 = node(elem(idx4,3),:);\n m23 = (p2 + p3)/2;\n m1 = (m23 + p3)/2;\n m2 = (m23 + p2)/2;\n isNotTB = phi(m1).*phi(m2) < 0;\n isTransitionTypeBElem(idx4(isNotTB)) = false;\n end\n % case 4: a Type B interface element whose third neighbor is a interface\n % and Type B element.\n idx5 = find(isTransitionTypeBElem & isInterfaceElem(neighbor(:,3)) & ...\n ~elemType(neighbor(:,3)));\n if ~isempty(idx5)\n p2 = node(elem(idx5,2),:);\n p3 = node(elem(idx5,3),:);\n m23 = (p2 + p3)/2;\n m1 = (m23 + p3)/2;\n m2 = (m23 + p2)/2;\n isNotTB = phi(m1).*phi(m2) < 0;\n isTransitionTypeBElem(idx5(isNotTB)) = false;\n end\n typeB = (isMark & ~elemType & ~isTransitionTypeBElem); \nend\n\n% find interface elements\ninterfaceElemIdx= markinterface(elem,phiValue);\ninterfaceElem = elem(interfaceElemIdx,:);\n% find interface nodes, which are the vertices of interface elements.\nisInterfaceNode = false(size(node,1),1);\nisInterfaceNode(interfaceElem(:))=true;\nT = auxstructure(elem);\nedge = T.edge;\nedge2elem = T.edge2elem;\nclear T;\n% case: Fig 2.7 (b)\nisEdge = edge2elem(:,1) ~= edge2elem(:,2);\nisEdge = isEdge & (isInterfaceNode(edge(:,1)) | isInterfaceNode(edge(:,2)) |...\n isInterfaceNode(elem(edge2elem(:,1),1)) | isInterfaceNode(elem(edge2elem(:,2),1)));\nisEdge = isEdge & edge2elem(:,3) == 1 & edge2elem(:,4)==1;\nisEdge = isEdge & ~elemType(edge2elem(:,1));\nisMark = false(size(elem,1),1);\nisMark(edge2elem(isEdge,1)) = true;\nisMark(edge2elem(isEdge,2)) = true;\n[node,elem,~, ~,tree] = bisect(node,elem,isMark);\nN1 = size(node,1);\nphiValue(N0+1:N1) = phi(node(N0+1:N1,:));\n% N0 = N1;\nelemType = updatetype(elemType,tree(:,[2,3]));\n\ndisplay('Finish Step 3: transform the type B of element to type A!');\n\n\n%% Step 4: Move some interface nodes onto the interface\n% \n% Here we just move interface nodes along the shortest edges of all the\n% type A interface elements. For a such kind of edge, we get the\n% intersection points and compute the distances between the two endpoints\n% and the intersection points. An interface node maybe have two moving\n% direction, just choose a direction which move shorter distance, then the\n% qualities of the elements connecting to this node will decrease less.\n\ninterfaceElemIdx= markinterface(elem,phiValue);\ninterfaceElem = elem(interfaceElemIdx,:);\nT = auxstructure(interfaceElem);\nedge = double(T.edge);\nedge2elem = T.edge2elem;\nisSpecial = elemType(interfaceElemIdx(edge2elem(:,1))) & ...\n ~elemType(interfaceElemIdx(edge2elem(:,2))) & edge2elem(:,3) == 1;\nisSpecial = isSpecial | (~elemType(interfaceElemIdx(edge2elem(:,1))) & ...\n elemType(interfaceElemIdx(edge2elem(:,2))) & edge2elem(:,4) == 1);\nisShortEdge = (edge2elem(:,1) ~= edge2elem(:,2)) & ~(edge2elem(:,3) == 1 & ...\n edge2elem(:,4) == 1) & ~isSpecial;\nA = node(edge(isShortEdge,1),:);\nB = node(edge(isShortEdge,2),:);\nh = sqrt(sum((A-B).^2,2));\nM = findintersectbisect(phi,A,B);\nh1 = sqrt(sum((A-M).^2,2));\nh2 = h - h1;\nt = sparse(edge(isShortEdge,[1,2]),edge(isShortEdge,[2,1]),[h1./h,h2./h], size(node,1),size(node,1));\nt1 = sparse(edge(isShortEdge,[1,2]),edge(isShortEdge,[2,1]),repmat(cumsum(ones(size(M,1),1)),1,2), size(node,1),size(node,1));\n[maxt,I] = max(t,[],1);\nisIrregularNode = maxt >= 0.5;\nidx = find(isIrregularNode);\nidx1 = I(idx)+(idx - 1)*size(node,1);\n\noldNodeIdx = [oldNodeIdx;idx'];\noldNode = [oldNode;node(idx,:)];\n\nnode(idx,:) = M(t1(idx1),:);\n\nphiValue(idx) = 0;\n\ndisplay('Finish Step 4: move the nearest nodes to interface!');\n% figure\n% showmesh(node,elem);\n% findelem(node,elem,interfaceElemIdx,'noindex');\n% plotcurve(a);\n\n%% Step 5: Edge swap\n%\n% We just consider the case that two elements share a common longest edge,\n% whose one or two of its four vertices are moved on the interface. After\n% moving, the qualities of this two elements will change(and most case,\n% the quality will decrease). If edge swapping can improve the qualities,\n% we do edge swapping for this two elements.\n% \n% But if the common longest edge of the two element is an interface edge,\n% namely its two endpoints are on the interface, we can't use edge\n% swapping. In this case, we deal with it in Step 7. Just find the element\n% patchs of the first vertices of these two element, and replace this two\n% vertices by the centroids of the element patchs, respectively.\n\nT = auxstructure(elem);\nedge = double(T.edge);\nedge2elem = T.edge2elem; \nclear T;\n\nleftElemIdx = edge2elem(:,1); % the index of the first neighbor of edge \nrightElemIdx = edge2elem(:,2); % the index of the second neighbor of edge\n\nisIrregularNode = full(isIrregularNode)';\nisLongestEdge = (edge2elem(:,1) ~= edge2elem(:,2)) & ...\n edge2elem(:,3) == 1 & edge2elem(:,4)== 1 & ...\n (isIrregularNode(edge(:,1)) | isIrregularNode(edge(:,2)) | ...\n isIrregularNode(elem(leftElemIdx,1)) | isIrregularNode(elem(rightElemIdx,1)));\n\nisCrossLongestEdge = (edge2elem(:,1) ~= edge2elem(:,2)) & ...\n edge2elem(:,3) == 1 & edge2elem(:,4)== 1 & ...\n isIrregularNode(elem(leftElemIdx,1)) & isIrregularNode(elem(rightElemIdx,1)) &...\n ~isIrregularNode(edge(:,1)) & ~isIrregularNode(edge(:,2));\n\nisInterfaceEdge = isIrregularNode(edge(:,1)) & isIrregularNode(edge(:,2));\nisInterfaceEdge = isLongestEdge & isInterfaceEdge ;\nisInterfaceEdge = isInterfaceEdge & ~isIrregularNode(elem(leftElemIdx,1)) ;\nisInterfaceEdge = isInterfaceEdge & ~isIrregularNode(elem(rightElemIdx,1));\n\nisLongestEdge(isInterfaceEdge) = false;\n\nleftElemIdx = edge2elem(isLongestEdge,1);\nrightElemIdx = edge2elem(isLongestEdge,2);\n\nleftElem = elem(leftElemIdx,:);\nrightElem = elem(rightElemIdx,:);\n\nleftElemNew = [leftElem(:,2), rightElem(:,1),leftElem(:,1)];\nrightElemNew = [rightElem(:,2), leftElem(:,1),rightElem(:,1)];\n\nl1 = triangleratio(node,leftElem);\nr1 = triangleratio(node,rightElem);\n\nl2 = triangleratio(node,leftElemNew);\nr2 = triangleratio(node,rightElemNew);\n\nnotNeedSwap = min([l1,r1],[],2) >= min([l2,r2],[],2) & ~isCrossLongestEdge(isLongestEdge);\n\nleftElemNew(notNeedSwap,:) = leftElem(notNeedSwap,:);\nrightElemNew(notNeedSwap,:) = rightElem(notNeedSwap,:);\n\noldElemIdx =[oldElemIdx;leftElemIdx;rightElemIdx];\noldElem = [oldElem;elem([leftElemIdx;rightElemIdx],:)];\n\nelem(leftElemIdx,:) = leftElemNew;\nelem(rightElemIdx,:) = rightElemNew;\n\ndisplay('Finish Step 5: edge swap!')\n\n%% Step 6: Mesh smoothing for near interface nodes\n% q = minangle(node,elem);\n% [minq,I] = min(q);\n\nT = auxstructure(elem);\n% edge = double(T.edge);\nneighbor = double(T.neighbor);\nclear T;\n\nisInterfaceNode = (msign(phiValue) == 0);\n\nbadElem = find(~isInterfaceNode(elem(:,1)) & isInterfaceNode(elem(:,2)) ...\n & isInterfaceNode(elem(:,3)));\nv1 = node(elem(badElem,3),:) - node(elem(badElem,2),:);\nv2 = node(elem(badElem,1),:) - node(elem(badElem,3),:);\nv3 = node(elem(badElem,2),:) - node(elem(badElem,1),:);\nbadElem = badElem(sum(v2.^2,2)+sum(v3.^2,2) < sum(v1.^2,2)-eps);\nmoveNodeIdx = elem(badElem,1);\nif ~isempty(moveNodeIdx)\n N = size(node,1);\n NT = size(elem,1);\n v2t = sparse(elem,[(1:NT)',(1:NT)',(1:NT)'],1,N,NT);\n area = simplexvolume(node,elem);\n bc = (node(elem(:,1),:) + node(elem(:,2),:) + node(elem(:,3),:))/3;\n oldNodeIdx = [oldNodeIdx;moveNodeIdx];\n oldNode = [oldNode;node(moveNodeIdx,:)];\n ba = v2t(moveNodeIdx,:)*area;\n node(moveNodeIdx,:) = v2t(moveNodeIdx,:)*([area,area].*bc)./[ba,ba];\nend\n% case:\nbadElem2 = find(~isInterfaceNode(elem(:,2)) & isInterfaceNode(elem(:,1)) ...\n & isInterfaceNode(elem(:,3)) & ~elemType(neighbor(:,1)));\nv1 = node(elem(badElem2,3),:) - node(elem(badElem2,2),:);\nv2 = node(elem(badElem2,1),:) - node(elem(badElem2,3),:);\nv3 = node(elem(badElem2,2),:) - node(elem(badElem2,1),:);\nbadElem2 = badElem2(sum(v2.^2,2)+sum(v3.^2,2)\n% March 2003\n\n% wrap the filter around the origin and pad with zeros\npadf = zeros(size(im));\nr = floor(size(f,1)/2);\npadf(1:r+1,1:r+1) = f(r+1:end,r+1:end);\npadf(1:r,end-r+1:end) = f(r+2:end,1:r);\npadf(end-r+1:end,1:r) = f(1:r,r+2:end);\npadf(end-r+1:end,end-r+1:end) = f(1:r,1:r);\n\n% magic\nfftim = fft2(im);\nfftf = fft2(padf);\nfim = real(ifft2(fftim.*fftf));\n\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SpatialLayout_shrink/spatiallayoutcode/GeometricContext/geomContext_src_07_02_08/src/textons/fftconv2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7284521490095799}} {"text": "function [ n_data, f, s, p, cdf ] = negative_binomial_cdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% NEGATIVE_BINOMIAL_CDF_VALUES returns values of the negative binomial CDF.\n%\n% Discussion:\n%\n% Assume that a coin has a probability P of coming up heads on\n% any one trial. Suppose that we plan to flip the coin until we\n% achieve a total of S heads. If we let F represent the number of\n% tails that occur in this process, then the value of F satisfies\n% a negative binomial PDF:\n%\n% PDF(F,S,P) = Choose ( F from F+S-1 ) * P**S * (1-P)**F\n%\n% The negative binomial CDF is the probability that there are F or\n% fewer failures upon the attainment of the S-th success. Thus,\n%\n% CDF(F,S,P) = sum ( 0 <= G <= F ) PDF(G,S,P)\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Needs[\"Statistics`DiscreteDistributions`]\n% dist = NegativeBinomialDistribution [ s, p ]\n% CDF [ dist, f ]\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% F C Powell,\n% Statistical Tables for Sociology, Biology and Physical Sciences,\n% Cambridge University Press, 1982.\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 F, the maximum number of failures.\n%\n% Output, integer S, the number of successes.\n%\n% Output, real P, the probability of a success on one trial.\n%\n% Output, real CDF, the probability of at most F failures \n% before the S-th success.\n%\n n_max = 27;\n\n cdf_vec = [ ...\n 0.6367187500000000E+00, ...\n 0.3632812500000000E+00, ...\n 0.1445312500000000E+00, ...\n 0.5000000000000000E+00, ...\n 0.2265625000000000E+00, ...\n 0.6250000000000000E-01, ...\n 0.3437500000000000E+00, ...\n 0.1093750000000000E+00, ...\n 0.1562500000000000E-01, ...\n 0.1792000000000000E+00, ...\n 0.4096000000000000E-01, ...\n 0.4096000000000000E-02, ...\n 0.7047000000000000E-01, ...\n 0.1093500000000000E-01, ...\n 0.7290000000000000E-03, ...\n 0.9861587127990000E+00, ...\n 0.9149749500510000E+00, ...\n 0.7471846521450000E+00, ...\n 0.8499053647030009E+00, ...\n 0.5497160941090026E+00, ...\n 0.2662040052146710E+00, ...\n 0.6513215599000000E+00, ...\n 0.2639010709000000E+00, ...\n 0.7019082640000000E-01, ...\n 0.1000000000000000E+01, ...\n 0.1990000000000000E-01, ...\n 0.1000000000000000E-03 ];\n\n f_vec = [ ...\n 4, 3, 2, ...\n 3, 2, 1, ...\n 2, 1, 0, ...\n 2, 1, 0, ...\n 2, 1, 0, ...\n 11, 10, 9, ...\n 17, 16, 15, ...\n 9, 8, 7, ...\n 2, 1, 0 ];\n\n p_vec = [ ...\n 0.50E+00, ...\n 0.50E+00, ...\n 0.50E+00, ...\n 0.50E+00, ...\n 0.50E+00, ...\n 0.50E+00, ...\n 0.50E+00, ...\n 0.50E+00, ...\n 0.50E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n 0.40E+00, ...\n 0.30E+00, ...\n 0.30E+00, ...\n 0.30E+00, ...\n 0.30E+00, ...\n 0.30E+00, ...\n 0.30E+00, ...\n 0.10E+00, ...\n 0.10E+00, ...\n 0.10E+00, ...\n 0.10E+00, ...\n 0.10E+00, ...\n 0.10E+00, ...\n 0.10E-01, ...\n 0.10E-01, ...\n 0.10E-01 ];\n\n s_vec = [ ...\n 4, 5, 6, ...\n 4, 5, 6, ...\n 4, 5, 6, ...\n 4, 5, 6, ...\n 4, 5, 6, ...\n 1, 2, 3, ...\n 1, 2, 3, ...\n 1, 2, 3, ...\n 0, 1, 2 ];\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 f = 0;\n s = 0;\n p = 0.0;\n cdf = 0.0;\n else\n f = f_vec(n_data);\n s = s_vec(n_data);\n p = p_vec(n_data);\n cdf = cdf_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/prob/negative_binomial_cdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7284521373045987}} {"text": "function d = ddiff ( d1, d2 )\n\n%*****************************************************************************80\n%\n%% DDIFF returns the signed distance to a region that is the difference of two regions.\n%\n% Discussion:\n%\n% The author comments that this is not the true signed distance function for\n% the difference set, in particular, around corners.\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 D1, D2, the signed distances to region 1 and 2.\n%\n% Output, real D, the signed distance to the region formed by\n% removing from region 1 its intersection with region 2.\n%\n d = max ( d1, -d2 );\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/distmesh/ddiff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772482857831, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7283900637719836}} {"text": "function a = bab_eigen_right ( n, alpha, beta )\n\n%*****************************************************************************80\n%\n%% BAB_EIGEN_RIGHT returns the right eigenvectors of the BAB matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Input, real ALPHA, BETA, the parameters.\n%\n% Output, real A(N,N), the right eigenvector matrix.\n%\n a = zeros ( n, n );\n\n for i = 1: n\n for j = 1 : n\n angle = ( i * j ) * pi / ( n + 1 );\n a(i,j) = sqrt ( 2.0 / ( n + 1 ) ) * sin ( angle );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/bab_eigen_right.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7283678250498133}} {"text": "function b = r8pbu_mxv ( n, mu, a, x )\n\n%*****************************************************************************80\n%\n%% R8PBU_MXV multiplies a R8PBU matrix times a vector.\n%\n% Discussion:\n%\n% The R8PBU storage format is for a symmetric positive definite band matrix.\n%\n% To save storage, only the diagonal and upper triangle of A is stored,\n% in a compact diagonal format that preserves columns.\n%\n% The diagonal is stored in row MU+1 of the array.\n% The first superdiagonal in row MU, columns 2 through N.\n% The second superdiagonal in row MU-1, columns 3 through N.\n% The MU-th superdiagonal in row 1, columns MU+1 through N.\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, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, integer MU, the number of superdiagonals in the matrix.\n% MU must be at least 0 and no more than N-1.\n%\n% Input, real A(MU+1,N), the R8PBU matrix.\n%\n% Input, real X(N), the vector to be multiplied by A.\n%\n% Output, real B(N), the result vector A * x.\n%\n\n%\n% Multiply X by the diagonal of the matrix.\n%\n b(1:n) = a(mu+1,1:n) .* x(1:n);\n%\n% Multiply X by the superdiagonals of the matrix.\n%\n for i = mu : -1 : 1\n for j = mu+2-i : n\n ieqn = i + j - mu - 1;\n b(ieqn) = b(ieqn) + a(i,j) * x(j);\n b(j) = b(j) + a(i,j) * x(ieqn);\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/r8pbu_mxv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.728294477502846}} {"text": "function madReadings = removeOLMADx5(readings)\n%This function removes outliers from the data set using the median\n%absolute deviation method with a x5 factor. The formula used is \n%MAD = Median { | y(i) - m | / 0.6745 }\n\nmed = median(readings); %get median value of readings\nx = abs((readings - med)); %get absolute value of each reading minus median value\nMADx5 = median(x/.6745)*5; %get value of x array and multiply it by 5, result is outlier factor\nj = 1; %variable for non-outlier array\nmadReadings = zeros(1,length(readings));%allocate array for storing readings with outliers removed\n\nfor i = 1:length(readings) %this loop removes outliears\n if readings(i) <= (med + MADx5) && readings(i) >= (med - MADx5)\n madReadings(j) = readings(i);%if not an outlier add to array\n j = j + 1;\n end\n\nend\n\nmadReadings((j):length(madReadings)) = [];%delete empty array items\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/31319-stability-analyzer-53230a/Stability Analyzer 2.0/removeOLMADx5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7282944728329142}} {"text": "function mi = BF_MutualInformation(v1,v2,r1,r2,numBins)\n% BF_MutualInformation Mutual information between two data vectors using bin counting.\n%\n% Mutual information computed using a histogram-based, bin-counting method.\n%\n%---INPUTS:\n% v1, the first input vector\n% v2, the second input vector\n% r1, the bin-partitioning method for the first input vector, v1\n% r2, the bin-partitioning method for the second input vector, v2\n% numBins, the number of bins to partition each vector into.\n%\n% NB: r1 and r2 can also be two-component vectors, that specify a custom range\n% for binning\n%\n%---OUTPUT:\n% mi, the mutual information computed between v1 and v2\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 and set defaults:\n% ------------------------------------------------------------------------------\n% by default, take a range equal to the range of the vectors\nif nargin < 3 || isempty(r1)\n r1 = 'range';\nend\nif nargin < 4 || isempty(r2)\n r2 = 'range';\nend\n% use 10 bins for the histograms (=100 bins in 2d)\nif nargin < 5 || isempty(numBins)\n numBins = 10;\nend\n% ------------------------------------------------------------------------------\n\nif length(v1) ~= length(v2)\n error('input vectors must be the same length');\nend\n\nN = length(v1); % length of vectors\n\n% Make sure both column vectors\nif size(v1,2) > size(v1,1), v1 = v1'; end\nif size(v2,2) > size(v2,1), v2 = v2'; end\n\n% Create histograms:\n% (i) in v1\nedgesi = SUB_GiveMeEdges(r1,v1,numBins);\n[ni, bini] = histc(v1, edgesi);\n\n% (ii) in v2\nedgesj = SUB_GiveMeEdges(r2,v2,numBins);\n[nj, binj] = histc(v2, edgesj);\n\n% ------------------------------------------------------------------------------\n%% Create a joint histogram:\n% ------------------------------------------------------------------------------\n\n% We have the edges in each dimension: edgesi, and edgesj\nhistxy = zeros(numBins);\nfor i2 = 1:numBins\n for j2 = 1:numBins\n histxy(i2,j2) = sum(bini==i2 & binj==j2);\n end\nend\n\n% Normalize counts to probabilities\np_i = ni(1:numBins)/N;\np_j = nj(1:numBins)/N;\np_ij = histxy/N;\np_ixp_j = p_i*p_j';\nsumme = (p_ixp_j > 0 & p_ij > 0);\n\n% Do a matrix-sum mutual information calculation:\nif any(summe(:) == 1)\n mi = sum(p_ij(summe).*log(p_ij(summe)./p_ixp_j(summe)));\nelse\n fprintf(1,['The histograms aren''t catching any points?? ' ...\n 'Perhaps due to an inappropriate custom range for binning the data...\\n']);\n mi = NaN; return\nend\n\n% ------------------------------------------------------------------------------\n% ------------------------------------------------------------------------------\nfunction edges = SUB_GiveMeEdges(r,v,nbins)\n EE = 1E-6; % this small addition gets lost in the last bin\n if strcmp(r,'range')\n edges = linspace(min(v),max(v)+EE,nbins+1);\n\n elseif strcmp(r,'quantile') % bin edges based on quantiles\n edges = quantile(v,linspace(0,1,nbins+1));\n% edges(1) = edges(1) - 0.1;\n edges(end) = edges(end) + EE;\n% edges = sort(unique(edges)); % in case you have many repeated values -- will bias MI calculation\n elseif length(r)==2 % a two-component vector\n edges = linspace(r(1),r(2)+EE,nbins+1);\n else\n error('Unknown partitioning method ''%s''',r);\n end\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/PeripheryFunctions/BF_MutualInformation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7282944728329142}} {"text": "function cdf = burr_cdf ( x, a, b, c, d )\n\n%*****************************************************************************80\n%\n%% BURR_CDF evaluates the Burr CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the CDF.\n%\n% Input, real A, B, C, D, the parameters of the PDF.\n% 0 < B,\n% 0 < C.\n%\n% Output, real CDF, the value of the CDF.\n%\n if ( x <= a )\n\n cdf = 0.0;\n\n else\n\n cdf = 1.0 / ( 1.0 + ( b / ( x - a ) )^c )^d;\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/burr_cdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7282944668416262}} {"text": "% fits quadratic to y = f(x) and outputs yq = f(xq)\n% x = nsamps x 1\n% y = nsamps x nt\n% xq = nsampsq x 1\n% yq = nsampsq x nt\nfunction yq = fitQuad(x,y,xq)\n\nX = [ones(numel(x),1) x x.^2];\nXT = (X'*X)\\X';\n\na = XT * y;\n\nXQ = [ones(numel(xq),1) xq xq.^2];\nyq = XQ * a;", "meta": {"author": "cortex-lab", "repo": "Suite2P", "sha": "c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5", "save_path": "github-repos/MATLAB/cortex-lab-Suite2P", "path": "github-repos/MATLAB/cortex-lab-Suite2P/Suite2P-c6a8ea9f01ffc8555429978e7fe97f843ad5b6d5/utils/fitQuad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9504109798251322, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7282938921590971}} {"text": "function B = barycentric_coordinates(P,varargin)\n % BARYCENTRIC_COORDINATES Computes barycentric coordinates of point p in\n % simplex (v1,v2,v3)\n % \n % B = barycentric_coordinates(P,V1,V2,V3, ...)\n %\n % Inputs:\n % P #P by dim list of query point locations\n % V1 #P by dim list of simplex corner locations\n % V2 #P by dim list of simplex corner locations\n % ...\n % Outputs:\n % B #P by dim+1 list of barycentric coordinates\n %\n\n % SHOULD BE USING VARGIN TO ACCEPT ARBITRARY DIMENSION INPUT\n for varg = varargin\n assert(size(P,1) == size(varg{1},1), 'All inputs should be same length');\n assert(size(P,2) == size(varg{1},2), 'All inputs should be same dimension');\n end\n\n function v = volume(ad,bd,cd)\n r =[bd(:,2).*cd(:,3)-bd(:,3).*cd(:,2), ...\n bd(:,3).*cd(:,1)-bd(:,1).*cd(:,3), ...\n bd(:,1).*cd(:,2)-bd(:,2).*cd(:,1)];\n v = -sum(ad.*r,2)./6;\n end\n\n n = size(P,1);\n switch numel(varargin)\n case 4\n V1 = varargin{1};\n V2 = varargin{2};\n V3 = varargin{3};\n V4 = varargin{4};\n V1P = V1-P;\n V2P = V2-P;\n V3P = V3-P;\n V4P = V4-P;\n %T = bsxfun(@plus,(1:n)',(0:3)*n);\n A1 = volume(V2P,V4P,V3P);\n A2 = volume(V1P,V3P,V4P);\n A3 = volume(V1P,V4P,V2P);\n A4 = volume(V1P,V2P,V3P);\n A = volume(V1-V4,V2-V4,V3-V4);\n if size(P,2)>3 && max(abs(sum([A1 A2 A3 A4],2)-A))>1e-14\n warning('Possibly negative coordinates. Not supported in dim~=3');\n end\n B = bsxfun(@rdivide,[A1 A2 A3 A4],A);\n case 3\n V1 = varargin{1};\n V2 = varargin{2};\n V3 = varargin{3};\n A1 = doublearea([ P;V2;V3],[1:n;n+[1:n;n+(1:n)]]');\n A2 = doublearea([V1; P;V3],[1:n;n+[1:n;n+(1:n)]]');\n A3 = doublearea([V1;V2; P],[1:n;n+[1:n;n+(1:n)]]');\n A = doublearea([V1;V2;V3],[1:n;n+[1:n;n+(1:n)]]');\n if size(P,2)>2 && max(abs(sum([A1 A2 A3],2)-A))>1e-14\n warning('Possibly negative coordinates. Not supported in dim~=2');\n end\n B = bsxfun(@rdivide,[A1 A2 A3],A);\n case 2\n V1 = varargin{1};\n V2 = varargin{2};\n A1 = edge_lengths([P;V2],[1:n;n+[1:n]]');\n A2 = edge_lengths([V1;P],[1:n;n+[1:n]]');\n A = edge_lengths([V1;V2],[1:n;n+[1:n]]');\n if size(P,2)>1 && max(abs(sum([A1 A2],2)-A))>1e-14\n warning('Possibly negative coordinates. Not supported in dim~=1');\n end\n B = bsxfun(@rdivide,[A1 A2],A);\n otherwise\n error(sprintf('%d-simplices not supported',numel(varargin)));\n end\nend\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_gptoolbox/mesh/barycentric_coordinates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7282938867774856}} {"text": "% Kernel Normalized Least-Mean-Square algorithm with Coherence Criterion\n%\n% C. Richard, J.C.M. Bermudez, and P. Honeine, \"Online Prediction of Time\n% Series Data With Kernels,\" IEEE Transactions on Signal Processing,\n% vol. 57, no. 3, pp. 1058-1067, March 2009,\n% http://dx.doi.org/10.1109/TSP.2008.2009895\n%\n% Remark: memories are initialized empty in this implementation\n%\n% This file is part of the Kernel Adaptive Filtering Toolbox for Matlab.\n% https://github.com/steven2358/kafbox/\n\nclassdef knlms < kernel_adaptive_filter\n \n properties (GetAccess = 'public', SetAccess = 'private') % parameters\n eta = .5; % step size\n mu0 = .95; % coherence criterion threshold\n eps = 1E-2; % regularization\n kerneltype = 'gauss'; % kernel type\n kernelpar = 1; % kernel parameter\n end\n \n properties (GetAccess = 'public', SetAccess = 'private') % variables\n dict = []; % dictionary\n modict = []; % modulus of the dictionary elements\n alpha = []; % expansion coefficients\n end\n \n methods\n function kaf = knlms(parameters) % constructor\n if (nargin > 0) % copy valid parameters\n for fn = fieldnames(parameters)'\n if ismember(fn,fieldnames(kaf))\n kaf.(fn{1}) = parameters.(fn{1});\n end\n end\n end\n end\n \n function y_est = evaluate(kaf,x) % evaluate the algorithm\n if size(kaf.dict,1)>0\n k = kernel(kaf.dict,x,kaf.kerneltype,kaf.kernelpar);\n y_est = k'*kaf.alpha;\n else\n y_est = zeros(size(x,1),1);\n end\n end\n \n function train(kaf,x,y) % train the algorithm\n if size(kaf.dict,2)==0 % initialize\n k = kernel(x,x,kaf.kerneltype,kaf.kernelpar);\n kaf.dict = x;\n kaf.modict = sqrt(k);\n kaf.alpha = 0;\n else\n k = kernel(kaf.dict,x,kaf.kerneltype,kaf.kernelpar);\n kx = kernel(x,x,kaf.kerneltype,kaf.kernelpar);\n C = k./(sqrt(kx)*kaf.modict); % coherence\n if (max(C) <= kaf.mu0) % coherence criterion\n kaf.dict = [kaf.dict; x]; % order increase\n kaf.modict = [kaf.modict; sqrt(kx)];\n kaf.alpha = [kaf.alpha; 0]; % reserve spot\n end\n end\n \n k = kernel(kaf.dict,x,kaf.kerneltype,kaf.kernelpar);\n kaf.alpha = kaf.alpha + ... % update coefficients \n kaf.eta / (kaf.eps + k'*k) * (y - k'*kaf.alpha) * k;\n end\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/knlms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7282663490120481}} {"text": "function [a,t]=v_rotqr2ax(q)\n%V_ROTQR2AX converts a real quaternion to the corresponding rotation axis and angle\n% Inputs: \n%\n% Q(4,1) real-valued quaternion (with magnitude = 1)\n%\n% Outputs:\n%\n% A(3,1) Unit vector in the direction of the rotation axis.\n% T Rotation angle in radians (in range 0 to 2pi)\n%\n% In the quaternion representation of a rotation, and q(1) = cos(t/2) \n% where t is the angle of rotation in the range 0 to 2pi\n% and q(2:4)/sin(t/2) is a unit vector lying along the axis of rotation\n% a positive rotation about [0 0 1] takes the X axis towards the Y axis.\n% \n% Copyright (C) Mike Brookes 2007-2018\n% Version: $Id: v_rotqr2ax.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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\na=q(2:4);\nm=sqrt(a'*a);\nt=2*atan2(m,q(1)); % avoids problems if unnormalized\nif m>0\n a=a/m;\nelse\n a=[0 0 1]';\nend\nif ~nargout\n v_rotqr2ro(q); % plot a rotated cube\nend\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_rotqr2ax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7282548578059805}} {"text": "function value = r4_normal_01_cdf_inverse ( p )\n\n%*****************************************************************************80\n%\n%% R4_NORMAL_01_CDF_INVERSE inverts the standard normal CDF.\n%\n% Discussion:\n%\n% The result is accurate to about 1 part in 10**7.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 December 2004\n%\n% Author:\n%\n% Original FORTRAN77 version by Michael Wichura.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Michael Wichura,\n% The Percentage Points of the Normal Distribution,\n% Algorithm AS 241,\n% Applied Statistics,\n% Volume 37, Number 3, pages 477-484, 1988.\n%\n% Parameters:\n%\n% Input, real P, the value of the cumulative probability densitity function.\n% 0 < P < 1. If P is not in this range, an \"infinite\" value is returned.\n%\n% Output, real VALUE, the normal deviate value with the property that\n% the probability of a standard normal deviate being less than or\n% equal to the value is P.\n%\n a = [ 3.3871327179, 50.434271938, 159.29113202, 59.109374720 ]; \n b = [ 1.0, 17.895169469, 78.757757664, 67.187563600 ];\n c = [ 1.4234372777, 2.7568153900, 1.3067284816, 0.17023821103 ];\n const1 = 0.180625;\n const2 = 1.6;\n d = [ 1.0, 0.73700164250, 0.12021132975 ];\n e = [ 6.6579051150, 3.0812263860, 0.42868294337, 0.017337203997 ];\n f = [ 1.0, 0.24197894225, 0.012258202635 ];\n split1 = 0.425;\n split2 = 5.0;\n\n if ( p <= 0.0 )\n value = -r4_huge ( );\n return\n end\n\n if ( 1.0 <= p )\n value = r4_huge ( );\n return\n end \n\n q = p - 0.5;\n\n if ( abs ( q ) <= split1 )\n\n r = const1 - q * q;\n value = q * r4poly_value ( 4, a, r ) / r4poly_value ( 4, b, r );\n\n else\n\n if ( q < 0.0 )\n r = p;\n else\n r = 1.0 - p;\n end\n\n if ( r <= 0.0 )\n value = -1.0;\n error ( 'R4_NORMAL_CDF_INVERSE - Fatal error!' );\n end\n\n r = sqrt ( -log ( r ) );\n\n if ( r <= split2 )\n\n r = r - const2;\n\n value = r4poly_value ( 4, c, r ) / r4poly_value ( 3, d, r );\n\n else\n\n r = r - split2;\n\n value = r4poly_value ( 4, e, r ) / r4poly_value ( 3, f, r );\n\n end\n\n if ( q < 0.0 )\n value = -value;\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/asa241/r4_normal_01_cdf_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.7282548382078128}} {"text": "function [q] = rotMatToQuat(R)\n\n[r,c] = size( R );\nR=R';\n\nif( r ~= 3 | c ~= 3 )\n fprintf( 'R must be a 3x3 matrix\\n\\r' );\n return;\nend\n\nRxx = R(1,1); Rxy = R(1,2); Rxz = R(1,3);\nRyx = R(2,1); Ryy = R(2,2); Ryz = R(2,3);\nRzx = R(3,1); Rzy = R(3,2); Rzz = R(3,3);\n\nw = sqrt( trace( R ) + 1 ) / 2;\n\n% check if w is real. Otherwise, zero it.\nif( imag( w ) > 0 )\n w = 0;\nend\n\nx = sqrt( 1 + Rxx - Ryy - Rzz ) / 2;\ny = sqrt( 1 + Ryy - Rxx - Rzz ) / 2;\nz = sqrt( 1 + Rzz - Ryy - Rxx ) / 2;\n\n[~, i ] = max( [w,x,y,z] );\n\nif( i == 1 )\n x = ( Rzy - Ryz ) / (4*w);\n y = ( Rxz - Rzx ) / (4*w);\n z = ( Ryx - Rxy ) / (4*w);\nend\n\nif( i == 2 )\n w = ( Rzy - Ryz ) / (4*x);\n y = ( Rxy + Ryx ) / (4*x);\n z = ( Rzx + Rxz ) / (4*x);\nend\n\nif( i == 3 )\n w = ( Rxz - Rzx ) / (4*y);\n x = ( Rxy + Ryx ) / (4*y);\n z = ( Ryz + Rzy ) / (4*y);\nend\n\nif( i == 4 )\n w = ( Ryx - Rxy ) / (4*z);\n x = ( Rzx + Rxz ) / (4*z);\n y = ( Ryz + Rzy ) / (4*z);\nend\n\nq = [x; y; z; w];\n\nend", "meta": {"author": "yuzhou42", "repo": "MSCKF", "sha": "d95d90c85b24f27001bd0ecdce8739b6e602b6df", "save_path": "github-repos/MATLAB/yuzhou42-MSCKF", "path": "github-repos/MATLAB/yuzhou42-MSCKF/MSCKF-d95d90c85b24f27001bd0ecdce8739b6e602b6df/msckf/utils/rotMatToQuat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.7282347693351058}} {"text": "function value = givens_determinant ( n )\n\n%*****************************************************************************80\n%\n%% GIVENS_DETERMINANT returns the determinant of the GIVENS matrix.\n%\n% Discussion:\n%\n% Since a formula for the eigenvalues is known, we compute the\n% determinant as the product of those values.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real VALUE, the determinant.\n%\n value = 1.0;\n\n for i = 1 : n\n angle = ( 2 * i - 1 ) * pi / ( 4 * n );\n value = value * 0.5 / ( cos ( angle ) )^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/givens_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7281653396012168}} {"text": "function determ = conference_determinant ( n )\n\n%*****************************************************************************80\n%\n%% CONFERENCE_DETERMINANT returns the determinant of the CONFERENCE 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 N, the order of the matrix. N-1 must be an odd prime,\n% or a power of an odd prime.\n%\n% Output, real DETERM, the determinant.\n%\n if ( mod ( n - 1, 4 ) == 1 )\n determ = - sqrt ( ( n - 1 )^n );\n else\n determ = + sqrt ( ( 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/test_mat/conference_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7281653287867716}} {"text": "%LAPLACIAN_PERRINX Compute surface Laplacian of EEG data.\n% [surf_lap,G,H] = laplacian_perrinX(data,x,y,z[,leg_order,smoothing]);\n% \n% INPUTS : \n% data : EEG data (can be N-D, but first dimension must be electrodes)\n% x,y,z : x,y,z coordinates of electrode positions (e.g., [EEG.chanlocs.X])\n%\n% (optional inputs)\n% leg_order : order of Legendre polynomial (default is 20 [40 for >100 electrodes])\n% smoothing : G smoothing parameter (lambda), set to 1e-5 by default\n%\n%\n% OUTPUTS :\n% surf_lap : the surface Laplacian (second spatial derivative)\n% (optional outputs)\n% G,H : G and H matrices\n% \n% This is an implementation of algorithms described by \n% Perrin, Pernier, Bertrand, and Echallier (1989). PubMed #2464490\n\n% mikexcohen@gmail.com\n\nfunction [surf_lap,G,H] = laplacian_perrinX(data,x,y,z,varargin) % vararg order: leg_order,smoothing\n\nnumelectrodes = numel(x);\n\nif nargin<4\n help laplacian_perrinX\n error('Read help file!')\nend\n\n%% compute G and H matrices\n\n% initialize\nG=zeros(numelectrodes);\nH=zeros(numelectrodes);\ncosdist=zeros(numelectrodes);\n\n% default parameters for +/- 100 electrodes\nif numelectrodes>100\n m=3; leg_order=40;\nelse\n m=4; leg_order=20;\nend\n\nif numel(varargin)>0 && ~isempty(varargin{1})\n leg_order=varargin{1};\nend\n\n% scale XYZ coordinates to unit sphere\n[junk,junk,spherical_radii] = cart2sph(x,y,z);\nmaxrad = max(spherical_radii);\nx = x./maxrad;\ny = y./maxrad;\nz = z./maxrad;\n\nfor i=1:numelectrodes\n for j=i+1:numelectrodes\n cosdist(i,j) = 1 - (( (x(i)-x(j))^2 + (y(i)-y(j))^2 + (z(i)-z(j))^2 ) / 2 );\n end\nend\ncosdist = cosdist+cosdist' + eye(numelectrodes);\n\n\n% compute Legendre polynomial\nlegpoly = zeros(leg_order,numelectrodes,numelectrodes);\nfor ni=1:leg_order\n temp = legendre(ni,cosdist);\n legpoly(ni,:,:) = temp(1,:,:);\nend\n\n% precompute electrode-independent variables\ntwoN1 = 2*(1:leg_order)+1;\ngdenom = ((1:leg_order).*((1:leg_order)+1)).^m;\nhdenom = ((1:leg_order).*((1:leg_order)+1)).^(m-1);\n\nfor i=1:numelectrodes\n for j=i:numelectrodes\n \n g=0; h=0;\n \n for ni=1:leg_order\n % compute G and H terms\n g = g + (twoN1(ni)*legpoly(ni,i,j)) / gdenom(ni);\n h = h - (twoN1(ni)*legpoly(ni,i,j)) / hdenom(ni);\n end\n G(i,j) = g/(4*pi);\n H(i,j) = -h/(4*pi);\n end\nend\n\n% mirror matrix\nG=G+G'; H=H+H';\n\n% correct for diagonal-double\nG = G-eye(numelectrodes)*G(1)/2;\nH = H-eye(numelectrodes)*H(1)/2;\n\n%% compute laplacian\n\n% reshape data to electrodes X time/trials\norig_data_size = squeeze(size(data));\nif any(orig_data_size==1)\n data=data(:);\nelse\n data = reshape(data,orig_data_size(1),prod(orig_data_size(2:end)));\nend\n\n% smoothing constant\nif numel(varargin)==2\n smoothing=varargin{2};\nelse\n smoothing=1e-5;\nend\n\n% add smoothing constant to diagonal \n% (change G so output is unadulterated)\nGs = G + eye(numelectrodes)*smoothing;\n\n% compute C matrix\nGsinvS = sum(inv(Gs));\ndataGs = data'/Gs;\nC = dataGs - (sum(dataGs,2)/sum(GsinvS))*GsinvS;\n\n% compute surface Laplacian (and reshape to original data size)\nsurf_lap = reshape((C*H')',orig_data_size);\n\n%% end\n", "meta": {"author": "mikexcohen", "repo": "AnalyzingNeuralTimeSeries", "sha": "e97c2e97f73c77dad1a258338e7ab94c78f515dd", "save_path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries", "path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries/AnalyzingNeuralTimeSeries-e97c2e97f73c77dad1a258338e7ab94c78f515dd/laplacian_perrinX.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7281601787001025}} {"text": " \t% Stergerea spatiul de lucru si a figurii curente\n\tclear; clf;\t\n\t\t\t% Introducerea punctelor definite\n\t\t\t% -\tvectorul x cu abscisele punctelor\n\tx=0:5;\t\t\t\n % -\tvectorul y cu ordonatele punctelor\n\ty=[0 0.5 4.5 0 2 0];\t\n\t\t\t% Generarea vectorului xx cu pasul fin\n\txx=0:0.1:5;\n % Reprezentarea grafica cu subplot-uri\n\th=subplot(2,2,1)\n % Precizarea positiei si marimii celulei de figura\n set(h,'position',[0.05,0.55,0.4,0.4])\n % Se reprezinta cu *-uri negre punctele date\n\tplot(x,y,'ko');\n\thold on\n\t\t % Interpolarea liniara\n % si reprezentarea functiilor obtinute\n\tyy=interp1(x,y,xx,'linear');\n\tplot(xx,yy,'r','LineWidth',1.5);\n % Personalizrea reprezentarii grafice\n\tgrid on;\n\ttitle('LINEAR');\t\n\t\n\t\t % Interpolarea de tip nearest\n\th=subplot(2,2,2)\n\tset(h,'position',[0.5,0.55,0.4,0.4])\n plot(x,y,'ko');\n\thold on\n\tyy=interp1(x,y,xx,'nearest');\n\tplot(xx,yy,'g','LineWidth',1.5);\n\tgrid on;\n\ttitle('NEAREST');\t\n \n\t\t\t% Interpolarea de tip spline\n\th=subplot(2,2,3)\n set(h,'position',[0.05,0.05,0.4,0.4])\n \tplot(x,y,'ko');\n\thold on\n\tyy=interp1(x,y,xx,'spline');\n\tplot(xx,yy,'m','LineWidth',1.5);\n\tgrid on;\n\ttitle('SPLINE')\n\t\n % Interpolarea de tip cubic\n\th=subplot(2,2,4)\n set(h,'position',[0.5,0.05,0.4,0.4])\n plot(x,y,'ko');\n\thold on\n\tyy=interp1(x,y,xx,'cubic');\n\tplot(xx,yy,'b','LineWidth',1.5);\n\tgrid on;\n\ttitle('CUBIC')", "meta": {"author": "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/8/Ex_8_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357702, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7281601780452523}} {"text": "function [J, grad] = linearRegCostFunction(X, y, theta, lambda)\n%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear \n%regression with multiple variables\n% [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the \n% cost of using theta as the parameter for linear regression to fit the \n% data points in X and y. Returns the cost in J and the gradient in grad\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost and gradient of regularized linear \n% regression for a particular choice of theta.\n%\n% You should set J to the cost and grad to the gradient.\n%\ntempTheta = theta;\ntempTheta(1) = 0;\n\nJ = (1 / (2*m) ) * sum(((X * theta)-y).^2) + (lambda / (2 * m))*sum(tempTheta.^2);\ntemp = X * theta;\nerror = temp - y;\ngrad = (1 / m) * (X' * error) + (lambda/m)*tempTheta;\n\n\n\n\n\n\n\n\n% =========================================================================\n\ngrad = grad(:);\n\nend\n", "meta": {"author": "AvaisP", "repo": "machine-learning-programming-assignments-coursera-andrew-ng", "sha": "45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf", "save_path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng", "path": "github-repos/MATLAB/AvaisP-machine-learning-programming-assignments-coursera-andrew-ng/machine-learning-programming-assignments-coursera-andrew-ng-45268fc67ee60f65c2e07dbc7a2ef7c45f0d4ecf/machine-learning-ex5/ex5/linearRegCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7281601688229742}} {"text": "\ndisp('Fitting AR model to AR-5 process data with known coefficients');\n\nsecs=5;\nns=128;\nt=[1/ns:1/ns:secs];\nN=length(t);\nnoise_var=1^2;\nnoise=sqrt(noise_var)*randn(1,N);\na_true=[-1.8517,1.3741,0.1421,-0.6852,0.3506];\ny=filter(1,[1,a_true],noise);\ny=y(1:N);\nfigure\nplot(t,y);\nxlabel('Seconds');\ntitle('Sample of AR-5 process');\n\ntotal_variance=std(y)^2;\nsignal_variance=total_variance-noise_var;\nsnr=sqrt(signal_variance)/sqrt(noise_var);\ndisp(sprintf('SNR=%1.3f',snr));\n\ndisp('For model order p=5');\nar=spm_ar (y,5);\n\ndisp(' ');\ndisp('True coefficients');\ndisp(a_true);\n\ndisp(' ');\ndisp('Estimated coefficients');\ndisp(ar.a_mean');\n\n\nfor p=1:10,\n disp(sprintf('Now fitting model with p=%d coefficients',p));\n ar=spm_ar (y,p,0);\n logev(p)=ar.fm;\nend\nlogev=logev-min(logev);\nfigure\nbar(logev);\nylabel('Log Evidence');\nxlabel('Model order');", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/spectral/spm_ar_demo_coeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7281565821731617}} {"text": "function [fittedCircle, circleNormal] = fitCircle3d(pts)\n%FITCIRCLE3D Fit a 3D circle to a set of points.\n%\n% [FITTEDCIRCLE, CIRCLENORMAL] = fitCircle3d(PTS)\n%\n% Example\n% % points on a 2d circle with noise\n% nop = randi([5 50],1,1);\n% radius = randi([5 25],1,1);\n% points2d = circleToPolygon([0 0 radius], nop);\n% points2d(1,:) = [];\n% points2d = points2d + rand(size(points2d));\n% points2d(:,3)=rand(length(nop),1);\n% % apply random rotation and translation\n% [theta, phi] = randomAngle3d;\n% theta = rad2deg(theta);\n% phi = rad2deg(phi);\n% tfm = eulerAnglesToRotation3d(phi, theta, 0);\n% trans = randi([-250 250],3,1);\n% tfm(1:3,4)=trans;\n% points3d = awgn(transformPoint3d(points2d, tfm),1);\n% % fit 3d circle\n% [fittedCircle, circleNormal] = fitCircle3d(points3d);\n% % plot 3d points and 3d circle\n% figure('Color','w'); hold on; axis equal tight; view(3);\n% xlabel('X');ylabel('Y');zlabel('Z');\n% drawPoint3d(points3d)\n% drawCircle3d(fittedCircle, 'k')\n% drawVector3d(fittedCircle(1:3), circleNormal*fittedCircle(4))\n%\n% See also\n% circle3dOrigin, circle3dPosition, circle3dPoint, intersectPlaneSphere\n% drawCircle3d, drawCircleArc3d, drawEllipse3d\n%\n% ------\n% Authors: oqilipo, David Legland\n% created: 2017-05-09\n\n% Mean of all points\nmeanPoint = mean(pts,1);\n\n% Center points by subtracting the meanPoint\ncenteredPoints = pts - repmat(meanPoint,size(pts,1),1);\n\n% Project 3D data to a plane\n[~,~,V]=svd(centeredPoints);\ntfmPoints = transformPoint3d(centeredPoints, V');\n\n% Fit a circle to the points in the xy-plane\ncircleParamter = CircleFitByTaubin(tfmPoints(:,1:2));\ncenter2d = circleParamter(1:2); \nradius=circleParamter(3);\ncenter3d = transformPoint3d([center2d, 0], [inv(V'), meanPoint']);\ncircleNormal = V(:,3)';\n[theta, phi, ~] = cart2sph2(circleNormal);\nfittedCircle = [center3d radius rad2deg(theta) rad2deg(phi) 0];\n\nend\n\n% Circle Fit (Taubin method)\n% version 1.0 (2.24 KB) by Nikolai Chernov\n% http://www.mathworks.com/matlabcentral/fileexchange/22678\nfunction Par = CircleFitByTaubin(XY)\n\n%--------------------------------------------------------------------------\n% \n% Circle fit by Taubin\n% G. Taubin, \"Estimation Of Planar Curves, Surfaces And Nonplanar\n% Space Curves Defined By Implicit Equations, With \n% Applications To Edge And Range Image Segmentation\",\n% IEEE Trans. PAMI, Vol. 13, pages 1115-1138, (1991)\n%\n% Input: XY(n,2) is the array of coordinates of n points x(i)=XY(i,1), y(i)=XY(i,2)\n%\n% Output: Par = [a b R] is the fitting circle:\n% center (a,b) and radius R\n%\n% Note: this fit does not use built-in matrix functions (except \"mean\"),\n% so it can be easily programmed in any programming language\n%\n%--------------------------------------------------------------------------\n\nn = size(XY,1); % number of data points\n\ncentroid = mean(XY); % the centroid of the data set\n\n% computing moments (note: all moments will be normed, i.e. divided by n)\n\nMxx = 0; Myy = 0; Mxy = 0; Mxz = 0; Myz = 0; Mzz = 0;\n\nfor i=1:n\n Xi = XY(i,1) - centroid(1); % centering data\n Yi = XY(i,2) - centroid(2); % centering data\n Zi = Xi*Xi + Yi*Yi;\n Mxy = Mxy + Xi*Yi;\n Mxx = Mxx + Xi*Xi;\n Myy = Myy + Yi*Yi;\n Mxz = Mxz + Xi*Zi;\n Myz = Myz + Yi*Zi;\n Mzz = Mzz + Zi*Zi;\nend\n\nMxx = Mxx/n;\nMyy = Myy/n;\nMxy = Mxy/n;\nMxz = Mxz/n;\nMyz = Myz/n;\nMzz = Mzz/n;\n\n% computing the coefficients of the characteristic polynomial\n\nMz = Mxx + Myy;\nCov_xy = Mxx*Myy - Mxy*Mxy;\nA3 = 4*Mz;\nA2 = -3*Mz*Mz - Mzz;\nA1 = Mzz*Mz + 4*Cov_xy*Mz - Mxz*Mxz - Myz*Myz - Mz*Mz*Mz;\nA0 = Mxz*Mxz*Myy + Myz*Myz*Mxx - Mzz*Cov_xy - 2*Mxz*Myz*Mxy + Mz*Mz*Cov_xy;\nA22 = A2 + A2;\nA33 = A3 + A3 + A3;\n\nxnew = 0;\nynew = 1e+20;\nepsilon = 1e-12;\nIterMax = 20;\n\n% Newton's method starting at x=0\n\nfor iter=1:IterMax\n yold = ynew;\n ynew = A0 + xnew*(A1 + xnew*(A2 + xnew*A3));\n if abs(ynew) > abs(yold)\n disp('Newton-Taubin goes wrong direction: |ynew| > |yold|');\n xnew = 0;\n break;\n end\n Dy = A1 + xnew*(A22 + xnew*A33);\n xold = xnew;\n xnew = xold - ynew/Dy;\n if (abs((xnew-xold)/xnew) < epsilon), break, end\n if (iter >= IterMax)\n disp('Newton-Taubin will not converge');\n xnew = 0;\n end\n if (xnew<0.)\n fprintf(1,'Newton-Taubin negative root: x=%f\\n',xnew);\n xnew = 0;\n end\nend\n\n% computing the circle parameters\n\nDET = xnew*xnew - xnew*Mz + Cov_xy;\nCenter = [Mxz*(Myy-xnew)-Myz*Mxy , Myz*(Mxx-xnew)-Mxz*Mxy]/DET/2;\n\nPar = [Center+centroid , sqrt(Center*Center'+Mz)];\n\nend % CircleFitByTaubin\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/fitCircle3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7281565807964148}} {"text": "function stats = optMyopic(returns, gamma, rf, accuracy)\n%OPTMYOPIC: Calculate the optimal portfolio weight through the Myopic\n%strategy or alternatively the Buy-and-Hold strategy\n%\n% STATS = OPTMYOPIC(returns, ...) retrieves the optimal portfolio weight\n% using the myopic strategy. A grid search is used, based on the input\n% variable 'returns'. At any grid point, the conditional expectation is\n% calculated. In the end, the portfolio weight with the highest\n% conditional expectation is selected.\n% Alternatively, one can use this function to calculate the optimal\n% portfolio with the buy-and-hold strategy. For an investor with\n% investment horizon of 'K' periods, define the cumulative returns over\n% the past 'K' periods and use K*rf instead of rf.\n%\n% Note that it is optimal to invest myopically when there are not state\n% variables and when the future states and returns are independent\n% (conditional on the state variables), in continuous time. Moreover,\n% long-term investors should invest myopically when returns are identical\n% and independent distributed.\n%\n% 'returns'\t: is a 'n-by-1' vector. One could use realized returns or\n% simulated path returns (see also example).\n%\n% The following assumptions are relevant: \n% - A tradeoff is made between the input 'returns' and the risk free rate 'rf'\n% \t- The input consists only of the (simulated) returns.\n% - Weights are restricted between 0 and 1.\n%\n% STATS = OPTMYOPIC(returns, 'gamma', ...) allows you to specify an own\n% risk aversion parameter 'gamma'.\n% 'gamma' : risk-aversion constant, initially set to 5.\n%\n% STATS = OPTMYOPIC(returns, gamma, 'rf', ...) allows you to specify the\n% risk free rate, relevant for your optimization problem.\n% 'rf' : the risk free rate constant, initial set to 0.\n%\n% STATS = OPTMYOPIC(returns, gamma, rf, 'accuracy') allows you to extend\n% the accuracy of the grid, initially set to 0.01.\n% 'accuracy': the single step length in the grid\n%\n% STATS = OPTMYOPIC(...) returns the structure 'stats' consisting of:\n% 'stats.optWeight' : the optimal portfolio weight (in risky asset)\n% 'stats.optCU' : optimal conditional expectation\n% \n% NB: - For three assets we need a two dimensional grid, which\n% leads appearantly to the curse of dimensionality. There are\n% methods that solve this problem, however such solutions are\n% beyond the scope of this code.\n%\n% Semin Ibisevic (2012)\n% $Date: 02/05/2012$\n%\n% -------------------------------------------------------------------------\n% References\n%\n% B.F. Diris. Portfolio Management. Econometric Institute, 2012. Lecture\n% FEM21010.\n% -------------------------------------------------------------------------\n\n[n, m] = size(returns);\nif m >= n, error('optMyopic:InvalidInput','The number of rows should be sufficiently larger than the number of columns'); end\nif m > 1, error('optMyopic:InvalidInput','The input should consist only of one column. Note: to calculate the portfolio weights using the Buy-and-Hold strategy, use cumulative returns over the past k periods instead.'); end\n\nif nargin < 1, error('optMyopic:InsufficientParameters','Input variable is necessary'); end\nif nargin < 2, gamma = 5; end % default risk aversion\nif nargin < 3, rf = 0; end % default risk free rate\nif nargin < 4, accuracy = 0.01; end \n\n% One-dimensional grid\ngrid = 0.00:accuracy:1.00;\n\n% init\nU = zeros(n,size(grid,2));\nCU = zeros(1,size(grid,2));\nCUopt = -10^(9);\ngridopt = 0;\n\n% -------------------------------------------------------------------------\n\n% pick portfolio weight from the grid\nwIter = 1;\nfor w = grid\n \n % define the realized utility value for all i = 1,...,n\n U(:,wIter) = (1/(1-gamma)) * ( w*exp( returns ) + (1-w)*exp( rf ) ).^(1-gamma);\n \n % approximate the conditional expected utlity for grid point w\n CU(wIter) = (1/n)*sum( U(:,wIter) );\n \n % update\n if CU(wIter) > CUopt\n CUopt = CU(wIter);\n gridopt = w;\n end\n \n wIter = wIter + 1;\n \nend\n\nstats.optWeight = gridopt;\nstats.optCU = CUopt;\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/35039-simple-portfolio-optimization-methods/optMyopic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7281565672818598}} {"text": "function [min_width, min_angle] = minimumCaliperDiameter(points)\n%MINIMUMCALIPERDIAMETER Minimum caliper diameter of a set of points\n%\n% WIDTH = minimumCaliperDiameter(POINTS)\n% Computes the minimum width of a set of points. As polygons and\n% polylines are represented as point lists, this function works also for\n% polygons and polylines.\n%\n% [WIDTH THETA] = minimumCaliperDiameter(POINTS)\n% Also returns the direction of minimum width. The direction corresponds\n% to the horizontal angle of the edge that minimizes the width. THETA is\n% given in radians, between 0 and PI.\n%\n%\n% Example\n% % Compute minimal caliper diameter, and check coords of rotated points\n% % have expected extent\n% points = randn(30, 2);\n% [width theta] = minimumCaliperDiameter(points);\n% points2 = transformPoint(points, createRotation(-theta));\n% diff = max(points2) - min(points2);\n% abs(width - diff(2)) < 1e-10\n% ans =\n% 1\n%\n% References\n% Algorithms use rotating caliper. Implementation was based on that of\n% Wikipedia:\n% http://en.wikipedia.org/wiki/Rotating_calipers\n%\n% See also\n% polygons2d, convexHull, orientedBox\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2011-04-08, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform.\n\n% first, compute convex hull of the polygon\ninds = convhull(points(:,1), points(:,2));\nhull = points(inds, :);\n\n% if first and last points are the same, remove the last one\nif inds(1) == inds(end)\n hull = hull(1:end-1, :);\nend\n\n% number of hull vertices\nnV = size(hull, 1);\n\n% default values\nrotated_angle = 0;\nmin_width = inf;\nmin_angle = 0;\n\n% avoid degenerated cases\nif nV < 3\n return;\nend\n\n[tmp, p_a] = min(hull(:, 2)); %#ok\n[tmp, p_b] = max(hull(:, 2)); %#ok\n\ncaliper_a = [ 1 0]; % Caliper A points along the positive x-axis\ncaliper_b = [-1 0]; % Caliper B points along the negative x-axis\n\nwhile rotated_angle < pi\n % compute the direction vectors corresponding to each edge\n ind_a2 = mod(p_a, nV) + 1;\n vector_a = hull(ind_a2, :) - hull(p_a, :);\n \n ind_b2 = mod(p_b, nV) + 1;\n vector_b = hull(ind_b2, :) - hull(p_b, :);\n \n % Determine the angle between each caliper and the next adjacent edge\n % in the polygon \n angle_a = vectorAngle(caliper_a, vector_a);\n angle_b = vectorAngle(caliper_b, vector_b);\n \n % Determine the smallest of these angles\n minAngle = min(angle_a, angle_b);\n \n % Rotate the calipers by the smallest angle\n caliper_a = rotateVector(caliper_a, minAngle);\n caliper_b = rotateVector(caliper_b, minAngle);\n \n rotated_angle = rotated_angle + minAngle;\n \n % compute current width, and update opposite vertex\n if angle_a < angle_b\n line = createLine(hull(p_a, :), hull(ind_a2, :));\n width = distancePointLine(hull(p_b, :), line);\n p_a = mod(p_a, nV) + 1;\n \n else\n line = createLine(hull(p_b, :), hull(ind_b2, :));\n width = distancePointLine(hull(p_a, :), line);\n p_b = mod(p_b, nV) + 1;\n\n end\n \n % update minimum width and corresponding angle if needed\n if width < min_width\n min_width = width;\n min_angle = rotated_angle;\n end\n\nend\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/polygons2d/minimumCaliperDiameter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7281565557059686}} {"text": "% calculate error between an ellipse and a point\n% expected input form : ellipse = [x0 y0 A B alpha], point = [x y]\nfunction error = calcEllipseCost(ellipse, point) \n\n% Initial setting\nx = point(2); y = point(1);\nx0 = ellipse(1); y0 = ellipse(2);\na = ellipse(4); b = ellipse(3);\nalpha = ellipse(5);\nQ = [cos(alpha), sin(alpha); -sin(alpha), cos(alpha)]; % inverse of rotation matrix\n\n% E(x',y') = abs(x'^2/a^2 + y'^2/b^2 - 1)\nv = Q*[x-x0;y-y0];\nv(1) = v(1)/a;\nv(2) = v(2)/b;\nerror = abs(1-v'*v);\n\nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/检测算法/Sushi-Dish-master/src/calcEllipseCost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475746920262, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7281166966791989}} {"text": "function [accepted, rejected] = fun_metropolis_hastings(param_init, iterations, data)\n\nx = param_init;\n\naccepted = [];\nrejected = [];\n\nfor i = 1:iterations\n x_new = fun_transition_model(x);\n x_lik = fun_log_likelihood(x, data);\n x_new_lik = fun_log_likelihood(x_new, data);\n \n if fun_acceptance(x_lik + log(fun_prior(x)), x_new_lik + log(fun_prior(x_new)))\n x = x_new;\n accepted = [accepted x_new(1)];\n else\n rejected = [rejected x_new(1)];\n end\nend", "meta": {"author": "angeloyeo", "repo": "gongdols", "sha": "7be9fbd988dec6edab1dc881cb22d63e6f69398d", "save_path": "github-repos/MATLAB/angeloyeo-gongdols", "path": "github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/통계학/MCMC/metropolis_hastings/Bayesian_estimation_with_MCMC/fun_metropolis_hastings.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475794701961, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7281166954163006}} {"text": "% COVARY - For vectors, covary(X) returns the variance of X.\n% For matrices, covary(X)is a row vector containing the\n% variance of each column of X.\n%\n% Notes: \n% covary(X) normalizes by N-1 where N is the sequence length. \n% This makes covary(X) the best unbiased estimate of the \n% covariance if X are from a normal distribution.\n% Does not require the Matlab Signal Processing Toolbox\n%\n% Author: Scott Makeig, SCCN/INC/UCSD, La Jolla, 2000 \n\n% Copyright (C) 2000 Scott Makeig, SCCN/INC/UCSD, scott@sccn.ucsd.edu\n%\n% This file is part of EEGLAB, see http://www.eeglab.org\n% for the documentation and details.\n%\n% Redistribution and use in source and binary forms, with or without\n% modification, are permitted provided that the following conditions are met:\n%\n% 1. Redistributions of source code must retain the above copyright notice,\n% this list of conditions and the following disclaimer.\n%\n% 2. Redistributions in binary form must reproduce the above copyright notice,\n% this list of conditions and the following disclaimer in the documentation\n% and/or other materials provided with the distribution.\n%\n% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n% THE POSSIBILITY OF SUCH DAMAGE.\n\n% 01-25-02 reformated help & license -ad \n\nfunction covout = covary(data)\n\ndata = data - mean(mean(data));\nif size(data,1) == 1\n data = data'; % make column vector\nend\ncovout = sum(data.*data)/(size(data,1)-1);\n\n\n", "meta": {"author": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/miscfunc/covary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7281166892360699}} {"text": "function [ rank, x ] = tuple_next ( m1, m2, n, rank, x )\n\n%*****************************************************************************80\n%\n%% TUPLE_NEXT computes the next element of a tuple space.\n%\n% Discussion:\n%\n% The elements are N vectors. Each entry is constrained to lie\n% between M1 and M2. The elements are produced one at a time.\n% The first element is\n% (M1,M1,...,M1),\n% the second element is\n% (M1,M1,...,M1+1),\n% and the last element is\n% (M2,M2,...,M2)\n% Intermediate elements are produced in lexicographic order.\n%\n% Example:\n%\n% N = 2, M1 = 1, M2 = 3\n%\n% INPUT OUTPUT\n% ------- -------\n% Rank X Rank X\n% ---- --- ----- ---\n% 0 * * 1 1 1\n% 1 1 1 2 1 2\n% 2 1 2 3 1 3\n% 3 1 3 4 2 1\n% 4 2 1 5 2 2\n% 5 2 2 6 2 3\n% 6 2 3 7 3 1\n% 7 3 1 8 3 2\n% 8 3 2 9 3 3\n% 9 3 3 0 0 0\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 M1, M2, the minimum and maximum entries.\n%\n% Input, integer N, the number of components.\n%\n% Input, integer RANK, counts the elements.\n% On first call, set RANK to 0. On subsequent calls, the input value of\n% RANK should be the output value of RANK from the previous call.\n%\n% Input, integer X(N), the previous tuple.\n%\n% Output, integer RANK, the order of the next tuple. When there are no\n% more elements, RANK will be returned as 0.\n%\n% Output, integer X(N,1), the next tuple.\n%\n if ( m2 < m1 )\n rank = 0;\n return\n end\n\n if ( rank <= 0 )\n\n x(1:n,1) = m1;\n rank = 1;\n\n else\n\n rank = rank + 1;\n i = n;\n\n while ( 1 )\n\n if ( x(i) < m2 )\n x(i) = x(i) + 1;\n break\n end\n\n x(i) = m1;\n\n if ( i == 1 )\n rank = 0;\n x(1:n) = m1;\n break\n end\n\n i = i - 1;\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/test_interp_nd/tuple_next.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8670357580842941, "lm_q1q2_score": 0.7280793772498321}} {"text": "%% Kruskal tensors\n% Kruskal format is a decomposition of a tensor X as the sum of the outer\n% products a the columns of matrices. For example, we might write\n% \n% $${\\mathcal X} = \\sum_r a_r \\circ b_r \\circ c_r$$\n% \n% where a subscript denotes column index and a circle denotes outer\n% product. In other words, the tensor X is built frm the columns of the\n% matrices A,B, and C. It's often helpful to explicitly specify a weight\n% for each outer product, which we do here:\n% \n% $${\\mathcal X} = \\sum_r \\lambda_r \\; a_r \\circ b_r \\circ c_r$$\n% \n% The |ktensor| class stores the components of the tensor X and can perform\n% many operations, e.g., |ttm|, without explicitly forming the tensor X. \n\n%% Kruskal tensor format via ktensor\n% Kruskal format stores a tensor as a sum of rank-1 outer products. For\n% example, consider a tensor of the following form.\n% \n% $$X = a_1 \\circ b_1 \\circ c_1 + a_2 \\circ b_2 \\circ c_2$$\n% \n% This can be stored in Kruskal form as follows.\nrand('state',0);\nA = rand(4,2); %<-- First column is a_1, second is a_2.\nB = rand(3,2); %<-- Likewise for B.\nC = rand(2,2); %<-- Likewise for C.\nX = ktensor({A,B,C}) %<-- Create the ktensor.\n%%\n% For Kruskal format, there can be any number of matrices, but every matrix\n% must have the same number of columns. The number of rows can vary.\nY = ktensor({rand(4,1),rand(2,1),rand(3,1)}) %<-- Another ktensor.\n%% Specifying weights in a ktensor\n% Weights for each rank-1 tensor can be specified by passing in a \n% column vector. For example, \n% \n% $$X = \\lambda_1 \\; a_1 \\circ b_1 \\circ c_1 + \\lambda_2 \\; a_2 \\circ b_2 \\circ c_2$$\n% \nlambda = [5.0; 0.25]; %<-- Weights for each factor.\nX = ktensor(lambda,{A,B,C}) %<-- Create the ktensor.\n%% Creating a one-dimensional ktensor\nY = ktensor({rand(4,5)}) %<-- A one-dimensional ktensor.\n%% Constituent parts of a ktensor\nX.lambda %<-- Weights or multipliers.\n%%\nX.U %<-- Cell array of matrices.\n%% Creating a ktensor from its constituent parts\nY = ktensor(X.lambda,X.U) %<-- Recreate X.\n%% Creating an empty ktensor\nZ = ktensor %<-- Empty ktensor.\n%% Use full or tensor to convert a ktensor to a tensor\nfull(X) %<-- Converts to a tensor. \n%% \ntensor(X) %<-- Same as above.\n%% Use double to convert a ktensor to a multidimensional array\ndouble(X) %<-- Converts to an array.\n%% Use tendiag or sptendiag to convert a ktensor to a ttensor.\n% A ktensor can be regarded as a ttensor with a diagonal core.\nR = length(X.lambda); %<-- Number of factors in X.\ncore = tendiag(X.lambda, repmat(R,1,ndims(X))); %<-- Create a diagonal core.\nY = ttensor(core, X.u) %<-- Assemble the ttensor.\n%%\nnorm(full(X)-full(Y)) %<-- They are the same.\n%% \ncore = sptendiag(X.lambda, repmat(R,1,ndims(X))); %<-- Sparse diagonal core.\nY = ttensor(core, X.u) %<-- Assemble the ttensor\n%%\nnorm(full(X)-full(Y)) %<-- They are the same.\n%% Use ndims and size for the dimensions of a ktensor\nndims(X) %<-- Number of dimensions.\n%%\nsize(X) %<-- Row vector of the sizes.\n%%\nsize(X,2) %<-- Size of the 2nd mode.\n%% Subscripted reference for a ktensor\nX(1,1,1) %<-- Assemble the (1,1,1) element (requires computation).\n%%\nX.lambda(2) %<-- Weight of 2nd factor.\n%%\nX.U{2} %<-- Extract a matrix.\n%%\nX{2} %<-- Same as above.\n%% Subscripted assignment for a ktensor\nX.lambda = ones(size(X.lambda)) %<-- Insert new multipliers.\n%%\nX.lambda(1) = 7 %<-- Change a single element of lambda.\n%%\nX{3}(1:2,1) = [1;1] %<-- Change the matrix for mode 3.\n%% Use end for the last array index.\nX(3:end,1,1) %<-- Calculated X(3,1,1) and X((4,1,1).\n%%\nX(1,1,1:end-1) %<-- Calculates X(1,1,1).\n%%\nX{end} %<-- Or use inside of curly braces. This is X{3}.\n%% Adding and subtracting ktensors\n% Adding two ktensors is the same as concatenating the matrices\nX = ktensor({rand(4,2),rand(2,2),rand(3,2)}) %<-- Data.\nY = ktensor({rand(4,2),rand(2,2),rand(3,2)}) %<-- More data.\n%%\nZ = X + Y %<-- Concatenates the factor matrices.\n%%\nZ = X - Y %<-- Concatenates as with plus, but changes the weights.\n%%\nnorm( full(Z) - (full(X)-full(Y)) ) %<-- Should be zero.\n%% Basic operations with a ktensor\n+X %<-- Calls uplus.\n%%\n-X %<-- Calls uminus.\n%%\n5*X %<-- Calls mtimes.\n%% Use permute to reorder the modes of a ktensor\npermute(X,[2 3 1]) %<-- Reorders modes of X\n%% Use arrange to normalize the factors of a ktensor\n% The function |arrange| normalizes the columns of the factors and then\n% arranges the rank-one pieces in decreasing order of size.\nX = ktensor({rand(3,2),rand(4,2),rand(2,2)}) % <-- Unit weights.\n%%\narrange(X) %<-- Normalized a rearranged.\n%% Use fixsigns for sign indeterminacies in a ktensor\n% The largest magnitude entry for each factor is changed to be\n% positive provided that we can flip the signs of _pairs_ of vectors in\n% that rank-1 component.\nY = X;\nY.u{1}(:,1) = -Y.u{1}(:,1); % switch the sign on a pair of columns\nY.u{2}(:,1) = -Y.u{2}(:,1)\n%%\nfixsigns(Y)\n%% Use ktensor to store the 'skinny' SVD of a matrix\nA = rand(4,3) %<-- A random matrix.\n%%\n[U,S,V] = svd(A,0); %<-- Compute the SVD.\nX = ktensor(diag(S),{U,V}) %<-- Store the SVD as a ktensor.\n%%\ndouble(X) %<-- Reassemble the original matrix.\n%% Displaying a ktensor\ndisp(X) %<-- Displays the vector lambda and each factor matrix.\n%% Displaying data\n% The |datadisp| function allows the user to associate meaning to the modes\n% and display those modes with the most meaning (i.e., corresponding to the\n% largest values). \nX = ktensor({[0.8 0.1 1e-10]',[1e-5 2 3 1e-4]',[0.5 0.5]'}); %<-- Create tensor.\nX = arrange(X) %<-- Normalize the factors.\n%%\nlabelsDim1 = {'one','two','three'}; %<-- Labels for mode 1.\nlabelsDim2 = {'A','B','C','D'}; %<-- Labels for mode 2.\nlabelsDim3 = {'on','off'}; %<-- Labels for mode 3.\ndatadisp(X,{labelsDim1,labelsDim2,labelsDim3}) %<-- Display.", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/libs/tensor_toolbox_2.5/doc/D_ktensor_doc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7280793763996793}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n% \n% \n% \n% problem 8- Use the Laplace Transform to solve the differential equation\n%\n% y'''(t)+y'(t)-2y(t)=dirac(t), y(0)=2, y'(0)=3 , y''(0)=1\n\n\nsyms t s Y\ny0=1;\nyd0=3; \ny2d0=1;\n\nx=dirac(t);\nX=laplace(x,s);\n\nY1=s*Y-y0;\nY2=s*Y1-yd0;\nY3=s*Y2-y2d0;\n\nG=Y3+Y1-2*Y-X;\nY=solve(G,Y);\n\ny=ilaplace(Y,t);\n\nezplot(y,[0 5])\nlegend('Solution y(t)')\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/9/c99g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7280694050409788}} {"text": "% I'm sure this one is not mine; I think it was Fran who wrote it.\n% Last checked: June 2021\n\nclc\n% define parameters\nc0 = 1;\n\n% define a 1D mesh\nL = 1;\nNr = 1000;\nmesh1 = createMeshSpherical1D(Nr, L);\nx = mesh1.cellcenters.x;\nxf = mesh1.facecenters.x;\n\n% define the boundaries\nBC = createBC(mesh1); % all Neumann\nBC.right.a=0;\nBC.right.b=1;\nBC.right.c=0;\n[Mbc, RHSbc] = boundaryCondition(BC);\n\n% define diffusion term\nD = createCellVariable(mesh1,1);\nDave = harmonicMean(D);\nMdiff = diffusionTermSpherical1D(Dave);\n\n% initial values\nc_old = createCellVariable(mesh1, c0);\nc = c_old;\n\n% solver\ndt = 1E-3;\nt = dt;\nN = 30;\n\nerr = 0;\ntvec = dt;\n\nit = 1;\n\nwhile t < 1\n % define the transient term\n [Mt, RHSt] = transientTerm(c_old, dt);\n \n % assemble the matrix and vector\n M = Mt-Mdiff+Mbc;\n RHS = RHSt+RHSbc;\n \n % solve PDE\n c = solvePDE(mesh1,M,RHS);\n c_old = c;\n \n % calculate analytic solution\n f = zeros(Nr,1);\n for n=1:N\n f = f + 2*(-1)^(n+1)/(n*pi)*exp(-(n*pi)^2*t)*sin(n*pi*x)./x;\n end\n \n tvec = [tvec; t];\n err = [err; trapz(x,(f-c.value(2:Nr+1)).^2)];\n \n if mod(it,10) == 0\n figure(1);\n plot(x, f, 'b', [0; x; 1], c.value,'ro'); \n title(sprintf('t=%.2e',t));\n xlabel('r')\n ylabel('c')\n legend('analytical','numerical')\n ylim([0,1]); \n drawnow;\n end\n t = t+dt;\n it = it + 1;\nend\n\nfigure(2)\nplot(tvec,sqrt(err))\nxlabel('t')\nylabel('absolute error')", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Examples/Tutorial/diff_sph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7279121627260267}} {"text": "% EX_STOKES_SQUARE_SG: solve the Stokes problem in the unit square with the SubGrid method.\n\n% 1) PHYSICAL DATA OF THE PROBLEM\nclear problem_data \n% Physical domain, defined as NURBS map given in a text file\nproblem_data.geo_name = 'geo_square.txt';\n\n% Type of boundary conditions for each side of the domain\nproblem_data.drchlt_sides = 1:4;\nproblem_data.nmnn_sides = [];\n\n% Physical parameters\nproblem_data.viscosity = @(x, y) ones (size (x));\n\n% Force term\nfx = @(x, y) (6 * x + y .* cos(x .* y) + 2 * cos(y) .* sin(x));\nfy = @(x, y) (x .* cos(x .* y) - 2 * cos(x) .* sin(y));\nproblem_data.f = @(x, y) cat(1, ...\n reshape (fx (x,y), [1, size(x)]), ...\n reshape (fy (x,y), [1, size(x)]));\n\n% Boundary terms\nuxex = @(x, y) (sin(x) .* cos(y));\nuyex = @(x, y) (-sin(y) .* cos(x));\n\nproblem_data.h = @(x, y, iside) cat(1, ...\n reshape (uxex (x,y), [1, size(x)]), ...\n reshape (uyex (x,y), [1, size(x)]));\n\n% Exact solution, to compute the errors\nproblem_data.velex = @(x, y) cat(1, ...\n reshape (uxex (x,y), [1, size(x)]), ...\n reshape (uyex (x,y), [1, size(x)]));\n\nproblem_data.pressex = @(x, y) (3 * x.^2 + sin(x .* y) - 1.239811742000564725943866);\n\nproblem_data.gradvelex = @test_stokes_square_bc_graduex;\n\n% 2) CHOICE OF THE DISCRETIZATION PARAMETERS\nclear method_data\nmethod_data.element_name = 'SG'; % Element type for discretization\nmethod_data.degree = [ 3 3]; % Degree of the splines (pressure space)\nmethod_data.regularity = [ 2 2]; % Regularity of the splines (pressure space)\nmethod_data.nsub = [10 10]; % Number of subdivisions\nmethod_data.nquad = [ 5 5]; % Points for the Gaussian quadrature rule\n\n% 3) CALL TO THE SOLVER\n[geometry, msh, space_v, vel, space_p, press] = ...\n solve_stokes (problem_data, method_data);\n\n% 4) POST-PROCESSING\n% 4.1) COMPARISON WITH EXACT SOLUTION\nerror_l2_p = sp_l2_error (space_p, msh, press, problem_data.pressex)\n[error_h1_v, error_l2_v] = ...\n sp_h1_error (space_v, msh, vel, problem_data.velex, problem_data.gradvelex)\n\n\n% 4.2) EXPORT TO PARAVIEW\noutput_file = 'SQUARE_SG_Deg3_Reg2_Sub10';\n\nfprintf ('The result is saved in the files %s \\n and %s \\n \\n', ...\n [output_file '_vel'], [output_file '_press']);\nvtk_pts = {linspace(0, 1, 20), linspace(0, 1, 20)};\nsp_to_vtk (press, space_p, geometry, vtk_pts, [output_file '_press'], 'press')\nsp_to_vtk (vel, space_v, geometry, vtk_pts, [output_file '_vel' ], {'velocity', 'divergence'}, {'value', 'divergence'})\n\n% 4.3) PLOT IN MATLAB\n[eu, F] = sp_eval (vel, space_v, geometry, vtk_pts);\n[X, Y] = deal (squeeze(F(1,:,:)), squeeze(F(2,:,:)));\n\nfigure()\nsubplot (1,2,2)\neu2 = problem_data.velex (X, Y);\nquiver (X, Y, squeeze(eu2(1,:,:)), squeeze(eu2(2,:,:)))\naxis equal\ntitle('Exact solution')\nsubplot (1,2,1)\nquiver (X, Y, squeeze(eu(1,:,:)), squeeze(eu(2,:,:)))\naxis equal\ntitle('Computed solution')\n\n%!demo\n%! ex_stokes_square_sg\n\n%!test\n%! problem_data.geo_name = 'geo_square.txt';\n%! problem_data.drchlt_sides = 1:4;\n%! problem_data.nmnn_sides = [];\n%! problem_data.viscosity = @(x, y) ones (size (x));\n%! fx = @(x, y) (6 * x + y .* cos(x .* y) + 2 * cos(y) .* sin(x));\n%! fy = @(x, y) (x .* cos(x .* y) - 2 * cos(x) .* sin(y));\n%! problem_data.f = @(x, y) cat(1, ...\n%! reshape (fx (x,y), [1, size(x)]), ...\n%! reshape (fy (x,y), [1, size(x)]));\n%! uxex = @(x, y) (sin(x) .* cos(y));\n%! uyex = @(x, y) (-sin(y) .* cos(x));\n%! problem_data.h = @(x, y, iside) cat(1, ...\n%! reshape (uxex (x,y), [1, size(x)]), ...\n%! reshape (uyex (x,y), [1, size(x)]));\n%! problem_data.velex = @(x, y) cat(1, ...\n%! reshape (uxex (x,y), [1, size(x)]), ...\n%! reshape (uyex (x,y), [1, size(x)]));\n%! problem_data.pressex = @(x, y) (3 * x.^2 + sin(x .* y) - 1.239811742000564725943866);\n%! problem_data.gradvelex = @test_stokes_square_bc_graduex;\n%! method_data.element_name = 'SG'; % Element type for discretization\n%! method_data.degree = [ 3 3]; % Degree of the splines (pressure space)\n%! method_data.regularity = [ 2 2]; % Regularity of the splines (pressure space)\n%! method_data.nsub = [10 10]; % Number of subdivisions\n%! method_data.nquad = [ 5 5]; % Points for the Gaussian quadrature rule\n%! [geometry, msh, space_v, vel, space_p, press] = ...\n%! solve_stokes (problem_data, method_data);\n%! error_l2_p = sp_l2_error (space_p, msh, press, problem_data.pressex);\n%! [error_h1_v, error_l2_v] = ...\n%! sp_h1_error (space_v, msh, vel, problem_data.velex, problem_data.gradvelex);\n%! assert (msh.nel, 400)\n%! assert (space_p.ndof, 169)\n%! assert (space_v.ndof, 1152)\n%! assert (error_l2_p, 1.95305776265391e-08, 1e-15)\n%! assert (error_h1_v, 1.89323099160505e-08, 1e-15)\n%! assert (error_l2_v, 2.87241772271343e-10, 1e-15)", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/examples/fluid/ex_stokes_square_sg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7279121587356173}} {"text": "function out = DK_crinkle(x)\n% DK_crinkle Computes James Theiler's crinkle statistic\n%\n% Calculates the \"crinkle statistic\" on a vector x\n% \t<(x_{t-1}-2*x_t+x_{t+1})^4> / < ( x_t^2 ) >^2\n%\tas proposed by James Theiler\n%\n% ------------------------------------------------------------------------------\n% Copyright (C) 1996, D. Kaplan \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% Subtract out the mean\nx = x - mean(x);\nx2 = mean(x.*x)^2;\n\nif x2 == 0\n\tout = 0;\n\treturn\nend\n\nd2 = 2*x(2:end-1) - x(1:end-2) - x(3:end);\nout = mean(d2.^ 4)/x2;\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/Toolboxes/Danny_Kaplan/DK_crinkle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.920789673717312, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7279121473753052}} {"text": "function sqnorm = multisqnorm(A)\n% Returns the squared Frobenius norms of the slices of a 3D matrix.\n%\n% function sqnorm = multisqnorm(A)\n%\n% Given a 3-dimensional matrix A of size n-by-m-by-N, returns a column\n% vector of length N such that sqnorm(i) = norm(A(:, :, i), 'fro')^2.\n%\n% See also: multiprod multitransp multitrace norms\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, June 17, 2015.\n% Contributors: \n% Change log: \n\n\n assert(ndims(A) <= 3, ...\n ['multisqnorm is only well defined for matrix arrays of 3 ' ...\n 'or less dimensions.']);\n [n, m, N] = size(A);\n \n % This is equivalent to squeeze(sum(norms(A, 2, 1).^2)), but faster.\n sqnorm = sum(reshape(A, n*m, N).^2, 1)';\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/multisqnorm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7279042749021051}} {"text": "function v = krawtchouk ( n, p, x, m )\n\n%*****************************************************************************80\n%\n%% KRAWTCHOUK evaluates the Krawtchouk polynomials at X.\n%\n% Discussion:\n%\n% The polynomial has a parameter P, which must be strictly between\n% 0 and 1, and a parameter M which must be a nonnegative integer.\n%\n% The Krawtchouk polynomial of order N, with parameters P and M,\n% evaluated at X, may be written K(N,P,X,M).\n%\n% The first two terms are:\n%\n% K(0,P,X,M) = 1\n% K(1,P,X,M) = X - P * M\n%\n% and the recursion, for fixed P and M is\n%\n% ( N + 1 ) * K(N+1,P,X,M) =\n% ( X - ( N + P * ( M - 2 * N))) * K(N, P,X,M)\n% - ( M - N + 1 ) * P * ( 1 - P ) * K(N-1,P,X,M)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Walter Gautschi,\n% Orthogonal Polynomials: Computation and Approximation,\n% Oxford, 2004,\n% ISBN: 0-19-850672-4,\n% LC: QA404.5 G3555.\n%\n% Parameters:\n%\n% Input, integer N, the highest order polynomial to evaluate.\n% 0 <= N.\n%\n% Input, real P, the parameter. 0 < P < 1.\n%\n% Input, real X, the evaluation parameter.\n%\n% Input, integer M, the parameter. 0 <= M.\n%\n% Output, real V(1:N+1), the values of the Krawtchouk polynomials\n% of orders 0 through N at X.\n%\n if ( n < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'KRAWTCHOUK - Fatal error!\\n' );\n fprintf ( 1, ' 0 <= N is required.\\n' );\n error ( 'KRAWTCHOUK - Fatal error!' );\n return\n end\n\n if ( p <= 0.0 || 1.0 <= p )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'KRAWTCHOUK - Fatal error!\\n' );\n fprintf ( 1, ' 0 < P < 1 is required.\\n' );\n error ( 'KRAWTCHOUK - Fatal error!' );\n return\n end\n\n if ( m < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'KRAWTCHOUK - Fatal error!\\n' );\n fprintf ( 1, ' 0 <= M is required.\\n' );\n error ( 'KRAWTCHOUK - Fatal error!' );\n return\n end\n\n OFFSET = 1;\n\n v = zeros(n+1,1);\n v(0+OFFSET) = 1.0;\n\n if ( 1 <= n )\n v(1+OFFSET) = x - p * m;\n end\n\n for i = 1 : n - 1\n v(i+1+OFFSET) = ( ( x - ( i + p * ( m - 2 * i ) ) ) * v(i+OFFSET) ...\n - ( m - i + 1 ) * p * ( 1 - p ) * v(i-1+OFFSET) ) ...\n / ( i + 1 );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/krawtchouk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652496, "lm_q2_score": 0.8175744695262777, "lm_q1q2_score": 0.7278818391632257}} {"text": "function qq = ppdiff(pp,j)\n%PPDIFF Differentiate piecewise polynomial.\n% QQ = PPDIFF(PP,J) returns the J:th derivative of a piecewise\n% polynomial PP. PP must be on the form evaluated by PPVAL. QQ is a\n% piecewise polynomial on the same form. Default value for J is 1.\n%\n% Example:\n% x = linspace(-pi,pi,9);\n% y = sin(x);\n% pp = spline(x,y);\n% qq = ppdiff(pp);\n% xx = linspace(-pi,pi,201);\n% plot(xx,cos(xx),'b',xx,ppval(qq,xx),'r')\n%\n% See also PPVAL, SPLINE, SPLINEFIT, PPINT\n\n% Author: Jonas Lundgren 2009\n\nif nargin < 1, help ppdiff, return, end\nif nargin < 2, j = 1; end\n\n% Check diff order\nif ~isreal(j) || mod(j,1) || j < 0\n msgid = 'PPDIFF:DiffOrder';\n message = 'Order of derivative must be a non-negative integer!';\n error(msgid,message)\nend\n\n% Get coefficients\ncoefs = pp.coefs;\n[m n] = size(coefs);\n\nif j == 0\n % Do nothing\nelseif j < n\n % Derivative of order J\n D = [n-j:-1:1; ones(j-1,n-j)];\n D = cumsum(D,1);\n D = prod(D,1);\n coefs = coefs(:,1:n-j);\n for k = 1:n-j\n coefs(:,k) = D(k)*coefs(:,k);\n end\nelse\n % Derivative kills PP\n coefs = zeros(m,1);\nend\n\n% Set output\nqq = pp;\nqq.coefs = coefs;\nqq.order = size(coefs,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/13812-splinefit/ppdiff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7278818347776214}} {"text": "function D = dtiSelfDiffusionOfWater(temperature, pressure)\n%\n% D = dtiSelfDiffusionOfWater([temperature=37], [pressure=101.325])\n%\n% Returns the self-diffusion coefficient of water \n% (in micrometers^2/millisecond) at the given temperature (in\n% Centigrade) and pressure (in kPa). (These default to body temp\n% and standard atmospheric pressure.)\n%\n% The function used to compute D is from Krynicki, Green & Sawyer\n% (1978). Pressure and temperature dependence of self-diffusion in\n% water. Faraday Discuss. Chem. Soc., 66, 199 - 208.\n%\n% The results also agree pretty well with the values presented in Mills\n% (1973). Self-Diffusion in Normal and Heavy Water. JPhysChem 77(5), pg.\n% 685 - 688. Mills estimates the self-diffusion of normal water at 35 deg C\n% to be 2.919 micrometers^2/ms. This function returns 2.862 at that temp, a\n% difference of about 2%. \n% \n% E.g.:\n% x=[20:40];figure;plot(x,dtiSelfDiffusionOfWater(x));xlabel('T (C)');ylabel('D (\\mum^2/ms)')\n%\n% See also:\n% http://www.lsbu.ac.uk/water/explan5.html\n%\n% Note that the relationship between diffusivity and temperature is nearly\n% linear over the biologically useful range (e.g. 20-40 deg C) and is very\n% well fit by a 3rd order polynomial. Thus, to find t (in Centigrade) given\n% d and standard pressure, use: \n%\n% p=[0.6056 -6.6855 39.2757 -36.8468]; t = polyval(p,d);\n% \n%\n% HISTORY:\n% 2006.10.06 Bob Dougherty (RFD): Wrote it.\n\nif(~exist('pressure','var')||isempty(pressure))\n P = 101.325;\nelse\n P = pressure;\nend\nif(~exist('temperature','var')||isempty(temperature))\n T = 273.15+37;\nelse\n T = temperature+273.15;\nend\n\n% D is in micrometers^2/millisec\n% T is in Kelvins (C + 273.15)\n% P is in kPa (100 kPa = 1 bar)\nD = 12.5 .* exp(P*-5.22*10^-6) .* sqrt(T) .* exp(-925.*exp(P.*-2.6.*10^-6)./(T-(95+P.*2.61.*10^-4)));\nreturn;\n\nfprintf('D = %0.2f micrometers^2/msec (@ %0.1f C & %0.1f kPa).\\n',D,T-273.15,P);\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/models/dtiSelfDiffusionOfWater.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7278818288417039}} {"text": "% Driver script for solving the 1D Poisson equation\nGlobals1D;\n\n% Polynomial order used for approximation \nN =4;\n\n% Read in Mesh\n[Nv, VX, K, EToV] = MeshGen1D(0,2*pi,10);\n\n% Initialize solver and construct grid and metric\nStartUp1D;\n\n% Set RHS\nf = -J.*((invV'*invV)*sin(x));\n\n% Set up operator\n[A] = PoissonCstab1D();\n\n% Solve Problem\nsolvec = A\\f(:);\nu = reshape(solvec,Np,K);\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/Codes1D/PoissonCDriver1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750387190132, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7278100142635561}} {"text": "function [A,b,P]=gausscppSolve1(A,b)\n%function [A,b,P]=gausscppSolve1(A,b)\n%forward gaussian elimination with partial pivoting\n\n[m n]=size(A);\nif (m~=n), error('matrix must be square!'); end\n%initialize pivoting vector\nP = (1:m)';\nfor i=1:(n-1) %sweep through rows\n %maximum of i-th column below diagonal\n [mx imx]= max(abs(A(i:m,i))); \n %row f and column c where |afc| is maximum for the submatrix A(i:m,i)\n f = imx + i - 1;\n c = i;\n %exchange i-th and f-th row for all the system\n dummy = A(i,:);\n A(i,:) = A(f,:);\n A(f,:) = dummy;\n dummy = b(i,:);\n b(i,:) = b(f,:);\n b(f,:) = dummy;\n dummy = P(i);\n P(i) = P(f);\n P(f) = dummy;\n ip1=i+1;\n for j=ip1:m %sweep the remaining rows\n mij=A(j,i)/A(i,i);\n %A(j,:)=A(j,:) - mij* A(i,:);\n A(j,ip1:n)=A(j,ip1:n) - mij* A(i,ip1:n);\n b(j,:)=b(j,:) - mij*b(i,:);\n %keep the pivot for further LU uses\n A(j,i)=mij;\n end\nend\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/analysis/mptoolbox/mp_gausscppSolve1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850128595115, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7277742201760897}} {"text": "function qwv_2d_test01 ( )\n\n%*****************************************************************************80\n%\n%% QWV_2D_TEST01 tests QWV_2D for a trio of points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 May 2014\n%\n% Author:\n%\n% John Burkardt\n%\n a = -1.0;\n b = +1.0;\n c = -1.0;\n d = +1.0;\n\n t = 1;\n n = ( ( t + 1 ) * ( t + 2 ) ) / 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QWV_2D_TEST01:\\n' );\n fprintf ( 1, ' Compute the weights associated with an interpolatory\\n' );\n fprintf ( 1, ' quadrature rule defined by N=(T+1)*(T+2)/2 points,\\n' );\n fprintf ( 1, ' exact for polynomials of total degree T or less.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Degree T = %d\\n', t );\n fprintf ( 1, ' Number of points N = %d\\n', n );\n fprintf ( 1, ' X Interval = [%g,%g]\\n', a, b );\n fprintf ( 1, ' Y Interval = [%g,%g]\\n', c, d );\n%\n% Set the points.\n%\n x(1) = 1.0;\n y(1) = -1.0;\n x(2) = 1.0;\n y(2) = 1.0;\n x(3) = -1.0;\n y(3) = 1.0;\n\n r8vec2_print ( n, x, y, ' Abscissas:' )\n%\n% Compute the weights.\n%\n w = qwv_2d ( t, n, a, b, c, d, x, y );\n\n r8vec_print ( n, w, ' Weights:' );\n\n return\nend\n", "meta": {"author": "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_weights_vandermonde_2d/qwv_2d_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7277466357931054}} {"text": "function [xdx, xdy, ydx, ydy] = jacobian_matrix2d(vectorField)\n% JACOBIAND_MATRIX2D Estimates the elements of the jacobian matrix\n%\n% function [xdx xdy ydx ydy] = jacobian_matrix2d(vectorField)\n%\n% INPUT ARGUMENTS\n% vectorField - Vectorfield to estimate the Jacobian for\n%\n% OPTIONAL INPUT ARGUMENTS\n% N/A\n%\n% OUTPUT ARGUMENTS\n% xdx ... - Matrix elements of the Jacobian\n\n% Copyright (c) 2012 Daniel Forsberg\n% danne.forsberg@outlook.com\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[xdx xdy] = gradient(vectorField{1});\n[ydx ydy] = gradient(vectorField{2});\n", "meta": {"author": "fordanic", "repo": "image-registration", "sha": "36c23d5da1f035b07c66a04fe5bac20de1bd1c74", "save_path": "github-repos/MATLAB/fordanic-image-registration", "path": "github-repos/MATLAB/fordanic-image-registration/image-registration-36c23d5da1f035b07c66a04fe5bac20de1bd1c74/registration/field-operations/jacobian_matrix2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.7277228890824083}} {"text": "function ellipse_monte_carlo_test01 ( )\n\n%*****************************************************************************80\n%\n%% ELLIPSE_MONTE_CARLO_TEST01 uses ELLIPSE01_SAMPLE with an increasing number of points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n a = [ ...\n 9.0, 1.0; ...\n 1.0, 4.0 ]';\n e_test = [ ...\n 0, 0; ...\n 1, 0; ...\n 0, 1; ...\n 2, 0; ...\n 1, 1; ...\n 0, 2; ...\n 3, 0 ]';\n r = 2.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ELLIPSE_MONTE_CARLO_TEST01\\n' );\n fprintf ( 1, ' Use ELLIPSE01_SAMPLE to estimate integrals\\n' );\n fprintf ( 1, ' in the ellipse x'' * A * x <= r^2.\\n' );\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N 1 X Y ' );\n fprintf ( 1, ' X^2 XY Y^2 X^3\\n' );\n fprintf ( 1, '\\n' );\n\n n = 1;\n\n while ( n <= 65536 )\n\n [ x, seed ] = ellipse_sample ( n, a, r, seed );\n\n fprintf ( 1, ' %8d', n );\n\n for j = 1 : 7\n\n e(1:2) = e_test(1:2,j);\n\n value = monomial_value ( 2, n, e, x );\n\n result = ellipse_area1 ( a, r ) * sum ( value(1:n) ) / n;\n fprintf ( ' %14.6g', result );\n\n end\n\n fprintf ( 1, '\\n' );\n\n n = 2 * 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/ellipse_monte_carlo/ellipse_monte_carlo_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7277228889994546}} {"text": "function [normF, normLoc] = norm(f, n)\n%NORM Norm of a CHEBFUN object.\n% For scalar-valued column CHEBFUN objects:\n% NORM(F) = sqrt(integral of abs(F)^2).\n% NORM(F, 2) is the same as NORM(F).\n% NORM(F, 'fro') is also the same as NORM(F).\n% NORM(F, 1) = integral of abs(F).\n% NORM(F, P) = (integral of abs(F)^P)^(1/P).\n% NORM(F, inf) = max(abs(F)).\n% NORM(F, -inf) = min(abs(F)).\n%\n% For array-valued column CHEBFUN objects:\n% NORM(F) is the Frobenius norm, sqrt(sum(svd(F).^2)).\n% NORM(F, 'fro') is the same as NORM(F).\n% NORM(F, 1) is the maximum of the 1-norms of the columns of F.\n% NORM(F, 2) is the largest singular value of F.\n% NORM(F, inf) is the maximum of the 1-norms of the rows of F.\n% NORM(F, -inf) is the minimum of the 1-norms of the rows of F.\n% NORM(F, P) is the P-th root of the maximum of the sum of the P-th\n% powers of the magnitudes of the columns of F.\n%\n% Furthermore, the +\\-inf norms for scalar-valued CHEBFUN objects may also\n% return a second output, giving the position where the max/min occurs. For\n% array-valued CHEBFUN objects, the 1 norm can return as its 2nd output the\n% index of the column with the largest norm, while the inf and -inf norms\n% can return as their 2nd output the point in the domain of the CHEBFUN at\n% which the norm is attained.\n%\n% If F is a row CHEBFUN, NORM(F, TYPE) is equal to NORM(F.', TYPE).\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 CHEBFUN has norm 0:\nif ( isempty(f) )\n normF = 0;\n return\nend\n\nif ( nargin == 1 )\n n = 'fro'; \t% Frobenius norm is the default (2 norm would be much slower).\nend\n\n% Initialise:\nnormLoc = [];\nif ( numel(f) > 1 )\n numCols = numel(f);\nelse\n numCols = size(f.funs{1}, 2);\nend\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%% SCALAR-VALUED CHEBFUNS %%%%%%%%%%%%%%%%%%%%%%%%%%%%\nif ( numCols == 1 )\n switch n\n case 1\n if ( nargout == 2 )\n error('CHEBFUN:CHEBFUN:norm:argout', ...\n 'Cannot return two outputs for 1-norms');\n end\n normF = sum(abs(f));\n\n case {2, 'fro'}\n if ( nargout == 2 )\n error('CHEBFUN:CHEBFUN:norm:argout', ...\n 'Cannot return two outputs for ''fro''-norms');\n end\n f.isTransposed = 0;\n normF = sqrt(abs(innerProduct(f, f)));\n\n case {inf, 'inf'}\n if ( isreal(f) )\n [normF, normLoc] = minandmax(f);\n [normF, idx] = max(abs(normF));\n normLoc = normLoc(idx);\n else\n [normF, normLoc] = max(conj(f).*f);\n normF = sqrt(normF);\n end\n\n case {-inf, '-inf'}\n [normF, normLoc] = min(conj(f).*f);\n normF = sqrt(normF);\n\n otherwise\n if ( isnumeric(n) && isreal(n) )\n if ( nargout == 2 )\n error('CHEBFUN:CHEBFUN:norm:argout', ...\n 'Cannot return two outputs for p-norms.');\n end\n if ( mod(n, 2) == 0 )\n normF = sum((conj(f).*f).^(n/2))^(1/n);\n else\n normF = sum(abs(f).^n)^(1/n);\n end\n else\n error('CHEBFUN:CHEBFUN:norm:unknownNorm', ...\n 'The only matrix norms available are 1, 2, inf, and ''fro''.');\n end\n end\n\n%% %%%%%%%%%%%%%%%%%%%%%%%%%% ARRAY-VALUED CHEBFUNS %%%%%%%%%%%%%%%%%%%%%%%%%%%%\nelse\n if ( f(1).isTransposed )\n f = f.';\n end\n\n switch n\n case 1\n f = mat2cell(f);\n normF = zeros(1, numel(f));\n for k = 1:numel(f)\n normF(k) = norm(f{k}, 1);\n end\n [normF, normLoc] = max(normF);\n\n case 2\n if (nargout == 2 )\n error('CHEBFUN:CHEBFUN:norm:argout', ...\n ['Cannot return two outputs for 2-norms of ' ...\n 'array-valued CHEBFUNs.']);\n end\n s = svd(f, 0);\n normF = s(1);\n\n case 'fro'\n if ( nargout == 2 )\n error('CHEBFUN:CHEBFUN:norm:argout', ...\n ['Cannot return two outputs for ''fro''-norms of ' ...\n 'array-valued CHEBFUNs.']);\n end\n normF = sqrt(sum(sum(f.*conj(f))));\n\n case {'inf', inf}\n [normF, normLoc] = max(sum(abs(f), 2));\n\n case {'-inf', -inf}\n [normF, normLoc] = min(sum(abs(f), 2));\n\n otherwise\n if ( isnumeric(n) && isreal(n) )\n [normF, normLoc] = max(sum(abs(f).^n, 2));\n normF = normF^(1/n);\n else\n error('CHEBFUN:CHEBFUN:norm:unknownNorm', ...\n 'The only matrix norms available are 1, 2, inf, and ''fro''.');\n end\n\n end\n\nend\n\n% Discard possible imaginary rounding errors:\nnormF = real(normF);\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/norm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7277228827281765}} {"text": "function [boxedX,Bx,By]=boxpdf(X)\n% Forces the pdf of data to have a boxed distribution using a data adaptive lookup table. \n% \n% [boxedX,Bx,By]=boxpdf(X)\n%\n% boxedX=N(X) where N is an data adaptive monotonically increasing function.\n% boxedX vary between zero and one. \n% \n% Bx,By describes the lookup table\n% \n% (c) Aslak Grinsted 2002-2004\n\n\n%tested with: [prctile(x,boxpdf(x)*100)-x]\n\n%home made fast unique:\n[Bx,Js]=sort(X(:)); \nn=size(Bx,1);\nd=(diff(Bx)~=0);\n\nI=(1:n)';\nI=I([d;logical(1)]);\n%if (nargout>1)\n Bx=Bx(I);\n%end\n\nJ=cumsum([1;d]);\n\nn=length(X);\nI=[0;I];\n\nBy=(.5/n)*(I(1:(end-1))+(I(2:end))); %percentile\n\n\n%boxedX=By(J(Js([2:end 1])));\nboxedX=interp1q(Bx,By,X);\n% \n% %old boxpdf:\n% \n% [sx i]=sort(X(:));\n% [n, m] = size(sx);\n% minx = min(sx);\n% maxx = max(sx);\n% range = maxx-minx;\n% \n% \n% % Use the same Y vector if all columns have the same count\n% eprob = [0.5./n:1./n:(n - 0.5)./n]';\n% \n% \n% %group x's with same value\n% I=[1; find(diff(sx)~=0)+1]; %unique indices\n% Bx=sx(I); %unique values\n% nI=diff([I;length(sx)+1])-1;\n% By=zeros(length(Bx),1);\n% for i=length(I):-1:1\n% \n% By(i,1)=mean(eprob(I(i)+(0:nI(i))));\n% end\n% %plot(sx,y);\n% \n% \n% \n% boxedX=interp1q(Bx,By,X);\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/WaveletToolbox/boxpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7276885885179764}} {"text": "function f = p39_f ( n, x )\n\n%*****************************************************************************80\n%\n%% P39_F evaluates the objective function for problem 39.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 January 2001\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Zbigniew Michalewicz,\n% Genetic Algorithms + Data Structures = Evolution Programs,\n% Third Edition,\n% Springer Verlag, 1996,\n% ISBN: 3-540-60676-9,\n% LC: QA76.618.M53.\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 f = x(1) * x(1) + 2.0 * x(2) * x(2) ...\n - 0.3 * cos ( 3.0 * pi * x(1) ) ...\n * cos ( 4.0 * pi * x(2) ) + 0.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/p39_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7276672813638613}} {"text": "function R = RPYtoRot_ZXY(phi,theta,psi)\n%RPYtoRot_ZXY Converts roll, pitch, yaw to a body-to-world Rotation matrix\n% The rotation matrix in this function is world to body [bRw] you will\n% need to transpose this matrix to get the body to world [wRb] such that\n% [wP] = [wRb] * [bP], where [bP] is a point in the body frame and [wP]\n% is a point in the world frame\n% written by Daniel Mellinger\n%\n\nR = [cos(psi)*cos(theta) - sin(phi)*sin(psi)*sin(theta), ...\n cos(theta)*sin(psi) + cos(psi)*sin(phi)*sin(theta), ...\n -cos(phi)*sin(theta); ...\n -cos(phi)*sin(psi),...\n cos(phi)*cos(psi), ...\n sin(phi);...\n cos(psi)*sin(theta) + cos(theta)*sin(phi)*sin(psi),...\n sin(psi)*sin(theta) - cos(psi)*cos(theta)*sin(phi),...\n cos(phi)*cos(theta)];\n\nend\n", "meta": {"author": "yrlu", "repo": "quadrotor", "sha": "a7d951902567d75996d7b30cff7b2bc05e993602", "save_path": "github-repos/MATLAB/yrlu-quadrotor", "path": "github-repos/MATLAB/yrlu-quadrotor/quadrotor-a7d951902567d75996d7b30cff7b2bc05e993602/traj_planning/utils/RPYtoRot_ZXY.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.7276644163412438}} {"text": "function [V,S] = alphavol(X,R,fig)\n% ALPHAVOL Alpha shape of 2D or 3D point set.\n%\n% V = ALPHAVOL(X,R) gives the area or volume V of the basic alpha shape\n% for a 2D or 3D point set. X is a coordinate matrix of size Nx2 or Nx3.\n%\n% R is the probe radius with default value R = Inf. In the default case\n% the basic alpha shape (or alpha hull) is the convex hull.\n%\n% [V,S] = ALPHAVOL(X,R) outputs a structure S with fields:\n% S.tri - Triangulation of the alpha shape (Mx3 or Mx4)\n% S.vol - Area or volume of simplices in triangulation (Mx1)\n% S.rcc - Circumradius of simplices in triangulation (Mx1)\n% S.bnd - Boundary facets (Px2 or Px3)\n%\n% ALPHAVOL(X,R,1) plots the alpha shape.\n%\n% % 2D Example - C shape\n% t = linspace(0.6,5.7,500)';\n% X = 2*[cos(t),sin(t)] + rand(500,2);\n% subplot(221), alphavol(X,inf,1);\n% subplot(222), alphavol(X,1,1);\n% subplot(223), alphavol(X,0.5,1);\n% subplot(224), alphavol(X,0.2,1);\n%\n% % 3D Example - Sphere\n% [x,y,z] = sphere;\n% [V,S] = alphavol([x(:),y(:),z(:)]);\n% trisurf(S.bnd,x,y,z,'FaceColor','blue','FaceAlpha',1)\n% axis equal\n%\n% % 3D Example - Ring\n% [x,y,z] = sphere;\n% ii = abs(z) < 0.4;\n% X = [x(ii),y(ii),z(ii)];\n% X = [X; 0.8*X];\n% subplot(211), alphavol(X,inf,1);\n% subplot(212), alphavol(X,0.5,1);\n%\n% See also DELAUNAY, TRIREP, TRISURF\n\n% Author: Jonas Lundgren 2010\n\n% 2010-09-27 First version of ALPHAVOL.\n% 2010-10-05 DelaunayTri replaced by DELAUNAYN. 3D plots added.\n% 2012-03-08 More output added. DELAUNAYN replaced by DELAUNAY.\n\nif nargin < 2 || isempty(R), R = inf; end\nif nargin < 3, fig = 0; end\n\n% Check coordinates\ndim = size(X,2);\nif dim < 2 || dim > 3\n error('alphavol:dimension','X must have 2 or 3 columns.')\nend\n\n% Check probe radius\nif ~isscalar(R) || ~isreal(R) || isnan(R)\n error('alphavol:radius','R must be a real number.')\nend\n\n% Unique points\n[X,imap] = unique(X,'rows');\n\n% Delaunay triangulation\nT = delaunay(X);\n\n% Remove zero volume tetrahedra since\n% these can be of arbitrary large circumradius\nif dim == 3\n n = size(T,1);\n vol = volumes(T,X);\n epsvol = 1e-12*sum(vol)/n;\n T = T(vol > epsvol,:);\n holes = size(T,1) < n;\nend\n\n% Limit circumradius of simplices\n[~,rcc] = circumcenters(TriRep(T,X));\nT = T(rcc < R,:);\nrcc = rcc(rcc < R);\n\n% Volume/Area of alpha shape\nvol = volumes(T,X);\nV = sum(vol);\n\n% Return?\nif nargout < 2 && ~fig\n return\nend\n\n% Turn off TriRep warning\nwarning('off','MATLAB:TriRep:PtsNotInTriWarnId')\n\n% Alpha shape boundary\nif ~isempty(T)\n % Facets referenced by only one simplex\n B = freeBoundary(TriRep(T,X));\n if dim == 3 && holes\n % The removal of zero volume tetrahedra causes false boundary\n % faces in the interior of the volume. Take care of these.\n B = trueboundary(B,X);\n end\nelse\n B = zeros(0,dim);\nend\n\n% Plot alpha shape\nif fig\n if dim == 2\n % Plot boundary edges and point set\n x = X(:,1);\n y = X(:,2);\n plot(x(B)',y(B)','r','linewidth',2), hold on\n plot(x,y,'k.'), hold off\n str = 'Area';\n elseif ~isempty(B)\n % Plot boundary faces\n trisurf(TriRep(B,X),'FaceColor','red','FaceAlpha',1/3);\n str = 'Volume';\n else\n cla\n str = 'Volume';\n end\n axis equal\n str = sprintf('Radius = %g, %s = %g',R,str,V);\n title(str,'fontsize',12)\nend\n\n% Turn on TriRep warning\nwarning('on','MATLAB:TriRep:PtsNotInTriWarnId')\n\n% Return structure\nif nargout == 2\n S = struct('tri',imap(T),'vol',vol,'rcc',rcc,'bnd',imap(B));\nend\n\n\n%--------------------------------------------------------------------------\nfunction vol = volumes(T,X)\n%VOLUMES Volumes/areas of tetrahedra/triangles\n\n% Empty case\nif isempty(T)\n vol = zeros(0,1);\n return\nend\n\n% Local coordinates\nA = X(T(:,1),:);\nB = X(T(:,2),:) - A;\nC = X(T(:,3),:) - A;\n \nif size(X,2) == 3\n % 3D Volume\n D = X(T(:,4),:) - A;\n BxC = cross(B,C,2);\n vol = dot(BxC,D,2);\n vol = abs(vol)/6;\nelse\n % 2D Area\n vol = B(:,1).*C(:,2) - B(:,2).*C(:,1);\n vol = abs(vol)/2;\nend\n\n\n%--------------------------------------------------------------------------\nfunction B = trueboundary(B,X)\n%TRUEBOUNDARY True boundary faces\n% Remove false boundary caused by the removal of zero volume\n% tetrahedra. The input B is the output of TriRep/freeBoundary.\n\n% Surface triangulation\nfacerep = TriRep(B,X);\n\n% Find edges attached to two coplanar faces\nE0 = edges(facerep);\nE1 = featureEdges(facerep, 1e-6);\nE2 = setdiff(E0,E1,'rows');\n\n% Nothing found\nif isempty(E2)\n return\nend\n\n% Get face pairs attached to these edges\n% The edges connects faces into planar patches\nfacelist = edgeAttachments(facerep,E2);\npairs = cell2mat(facelist);\n\n% Compute planar patches (connected regions of faces)\nn = size(B,1);\nC = sparse(pairs(:,1),pairs(:,2),1,n,n);\nC = C + C' + speye(n);\n[~,p,r] = dmperm(C);\n\n% Count planar patches\niface = diff(r);\nnum = numel(iface);\n\n% List faces and vertices in patches\nfacelist = cell(num,1);\nvertlist = cell(num,1);\nfor k = 1:num\n\n % Neglect singel face patches, they are true boundary\n if iface(k) > 1\n \n % List of faces in patch k\n facelist{k} = p(r(k):r(k+1)-1);\n \n % List of unique vertices in patch k\n vk = B(facelist{k},:);\n vk = sort(vk(:))';\n ik = [true,diff(vk)>0];\n vertlist{k} = vk(ik);\n \n end\nend\n\n% Sort patches by number of vertices\nivert = cellfun(@numel,vertlist);\n[ivert,isort] = sort(ivert);\nfacelist = facelist(isort);\nvertlist = vertlist(isort);\n\n% Group patches by number of vertices\np = [0;find(diff(ivert));num] + 1;\nipatch = diff(p);\n\n% Initiate true boundary list\nibound = true(n,1);\n\n% Loop over groups\nfor k = 1:numel(ipatch)\n\n % Treat groups with at least two patches and four vertices\n if ipatch(k) > 1 && ivert(p(k)) > 3\n\n % Find double patches (identical vertex rows)\n V = cell2mat(vertlist(p(k):p(k+1)-1));\n [V,isort] = sortrows(V);\n id = ~any(diff(V),2);\n id = [id;0] | [0;id];\n id(isort) = id;\n\n % Deactivate faces in boundary list\n for j = find(id')\n ibound(facelist{j-1+p(k)}) = 0;\n end\n \n end\nend\n\n% Remove false faces\nB = B(ibound,:);\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/alphavol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.7275631006656488}} {"text": "function [ rexp, sexp ] = poly_t6 ( )\n\n%*****************************************************************************80\n%\n%% POLY_T6 returns the monomials associated with a 6 node triangle.\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% Formula:\n%\n% Given coefficients A(I), the polynomial interpolant at (R,S) is\n%\n% P(R,S) = sum ( 1 <= I <= N ) A(I) * R**REXP(I) * S**SEXP(I)\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, integer REXP(6), SEXP(6), the powers of R and S associated\n% with each monomial.\n%\n rexp(1:6) = [ 0, 0, 1, 0, 1, 2 ];\n sexp(1:6) = [ 0, 1, 0, 2, 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/fem2d_pack/poly_t6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7275630982837881}} {"text": "function a = companion_inverse ( n, x )\n\n%*****************************************************************************80\n%\n%% COMPANION_INVERSE returns the inverse of the COMPANION matrix.\n%\n% Example:\n%\n% N = 5, X = ( 1, 2, 3, 4, 5 )\n%\n% 0 1 0 0 0\n% 0 0 1 0 0\n% 0 0 0 1 0\n% 0 0 0 0 1\n% 1/1 -5/1 -4/1 -3/1 -2/1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 July 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gene Golub, Charles Van Loan,\n% Matrix Computations, second edition,\n% Johns Hopkins University Press, Baltimore, Maryland, 1989,\n% section 7.4.6.\n%\n% Charles Kenney, Alan Laub,\n% Controllability and stability radii for companion form systems,\n% Math. Control Signals Systems,\n% Volume 1, 1988, pages 239-256.\n%\n% James Wilkinson,\n% The Algebraic Eigenvalue Problem,\n% Oxford University Press,\n% 1965, page 12.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real X(N), the coefficients of the polynomial\n% which define the matrix. X(1) must not be zero.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for j = 1 : n\n for i = 1 : n\n\n if ( i == n )\n\n if ( j == 1 )\n a(i,j) = 1.0 / x(1);\n else\n a(i,j) = - x(n+2-j) / x(1);\n end\n\n elseif ( i == j - 1 )\n a(i,j) = 1.0;\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/companion_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.727563094174389}} {"text": "%% SQUAREPOISSONWG Poisson equation in a square domain solved by Weak Galerkin method.\n%\n% squarePoissoWGn computes the lowest order Weak Galerkin approximations\n% of the Poisson equation in the unit square on a sequence of meshes\n% obtained by uniform refinement. \n%\n% See also PoissonWG, \n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all; clear variables;\n\n%% Parameters \nmaxIt = 4; \nN = zeros(maxIt,1);\nh = zeros(maxIt,1);\nerruIuh = zeros(maxIt,1);\n\n%% Generate an initial mesh \n[node,elem] = squaremesh([0 1 0 1], 0.25);\n%bdFlag = setboundary(node,elem,'Dirichlet','~(x==0)','Neumann','x==0');\nbdFlag = setboundary(node,elem,'Dirichlet','all','Neumann','y==1');\n%bdFlag = setboundary(node,elem,'Dirichlet');\nfor k = 1:3\n [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n% [node,elem,bdFlag] = uniformbisect(node,elem,bdFlag);\nend\n\n%% Get the data of the pde\npde = sincosdata;\n% pde = mixBCdata;\n% option.solver = 'mg';\n\n%% Finite Element Method \nfor k = 1:maxIt\n % solve the equation\n [soln,eqn,info] = PoissonWG(node,elem,bdFlag,pde);\n N(k) = size(elem,1);\n h(k) = 1./(sqrt(size(node,1))-1);\n % compute error\n uI = zeros(N(k)+size(eqn.edge,1),1);\n uI(1:N(k)) = pde.exactu((node(elem(:,1),:)+node(elem(:,2),:)+node(elem(:,3),:))/3);\n uI(N(k)+1:end) = pde.exactu((node(eqn.edge(:,1),:)+node(eqn.edge(:,2),:))/2);\n erruIuh(k) = sqrt((soln.u-uI)'*eqn.A*(soln.u-uI));\n % refine mesh\n [node,elem,bdFlag] = uniformrefine(node,elem,bdFlag);\n% [node,elem,bdFlag] = uniformbisect(node,elem,bdFlag);\nend\n\n%% Plot convergence rates\nfigure(2);\nshowrateh(h,erruIuh);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/fem/Poisson/squarePoissonWG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7275281869236719}} {"text": "function moment = truncated_normal_b_moment ( order, mu, sigma, b )\n\n%*****************************************************************************80\n%\n%% TRUNCATED_NORMAL_B_MOMENT returns a moment of the upper truncated Normal PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 September 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Phoebus Dhrymes,\n% Moments of Truncated Normal Distributions,\n% May 2005.\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the moment.\n% 0 <= ORDER.\n%\n% Input, real MU, SIGMA, the mean and standard deviation of the\n% parent Normal distribution.\n%\n% Input, real B, the upper truncation limit.\n%\n% Output, real MOMENT, the moment of the PDF.\n%\n if ( order < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRUNCATED_NORMAL_B_MOMENT - Fatal error!\\n' );\n fprintf ( 1, ' ORDER < 0.\\n' );\n error ( 'TRUNCATED_NORMAL_B_MOMENT - Fatal error!\\n' );\n end\n\n h = ( b - mu ) / sigma;\n pdf = normal_01_pdf ( h );\n cdf = normal_01_cdf ( h );\n\n if ( cdf == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRUNCATED_NORMAL_B_MOMENT - Fatal error!\\n' );\n fprintf ( 1, ' PDF/CDF ratio fails, because CDF too small.\\n', cdf );\n fprintf ( 1, ' PDF = %g\\n', pdf );\n fprintf ( 1, ' CDF = %g\\n', cdf );\n error ( 'TRUNCATED_NORMAL_B_MOMENT - Fatal error!\\n' );\n end\n\n f = pdf / cdf;\n\n moment = 0.0;\n irm2 = 0.0;\n irm1 = 0.0;\n\n for r = 0 : order\n\n if ( r == 0 )\n ir = 1.0;\n elseif ( r == 1 )\n ir = - f;\n else\n ir = - h ^ ( r - 1 ) * f + ( r - 1 ) * irm2;\n end\n\n moment = moment + r8_choose ( order, r ) ...\n * mu ^ ( order - r ) ...\n * sigma ^ r * ir;\n\n irm2 = irm1;\n irm1 = ir;\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_b_moment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7275281767624261}} {"text": "function q = p04_q ( m, c, w )\n\n%*****************************************************************************80\n%\n%% P04_Q evaluates the integral for problem p04.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 29 August 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Alan Genz,\n% A Package for Testing Multiple Integration Subroutines,\n% in Numerical Integration: Recent Developments, Software\n% and Applications,\n% edited by Patrick Keast and Graeme Fairweather,\n% Reidel, 1987, pages 337-340,\n% ISBN: 9027725144,\n% LC: QA299.3.N38.\n%\n% Parameters:\n%\n% Input, integer M, the dimension of the argument.\n%\n% Input, real C(M), W(M), the problem parameters.\n%\n% Output, real Q, the integral.\n%\n q = 1.0;\n\n for i = 1 : m\n\n q = q * sqrt ( pi ) ...\n * ( erf ( c(i) * ( 1.0 - w(i) ) ) ...\n + erf ( c(i) * w(i) ) ) ...\n / ( 2.0 * c(i) );\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_interp_nd/p04_q.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7275230855547481}} {"text": "function varargout = kullbackleibler(varargin)\n% KULLBACKLEIBLER\n%\n% y = KULLBACKLEIBLER(x,y)\n%\n% Computes/declares the convex Kullback-Leibler divergence sum(x.*log(x./y))\n% Alternatively -sum(x.*log(y/x)), i.e., negated perspectives of log(y)\n%\n% See also ENTROPY, CROSSENTROPY\n\n\nswitch class(varargin{1})\n\n case 'double' \n if nargin == 1\n z = varargin{1};\n z = reshape(z,[],2);\n x = z(:,1);\n y = z(:,2);\n else\n x = varargin{1}(:);\n y = varargin{2}(:);\n end\n l = log(x./y);\n l(x<=0) = 0;\n l = real(l);\n varargout{1} = sum(x.*l); \n\n case {'sdpvar','ndsdpvar'}\n\n varargin{1} = reshape(varargin{1},[],1);\n varargin{2} = reshape(varargin{2},[],1); \n \n if length(varargin{1})~=length(varargin{2})\n if length(varargin{1})==1\n varargin{1} = repmat(varargin{1},length(varargin{2}),1);\n elseif length(varargin{2})==1\n varargin{2} = repmat(varargin{2},length(varargin{1}),1);\n else\n error('Dimension mismatch in kullbackleibler')\n end\n end\n \n varargout{1} = yalmip('define',mfilename,[varargin{1};varargin{2}]);\n \n case 'char'\n\n X = varargin{3};\n F = [X >= 0];\n\n operator = struct('convexity','convex','monotonicity','none','definiteness','none','model','callback');\n operator.range = [-inf inf];\n operator.domain = [0 inf]; \n operator.derivative = @derivative;\n\n varargout{1} = F;\n varargout{2} = operator;\n varargout{3} = X;\n\n otherwise\n error('SDPVAR/KULLBACKLEIBLER called with CHAR argument?');\nend\n\nfunction df = derivative(x)\nz = abs(reshape(x,[],2));\nx = z(:,1);\ny = z(:,2);\n% Use KL = -Entropy + Cross Entropy\ndf = [1+log(x);0*y] + [-log(y);-x./y];\n\n\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/operators/kullbackleibler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7275230851960479}} {"text": "%% Transient diffusion equation\n%% PDE and boundary conditions\n% The transient diffusion equation reads\n%\n% $$\\alpha\\frac{\\partial c}{\\partial t}+\\nabla.\\left(-D\\nabla c\\right)=0,$$\n%\n% where $c$ is the independent variable (concentration, temperature, etc)\n% , $D$ is the diffusion coefficient, and $\\alpha$ is a constant.\n% Written by Ali A. Eftekhari\n% Last checked: June 2021\nclc\n\n%% Define the domain and create a mesh structure\nL = 50; % domain length\nNx = 20; % number of cells\nm = createMesh3D(Nx,Nx,Nx, L,L,L);\n%% Create the boundary condition structure\nBC = createBC(m); % all Neumann boundary condition structure\nBC.left.a(:) = 0; BC.left.b(:)=1; BC.left.c(:)=0; % left boundary\nBC.right.a(:) = 0; BC.right.b(:)=1; BC.right.c(:)=0; % right boundary\nBC.top.a(:) = 0; BC.top.b(:)=1; BC.top.c(:)=0; % top boundary\nBC.bottom.a(:) = 0; BC.bottom.b(:)=1; BC.bottom.c(:)=0; % bottom boundary\n%% define the transfer coeffs\nD_val = 1;\nD = createCellVariable(m, D_val);\nalfa = createCellVariable(m, 1);\n%% define initial values\nc_init = 1;\nc_old = createCellVariable(m, c_init,BC); % initial values\nc = c_old; % assign the old value of the cells to the current values\n%% loop\ndt = 1; % time step\nfinal_t = 50;\nfor t=dt:dt:final_t\n [M_trans, RHS_trans] = transientTerm(c_old, dt, alfa);\n Dave = harmonicMean(D);\n Mdiff = diffusionTerm(Dave);\n [Mbc, RHSbc] = boundaryCondition(BC);\n M = M_trans-Mdiff+Mbc;\n RHS = RHS_trans+RHSbc;\n c = solvePDE(m,M, RHS);\n c_old = c;\nend\n%% visualization\nvisualizeCells(c)\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Examples/Tutorial/diffusiontutorial3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7275230833940624}} {"text": "function D = diffmat(n, m)\n%DIFFMAT Differentiation matrices for ultraspherical spectral method.\n% D = DIFFMAT(N, M) returns the differentiation matrix that takes N Chebyshev\n% coefficients and returns N C^{(M)} coefficients that represent the derivative\n% of the Chebyshev series. Here, C^{(K)} is the ultraspherical polynomial basis\n% with parameter K.\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 m = 1;\nend\n\n% Create the differentation matrix.\nif ( m > 0 )\n D = spdiags((0 : n - 1)', 1, n, n);\n for s = 1:m-1\n D = spdiags(2*s*ones(n, 1), 1, n, n) * D;\n end\nelse\n D = speye(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/@ultraS/diffmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7275230790726909}} {"text": "function M = spm_mesh_polyhedron(name)\n% Return one of the Platonic solids with triangle faces\n% FORMAT M = spm_mesh_polyhedron(name)\n% name - polyhedron name\n% (one of {'tetrahedron','octahedron','icosahedron'})\n% \n% M - patch structure\n%__________________________________________________________________________\n%\n% See https://www.wikipedia.org/wiki/Platonic_solid\n%__________________________________________________________________________\n% Copyright (C) 2012-2018 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin\n% $Id: spm_mesh_polyhedron.m 7383 2018-07-31 10:53:37Z guillaume $\n\n\nswitch lower(name)\n \n case 'tetrahedron'\n M.vertices = [ 1 0 -1/sqrt(2) ;\n -1 0 -1/sqrt(2) ;\n 0 1 1/sqrt(2) ;\n 0 -1 1/sqrt(2) ];\n M.faces = [ 1 2 3 ;\n 1 2 4 ;\n 2 3 4 ;\n 3 1 4];\n\n case 'octahedron'\n M.vertices = [ 0 0 1 ;\n 1 0 0 ;\n 0 1 0 ;\n -1 0 0 ;\n 0 -1 0 ;\n 0 0 -1 ];\n M.faces = [ 1 2 3 ;\n 1 3 4 ;\n 1 4 5 ;\n 1 5 2 ;\n 6 3 2 ;\n 6 4 3 ;\n 6 5 4 ;\n 6 2 5 ];\n \n case 'icosahedron'\n r = (1 + sqrt(5)) / 2;\n M.vertices = [ 1 0 -r ;\n 0 r -1 ;\n r 1 0 ;\n r -1 0 ;\n 0 -r -1 ;\n -1 0 -r ;\n -r 1 0 ;\n 0 r 1 ;\n 1 0 r ;\n 0 -r 1 ;\n -r -1 0 ;\n -1 0 r ];\n M.faces = [ 1 2 3 \n 3 4 1\n 1 4 5\n 5 6 1\n 1 6 2\n 2 6 7\n 7 8 2\n 2 8 3\n 3 8 9\n 9 4 3\n 4 9 10\n 4 10 5\n 10 11 5\n 5 11 6\n 6 11 7\n 7 12 8\n 8 12 9\n 9 12 10\n 10 12 11\n 11 12 7 ];\n \n otherwise\n error('''%s'' is not a Platonic solid with triangle faces.',name);\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_mesh_polyhedron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.727523076912005}} {"text": "%--------------------------------------------------------------------------\n% [dataout] = steeringvector(array_pos,sig_pos)\n%--------------------------------------------------------------------------\n% 功能:\n% 空间传播方法计算导向矢量\n%--------------------------------------------------------------------------\n% 输入:\n% array_pos 接收信号阵列坐标,按照列排列\n% sig_pos 发射信号阵列坐标 按照列排列\n% lambda 载频波长\n% 输出:\n% A 导向矢量\n%--------------------------------------------------------------------------\n% 例子:\n% c = 3e8;\n% fc = 20e9;\n% lambda = c/fc;\n% tgt_angle = [50 90 140]; \n% R = [1000 5600 9000];\n% \n% tgt_pos = [R.*cosd(tgt_angle);R.*sind(tgt_angle);zeros(1,3)]; \n% radar_pos = [zeros(1,8);lambda/2*(1:8)-4*lambda/2 - lambda/4;zeros(1,8)];\n% steering_vector(radar_pos,tgt_pos(:,1),lambda)\n%--------------------------------------------------------------------------\nfunction A = steering_vector(array_pos,sig_pos,lambda)\nfor idx = 1:size(array_pos,2)\n R(idx,:) = norm(array_pos(:,idx)-sig_pos);\nend\nA = exp(1j.*2*pi*R./lambda);\nA = conj(A);\nend", "meta": {"author": "qwe14789cn", "repo": "SP", "sha": "4134ad2e50a446a3d496517720358a808da2f059", "save_path": "github-repos/MATLAB/qwe14789cn-SP", "path": "github-repos/MATLAB/qwe14789cn-SP/SP-4134ad2e50a446a3d496517720358a808da2f059/+sp/steering_vector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7275182073260907}} {"text": "% FITELLIPSE Least-squares fit of ellipse to 2D points.\n% A = FITELLIPSE(X, Y) returns the parameters of the best-fit\n% ellipse to 2D points (X, Y).\n% The returned vector A contains the center, radii, and orientation\n% of the ellipse, stored as (Cx, Cy, Rx, Ry, theta_radians)\n%\n\n% Authors: Andrew Fitzgibbon, Maurizio Pilu, Bob Fisher\n% Reference: \"Direct Least Squares Fitting of Ellipses\", IEEE T-PAMI, 1999\n%\n% @Article{Fitzgibbon99,\n% author = \"Fitzgibbon, A.~W.and Pilu, M. and Fisher, R.~B.\",\n% title = \"Direct least-squares fitting of ellipses\",\n% journal = pami,\n% year = 1999,\n% volume = 21,\n% number = 5,\n% month = may,\n% pages = \"476--480\"\n% }\n%\n% This is a more bulletproof version than that in the paper, incorporating\n% scaling to reduce roundoff error, correction of behaviour when the input\n% data are on a perfect hyperbola, and returns the geometric parameters\n% of the ellipse, rather than the coefficients of the quadratic form.\n%\n% See also http://research.microsoft.com/en-us/um/people/awf/ellipse/\n%\nfunction a = fitEllipse(X, Y)\n % normalize data\n mx = mean(X);\n my = mean(Y);\n sx = (max(X)-min(X))/2;\n sy = (max(Y)-min(Y))/2;\n\n x = (X-mx)/sx;\n y = (Y-my)/sy;\n\n % Force to column vectors\n x = x(:);\n y = y(:);\n\n % Build design matrix\n D = [ x.*x x.*y y.*y x y ones(size(x)) ];\n\n % Build scatter matrix\n S = D'*D;\n\n % Build 6x6 constraint matrix\n C(6,6) = 0; C(1,3) = -2; C(2,2) = 1; C(3,1) = -2;\n\n % Solve eigensystem\n if 0\n % Old way, numerically unstable if not implemented in matlab\n [gevec, geval] = eig(S,C);\n\n % Find the negative eigenvalue\n I = find(real(diag(geval)) < 1e-8 & ~isinf(diag(geval)));\n\n % Extract eigenvector corresponding to negative eigenvalue\n A = real(gevec(:,I));\n else\n % New way, numerically stabler in C [gevec, geval] = eig(S,C);\n\n % Break into blocks\n tmpA = S(1:3,1:3);\n tmpB = S(1:3,4:6);\n tmpC = S(4:6,4:6);\n tmpD = C(1:3,1:3);\n tmpE = inv(tmpC)*tmpB';\n [evec_x, eval_x] = eig(inv(tmpD) * (tmpA - tmpB*tmpE));\n\n % Find the positive (as det(tmpD) < 0) eigenvalue\n I = find(real(diag(eval_x)) < 1e-8 & ~isinf(diag(eval_x)));\n\n % Extract eigenvector corresponding to negative eigenvalue\n A = real(evec_x(:,I));\n\n % Recover the bottom half...\n evec_y = -tmpE * A;\n A = [A; evec_y];\n end\n\n % unnormalize\n par = [\n A(1)*sy*sy, ...\n A(2)*sx*sy, ...\n A(3)*sx*sx, ...\n -2*A(1)*sy*sy*mx - A(2)*sx*sy*my + A(4)*sx*sy*sy, ...\n -A(2)*sx*sy*mx - 2*A(3)*sx*sx*my + A(5)*sx*sx*sy, ...\n A(1)*sy*sy*mx*mx + A(2)*sx*sy*mx*my + A(3)*sx*sx*my*my ...\n - A(4)*sx*sy*sy*mx - A(5)*sx*sx*sy*my ...\n + A(6)*sx*sx*sy*sy ...\n ]';\n\n % Convert to geometric radii, and centers\n\n thetarad = 0.5*atan2(par(2),par(1) - par(3));\n cost = cos(thetarad);\n sint = sin(thetarad);\n sin_squared = sint.*sint;\n cos_squared = cost.*cost;\n cos_sin = sint .* cost;\n\n Ao = par(6);\n Au = par(4) .* cost + par(5) .* sint;\n Av = - par(4) .* sint + par(5) .* cost;\n Auu = par(1) .* cos_squared + par(3) .* sin_squared + par(2) .* cos_sin;\n Avv = par(1) .* sin_squared + par(3) .* cos_squared - par(2) .* cos_sin;\n\n % ROTATED = [Ao Au Av Auu Avv]\n\n tuCentre = - Au./(2.*Auu);\n tvCentre = - Av./(2.*Avv);\n wCentre = Ao - Auu.*tuCentre.*tuCentre - Avv.*tvCentre.*tvCentre;\n\n uCentre = tuCentre .* cost - tvCentre .* sint;\n vCentre = tuCentre .* sint + tvCentre .* cost;\n\n Ru = -wCentre./Auu;\n Rv = -wCentre./Avv;\n\n Ru = sqrt(abs(Ru)).*sign(Ru);\n Rv = sqrt(abs(Rv)).*sign(Rv);\n\n a = [uCentre, vCentre, Ru, Rv, thetarad];\nend", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Analysis/+general/fitEllipse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.7931059487389966, "lm_q1q2_score": 0.727518188939451}} {"text": "function xfat = r8mat_expand_linear ( m, n, x, mfat, nfat )\n\n%*****************************************************************************80\n%\n%% R8MAT_EXPAND_LINEAR linearly interpolates new data into an R8MAT.\n%\n% Discussion:\n%\n% In this routine, the expansion is specified by giving the number\n% of intermediate values to generate between each pair of original\n% data rows and columns.\n%\n% The interpolation is not actually linear. It uses the functions\n%\n% 1, x, y, and xy.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, N, the number of rows and columns of input data.\n%\n% Input, real X(M,N), the original data.\n%\n% Input, integer MFAT, NFAT, the number of data values to interpolate\n% between each row, and each column, of original data values.\n%\n% Output, real XFAT(M2,N2), the fattened data, where\n% M2 = (M-1)*(MFAT+1)+1,\n% N2 = (N-1)*(NFAT+1)+1.\n%\n for i = 1 : m\n\n if ( i < m )\n ihi = mfat;\n else\n ihi = 0;\n end\n\n for j = 1 : n\n\n if ( j < n )\n jhi = nfat;\n else\n jhi = 0;\n end\n\n if ( i < m )\n ip1 = i+1;\n else\n ip1 = i;\n end\n\n if ( j < n )\n jp1 = j+1;\n else\n jp1 = j;\n end\n\n x00 = x(i,j);\n x10 = x(ip1,j);\n x01 = x(i,jp1);\n x11 = x(ip1,jp1);\n\n for ii = 0 : ihi\n\n s = ii / ( ihi + 1 );\n\n for jj = 0 : jhi\n\n t = jj / ( jhi + 1 );\n\n iii = 1 + ( i - 1 ) * ( mfat + 1 ) + ii;\n jjj = 1 + ( j - 1 ) * ( nfat + 1 ) + jj;\n\n xfat(iii,jjj) = ...\n x00 ...\n + s * ( x10 - x00 ) ...\n + t * ( x01 - x00 ) ...\n + s * t * ( x11 - x10 - x01 + x00 );\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/r8lib/r8mat_expand_linear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.8558511432905481, "lm_q1q2_score": 0.7274488024505469}} {"text": "function [x,y,s,exitCode]=secondOrderConeInteriorPoint(A,b,c,blockLengths,params)\n%%SECONDORDERCONEINTERIORPOINT Perform second order cone programming\n% (SOCP) using an interior point algorithm. This solves the\n% primal optimization problem:\n% minimize sum_{i=1}^n c_i'*x_i\n% subject to sum_{i=1}^n A_i*x_i=b\n% and x_i(1)-norm(x_i(2:end))>=0 (second order cone constraint)\n% which is equivalent to the dual optimization problem\n% maximize b'*y\n% subject to sum_{i=1}^n A_i'*y_i+s_i=c_i\n% and s_i(1)-norm(s_i(2:end))>=0\n% Many types of optimization problems can be formulated as SOCP\n% problems. This function only supports optimization in the real\n% domain.\n%\n%INPUTS: A A real mXsum(blockLengths) matrix containing coefficients for\n% all of the constraints on the primal. A must have full row rank.\n% With regard to the A_i in the problem formulation,\n% A=[A_1,a_2,...A_n]\n% b An mX1 real vector the coefficients of the dual objective\n% function to maximize.\n% c A sum(blockLengths)X1 vector containing the coefficients of the\n% primal objective function to minimize. With regard to the c_i in\n% the problem formulation, c=[c_1;c_2;...;c_n].\n% blockLengths An nX1 vector containing the length of each of the cone\n% constraints. That is the first primal cone constraint is \n% x(1)-norm(x(2:blockLengths(1)))>=0. The second is \n% x(blockLengths(1)+1)-norm(x((blockLengths(1)+1):(blockLengths(1)+blockLengths(2)-1)))\n% and so on when considering the full stacked x vector (all of the\n% x_i stacked).\n% params An optional structure of parameters controlling the behaviour of\n% the algorithm. Possible members of the structure are:\n% gammaScal\n% 'delta' A onstant parameter affecting the scale of a line search\n% in the algorithm. 04&&~isempty(params))\n if(isfield(params,'gammaScal'))\n gammaScal=params.gammaScal;\n end\n \n if(isfield(params,'delta'))\n delta=params.delta;\n end\n \n if(isfield(params,'sigma'))\n sigma=params.sigma;\n end\n \n if(isfield(params,'mu0'))\n mu0=params.mu0;\n end\n \n if(isfield(params,'maxIter'))\n maxIter=params.maxIter;\n end\n \n if(isfield(params,'epsNormH'))\n epsNormH=params.epsNormH;\n end\n \n if(isfield(params,'minProgress'))\n minProgress=params.minProgress;\n end\nend\n\n%Initialization before step 1\nmu=mu0*ones(numBlocks,1);\nzBar=[zeros(k+m,1);mu];%A constant\n\n%We want initial x values that satisfy the cone constraints. We could set\n%then all zero, but that would put it right on the boundary, so we will\n%make all of the first elements of the cone constraints 1 and the rest\n%zero, which puts it a bit away from the boundary.\nx=zeros(k,1);\ncurIdx=1;\nfor curBlock=1:numBlocks\n x(curIdx)=1;\n curIdx=curIdx+blockLengths(curBlock);\nend\n\n%Initial dual variables.\ny=zeros(m,1);%Dual variables initially just zero.\ns=c-A'*y;%s must satisfy A'*y+s=c.\nH=HFun(x,s,mu,A,b,blockIndices);\nnormH=norm(H);\nnormHPrev=Inf;\n\nlkPrev=0;\n\n%gammaVal satisfies both of the constraints for gamma: It is less than 1\n%(as gammaScal is less than 1) and it is less than 1/normH.\ngammaVal=gammaScal*min(1,1/normH);\n\nif(any(~isreal(H)|~isfinite(H)))\n x=[];\n y=[];\n s=[];\n exitCode=3;%Numerical errors.\n return; \nend\n\nfor curIter=1:maxIter\n%%Step 1\n if(normH=0. In this instance,\n %rather than just searching from 0 and going upwards, we start at the\n %last found value. In large problems, this can make a difference as lk\n %does not necessarily change much and is often not just 0.\n\n lk=lkPrev;\n lambda=delta^lk;\n xNew=x+lambda*deltaX;\n yNew=y+lambda*deltaY;\n muNew=mu+lambda*deltaMu;\n sNew=c-A'*yNew;\n HNew=HFun(xNew,sNew,muNew,A,b,blockIndices);\n normHNew=norm(HNew);\n boolValPrev=normHNew<=(1-sigma*(1-gammaVal*mu0)*lambda)*normH;\n \n while(1)\n if(boolValPrev==true)\n if(lk==0)\n break;\n end\n lk=lk-1;\n else\n lk=lk+1;\n end\n lambda=delta^lk;\n xNew=x+lambda*deltaX;\n yNew=y+lambda*deltaY;\n muNew=mu+lambda*deltaMu;\n sNew=c-A'*yNew;\n HNew=HFun(xNew,sNew,muNew,A,b,blockIndices);\n normHNew=norm(HNew);\n boolVal=normHNew<=(1-sigma*(1-gammaVal*mu0)*lambda)*normH;\n \n if(boolVal==true && boolValPrev==false)\n break;\n end\n boolValPrev=boolVal;\n end\n \n %We subtract one, because the loop above wants to try to bound the\n %correct lk value.\n lkPrev=max(lk-1,0);\n \n x=xNew;\n y=yNew;\n mu=muNew;\n s=sNew;\n H=HNew;\n normHPrev=normH;\n normH=normHNew;\nend\n\n%Maximum number of iterations completed.\nexitCode=1;\n\nend\n\nfunction blockIndices=makeIndexList(blockLengths)\n%%MAKEINDEXLIST This takes the vector of block lentghs and returns a cell\n% array where the ith element contains the indices of the\n% components in the ith block.\n\nnumBlocks=length(blockLengths);\n\nblockIndices=cell(numBlocks,1);\ncurIdx=1;\nfor curBlock=1:numBlocks\n blockIndices{curBlock}=curIdx:(curIdx+blockLengths(curBlock)-1);\n curIdx=curIdx+blockLengths(curBlock);\nend\nend\n\nfunction H=HFun(x,s,mu,A,b,blockIndices)\n%%HFUN This implements the function H(z) from Equation 6. Note that s is\n%%used instead of y, because c-A'*y is supposed to be passed as the second\n%%argument to phiFun and that is equal to s.\n\nH=[b-A*x;\n phiFun(x,s,mu,blockIndices);\n mu];\nend\n\nfunction gradG=HFunGrad(x,s,mu,A,blockIndices)\n%%GRADH This function implements the gradient of H(z) in Equation 10. It\n% has been modified to handle more than one constraint.\n\nm=size(A,1);\nk=size(A,2);\nnumBlocks=length(blockIndices);\n\nM=zeros(k,k);\nN=zeros(k,k);\nP=zeros(k,numBlocks);\n\n%Allocate space and zero.\ngradG=zeros(m+k+numBlocks,m+k+numBlocks);\n\ngradG(1:m,1:k)=-A;%The first m rows.\n\nfor curBlock=1:numBlocks\n sel=blockIndices{curBlock};\n xCur=x(sel);\n sCur=s(sel);\n muCur=mu(curBlock);\n \n %e is defined toward the beginning of section 2.\n blockLength=length(sel);\n e=zeros(blockLength,1);\n e(1)=1;\n \n w1Bar=xCur+muCur*sCur;%s=c-A'*y\n w2Bar=muCur*xCur+sCur;\n wBar=vectorSqrt(vectorSquared(w1Bar)+vectorSquared(w2Bar)+2*muCur^2*e);\n \n %Lw is defined at the beginning of Section 2. Lw should be positive\n %definite, but is often pooly conditioned, so we use a pseudoinverse.\n Lw=Lx(wBar);\n [LwChol,cholDidFail]=chol(Lw,'lower');\n if(cholDidFail)\n LwInv=pinv(Lx(wBar));\n else\n opts.LT=true;\n opts.UT=false;\n %Solve using forward substitution.\n temp=linsolve(LwChol,eye(size(Lw)),opts);\n opts.UT=true;\n opts.LT=false;\n %Solve using backward substitution.\n LwInv=linsolve(LwChol',temp,opts);\n end\n\n Lw1=Lx(w1Bar);\n Lw2=Lx(w2Bar);\n \n M(sel,sel)=(1+muCur)*eye(blockLength,blockLength)-LwInv*(Lw1+muCur*Lw2);\n N(sel,sel)=(1+muCur)*eye(blockLength,blockLength)-LwInv*(muCur*Lw1+Lw2);\n P(sel,curBlock)=xCur+sCur-LwInv*(Lw1*sCur+Lw2*xCur+2*muCur*e); \nend\n\ngradG((m+1):(m+k),1:k)=M;\ngradG((m+1):(m+k),(k+1):(k+m))=-N*A';\ngradG((m+1):(m+k),(k+m+1):(k+m+numBlocks))=P;\ngradG((m+k+1):(m+k+numBlocks),(m+k+1):(m+k+numBlocks))=eye(numBlocks,numBlocks);\n\nend\n\nfunction val=Lx(x)\n%%LX Create the arrow-shaped matrix Lx that is given toward the beginning\n% of section 2. x must be a single set of cone variables.\n\n x0=x(1);\n xBar=x(2:end);\n xBarLen=length(xBar);\n \n val=[x0,xBar';\n xBar,x0*eye(xBarLen,xBarLen)];\nend\n\n\nfunction phi=phiFun(x,s,mu,blockIndices)\n%%PHIBAR This implements phi(x,s,mu) from Equation 4. It has been modified\n%%to deal with multiple blocks. in this instance, the value for each block\n%%is stacked.\n\nnumBlocks=length(blockIndices);\n\nphi=zeros(length(x),1);\n\n%jordan_sqrt(jordan_square\nfor curBlock=1:numBlocks\n sel=blockIndices{curBlock};\n \n %e is defined toward the beginning of section 2.\n numIdx=length(sel);\n e=zeros(numIdx,1);\n e(1)=1;\n \n muCur=mu(curBlock);\n xCur=x(sel);\n sCur=s(sel);\n\n phi(sel)=(1+muCur)*(xCur+sCur)-vectorSqrt(vectorSquared(xCur+muCur*sCur)+vectorSquared(muCur*xCur+sCur)+2*muCur^2*e);\nend\n\nend\n\nfunction xSquared=vectorSquared(x)\n%%VECTORSQUARED In Section 2, a definition of the square a second order\n%cone vector in terms of a spectral factorization is given. It is\n%%implemented in this function.\n\n[lambda,u]=vectorSpectralFact(x);\n\nxSquared=lambda(1)^2*u(:,1)+lambda(2)^2*u(:,2);\n\nend\n\nfunction sqrtX=vectorSqrt(x)\n%%VECTORSQRT In Section 2, a definition of the square root of a second\n%%order cone vector in terms of a spectral factorization is given. It is\n%%implemented in this function.\n\n[lambda,u]=vectorSpectralFact(x);\n\n%sqrtX should be real.\nsqrtX=sqrt(lambda(1))*u(:,1)+sqrt(lambda(2))*u(:,2);\n\nend\n\nfunction [lambda,u]=vectorSpectralFact(x)\n%%SPECTRALFACT In section 2, a spectral factorization of a second order\n% cone vector is defined. The vector is factored into spectral values\n% lambda and spectral vectors u. This function computes the\n% factorization.\n\nx0=x(1);\nx1=x(2:end);\nx1Mag=norm(x1);\n\n%lambda should be positive. However, finite precision errors might push it\n%negative.\nlambda=abs([x0-x1Mag;x0+x1Mag]);\n\nx1Norm=x1/x1Mag;\nif(~all(isfinite(x1Norm)))\n x1Norm=zeros(size(x1));\n x1Norm(1)=1;\nend\n\nu=(1/2)*[[1;-x1Norm],[1;x1Norm]];\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/secondOrderConeInteriorPoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305638, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7274381366058157}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% \tWRITE A FUNCTION THAT COMPUTES THE JACOBIAN OF A ROBOT\n%\n% Jn = compute_jacobian(robot, q)\n% \n% The method exposed here as a solution is translated from the method in:\n% \n% \"Robot Modeling and Control\". Mark W. Spong, Seth Hutchinson, M. Vidyasagar\n% Ed. Wiley\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Copyright (C) 2016, 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 Jn = compute_jacobian(robot, q)\nJn = []; %Initialize J\nfor i=1:robot.DOF,\n Ji = jacobian_submatrix(robot, q, i); \n Jn = [Jn Ji]; % Add submatrix to J\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Computes the value of the submatrix Ji which accounts for the\n% contribution of joint i (either rotational or prismatic) in the\n% rotational and translational speed of the end effector.\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Ji = jacobian_submatrix(robot, q, i)\n%CAution, the following functions are evaluated according to the values of q\n%compute direct kinematics for serial robotics\ntheta = eval(robot.DH.theta);\nd = eval(robot.DH.d);\na = eval(robot.DH.a);\nalfa = eval(robot.DH.alpha);\n\n%load the position/orientation of the robot's base\nT = robot.T0;\n%Compute Matrix until joint i-1 (note that no computation is performed for i=1)\nfor j=1:i-1,\n T=T*dh(theta(j), d(j), a(j), alfa(j)); \nend\n\n% obtain z_{i-1}\nzim = T(1:3,3);\n% obtain o_{i-1}\noim = T(1:3,4);\n%a zero vector\nzero = zeros(3,1);\n\n%Compute the end effector's position\nT = directkinematic(robot, q);\non = T(1:3,4);\n\n%rotational joint\nif robot.kind(i) == 'R'\n Ji = [cross(zim,(on-oim)); zim];\nelse %prismatic joint\n Ji = [zim; zero];\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/exercises/jacobian_analysis/solution/compute_jacobian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7274381258980147}} {"text": "function [ MRI_signal_noisy ] = add_Rician_noise_to_simulated_dMRI_data( MRI_signal, SNR )\n%ADD_RICIAN_NOISE_TO_SIMULATED_DMRI_DATA adds Rician noise to simulated\n%MRI_signals.\n%\n% inputs: noisefree MRI_signal and SNR\n% outputs: noisy MRI_signal\n%\n% noisy signal, S = |S* + N1 + iN2|\n% where S* = noise-free signal\n% N1 and N2 are random numbers, drawn from normal distribution, with mean=0, and std = 1/SNR.\n\n% Author: Joanne Bates \n% Copyright (c) 2015 University of Oxford\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\nno_of_directions = size(MRI_signal); \nN1 = (1/SNR).*randn(no_of_directions);\nN2 = (1/SNR).*randn(no_of_directions);\n\nMRI_signal_noisy = abs(MRI_signal + N1 + 1i.*N2);\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/DiffusionMRIToolbox/add_Rician_noise_to_simulated_dMRI_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.7853085859124003, "lm_q1q2_score": 0.7274342789532379}} {"text": "function yhat=spence21(y)\n% function for Spencer's 21-point graduation rule.\n% set out following Spencer's hand-calculation method,\n% which isn't the shortest computer program!\n\noten = ones(10,1);\nn = length(y);\ny = [ oten*y(1); y; oten*y(n) ];\n\nn = length(y);\nk = 4:(n-3);\ny1 = -y(k-3) + y(k-1) + 2*y(k) + y(k+1) -y(k+3);\n\nn = length(y1);\nk = 4:(n-3);\ny2 = y1(k-3)+y1(k-2)+y1(k-1)+y1(k)+y1(k+1)+y1(k+2)+y1(k+3);\n\nn = length(y2);\nk = 3:(n-2);\ny3 = y2(k-2)+y2(k-1)+y2(k)+y2(k+1)+y2(k+2);\n\nn = length(y3);\nk = 3:(n-2);\ny4 = y3(k-2)+y3(k-1)+y3(k)+y3(k+1)+y3(k+2);\n\nyhat = y4/350;\nreturn;\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/locfit/m/spence21.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7274342677694888}} {"text": "function [ a, seed ] = wathen_ge ( nx, ny, n, seed )\n\n%*****************************************************************************80\n%\n%% WATHEN_GE returns the Wathen matrix, using general (GE) 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% 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% 04 June 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(N,N), the matrix.\n%\n a = zeros ( n, 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 [ rho, seed ] = r8mat_uniform_01 ( nx, ny, seed );\n rho = 100.0 * rho;\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 for krow = 1 : 8\n for kcol = 1 : 8\n a(node(krow),node(kcol)) = a(node(krow),node(kcol)) ...\n + rho(i,j) * 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/sparse_display/wathen_ge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7274131266447922}} {"text": "function H = hessian_2sided_nrows(f,x,k,varargin)\n% Computes the last K rows of a 2-sided finite difference Hessian\n%\n% USAGE:\n% H=hessian_2sided_nrows(FUNC,X,K,VARARGIN)\n%\n% INPUTS:\n% FUNC - Function name, fval = func(x,varargin)\n% X - Vector of parameters (N x 1)\n% K - Number of rows to compute\n% VARARGIN - Optional arguments passed to the function\n%\n% OUTPUTS:\n% H - Finite difference, 2-sided hessian: N x K\n%\n% COMMENTS:\n% Modification of hessian_2sided\n% See also HESSIAN_2SIDED\n\n% Code originally from COMPECON toolbox [www4.ncsu.edu/~pfackler]\n% documentation modified to fit the format of the Econometrics Toolbox\n% by James P. LeSage, Dept of Economics\n% University of Toledo\n% 2801 W. Bancroft St,\n% Toledo, OH 43606\n% jlesage@spatial-econometrics.com\n%\n% Further modified (to do 2-sided numerical derivs, rather than 1) by:\n% Modifications Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 9/1/2005\n\nif size(x,2)>size(x,1)\n x=x';\nend\nif size(x,2)~=1\n error('X must be a column vector.')\nend\nn = size(x,1);\n\ntry\n feval(f,x,varargin{:});\ncatch FE\n errtxt=['There was an error evaluating the function. Please check the arguements. The specific error was:' FE.message];\n error(errtxt);\nend\n\n\nfx = feval(f,x,varargin{:});\n\n% Compute the stepsize (h)\nh = eps.^(1/3)*max(abs(x),1e-2);\nxh = x+h;\nh = xh-x;\n\nee = sparse(1:n,1:n,h,n,n);\n\n% Compute forward and backward steps\ngp = zeros(n,1);\ngm = zeros(n,1);\nfor i=1:n\n gp(i) = feval(f,x+ee(:,i),varargin{:});\n gm(i) = feval(f,x-ee(:,i),varargin{:});\nend\n\nhh=h*h';\nHm=NaN*ones(n);\nHp=NaN*ones(n);\n% Compute \"double\" forward and backward steps\nfor i=n-k+1:n\n for j=1:n\n Hp(i,j) = feval(f,x+ee(:,i)+ee(:,j),varargin{:});\n Hp(j,i)=Hp(i,j);\n Hm(i,j) = feval(f,x-ee(:,i)-ee(:,j),varargin{:});\n Hm(j,i)=Hm(i,j);\n end\nend\n%Compute the hessian\nH = zeros(n);\nfor i=(n-k+1):n\n for j=1:n\n H(i,j) = (Hp(i,j)-gp(i)-gp(j)+fx+fx-gm(i)-gm(j)+Hm(i,j))/hh(i,j)/2;\n H(j,i) = H(i,j);\n end\nend\n\n%Only the final K rows\nH=H((n-k+1):n,:);\n", "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/utility/hessian_2sided_nrows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7273745588367304}} {"text": "function [ value, ifault ] = betain ( x, p, q, beta )\n\n%*****************************************************************************80\n%\n%% BETAIN computes the incomplete Beta function ratio.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 January 2008\n%\n% Author:\n%\n% Original FORTRAN77 version by KL Majumder, GP Bhattacharjee.\n% FORTRAN90 version by John Burkardt.\n%\n% Reference:\n%\n% KL Majumder, GP Bhattacharjee,\n% Algorithm AS 63:\n% The incomplete Beta Integral,\n% Applied Statistics,\n% Volume 22, Number 3, 1973, pages 409-411.\n%\n% Parameters:\n%\n% Input, real X, the argument, between 0 and 1.\n%\n% Input, real P, Q, the parameters, which\n% must be positive.\n%\n% Input, real BETA, the logarithm of the complete\n% beta function.\n%\n% Output, real BETAIN, the value of the incomplete\n% Beta function ratio.\n%\n% Output, integer IFAULT, error flag.\n% 0, no error.\n% nonzero, an error occurred.\n%\n acu = 0.1D-14;\n\n value = x;\n ifault = 0;\n%\n% Check the input arguments.\n%\n if ( p <= 0.0 | q <= 0.0 )\n ifault = 1;\n return\n end\n\n if ( x < 0.0 | 1.0 < x )\n ifault = 2;\n return\n end\n%\n% Special cases.\n%\n if ( x == 0.0 | x == 1.0 )\n return\n end\n%\n% Change tail if necessary and determine S.\n%\n psq = p + q;\n cx = 1.0 - x;\n\n if ( p < psq * x )\n xx = cx;\n cx = x;\n pp = q;\n qq = p;\n indx = 1;\n else\n xx = x;\n pp = p;\n qq = q;\n indx = 0;\n end\n\n term = 1.0;\n ai = 1.0;\n value = 1.0;\n ns = floor ( qq + cx * psq );\n%\n% Use the Soper reduction formula.\n%\n rx = xx / cx;\n temp = qq - ai;\n if ( ns == 0 )\n rx = xx;\n end\n\n while ( 1 )\n\n term = term * temp * rx / ( pp + ai );\n value = value + term;\n temp = abs ( term );\n\n if ( temp <= acu & temp <= acu * value )\n\n value = value * exp ( pp * log ( xx ) ...\n + ( qq - 1.0 ) * log ( cx ) - beta ) / pp;\n\n if ( indx )\n value = 1.0 - value;\n end\n\n break\n\n end\n\n ai = ai + 1.0;\n ns = ns - 1;\n\n if ( 0 <= ns )\n temp = qq - ai;\n if ( ns == 0 )\n rx = xx;\n end\n else\n temp = psq;\n psq = psq + 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/asa226/betain.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7273745572329192}} {"text": "function value = f_02 ( x )\n\n%*****************************************************************************80\n%\n%% F_02 evaluates 2*x-exp(-x).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 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 = 2.0 * x - exp ( - 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/brent/f_02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8354835432479663, "lm_q1q2_score": 0.7273696905518181}} {"text": "function grid_index = multigrid_scale_closed ( dim_num, order_nd, level_max, ...\n level_1d, grid_index )\n\n%*****************************************************************************80\n%\n%% MULTIGRID_SCALE_CLOSED renumbers a grid as a subgrid on a higher level.\n%\n% Discussion:\n%\n% This routine takes a grid associated with a given value of\n% LEVEL, and multiplies all the indices by a power of 2, so that\n% the indices reflect the position of the same points, but in\n% a grid of level LEVEL_MAX.\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% 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 ORDER_ND, the number of points in the grid.\n%\n% Input, integer LEVEL_MAX, the maximum value of LEVEL.\n%\n% Input, integer LEVEL_1D(DIM_NUM), the level in each dimension.\n%\n% Input, integer GRID_INDEX(DIM_NUM,POINT_NUM), the index\n% values for each grid point, based in the level for which the grid \n% was generated.\n%\n% Output, integer GRID_INDEX(DIM_NUM,POINT_NUM), the index\n% values for each grid point, appropriate for the grid as a subgrid \n% of a grid of level LEVEL_MAX.\n%\n for dim = 1 : dim_num\n\n if ( level_1d(dim) == 0 )\n\n if ( 0 == level_max )\n order_max = 1;\n else\n order_max = 2^level_max + 1;\n end\n\n grid_index(dim,1:order_nd) = floor ( ( order_max - 1 ) / 2 );\n\n else\n\n factor = 2^( level_max - level_1d(dim) );\n\n grid_index(dim,1:order_nd) = grid_index(dim,1:order_nd) * factor;\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/sandia_sparse/multigrid_scale_closed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7273696775482704}} {"text": "function spline_test07 ( )\n\n%*****************************************************************************80\n%\n%% TEST07 tests BASIS_MATRIX_OVERHAUSER_UNI, BASIS_MATRIX_TMP.\n%\n% Discussion:\n%\n% YDATA(1:NDATA) = ( TDATA(1:NDATA) + 2 )**2 + 3\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 February 2009\n%\n% Author\n%\n% John Burkardt\n%\n n = 4;\n ndata = 4;\n nsample = 4;\n tdata = [ -1.0E+00, 0.0E+00, 1.0E+00, 2.0E+00 ];\n ydata = [ 4.0E+00, 7.0E+00, 12.0E+00, 19.0E+00 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST07\\n' );\n fprintf ( 1, ' BASIS_MATRIX_OVERHAUSER_UNI sets up the basis\\n' );\n fprintf ( 1, ' matrix for the uniform Overhauser spline.\\n' );\n\n mbasis = basis_matrix_overhauser_uni ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' TDATA, YDATA\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : ndata\n fprintf ( 1, '%14f %14f\\n', tdata(i), ydata(i) );\n end\n\n left = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' T, Spline(T)\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : ndata\n\n if ( i == 0 )\n tlo = tdata(1) - 0.5E+00 * ( tdata(2) - tdata(1) );\n thi = tdata(1);\n elseif ( i < ndata )\n tlo = tdata(i);\n thi = tdata(i+1);\n elseif ( ndata <= i )\n tlo = tdata(ndata);\n thi = tdata(ndata) + 0.5E+00 * ( tdata(ndata) - tdata(ndata-1) );\n end\n\n if ( i < ndata )\n jhi = nsample - 1;\n else\n jhi = nsample;\n end\n\n for j = 0 : jhi\n\n tval = ( ( nsample - j ) * tlo ...\n + ( j ) * thi ) ...\n / nsample; \n\n yval = basis_matrix_tmp ( left, n, mbasis, ndata, tdata, ydata, tval );\n\n if ( 0 < i & j == 0 )\n mark = '*';\n else\n mark = ' ';\n end\n\n fprintf ( 1, '%c %14f %14f\\n', mark, tval, yval );\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/spline/spline_test07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7273596860867234}} {"text": "clear;\nclc;\nformat short;\n\n\n%% 线性代数及其应用第5版 5.8 Iterative Estimates For EienValues\n\n%% EXAMPLE 1\nA = [1.8 0.8; 0.2 1.2];\nv1 = [4 1]';\nx = [-0.5 1]';\n\nfor i = 1:8\n x = A*x;\nend\n\nx = x / norm(x);\nv1= v1 / norm(v1);\n% \n% fprintf(\"可以看到 x 逼近v1的方向\\r\\n\");\n% x\n% v1\n\n%% EXAMPLE 2\nA = [6 5; 1 2];\nx = [0 1]';\n\n\nfor i = 1:8\n x = A*x;\n lanbda = abs(max(x));\n x = x / lanbda;\n\nend\n\nx\nlanbda\n\n", "meta": {"author": "yandld", "repo": "nav_matlab", "sha": "da70cb2083de407409ebe1ec1096a308611cf063", "save_path": "github-repos/MATLAB/yandld-nav_matlab", "path": "github-repos/MATLAB/yandld-nav_matlab/nav_matlab-da70cb2083de407409ebe1ec1096a308611cf063/study/linear_algebra/power_method_eig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.798186784940666, "lm_q1q2_score": 0.7272915993871482}} {"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.gomp_2_mmv = zeros(num_ss, 1);\nsuccess_with_s.gomp_4_mmv = 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.gomp_2_mmv = 0;\n num_successes.gomp_4_mmv = 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 Generalized OMP MMV with L=2\n solver = spx.pursuit.joint.GOMP(Phi, K, 2);\n solver.L = 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.gomp_2_mmv = num_successes.gomp_2_mmv + success;\n\n % Create the solver for Generalized OMP MMV with L=4\n solver = spx.pursuit.joint.GOMP(Phi, K, 2);\n solver.L = 4;\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.gomp_4_mmv = num_successes.gomp_4_mmv + 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.gomp_2_mmv(ns) = num_successes.gomp_2_mmv / num_trials;\n success_with_s.gomp_4_mmv(ns) = num_successes.gomp_4_mmv / 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/gomp_mmv/ex_comparison_with_s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7272913473508765}} {"text": "function gegenbauer_rule ( order, alpha, a, b, filename )\n\n%*****************************************************************************80\n%\n%% GEGENBAUER_RULE generates a Gauss-Gegenbauer rule.\n%\n% Discussion:\n%\n% This program computes a standard Gauss-Gegenbauer quadrature rule\n% and writes it to a file.\n%\n% The user specifies:\n% * the ORDER (number of points) in the rule;\n% * the ALPHA parameter;\n% * A, the left endpoint;\n% * B, the right endpoint;\n% * FILENAME, the root name of the output files.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GEGENBAUER_RULE\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Compute a Gauss-Gegenbauer rule for approximating\\n' );\n fprintf ( 1, ' Integral ( A <= x <= B ) ((x-A)(B-X))^ALPHA f(x) dx\\n' );\n fprintf ( 1, ' of order ORDER.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The user specifies ORDER, ALPHA, A, B, and FILENAME.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ORDER is the number of points:\\n' );\n fprintf ( 1, ' ALPHA is the exponent:\\n' );\n fprintf ( 1, ' A is the left endpoint;\\n' );\n fprintf ( 1, ' B is the right endpoint;\\n' );\n fprintf ( 1, ' FILENAME is used to generate 3 files:\\n' );\n fprintf ( 1, ' filename_w.txt - the weight file\\n' );\n fprintf ( 1, ' filename_x.txt - the abscissa file.\\n' );\n fprintf ( 1, ' filename_r.txt - the region file.\\n' );\n%\n% Initialize the parameters.\n%\n beta = 0.0;\n%\n% Get ORDER.\n%\n if ( nargin < 1 )\n order = input ( ' Enter the rule order ORDER: ' );\n elseif ( ischar ( order ) )\n order = str2num ( order );\n else\n%\n% Get ALPHA.\n%\n if ( nargin < 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ALPHA is the exponent of ((x-A)(B-X)) in the integral:\\n' );\n fprintf ( 1, ' Note that -1.0 < ALPHA is required.\\n' );\n fprintf ( 1, '\\n' );\n alpha = input ( ' Enter the value of ALPHA: ' );\n elseif ( ischar ( alpha ) )\n alpha = str2num ( alpha );\n end\n%\n% Get A.\n%\n if ( nargin < 3 )\n a = input ( ' Enter the left endpoint A: ' );\n elseif ( ischar ( a ) )\n a = str2num ( a );\n end\n%\n% Get B.\n%\n if ( nargin < 4 )\n b = input ( ' Enter the right endpoint B: ' );\n elseif ( ischar ( b ) )\n b = str2num ( b );\n end\n%\n% Get FILENAME.\n%\n if ( nargin < 5 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' FILENAME is the ''root name'' of the quadrature files).\\n' );\n filename = input ( ' Enter FILENAME as a quoted string: ' );\n end\n%\n% Input summary.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ORDER = %d\\n', order );\n fprintf ( 1, ' ALPHA = %f\\n', alpha );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n fprintf ( 1, ' FILENAME = \"%s\".\\n', filename );\n%\n% Construct the rule.\n%\n kind = 3;\n [ x, w ] = cgqf ( order, kind, alpha, beta, a, b );\n%\n% Write the rule.\n%\n r = [ a, b ]';\n rule_write ( order, filename, x, w, r );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GEGENBAUER_RULE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction [ t, wts ] = cdgqf ( nt, kind, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CDGQF computes a Gauss quadrature formula with default A, B and simple knots.\n%\n% Discussion:\n%\n% This routine computes all the knots and weights of a Gauss quadrature\n% formula with a classical weight function with default values for A and B,\n% and only simple knots.\n%\n% There are no moments checks and no printing is done.\n%\n% Use routine EIQFS to evaluate a quadrature computed by CGQFS.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n parchk ( kind, 2 * nt, alpha, beta );\n%\n% Get the Jacobi matrix and zero-th moment.\n%\n [ aj, bj, zemu ] = class_matrix ( kind, nt, alpha, beta );\n%\n% Compute the knots and weights.\n%\n [ t, wts ] = sgqf ( nt, aj, bj, zemu );\n\n return\nend\nfunction [ t, wts ] = cgqf ( nt, kind, alpha, beta, a, b )\n\n%*****************************************************************************80\n%\n%% CGQF computes knots and weights of a Gauss quadrature formula.\n%\n% Discussion:\n%\n% The user may specify the interval (A,B).\n%\n% Only simple knots are produced.\n%\n% The user may request that the routine print the knots and weights,\n% and perform a moment check.\n%\n% Use routine EIQFS to evaluate this quadrature formula.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, real A, B, the interval endpoints.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Compute the Gauss quadrature formula for default values of A and B.\n%\n [ t, wts ] = cdgqf ( nt, kind, alpha, beta );\n%\n% All knots have multiplicity = 1.\n%\n mlt = zeros(nt,1);\n mlt(1:nt) = 1;\n%\n% NDX(I) = I.\n%\n ndx = ( 1 : nt );\n%\n% Scale the quadrature rule.\n%\n [ t, wts ] = scqf ( nt, t, mlt, wts, nt, ndx, kind, alpha, beta, a, b );\n\n return\nend\nfunction [ aj, bj, zemu ] = class_matrix ( kind, m, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CLASS_MATRIX computes the Jacobi matrix for a quadrature rule.\n%\n% Discussion:\n%\n% This routine computes the diagonal AJ and subdiagonal BJ\n% elements of the order M tridiagonal symmetric Jacobi matrix\n% associated with the polynomials orthogonal with respect to\n% the weight function specified by KIND.\n%\n% For weight functions 1-7, M elements are defined in BJ even\n% though only M-1 are needed. For weight function 8, BJ(M) is\n% set to zero.\n%\n% The zero-th moment of the weight function is returned in ZEMU.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, integer M, the order of the Jacobi matrix.\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Output, real AJ(M), BJ(M), the diagonal and subdiagonal\n% of the Jacobi matrix.\n%\n% Output, real ZEMU, the zero-th moment.\n%\n temp = eps;\n\n parchk ( kind, 2 * m - 1, alpha, beta );\n\n temp2 = 0.5;\n\n if ( 500.0 * temp < abs ( ( gamma ( temp2 ) )^2 - pi ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CLASS - Fatal error!\\n' );\n fprintf ( 1, ' Gamma function does not match machine parameters.\\n' );\n error ( 'CLASS - Fatal error!' );\n end\n\n bj = zeros(m,1);\n aj = zeros(m,1);\n\n if ( kind == 1 )\n\n ab = 0.0;\n\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod ( i, 2 );\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 2 )\n\n zemu = pi;\n\n aj(1:m) = 0.0;\n\n bj(1) = sqrt ( 0.5 );\n bj(2:m) = 0.5;\n\n elseif ( kind == 3 )\n\n ab = alpha * 2.0;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 )^2 ...\n / gamma ( ab + 2.0 );\n\n aj(1:m) = 0.0;\n bj(1) = 1.0 / ( 2.0 * alpha + 3.0 );\n for i = 2 : m\n bj(i) = i * ( i + ab ) / ( 4.0 * ( i + alpha )^2 - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 4 )\n\n ab = alpha + beta;\n abi = 2.0 + ab;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 ) ...\n * gamma ( beta + 1.0 ) / gamma ( abi );\n aj(1) = ( beta - alpha ) / abi;\n bj(1) = 4.0 * ( 1.0 + alpha ) * ( 1.0 + beta ) ...\n / ( ( abi + 1.0 ) * abi * abi );\n a2b2 = beta * beta - alpha * alpha;\n\n for i = 2 : m\n abi = 2.0 * i + ab;\n aj(i) = a2b2 / ( ( abi - 2.0 ) * abi );\n abi = abi^2;\n bj(i) = 4.0 * i * ( i + alpha ) * ( i + beta ) * ( i + ab ) ...\n / ( ( abi - 1.0 ) * abi );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 5 )\n\n zemu = gamma ( alpha + 1.0 );\n\n for i = 1 : m\n aj(i) = 2.0 * i - 1.0 + alpha;\n bj(i) = i * ( i + alpha );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 6 )\n\n zemu = gamma ( ( alpha + 1.0 ) / 2.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n bj(i) = ( i + alpha * mod ( i, 2 ) ) / 2.0;\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 7 )\n\n ab = alpha;\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod(i,2);\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 8 )\n\n ab = alpha + beta;\n zemu = gamma ( alpha + 1.0 ) * gamma ( - ( ab + 1.0 ) ) ...\n / gamma ( - beta );\n apone = alpha + 1.0;\n aba = ab * apone;\n aj(1) = - apone / ( ab + 2.0 );\n bj(1) = - aj(1) * ( beta + 1.0 ) / ( ab + 2.0 ) / ( ab + 3.0 );\n for i = 2 : m\n abti = ab + 2.0 * i;\n aj(i) = aba + 2.0 * ( ab + i ) * ( i - 1 );\n aj(i) = - aj(i) / abti / ( abti - 2.0 );\n end\n\n for i = 2 : m - 1\n abti = ab + 2.0 * i;\n bj(i) = i * ( alpha + i ) / ( abti - 1.0 ) * ( beta + i ) ...\n / ( abti^2 ) * ( ab + i ) / ( abti + 1.0 );\n end\n\n bj(m) = 0.0;\n bj(1:m) = sqrt ( bj(1:m) );\n\n end\n\n return\nend\nfunction [ d, z ] = imtqlx ( n, d, e, z )\n\n%*****************************************************************************80\n%\n%% IMTQLX diagonalizes a symmetric tridiagonal matrix.\n%\n% Discussion:\n%\n% This routine is a slightly modified version of the EISPACK routine to\n% perform the implicit QL algorithm on a symmetric tridiagonal matrix.\n%\n% The authors thank the authors of EISPACK for permission to use this\n% routine.\n%\n% It has been modified to produce the product Q' * Z, where Z is an input\n% vector and Q is the orthogonal matrix diagonalizing the input matrix.\n% The changes consist (essentialy) of applying the orthogonal transformations\n% directly to Z as they are generated.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Roger Martin, James Wilkinson,\n% The Implicit QL Algorithm,\n% Numerische Mathematik,\n% Volume 12, Number 5, December 1968, pages 377-383.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real D(N), the diagonal entries of the matrix.\n%\n% Input, real E(N), the subdiagonal entries of the\n% matrix, in entries E(1) through E(N-1). \n%\n% Input, real Z(N), a vector to be operated on.\n%\n% Output, real D(N), the diagonal entries of the diagonalized matrix.\n%\n% Output, real Z(N), the value of Q' * Z, where Q is the matrix that \n% diagonalizes the input symmetric tridiagonal matrix.\n%\n itn = 30;\n\n prec = eps;\n\n if ( n == 1 )\n return\n end\n\n e(n) = 0.0;\n\n for l = 1 : n\n\n j = 0;\n\n while ( 1 )\n\n for m = l : n\n\n if ( m == n )\n break\n end\n\n if ( abs ( e(m) ) <= prec * ( abs ( d(m) ) + abs ( d(m+1) ) ) )\n break\n end\n\n end\n\n p = d(l);\n\n if ( m == l )\n break\n end\n\n if ( j == itn )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'IMTQLX - Fatal error!\\n' );\n fprintf ( 1, ' Iteration limit exceeded.\\n' );\n error ( 'IMTQLX - Fatal error!' );\n end\n\n j = j + 1;\n g = ( d(l+1) - p ) / ( 2.0 * e(l) );\n r = sqrt ( g * g + 1.0 );\n g = d(m) - p + e(l) / ( g + r8_sign ( g ) * abs ( r ) );\n s = 1.0;\n c = 1.0;\n p = 0.0;\n mml = m - l;\n\n for ii = 1 : mml\n\n i = m - ii;\n f = s * e(i);\n b = c * e(i);\n\n if ( abs ( f ) >= abs ( g ) )\n c = g / f;\n r = sqrt ( c * c + 1.0 );\n e(i+1) = f * r;\n s = 1.0 / r;\n c = c * s;\n else\n s = f / g;\n r = sqrt ( s * s + 1.0 );\n e(i+1) = g * r;\n c = 1.0 / r;\n s = s * c;\n end\n\n g = d(i+1) - p;\n r = ( d(i) - g ) * s + 2.0 * c * b;\n p = s * r;\n d(i+1) = g + p;\n g = c * r - b;\n f = z(i+1);\n z(i+1) = s * z(i) + c * f;\n z(i) = c * z(i) - s * f;\n\n end\n\n d(l) = d(l) - p;\n e(l) = g;\n e(m) = 0.0;\n\n end\n\n end\n\n for ii = 2 : n\n\n i = ii - 1;\n k = i;\n p = d(i);\n\n for j = ii : n\n if ( d(j) < p )\n k = j;\n p = d(j);\n end\n end\n\n if ( k ~= i )\n d(k) = d(i);\n d(i) = p;\n p = z(i);\n z(i) = z(k);\n z(k) = p;\n end\n\n end\n\n return\nend\nfunction parchk ( kind, m, alpha, beta )\n\n%*****************************************************************************80\n%\n%% PARCHK checks parameters ALPHA and BETA for classical weight functions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, integer M, the order of the highest moment to\n% be calculated. This value is only needed when KIND = 8.\n%\n% Input, real ALPHA, BETA, the parameters, if required\n% by the value of KIND.\n%\n if ( kind <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND <= 0.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check ALPHA for Gegenbauer, Jacobi, Laguerre, Hermite, Exponential.\n%\n if ( 3 <= kind && alpha <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' 3 <= KIND and ALPHA <= -1.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check BETA for Jacobi.\n%\n if ( kind == 4 && beta <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND == 4 and BETA <= -1.0.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check ALPHA and BETA for rational.\n%\n if ( kind == 8 )\n tmp = alpha + beta + m + 1.0;\n if ( 0.0 <= tmp || tmp <= beta )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND == 8 but condition on ALPHA and BETA fails.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n end\n\n return\nend\nfunction value = r8_sign ( x )\n\n%*****************************************************************************80\n%\n%% R8_SIGN returns the sign of an R8.\n%\n% Discussion:\n%\n% The value is +1 if the number is positive or zero, and it is -1 otherwise.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the number whose sign is desired.\n%\n% Output, real VALUE, the sign of X.\n%\n if ( 0 <= x )\n value = +1.0;\n else\n value = -1.0;\n end\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 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, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n% For smaller data files, and less precision, try:\n%\n% fprintf ( output_unit, ' %14.6f', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %24.16f', 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 rule_write ( order, filename, x, w, r )\n\n%*****************************************************************************80\n%\n%% RULE_WRITE writes a quadrature rule to a file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the rule.\n%\n% Input, string FILENAME, specifies the output files.\n% write files 'filename_w.txt', 'filename_x.txt', 'filename_r.txt' defining \n% weights, abscissas, and region.\n%\n% Input, real X(ORDER), the abscissas.\n%\n% Input, real W(ORDER), the weights.\n%\n% Input, real R(2), the region.\n%\n filename_x = strcat ( filename, '_x.txt' );\n filename_w = strcat ( filename, '_w.txt' );\n filename_r = strcat ( filename, '_r.txt' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1,' Creating quadrature files.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"Root\" file name is \"%s\".\\n', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Weight file will be \"%s\".\\n', filename_w );\n fprintf ( 1, ' Abscissa file will be \"%s\".\\n', filename_x );\n fprintf ( 1, ' Region file will be \"%s\".\\n', filename_r );\n\n r8mat_write ( filename_w, 1, order, w' );\n r8mat_write ( filename_x, 1, order, x' );\n r8mat_write ( filename_r, 1, 2, r' );\n\n return\nend\nfunction [ t, wts ] = scqf ( nt, t, mlt, wts, nwts, ndx, kind, alpha, ...\n beta, a, b )\n\n%*****************************************************************************80\n%\n%% SCQF scales a quadrature formula to a nonstandard interval.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real T(NT), the original knots.\n%\n% Input, integer MLT(NT), the multiplicity of the knots.\n%\n% Input, real WTS(NWTS), the weights.\n%\n% Input, integer NWTS, the number of weights.\n%\n% Input, integer NDX(NT), used to index the array WTS.\n% For more details see the comments in CAWIQ.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, real A, B, the interval endpoints.\n%\n% Output, real T(NT), the scaled knots.\n%\n% Output, real WTS(NWTS), the scaled weights.\n%\n temp = eps;\n\n parchk ( kind, 1, alpha, beta )\n\n if ( kind == 1 )\n\n al = 0.0;\n be = 0.0;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 2 )\n\n al = -0.5;\n be = -0.5;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 3 )\n\n al = alpha;\n be = alpha;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 4 )\n\n al = alpha;\n be = beta;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 5 )\n\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = 1.0 / b;\n al = alpha;\n be = 0.0;\n\n elseif ( kind == 6 )\n\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = 1.0 / sqrt ( b );\n al = alpha;\n be = 0.0;\n\n elseif ( kind == 7 )\n\n al = alpha;\n be = 0.0;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 8 )\n\n if ( a + b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' A + B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = a + b;\n al = alpha;\n be = beta;\n\n elseif ( kind == 9 )\n\n al = 0.5;\n be = 0.5;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n end\n\n p = slp^( al + be + 1.0 );\n\n for k = 1 : nt\n\n t(k) = shft + slp * t(k);\n l = abs ( ndx(k) );\n\n if ( l ~= 0 )\n tmp = p;\n for i = l : l + mlt(k) - 1\n wts(i) = wts(i) * tmp;\n tmp = tmp * slp;\n end\n end\n\n end\n\n return\nend\nfunction [ t, wts ] = sgqf ( nt, aj, bj, zemu )\n\n%*****************************************************************************80\n%\n%% SGQF computes knots and weights of a Gauss Quadrature formula.\n%\n% Discussion:\n%\n% This routine computes all the knots and weights of a Gauss quadrature\n% formula with simple knots from the Jacobi matrix and the zero-th\n% moment of the weight function, using the Golub-Welsch technique.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real AJ(NT), the diagonal of the Jacobi matrix.\n%\n% Input, real BJ(NT), the subdiagonal of the Jacobi\n% matrix, in entries 1 through NT-1. On output, BJ has been overwritten.\n%\n% Input, real ZEMU, the zero-th moment of the weight function.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Exit if the zero-th moment is not positive.\n%\n if ( zemu <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGQF - Fatal error!\\n' );\n fprintf ( 1, ' ZEMU <= 0.\\n' );\n error ( 'SGQF - Fatal error!' );\n end\n%\n% Set up vectors for IMTQLX.\n%\n wts = zeros ( nt, 1 );\n\n wts(1) = sqrt ( zemu );\n wts(2:nt) = 0.0;\n%\n% Diagonalize the Jacobi matrix.\n%\n [ t, wts ] = imtqlx ( nt, aj, bj, wts );\n\n wts(1:nt) = wts(1:nt).^2;\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/gegenbauer_rule/gegenbauer_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7270478812204759}} {"text": "function value = r8_factorial ( n )\n\n%*****************************************************************************80\n%\n%% R8_FACTORIAL returns N!.\n%\n% Definition:\n%\n% N! = Product ( 1 <= I <= N ) I\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 1999\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the argument of the function.\n% 0 <= N.\n%\n% Output, real VALUE, the factorial of N.\n%\n if ( n < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_FACTORIAL - Fatal error!\\n' );\n fprintf ( 1, ' N < 0.\\n' );\n error ( 'R8_FACTORIAL - Fatal error!' );\n end\n\n value = 1.0;\n\n for i = 2 : n\n value = value * 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/test_mat/r8_factorial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7270478808672581}} {"text": "%---------------------------------------------------------\n% Low-pass FIR digital differentiator (LPFIRDD) design -\n% via constrained quadratic programming (QP) -\n% [Copt,c]=lpfirdd(N,alpha,beta,r,idraw) - \n% By Dr Yangquan Chen\t\t019-07-1999 -\n% Email=; URL=http://www.crosswinds.net/~yqchen/\n% -------------------------------------------------------- \n% LPFIRDD: only 1st order derivative estimate\n% total taps=2N. c(i)=-c(i+N+1); c(N+1)=0 (central point)\n%\n% -N -N+1 -1 N\n% FIR=c(1)z +c(2)z +...+ c(N)z + 0 + ... + c(2N+1)z\n%\n% N\n% ------\n% \\ j -j\n% > Copt(j) * (z - z )\n% /\n% ------\n% j=1\n% N: Taps (N=2, similar to sgfilter(2,2,1,1)\n% alpha ~ beta: transit band of frequency \n%\t\t\t\t (in percentage of Nyquest freq)\n% r: the polynomial order. r<=N Normally, set it to 1.\n%---------------------------------------------------------------\nfunction [Copt,bd]=lpfirdd(N,alpha,beta,r,idraw)\n% testing parameters\n% alpha=1./pi;beta=1.5/pi;N=10;r=1;idraw=1;\nif (alpha>beta)\n disp('Error in alpha (alpha<=beta)');return;\nend\nif ((beta>1) | (beta <0)) \n disp('Error in Beta! (beta in [0,1]');return;\nend\nif ((alpha>1) | (alpha <0)) \n disp('Error in Alpha! (Alpha in [0,1]');return;\nend\n% default r=1\nif (r<1); r=1; end \n% matrix W\nW=zeros(r,N);\nfor ix=1:N;for jx=1:r;\n W(jx,ix)=ix^(2*jx-1);\nend;end\n%matrix L\nL=zeros(N,1);\nif (beta>alpha)\n\tfor ix=1:N\n\t L(ix)=(alpha*sin(ix*beta*pi)-beta*sin(ix*alpha*pi))/ix/ix/(beta-alpha);\n\tend\nelseif (beta==alpha)\n\tfor ix=1:N\n\t L(ix)=(ix*alpha*pi*cos(ix*alpha*pi)-sin(ix*alpha*pi))/ix/ix;\n\tend\nend \n% matrix e\nex=zeros(r,1);ex(1)=1;\n% optimal solution\nCopt=W'*inv(W*W')*(ex + 2.*W*L/pi)-2.*L/pi\nCopt=Copt/2;\n% fr plots\nif (idraw==1)\n bd=[-fliplr(Copt'),0,Copt']';\n\t%ad=1;sys_sg=tf(bd',ad,1./Fs);bode(sys_sg)\n\tFs=12790;nL=N;nR=N;npts=1000;%w=logspace(0,4,npts);\n\tw=((1:npts)-1)*pi/npts;\n\tj=sqrt(-1);ejw=zeros(nL+nR+1,npts);\n\tfor ix=(-nL:nR)\n\t\tejw(ix+nL+1,:)=exp(j*ix*w); \n\tend\n\tfreq=bd'*ejw;\n\tfigure;subplot(2,1,1)\n\tplot(w/pi*Fs/2,(abs(freq)));grid on;\n\thold on; ax=axis;ax(2)=Fs/2;axis(ax);\n\txlabel('freq. (Hz)');ylabel('amplitude (dB)');\n\tsubplot(2,1,2)\n\tplot(w/pi*Fs/2,180*(angle(freq))/pi );grid on;\n\thold on; ax=axis;ax(2)=Fs/2;axis(ax);\n xlabel('freq. (Hz)');ylabel('phase anlge (deg.)');\n \n\tfigure;subplot(2,1,1);Fs=12600; % Hz for U8\n\tsemilogx(w*Fs/pi/2,20*log10(abs(freq)));grid on;\n\thold on; ax=axis;ax(2)=Fs/2;axis(ax);\n\tsemilogx([Fs/2,Fs/2],[ax(3),ax(4)],'o-r');grid on;\n\txlabel('freq. (Hz)');ylabel('amplitude (dB)');\n\tsubplot(2,1,2)\n\tsemilogx(w*Fs/pi/2,180*(angle(freq))/pi );grid on;\n\thold on; ax=axis;ax(2)=Fs/2;axis(ax);\n\tsemilogx([Fs/2,Fs/2],[ax(3),ax(4)],'o-r');grid on;\n\txlabel('freq. (Hz)');ylabel('phase anlge (deg.)');\nend\nreturn\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/3516-low-pass-fir-digital-differentiator-design/lpfirdd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7270447088255565}} {"text": "function [vFrequency, vAmplitude] = fastfft(vData, SampleRate, Plot)\n\n%FASTFFT Create useful data from an FFT operation.\n% Usage: [vFrequency, vAmplitude] = fastfft(vData, SampleRate, [Plot])\n% \n% (no plot will be shown if the last input == 0 or is not included)\n%\n% This function inputs 'vData' as a vector (row or column),\n% 'SampleRate' as a number (samples/sec), 'Plot' as anything,\n% and does the following:\n%\n% 1: Removes the DC offset of the data\n% 2: Puts the data through a hanning window\n% 3: Calculates the Fast Fourier Transform (FFT)\n% 4: Calculates the amplitude from the FFT\n% 5: Calculates the frequency scale\n% 6: Optionally creates a Bode plot\n%\n% Created 7/22/03, Rick Auch, mekaneck@campbellsville.com\n\n%Make vData a row vector\nif size(vData,2)==1\n vData = vData';\nend\n\n%Calculate number of data points in data\nn = length(vData);\n\n%Remove DC Offset\nvData = vData - mean(vData);\n\n%Put data through hanning window using hanning subfunction\nvData = hanning(vData);\n\n%Calculate FFT\nvData = fft(vData);\n\n%Calculate amplitude from FFT (multply by sqrt(8/3) because of effects of hanning window)\nvAmplitude = abs(vData)*sqrt(8/3);\n\n%Calculate frequency scale\nvFrequency = linspace(0,n-1,n)*(SampleRate/n);\n\n%Limit both output vectors due to Nyquist criterion\nDataLimit = ceil(n/2);\nvAmplitude = vAmplitude(1:DataLimit);\nvFrequency = vFrequency(1:DataLimit);\n\nif exist('Plot', 'var')==1 & Plot~=0\n plot(vFrequency, vAmplitude);\n title('Bode Plot');\n xlabel('Frequency (Hz)');\n ylabel('Amplitude');\nend\n\n\n%------------------------------------------------------------------------------------------\n%Hanning Subfunction\nfunction vOutput = hanning(vInput)\n% This function takes a vector input and outputs the same vector,\n% multiplied by the hanning window function\n\n%Determine the number of input data points\nn = length(vInput);\n\n%Initialize the vector\nvHanningFunc = linspace(0,n-1,n);\n\n%Calculate the hanning funtion\nvHanningFunc = .5*(1-cos(2*pi*vHanningFunc/(n-1)));\n\n%Output the result\nvOutput = vInput.*vHanningFunc;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/3770-fastfft-function/fastfft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7270333539857294}} {"text": "function binv = beta_inv (x, a, b)\n% BETA_INV Inverse of the beta cumulative distribution function (cdf).\n% X = BETA_INV(P,A,B) returns the inverse of the beta cdf with\n% parameters A and B at the values in P.\n%\n% Copyright (c) 1995-1997, 2005-2007 Kurt Hornik\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 error('must provide 3 parameters')\nend\n\nif (~isscalar (a) || ~isscalar(b))\n if ((size(a,1) ~= size(b,1)) || (size(b,1) ~= size(x,1)))\n error ('betainv: x, a and b must be of common size or scalars');\n end\nend\n\n[n,nin] = size(x);\nbinv = zeros(n,nin);\n\nk = find ((x<0) || (x>1) || (a<0) || (b<0) || isnan(x));\nif (any(k))\n binv(k) = NaN;\nend\n\nk = find ((x==1) && (a>0) && (b>0));\nif (any (k))\n binv(k) = 1;\nend\n\nk = find ((x > 0) & (x < 1) & (a > 0) & (b > 0));\nif (any (k))\n if (~isscalar(a) || ~isscalar(b))\n a = a(k);\n b = b(k);\n y = a./(a+b);\n else\n y = a/(a + b)*ones(size(k));\n end\n x = x(k);\n l = find (y < eps);\n if (any (l))\n y(l) = sqrt (eps) * ones (length (l), 1);\n end\n l = find (y > 1 - eps);\n if (any (l))\n y(l) = 1 - sqrt (eps) * ones (length (l), 1);\n end\n \n y_old = y;\n for i = 1 : 10000\n h = (beta_cdf (y_old, a, b) - x) ./ beta_pdf (y_old, a, b);\n y_new = y_old - h;\n ind = find (y_new <= eps);\n if (any (ind))\n y_new (ind) = y_old (ind) / 10;\n end\n ind = find (y_new >= 1 - eps);\n if (any (ind))\n y_new (ind) = 1 - (1 - y_old (ind)) / 10;\n end\n h = y_old - y_new;\n if (max (abs (h)) < sqrt (eps))\n break;\n end\n y_old = y_new;\n end\n \n binv(k) = y_new;\nend\n\nend", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/dist/beta_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7270333469532481}} {"text": "function [P loglikelihood] = LearnCPDsGivenGraph(dataset, G, labels)\n%\n% Inputs:\n% dataset: N x 10 x 3, N poses represented by 10 parts in (y, x, alpha)\n% G: graph parameterization as explained in PA description\n% labels: N x 2 true class labels for the examples. labels(i,j)=1 if the \n% the ith example belongs to class j and 0 elsewhere \n%\n% Outputs:\n% P: struct array parameters (explained in PA description)\n% loglikelihood: log-likelihood of the data (scalar)\n%\n% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n\nN = size(dataset, 1);\nK = size(labels,2);\n\nloglikelihood = 0;\nP.c = zeros(1,K);\n\n% estimate parameters\n% fill in P.c, MLE for class probabilities\n% fill in P.clg for each body part and each class\n% choose the right parameterization based on G(i,1)\n% compute the likelihood - you may want to use ComputeLogLikelihood.m\n% you just implemented.\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\nhuman = dataset([labels(:,1)==1],:,:);\nalien = dataset([labels(:,2)==1],:,:);\nP.c = [size(human,1),size(alien,1)];\nP.c /= N;\nfor i = 1:10\n\tif G1(i,1) == 0\n\t\t[P.clg(i).mu_y(1),P.clg(i).sigma_y(1)] = FitGaussianParameters(human(:,i,1));\n\t\t[P.clg(i).mu_x(1),P.clg(i).sigma_x(1)] = FitGaussianParameters(human(:,i,2));\n\t\t[P.clg(i).mu_angle(1),P.clg(i).sigma_angle(1)] = FitGaussianParameters(human(:,i,3));\n\telse\n\t\t% calc beta and sigma\n\t\t[Betay,P.clg(i).sigma_y(1)] = FitLinearGaussianParameters(human(:,i,1),reshape(human(:,G1(i,2),:),size(human,1),3));\n\t\t[Betax,P.clg(i).sigma_x(1)] = FitLinearGaussianParameters(human(:,i,2),reshape(human(:,G1(i,2),:),size(human,1),3));\n\t\t[Betaangle,P.clg(i).sigma_angle(1)] = FitLinearGaussianParameters(human(:,i,3),reshape(human(:,G1(i,2),:),size(human,1),3));\n\t\tP.clg(i).theta(1,:) = [Betay(4),Betay(1:3)',Betax(4),Betax(1:3)',Betaangle(4),Betaangle(1:3)'];\n\n\tend\n\tif G2(i,1) == 0\n\t\t[P.clg(i).mu_y(2),P.clg(i).sigma_y(2)] = FitGaussianParameters(alien(:,i,1));\n\t\t[P.clg(i).mu_x(2),P.clg(i).sigma_x(2)] = FitGaussianParameters(alien(:,i,2));\n\t\t[P.clg(i).mu_angle(2),P.clg(i).sigma_angle(2)] = FitGaussianParameters(alien(:,i,3));\n\telse\n\t\t%calc beta and sigma\n\t\t[Betay,P.clg(i).sigma_y(2)] = FitLinearGaussianParameters(alien(:,i,1),reshape(alien(:,G2(i,2),:),size(alien,1),3));\n\t\t[Betax,P.clg(i).sigma_x(2)] = FitLinearGaussianParameters(alien(:,i,2),reshape(alien(:,G2(i,2),:),size(alien,1),3));\n\t\t[Betaangle,P.clg(i).sigma_angle(2)] = FitLinearGaussianParameters(alien(:,i,3),reshape(alien(:,G2(i,2),:),size(alien,1),3));\n\t\tP.clg(i).theta(2,:) = [Betay(4),Betay(1:3)',Betax(4),Betax(1:3)',Betaangle(4),Betaangle(1:3)'];\n\tend\nend\nloglikelihood = ComputeLogLikelihood(P,G,dataset);\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfprintf('log likelihood: %f\\n', loglikelihood);\n\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/LearnCPDsGivenGraph.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7270053107265809}} {"text": "function [P, R] = mdp_example_rand (S, A, is_sparse, mask)\n\n\n% mdp_example_rand Generate a random Markov Decision Process\n% Arguments -------------------------------------------------------------\n% S = number of states (> 0)\n% A = number of actions (> 0)\n% is_sparse = false to have matrices in plain format, true to have sparse matrices\n% optional (default false).\n% mask(SxS) = matrix with 0 and 1 (0 indicates a place for a zero probability), \n% optional (default, ones(S,S) )\n% Evaluation -------------------------------------------------------------\n% P(SxSxA) = transition probability matrix \n% R(SxSxA) = reward matrix\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\n% arguments checking\nif S < 1 || A < 1\n disp('--------------------------------------------------------')\n disp('MDP Toolbox ERROR: The number of states S ')\n disp('and the number of actions A must be upper than 1.')\n disp('--------------------------------------------------------')\nelseif nargin >= 4 && ( size(mask,1) ~= S || size(mask,2) ~= S )\n disp('--------------------------------------------------------')\n disp('MDP Toolbox ERROR: mask must be a SxS matrix') \n disp('--------------------------------------------------------')\nelse\n \n % initialization of optional arguments\n if nargin < 3; is_sparse = false; end;\n if nargin < 4; mask = ones(S,S); end;\n \n if is_sparse\n % definition of transition matrix : square stochastic matrix\n P = {};\n for a=1:A\n PP = sparse(mask .* rand(S));\n for s=1:S\n PP(s,:) = PP(s,:) / sum( PP(s,:) );\n end;\n P{a} = PP;\n end;\n \n % definition of reward matrix (values between -1 and +1)\n R = {};\n for a=1:A\n\t R{a} = sparse(mask .* ( 2*rand(S) - ones(S,S) ));\n end;\n else\n % definition of transition matrix : square stochastic matrix\n for a=1:A\n P(:,:,a) = mask .* rand(S);\n for s=1:S\n P(s,:,a) = P(s,:,a) / sum( P(s,:,a) );\n end;\n end;\n \n % definition of reward matrix (values between -1 and +1)\n for a=1:A\n\t R(:,:,a) = mask .* ( 2*rand(S) - ones(S,S) );\n end;\n end\n \nend;\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/25786-markov-decision-processes-mdp-toolbox/MDPtoolbox/mdp_example_rand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642533380189, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7270053095136914}} {"text": "function L = gaussianLogLikelihood(noise, mu, varsigma, y)\n\n% GAUSSIANLOGLIKELIHOOD Log-likelihood of data under Gaussian noise model.\n\n% NOISE\n\nN = size(mu, 1);\nD = size(mu, 2);\nvarsigma = varsigma + noise.sigma2;\nfor i = 1:D\n mu(:, i) = mu(:, i) + noise.bias(i);\nend\narg = (y - mu);\narg = arg.*arg./varsigma;\n\nL = - 0.5*sum(sum(log(varsigma))) ...\n - 0.5*sum(sum(arg)) ...\n - 0.5*N*D*log(2*pi);\n\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/noise/gaussianLogLikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7270053021778248}} {"text": "% ASTROTIK by Francesco Santilli\n% f2v computes velocity vector of an orbit at different true anomalies\n%\n% Usage: V = f2v(orbit,f,mi)\n%\n% where: orbit = [p e i o w] = 3d orbit elements\n% orbit = [p e w] = 2d orbit elements\n% p = semi-latus rectum [L] (p>0)\n% e = eccentricity [-] (e>=0)\n% i = inclinaion [rad]\n% o = raan [rad]\n% w = argument of perifocus [rad]\n% f(k) = true anomalies [rad]\n% mi = gravitational parameter [L^3*T^-2] (mi>0)\n% V(k,:) = velocity [L*T^-1]\n\nfunction V = f2v(orbit,f,mi)\n\n if ~(nargin == 3)\n error('Wrong number of input arguments.')\n end\n \n D = check(orbit,1);\n K = check(f,1);\n check(mi,0)\n \n if ~(D==3 || D==5)\n error('Wrong size of input arguments.')\n end\n\n d3 = (D==5);\n f = f(:);\n cf = cos(f);\n sf = sin(f);\n \n % rotation matrix\n if d3\n [p,e,i,o,w] = take(orbit);\n R = rotation([o i w]);\n R = R(1:2,:);\n else\n [p,e,w] = take(orbit);\n cw = cos(w);\n sw = sin(w);\n R = [ cw sw\n -sw cw];\n end\n \n if mi <= 0\n error('mi must be a strictly positive value.')\n end\n \n if p <= 0\n error('p must be a stricly positive value.')\n end\n \n if e < 0\n error('e must be a positive value.')\n end\n \n % velocity\n v = sqrt(mi/p);\n V = v * [-sf e+cf] * R;\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/f2v.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7905303162021597, "lm_q1q2_score": 0.7270052974828135}} {"text": "function ex9mbvp\n%EX9MBVP Example 9 of the BVP tutorial, solved as a multi-point BVP\n% This boundary value problem is the subject of Chapter 8 of \n% C.C. Lin and L.A. Segel, Mathematics Applied to Deterministic\n% Problems in the Natural Sciences, SIAM, Philadelphia, 1988. \n% The ODEs\n% \n% v' = (C - 1)/n\n% C' = (vC - min(x,1))/eta\n%\n% are solved on the interval [0, lambda]. The boundary conditions \n% are v(0) = 0, C(lambda) = 1, and continuity of v(x) and C(x) at \n% x = 1. Example EX9BVP shows how this three-point BVP is\n% reformulated for solution with BVP4C present in MATLAB 6.0.\n% Starting with MATLAB 7.0, BVP4C solves multi-point BVPs directly.\n%\n% The quantity of most interest is the emergent osmolarity Os =\n% 1/v(lambda). The parameters are related to another parameter\n% kappa by eta = lambda^2/(n*kappa^2). Lin and Segel develop an \n% approximate solution for Os valid for \"small\" n. Here the BVP is\n% solved for a range of kappa when lambda = 2 and n = 0.005. The\n% computed Os is compared to the approximation of Lin and Segel.\n\n% Copyright 2004, The MathWorks, Inc.\n\n % Known parameters, visible in nested functions.\n n = 5e-2;\n lambda = 2; \n \n % Initial mesh - duplicate the interface point x = 1.\n xinit = [0, 0.25, 0.5, 0.75, 1, 1, 1.25, 1.5, 1.75, 2]; lambda = 2;\n\n sol = bvpinit(xinit,[1 1]);\n\n fprintf(' kappa computed Os approximate Os \\n')\n for kappa = 2:5\n eta = lambda^2/(n*kappa^2); \n % After creating function handles, the new value of eta \n % will be used in nested functions.\n sol = bvp4c(@ex9mode,@ex9mbc,sol);\n \n K2 = lambda*sinh(kappa/lambda)/(kappa*cosh(kappa));\n approx = 1/(1 - K2);\n computed = 1/sol.y(1,end);\n fprintf(' %2i %10.3f %10.3f \\n',kappa,computed,approx);\n end\n\n figure\n plot(sol.x,sol.y(1,:),sol.x,sol.y(2,:),'--')\n legend('v(x)','C(x)')\n title('A three-point BVP.')\n xlabel(['\\lambda = ',num2str(lambda),', \\kappa = ',num2str(kappa),'.'])\n ylabel('v and C')\n \n % --------------------------------------------------------------------------\n % Nested functions\n %\n \n function dydx = ex9mode(x,y,region)\n %EX9MODE ODE function for Example 9 of the BVP tutorial. \n % Here the problem is solved directly, as a three-point BVP.\n dydx = zeros(2,1);\n dydx(1) = (y(2) - 1)/n;\n % The definition of C'(x) depends on the region.\n switch region\n case 1 % x in [0 1]\n dydx(2) = (y(1)*y(2) - x)/eta; \n case 2 % x in [1 lambda]\n dydx(2) = (y(1)*y(2) - 1)/eta; \n end\n end % ex9mode\n \n % --------------------------------------------------------------------------\n \n function res = ex9mbc(YL,YR)\n %EX9MBC Boundary conditions for Example 9 of the BVP tutorial.\n % Here the problem is solved directly, as a three-point BVP.\n res = [ YL(1,1) % v(0) = 0\n YR(1,1) - YL(1,2) % continuity of v(x) at x = 1\n YR(2,1) - YL(2,2) % continuity of C(x) at x = 1\n YR(2,end) - 1 ]; % C(lambda) = 1\n end % ex9mbc\n \n % --------------------------------------------------------------------------\n \nend % ex9mbvp\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/ex9mbvp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.7269485340374754}} {"text": "function [ value, ifault ] = gammds ( x, p )\n\n%*****************************************************************************80\n%\n%% GAMMDS computes the incomplete Gamma integral.\n%\n% Discussion:\n%\n% The parameters must be positive. An infinite series is used.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 January 2008\n%\n% Author:\n%\n% Original FORTRAN77 version by Chi Leung Lau.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Chi Leung Lau,\n% Algorithm AS 147:\n% A Simple Series for the Incomplete Gamma Integral,\n% Applied Statistics,\n% Volume 29, Number 1, 1980, pages 113-114.\n%\n% Parameters:\n%\n% Input, real X, P, the arguments of the incomplete\n% Gamma integral. X and P must be greater than 0.\n%\n% Output, real VALUE, the value of the incomplete\n% Gamma integral.\n%\n% Output, integer IFAULT, error flag.\n% 0, no errors.\n% 1, X <= 0 or P <= 0.\n% 2, underflow during the computation.\n%\n e = 1.0E-09;\n uflo = 1.0E-37;\n%\n% Check the input.\n%\n if ( x <= 0.0 )\n ifault = 1;\n value = 0.0;\n return\n end\n\n if ( p <= 0.0 )\n ifault = 1;\n value = 0.0;\n return\n end\n%\n% ALNGAM is the natural logarithm of the gamma function.\n%\n arg = p * log ( x ) - alngam ( p + 1.0 ) - x;\n\n if ( arg < log ( uflo ) )\n value = 0.0;\n ifault = 2;\n return\n end\n\n f = exp ( arg );\n\n if ( f == 0.0 )\n value = 0.0;\n ifault = 2;\n return\n end\n\n ifault = 0;\n%\n% Series begins.\n%\n c = 1.0;\n value = 1.0;\n a = p;\n\n while ( 1 )\n\n a = a + 1.0;\n c = c * x / a;\n value = value + c;\n\n if ( c <= e * value )\n break;\n end\n\n end\n\n value = value * 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/asa147/gammds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7268474984536654}} {"text": "%% Examples 10.17, 10.26, and 10.38: Benes-Daum and EKF/ERTS examples\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\n%%\n% Benes and Benes-Daum filter tests\n%\n % Check that we have the correct normalization constants and\n % moments. We should have (for x = x(t) with t >= t_k)\n %\n % p(x | Y_k) = \n % 1/sqrt{2 pi P} exp(-(x-m)^2/(2P)) exp(-1/2 P) cosh(x) / cosh(m)\n %\n % and\n %\n % E[x] = m + tanh(m) P\n % E[x^2] = m^2 + P^2 + 2 m tanh(m) P + P\n % V[x] = P + [1 - tanh(m)^2] P^2\n \n dx = 0.001;\n xx = -15:dx:15;\n dens = @(x,m,P) 1/sqrt(2*pi*P)*exp(-P/2)/cosh(m) * exp(-(x-m).^2/(2*P)) .* cosh(x);\n\n m = 1;\n P = 5;\n pp = dens(xx,m,P);\n figure(1); clf; plot(xx,pp);\n \n sum(pp .* dx)\n [sum(xx .* pp * dx) m+tanh(m)*P]\n [sum(xx.^2 .* pp * dx) m^2+P^2+2*m*tanh(m)*P+P]\n [sum((xx-m-tanh(m)*P).^2 .* pp * dx) P+(1-tanh(m)^2)*P^2]\n \n%%\n% Generate data\n%\n % Lock random seed\n if exist('rng') % Octave doesn't have rng\n rng(1) \n else\n randn('state',9);\n end\n \n steps = 500;\n meas_mod = 20;\n dt = 0.01;\n R = 0.1;\n\n X = [];\n Y = [];\n T = [];\n x0 = 0;\n x = x0;\n t = 0;\n for k=1:steps\n x = x + tanh(x) * dt + sqrt(dt)*randn;\n if rem(k,meas_mod) == 0\n y = x + sqrt(R)*randn;\n else\n y = NaN;\n end\n t = t + dt;\n X(k) = x;\n Y(k) = y;\n T(k) = t;\n end\n \n figure(1); clf\n plot(T,X,T,Y,'o');\n \n%%\n% Benes-Daum filter\n%\n EB = zeros(1,length(Y));\n VB = zeros(1,length(Y));\n MMB = zeros(1,length(Y));\n PPB = zeros(1,length(Y));\n\n mb0 = 0.1;\n Pb0 = 1;\n \n mb = mb0;\n Pb = Pb0;\n \n m0 = mb + Pb * tanh(mb);\n P0 = Pb + (1-tanh(mb)^2) * Pb^2;\n\n for k=1:length(Y)\n %\n % The Benes-Daum filter\n %\n Pb = Pb + dt;\n if ~isnan(Y(k))\n mb = mb + Pb / (R + Pb)*(Y(k) - mb);\n Pb = Pb - Pb^2/(R + Pb);\n end\n MMB(:,k) = mb;\n PPB(:,k) = Pb;\n EB(:,k) = mb + Pb * tanh(mb);\n VB(:,k) = Pb + (1-tanh(mb)^2) * Pb^2;\n end\n \n figure(1); clf;\n subplot(2,1,1);\n plot(T,MMB,T,EB);\n subplot(2,1,2);\n plot(T,PPB,T,VB);\n \n rmse_b = sqrt(mean((EB - X).^2))\n \n%%\n% Determine the quantiles of Benes solution\n%\n QQ1 = zeros(size(MMB));\n QQ2 = zeros(size(MMB));\n for k=1:length(MMB)\n pp = dens(xx,MMB(:,k),PPB(:,k));\n cu = cumsum(pp ./ sum(pp));\n ind1 = find(cu >= 2.5/100,1);\n ind2 = find(cu >= 97.5/100,1);\n QQ1(k) = xx(ind1);\n QQ2(k) = xx(ind2);\n end\n \n figure(1); clf;\n plot(T,EB,T,QQ1,'--',T,QQ2,'--');\n \n%%\n% EKF solution to the same problem\n%\n me = m0; \n Pe = P0;\n MMe = zeros(1,length(Y));\n PPe = zeros(1,length(Y));\n ekf_steps = 5;\n\n for k=1:length(Y)\n dt2 = dt/ekf_steps;\n for i=1:ekf_steps\n Pe = Pe + dt2 * (2 * (1 - tanh(me)^2) * Pe + 1);\n me = me + dt2 * tanh(me);\n end\n if ~isnan(Y(k))\n me = me + Pe / (R + Pe) * (Y(k) - me);\n Pe = Pe - Pe^2/(R + Pe);\n end\n MME(:,k) = me;\n PPE(:,k) = Pe;\n end\n\n rmse_e = sqrt(mean((MME - X).^2))\n \n figure(1); clf;\n subplot(2,2,1);\n plot(T,EB,T,QQ1,'--',T,QQ2,'--');\n subplot(2,2,2);\n plot(T,MME,T,MME-1.96*sqrt(PPE),'--',T,MME+1.96*sqrt(PPE),'--');\n \n subplot(2,2,3);\n plot(T,EB,T,MME)\n \n subplot(2,2,4);\n plot(T,VB,T,PPE)\n \n%%\n% ERTS Smoother\n%\n MMS = MME;\n PPS = PPE;\n ms = MME(end);\n Ps = PPE(end);\n for k=length(Y)-1:-1:1\n m = MME(k);\n P = PPE(k);\n dms = dt * tanh(m) + dt * ((1 - tanh(m)^2) * P + 1)/P * (ms - m);\n dPs = dt * 2 * ((1 - tanh(m)^2) * P + 1)/P * Ps - dt;\n ms = ms - dms;\n Ps = Ps - dPs;\n MMS(k) = ms;\n PPS(k) = Ps;\n end\n\n rmse_s = sqrt(mean((MMS - X).^2))\n \n figure(1); clf;\n plot(T,MMS,T,MMS-1.96*sqrt(PPS),'--',T,MMS+1.96*sqrt(PPS),'--');\n \n%%\n% Plot the final figures\n%\n \n %\n % Benes-Daum\n %\n figure(1); clf; hold on\n \n % Plot mean\n h0 = plot(T,EB,'-k');\n set(h0,'LineWidth',1);\n set(h0,'Color',[0.5 0.5 0.5]);\n\n % Plot uncetainty\n h1 = fill([T'; flipud(T')], [QQ1'; flipud(QQ2')],1);\n set(h1,'EdgeColor',[.7 .7 .7],'FaceColor',[.7 .7 .7])\n \n % Plot signal\n h2 = plot(T,X,'-k');\n set(h2,'LineWidth',1);\n \n % Plot mean\n h3 = plot(T,EB,'-k');\n set(h3,'LineWidth',1);\n set(h3,'Color',[0.5 0.5 0.5]);\n \n % Plot observations\n h4 = plot(T,Y,'+k');\n \n box on \n xlabel('Time, $t$'), ylabel('Signal, $x(t)$')\n \n legend([h0, h1, h2, h4],'BD mean','BD 95\\% quantiles','Signal','Observations') \n\n %\n % Benes-Daum vs EKF\n %\n figure(2); clf; hold on\n \n % Plot BD mean\n h1 = plot(T,EB,'-k');\n set(h1,'LineWidth',1);\n set(h1,'Color',[0.5 0.5 0.5]);\n\n % Plot EKF mean\n h2 = plot(T,MME,'--k');\n set(h2,'LineWidth',1);\n %set(h2,'Color',[0.0 0.0 0.0]);\n \n % Plot BD uncertainty\n h3 = fill([T'; flipud(T')], [QQ1'; flipud(QQ2')],1);\n set(h3,'EdgeColor',[.7 .7 .7],'FaceColor',[.7 .7 .7])\n \n % Plot BD mean\n h4 = plot(T,EB,'-k');\n set(h4,'LineWidth',1);\n set(h4,'Color',[0.5 0.5 0.5]);\n \n % Plot EKF mean\n h5 = plot(T,MME,'--k');\n set(h5,'LineWidth',1);\n set(h5,'Color',[0.0 0.0 0.0]);\n \n % Plot EKF uncertainty\n h6 = plot(T,MME-1.96*sqrt(PPE),'-.k',T,MME+1.96*sqrt(PPE),'-.k');\n set(h6,'LineWidth',.5);\n \n box on \n xlabel('Time, $t$'), ylabel('Signal, $x(t)$')\n legend([h1, h2, h3, h6(1)],'BD mean','EKF mean','BD 95\\% quantiles','EKF 95\\% quantiles') \n\n %\n % ERTS\n %\n figure(3); clf; hold on\n \n % Plot mean\n h0 = plot(T,MMS,'-k');\n set(h0,'LineWidth',1);\n set(h0,'Color',[0.5 0.5 0.5]);\n\n QQ1S = MMS-1.96*sqrt(PPS);\n QQ2S = MMS+1.96*sqrt(PPS);\n \n % Plot uncetainty\n h1 = fill([T'; flipud(T')], [QQ1S'; flipud(QQ2S')],1);\n set(h1,'EdgeColor',[.7 .7 .7],'FaceColor',[.7 .7 .7])\n \n % Plot signal\n h2 = plot(T,X,'-k');\n set(h2,'LineWidth',1);\n \n % Plot mean\n h3 = plot(T,MMS,'-k');\n set(h3,'LineWidth',1);\n set(h3,'Color',[0.5 0.5 0.5]);\n \n % Plot observations\n h4 = plot(T,Y,'+k');\n \n box on\n xlabel('Time, $t$'), ylabel('Signal, $x(t)$')\n \n legend([h0, h1, h2, h4],'ERTS mean','ERTS 95\\% quantiles','Signal','Observations') \n\n", "meta": {"author": "AaltoML", "repo": "SDE", "sha": "91111b0f1849ef0a0540c683bb2cf454ab4f2aff", "save_path": "github-repos/MATLAB/AaltoML-SDE", "path": "github-repos/MATLAB/AaltoML-SDE/SDE-91111b0f1849ef0a0540c683bb2cf454ab4f2aff/matlab/ch10_ex17_benes_daum_ekf_erts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7268252178734322}} {"text": "function f = calccod(x,y,dim,wantgain,wantmeansub,wantsafe)\n%\n% USAGE::\n% \n% f = calccod(x,y,dim,wantgain,wantmeansub,wantsafe)\n%\n% , are matrices with the same dimensions\n%\n% (optional) is the dimension of interest.\n% default to 2 if is a (horizontal) vector and to 1 if not.\n% special case is 0 which means to calculate globally.\n%\n% (optional) is\n%\n% - 0 means normal\n% - 1 means allow a gain to be applied to each case of \n% to minimize the squared error with respect to .\n% in this case, there cannot be any NaNs in or .\n% - 2 is like 1 except that gains are restricted to be non-negative.\n% so, if the gain that minimizes the squared error is negative,\n% we simply set the gain to be applied to be 0.\n% default: 0.\n%\n% (optional) is\n%\n% - 0 means do not subtract any mean. this makes it such that\n% the variance quantification is relative to 0.\n% - 1 means subtract the mean of each case of from both\n% and before performing the calculation. this makes\n% it such that the variance quantification\n% is relative to the mean of each case of .\n% note that occurs before .\n% default: 1.\n%\n% (optional) is whether to protect against NaNs. Default: 1.\n%\n% calculate the coefficient of determination (R^2) indicating\n% the percent variance in that is explained by . this is achieved\n% by calculating 100*(1 - sum((y-x).^2) / sum(y.^2)). note that\n% by default, we subtract the mean of each case of from both \n% and before proceeding with the calculation.\n% \n% the quantity is at most 100 but can be 0 or negative (unbounded). \n% note that this metric is sensitive to DC and scale and is not symmetric \n% (i.e. if you swap and , you may obtain different results). \n% it is therefore fundamentally different than Pearson's correlation \n% coefficient (see calccorrelation.m).\n%\n% if is true, NaNs are handled gracefully (a NaN causes \n% that data point to be ignored). if you are sure there are no NaNs,\n% you can turn off to increase execution speed.\n%\n% if there are no valid data points (i.e. all data points are\n% ignored because of NaNs), we return NaN for that case.\n%\n% Note some weird cases: \n% \n% calccod([],[]) is []\n%\n% Example::\n%\n% x = randn(1,100);\n% calccod(x,x+0.1*randn(1,100))\n%\n\n\n% history:\n% 2013/08/18 - fix pernicious case where is all zeros and is 1 or 2.\n% 2010/11/28 - add ==2 case\n% 2010/11/23 - changed the output range to percentages. thus, the range is (-Inf,100].\n% also, we removed the input since it was dumb.\n\n\n% input\nif ~exist('dim','var') || isempty(dim)\n if isvector(x) && size(x,1)==1\n dim = 2;\n else\n dim = 1;\n end\nend\nif ~exist('wantgain','var') || isempty(wantgain)\n wantgain = 0;\nend\nif ~exist('wantmeansub','var') || isempty(wantmeansub)\n wantmeansub = 1;\nend\nif ~exist('wantsafe','var') || isempty(wantsafe)\n wantsafe = 1;\nend\n\n% handle weird case up front\nif isempty(x)\n f = [];\n return;\nend\n\n% handle 0 case\nif dim==0\n x = x(:);\n y = y(:);\n dim = 1;\nend\n\n% handle gain\nif wantgain\n % to get the residuals, we want to do something like y-x*inv(x'*x)*x'*y\n temp = 1./dot(x,x,dim) .* dot(x,y,dim);\n if wantgain==2\n temp(temp < 0) = 0; % if the gain was going to be negative, rectify it to 0.\n end\n x = bsxfun(@times,x,temp);\nend\n\n% propagate NaNs (i.e. ignore invalid data points)\nif wantsafe\n x(isnan(y)) = NaN;\n y(isnan(x)) = NaN;\nend\n\n% handle mean subtraction\nif wantmeansub\n mn = nanmean(y,dim);\n y = bsxfun(@minus,y,mn);\n x = bsxfun(@minus,x,mn);\nend\n\n% finally, compute it\nf = 100*(1 - zerodiv(nansum((y-x).^2,dim),nansum(y.^2,dim),NaN,0));\n\n\n\n\n\n\n% JUNK:\n%\n% % (optional) is whether to apply signedarraypower(f,0.5)\n% % at the very end, giving something like a correlation coefficient (r).\n% % default: 1.\n% \n% if ~exist('wantr','var') || isempty(wantr)\n% wantr = 1;\n% end\n% \n% if wantr\n% f = signedarraypower(f,0.5);\n% end\n", "meta": {"author": "cvnlab", "repo": "GLMsingle", "sha": "e37bbc9f26362094e3a574f8d6c2156f5fa92077", "save_path": "github-repos/MATLAB/cvnlab-GLMsingle", "path": "github-repos/MATLAB/cvnlab-GLMsingle/GLMsingle-e37bbc9f26362094e3a574f8d6c2156f5fa92077/matlab/utilities/calccod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.726801007790445}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% calculation of the 'epsgg' matrix for circular holes using\n%%% analytical expression; the matrix is symmetric, i.e E'=E\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction epsi=epsgg(r, na, nb, b1, b2, N1, N2)\nN = N1*N2;\nepsilon=zeros(N1,N2); \nepsi=zeros(N,N); \n%%% filling factor, ratio between the area occupied by the cylinders and area of the unit cell\nf=(2*pi/sqrt(3))*r^2; \n\nfor l=1:N1\n for m=1:N2\n for n=1:N1\n for p=1:N2\n GGx=(l-n)*b1(1)+(m-p)*b2(1);\n GGy=(l-n)*b1(2)+(m-p)*b2(2);\t\n GG=sqrt(GGx^2+GGy^2); x=2*pi*GG;\n %%% GG is a scalar which changes with iteration and goes into Bessel function argument\t\n if (GG~=0)\n epsilon(p,n)=2*f*(na^2-nb^2)*besselj(1,x*r)/(x*r);\n else\n epsilon(p,n)=f*na^2+(1-f)*nb^2;\n end ; \n end; \n end; \n u=(l-1)*N2+m; %%% this is the line index\n epsi(u,:)=reshape(epsilon,1,N);\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/22808-eigenmodes-in-a-2d-photonic-crystal/epsgg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.7267767542910056}} {"text": "% LU 分解的紧凑方式\nfunction [L,U,x] = my_lu(A,b)\n\n[m,n]=size(A);\nif (m~=n)\n fprintf('\\n Error: A 不是方阵!\\n'); return; \nend\n\nL = eye(n); \nU = zeros(n);\n\nfor k = 1:n\n U(k,k) = A(k,k)-sum(L(k,1:k-1)'.*U(1:k-1,k));\n if (U(k,k) == 0)\n fprintf('\\n Error: 第 %d 个主元=0 !\\n',k); return; \n end\n for j = k+1:n\n U(k,j) = A(k,j) - sum(L(k,1:k-1)'.*U(1:k-1,j));\n L(j,k) = (A(j,k) - sum( L(j,1:k-1)'.*U(1:k-1,k) ))/U(k,k);\n end\nend\n\n% 求解Ly=b 和 Ux=y\ny(1) = b(1);\nfor i=2:n\n summary = 0;\n for t=1:i-1\n summary = summary + L(i,t) * y(t);\n end\n y(i)=b(i) - summary;\nend\nx(n) = y(n)/U(n,n);\nfor i = n-1 : -1 : 1\n summary = 0;\n for t=i+1:n\n summary = summary + U(i,t) * x(t);\n end\n x(i)=(y(i) - summary)/U(i,i);\nend\n\n\n% END\n", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第六章 线性方程组的直接法/my_lu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7266552715429124}} {"text": "% Program to form Admittance And Impedance Bus Formation....\n\nfunction ybus = ybus(); % Returns ybus\n\nlinedata = linedata6(); % Calling \"linedata6.m\" for Line Data...\nfb = linedata(:,1); % From bus number...\ntb = linedata(:,2); % To bus number...\nr = linedata(:,3); % Resistance, R...\nx = linedata(:,4); % Reactance, X...\nb = linedata(:,5); % Ground Admittance, B/2...\nz = r + i*x; % Z matrix...\ny = 1./z; % To get inverse of each element...\nb = i*b; % Make B imaginary...\n\nnbus = max(max(fb),max(tb)); % no. of buses...\nnbranch = length(fb); % no. of branches...\nybus = zeros(nbus,nbus); % Initialise YBus...\n \n % Formation of the Off Diagonal Elements...\n for k=1:nbranch\n ybus(fb(k),tb(k)) = -y(k);\n ybus(tb(k),fb(k)) = ybus(fb(k),tb(k));\n end\n \n % Formation of Diagonal Elements....\n for m=1:nbus\n for n=1:nbranch\n if fb(n) == m | tb(n) == m\n ybus(m,m) = ybus(m,m) + y(n) + b(n);\n end\n end\n end\n ybus; % Bus Admittance Matrix\n zbus = inv(ybus); % Bus Impedance Matrix", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39387-y-bus-calculation/ybus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240073565738, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7266552635029887}} {"text": "function [trans,rot,scale,skew] = affineDecompose(A)\n%\n% [trans,rot,scale,skew] = affineDecompose(A)\n%\n% Decomposes an affine (orthogonal linear) transformation matrix into its\n% four componets: translations, rotations scales and skews.\n%\n% (See affineBuild for more info.)\n%\n% HISTORY:\n% 2004.03.12 RFD (bob@white.stanford.edu) shamelessly copied the core\n% algorithm from spm99's spm_imatrix.m.\n% 2005.07.08 ras (sayres at stanford edu) imported into mrVista 2.0\n\n% Translations and zooms\n%-----------------------------------------------------------------------\nR = A(1:3,1:3);\nC = chol(R'*R);\nif(size(A,2)>3)\n trans = A(1:3,4)';\nelse\n trans = [0 0 0];\nend\nscale = diag(C)';\nif det(R)<0, scale(1)=-scale(1);end % Fix for -ve determinants\n\n% Shears\n%-----------------------------------------------------------------------\nC = diag(diag(C))\\C;\nskew = C([4 7 8]);\nR0 = affineBuild([0 0 0], [0 0 0], scale, skew);\nR0 = R0(1:3,1:3);\nR1 = R/R0;\n\n% This just leaves rotations in matrix R1\n%-----------------------------------------------------------------------\n%[ c5*c6, c5*s6, s5]\n%[-s4*s5*c6-c4*s6, -s4*s5*s6+c4*c6, s4*c5]\n%[-c4*s5*c6+s4*s6, -c4*s5*s6-s4*c6, c4*c5]\n\nrot(2) = asin(rang(R1(1,3)));\nif (abs(rot(2))-pi/2).^2 < 1e-9,\n\trot(1) = 0;\n\trot(3) = atan2(-rang(R1(2,1)), rang(-R1(3,1)/R1(1,3)));\nelse,\n\tc = cos(rot(2));\n\trot(1) = atan2(rang(R1(2,3)/c), rang(R1(3,3)/c));\n\trot(3) = atan2(rang(R1(1,2)/c), rang(R1(1,1)/c));\nend;\n\nreturn;\n\n% There may be slight rounding errors making b>1 or b<-1.\nfunction a = rang(b)\na = min(max(b, -1), 1);\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/xform/affineDecompose.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7266307426819384}} {"text": "function C = partitions(M,K)\n%PARTITIONS Find all partitions of a set.\n% C = PARTITIONS(N), for scalar N, returns a cell array, wherein each cell \n% has a various number of other cells representing the partitions of the \n% set of numbers {1,2,3,...N}. The length of C is the Bell number for N.\n% C = PARTITIONS(N), for vector N, returns the partitions of the vector\n% elements treated as members of a set.\n% C = PARTITIONS(N), for cell N, returns the partitions of the cell\n% elements treated as members of a set.\n% PARTITIONS(N,K) returns only the partitions of which have K members. \n%\n% K must be less than or equal to N for scalar N, or length(N).\n%\n%\n% Examples:\n%\n% C = partitions(4); % Find the partitions of set {1 2 3 4}\n% home % Makes for nice display for small enough N. Else use clc.\n% partdisp(C) % File accompanying PARTITIONS\n%\n% C = partitions({'peanut','butter','yummy'});\n% home\n% partdisp(C)\n%\n% C = partitions([5 7 8 50],3); % partitions of set {5 7 8 50}\n% home\n% partdisp(C,3)\n%\n% C = partitions(['a','b','c','d']); % for longer chars, use {}, not []\n% home\n% partdisp(C)\n%\n% Class support for inputs N,K:\n% float: double, single, char (N only)\n% \n% See also, nchoosek, perms, npermutek (On the FEX)\n%\n% Author: Matt Fig, \n% Contact: popkenai@yahoo.com\n% Date: 5/17/2009\n\nKflg = false; % No K passed in.\nCflg = false; % A set not passed in.\n\nif length(M)>1 \n N = length(M); % User passed {'here','there','everywhere'} for example.\n Cflg = true;\nelse\n if iscell(M) % User passed {2} for example.\n error('Set arguments must have more than one element.')\n end\n \n N = M;\nend\n\nif nargin>1\n Kflg = true; % Used in while loop below, K passed in.\n S = stirling(N,K); % The number of partitions, Stirling number.\n C = cell(S,min(1,K)); % Main Cell.\n cnt = 1; % Start the while loop counter.\nelse\n K = 0; % Since user doesn't want only certain partitions. \n S = ceil(sum((1:2*N).^N./cumprod(1:2*N))/exp(1)); % Bell number.\n C = cell(S,1); % Main Cell.\n \n if Cflg\n C{1} = {M};\n else\n C{1} = {1:N}; % First one is easy.\n end\n \n cnt = 2; % Start the while loop counter.\nend\n\nif K~=ceil(K) || numel(K)~=1 \n error('Second argument must be an integer of length 1. See help.')\nend\n\nif N<0 || K>N || K<0\n error('Arguments must be greater than zero, and K cannot exceed N.') \nend\n\nif N==0\n C = {{}}; % Easy case.\n return\nend\n\nif K==1\n if Cflg\n C{1} = {M}; % Easy case.\n else\n C{1} = {1:N}; % Easy case.\n end\n return\nend\n\nif Cflg\n NV = M;\nelse\n NV = 1:M; % Vector: base partition, RGF indexes into this guy.\nend\n\nNU = 1; % Number of unique indices in current partition.\nstp1 = N; % Controls assigning of indices.\nRGF = ones(1,N); % Holds the indexes.\nBLD = cell(1,N); % Smaller cell array will be used in creating larger.\n\nwhile cnt<=S\n idx1 = N; % Index into RGF.\n stp2 = RGF(idx1); % Works with stp1.\n\n while stp1(stp2)==1\n RGF(idx1) = 1; % Assign value to RGF.\n idx1 = idx1 - 1; % Need to increment idx1 for translation below.\n stp2 = RGF(idx1); % And set this guy for stp1 assign below.\n end\n\n NU = NU + idx1 - N; % Get provisional number of unique vals.\n stp1(1) = stp1(1) + N - idx1;\n\n if stp2==NU % Increment the number of unique elements.\n NU = NU +1;\n stp1(NU) = 0;\n end\n\n RGF(idx1) = stp2 + 1; % Increment this position.\n stp1(stp2) = stp1(stp2) - 1; % Translate indices of these two. \n stp1(stp2+1) = stp1(stp2+1) + 1; % Re-assign stopper.\n\n if NU==(~Kflg * NU + Kflg * K)\n % We could use: C{cnt} = accumarray(RGF',NV',[],@(x) {x}); (SLOW!!)\n % or the next lines to C{cnt} = TMP;\n TMP = BLD(1:NU); % Build subcell of correct size.\n TMP{1} = NV(RGF==1); % These first two are always here.... no loop.\n TMP{2} = NV(RGF==2);\n\n for ii = 3:NU % Build the rest of cell array, if any.\n TMP{ii} = NV(RGF==ii);\n end\n\n C{cnt} = TMP; % Assign cell at jj. \n cnt = cnt + 1;\n end\nend\n\n\n\nfunction S = stirling(N,K)\n% Calculate the Stirling number of the second kind. Subfunc to partitions.\n\nfor ii = K:-1:0\n S(ii+1) = (-1)^ii * prod(1:K) / (prod(1:(K-ii)) *...\n (prod(1:ii)))*(K - ii)^N; %#ok\nend\n\nS = 1/prod(1:K) * sum(S);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/24185-partitions/PARTITIONS/partitions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7266264894906262}} {"text": "function [ alpha ] = LiMapS(s, D, DINV, gamma, maxIter)\n%\n% [ alpha ] = LIMAPS(s, D, DINV, gamma)\n%\n% Returns the sparsest vector alpha which satisfies underdetermined \n% system of equations D*alpha=s, using Lipschitzian Mapping for Sparsity\n% Recovery algorithm. \n% The dictionary matrix D should have more columns than rows. The \n% number of rows of dictionary D must be equal to the length of the \n% column observation vector(or matrix) s.\n%\n% The observations signal(s) s and the dictionary D necessarily, must \n% be provided by the user. The other parameters have defult values, or\n% may be provided by the user.\n% \n% This algorithm work fine with matrix too, returning the sparsest matrix\n% alpha that satisfy the underdetermined system of equations D*alpha=s.\n% Then the dictionary D is of size [n x m], s must be of size [ s x T ] and\n% as consiquence the coefficients matirx alpha is of size [ m x T]\n% \n% s: \n% The observation vector (matrix)\n% \n% D: \n% The dictionary \n% \n% DINV (optional): \n% The pseudo-inverse of the dictionary matrix D\n%\n% gamma (optional): \n% The increase factor (default 1.01)\n%\n% maxIter (optional): \n% Maximum number of iterations (default 1000)\n%\n% Authors: Alessandro Adamo and Giuliano Grossi\n% Version: 1.0\n% Last modified: 1 Aug. 2011.\n%\n% WEB PAGE:\n% ------------------\n% http://dalab.dsi.unimi.it/limaps\n%\n% HISTORY:\n%--------------\n% Version 1.0: 1 Aug. 2011\n% first official version.\n%\n\nif(nargin<2||nargin>5)\n error('Wrong parameters number');\nend\nif(nargin==2)\n DINV=pinv(D);\n gamma=1.01;\n maxIter=1000;\nend\nif(nargin==3)\n gamma=1.01;\n maxIter=1000;\nend\nif(nargin==4)\n maxIter=1000;\nend\n\n\n%% -- INITIALIZATION --\nalpha = DINV*s;\n\nlambda = 1/max(abs(alpha(:)));\nepsilon=1e-5; % stopping criteria\nalpha_min=1e-2;\n\n%% -- CORE --\nfor i=1:maxIter\n \n alphaold=alpha;\n % apply sparsity constraction mapping: increase sparsity\n beta = alpha.*(1-exp(-lambda.*abs(alpha)));\n \n beta(abs(beta)1/lambda)>size(D,1))\n break;\n end\n end\n \nend\n\n%% -- REFINEMENT --\n\n% threshold the coefficients \nalpha(abs(alpha)0)\n% w - Shape parameter 2 / denominator degrees of freedom (w>0)\n% F - CDF of F-distribution with [v,w] degrees of freedom at points x\n%__________________________________________________________________________\n%\n% spm_Fcdf implements the Cumulative Distribution Function of the F-distribution.\n%\n% Definition:\n%--------------------------------------------------------------------------\n% The CDF F(x) of the F distribution with degrees of freedom v & w,\n% defined for positive integer degrees of freedom v & w, is the\n% probability that a realisation of an F random variable X has value\n% less than x F(x)=Pr{X0 & w>0, and for x in [0,Inf) (See Evans et al., Ch16).\n%\n% Variate relationships: (Evans et al., Ch16 & 37)\n%--------------------------------------------------------------------------\n% The square of a Student's t variate with w degrees of freedom is\n% distributed as an F-distribution with [1,w] degrees of freedom.\n%\n% For X an F-variate with v,w degrees of freedom, w/(w+v*X^2) has\n% distributed related to a Beta random variable with shape parameters\n% w/2 & v/2.\n%\n% Algorithm:\n%--------------------------------------------------------------------------\n% Using the relationship with the Beta distribution: The CDF of the\n% F-distribution with v,w degrees of freedom is related to the\n% incomplete beta function by:\n% Pr(X1;\nif sum(xa)>1 && any(any(diff(as(xa,:)),1))\n error('non-scalar args must match in size'), end\n\n%-Computation\n%--------------------------------------------------------------------------\n%-Initialise result to zeros\nF = zeros(rs);\n\n%-Only defined for strictly positive v & w. Return NaN if undefined.\nmd = ( ones(size(x)) & v>0 & w>0 );\nif any(~md(:))\n F(~md) = NaN;\n warning('Returning NaN for out of range arguments');\nend\n\n%-Non-zero where defined and x>0\nQ = find( md & x>0 );\nif isempty(Q), return, end\nif xa(1), Qx=Q; else Qx=1; end\nif xa(2), Qv=Q; else Qv=1; end\nif xa(3), Qw=Q; else Qw=1; end\n\n%-Compute\nF(Q) = 1 - betainc(w(Qw)./(w(Qw) + v(Qv).*x(Qx)),w(Qw)/2,v(Qv)/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_Fcdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7266163225870479}} {"text": "% SHIFT_TEST_1D.M\n% Plot how step responses vary at level 1 to 4 with 16 shifted steps\n% for DT CWT and DWT.\n%\n% Nick Kingsbury, Cambridge University, May 2002.\n\n% Generate 16 step functions as columns of matrix X.\nn = 120;\nx = cumsum([zeros(n,16);diag(ones(16,1));zeros(n,16)]) - 0.5;\n\n% Specify DT CWT filters here.\nbiort = 'near_sym_b';\nqshift = 'qshift_b';\n\n% Forward DT CWT on each column of x.\n[Yl,Yh] = dtwavexfm(x,4,biort,qshift);\n\n% Inverse DT CWT, one subband at a time, using gain_mask to select subbands.\nz1 = dtwaveifm(Yl*0,Yh,biort,qshift,[1 0 0 0]);\nz01 = dtwaveifm(Yl*0,Yh,biort,qshift,[0 1 0 0]);\nz001 = dtwaveifm(Yl*0,Yh,biort,qshift,[0 0 1 0]);\nz0001 = dtwaveifm(Yl*0,Yh,biort,qshift,[0 0 0 1]);\nz0000 = dtwaveifm(Yl,Yh,biort,qshift,[0 0 0 0]);\n\n% Check for perfect reconstruction: abs(error) < 1e-12.\nz = z1 + z01 + z001 + z0001 + z0000;\nDTCWT_error = max(abs(z(:)-x(:)))\n\n% Plot 16 input steps, x, and 16 step responses at each level, z1 to z0000.\nsetfig(1)\nset(gcf,'DefaultTextFontSize',12,'Color',[1 1 1]);\nset(gcf,'numbertitle','off','name',['Step responses at 16 adjacent shifts']);\nsubplot('position',[0.15 0.1 0.3 0.8]);\nsc = 1.2; % Scale offsets so sets of curves do not overlap.\non = ones(size(x,2)-1,1)/5; \noffset = sc*cumsum([0;on;1;on;1;on;1;on;1;on;1;on]/4).'; % Offsets for each curve.\nzdtcwt = [x+0.5 z1 z01 z001 z0001 z0000-0.5] - ones(size(x,1),1)*offset;\ntt = -40:40; % Limits of plot horizontally.\nplot(tt,zdtcwt(n+8+tt,:),'-b');\naxis off\ntext(0,-7*sc,'(a) Dual Tree CWT','horiz','c')\nxpos = -42; % Position of text labels.\ntext(xpos,0*sc,'Input','horiz','r','vert','m');\ntext(xpos,-0.9*sc,'Wavelets','horiz','r','vert','m');\ntext(xpos,-1.4*sc,'Level 1','horiz','r','vert','m');\ntext(xpos,-2.4*sc,'Level 2','horiz','r','vert','m');\ntext(xpos,-3.4*sc,'Level 3','horiz','r','vert','m');\ntext(xpos,-4.4*sc,'Level 4','horiz','r','vert','m');\ntext(xpos,-5.5*sc,'Scaling fn','horiz','r','vert','m');\ntext(xpos,-6*sc,'Level 4','horiz','r','vert','m');\ndrawnow\n\n\n% Now do DWT for comparison.\n\n% Specify DWT filters here.\nbiort = 'antonini';\n\n% Forward DWT on each column of x.\n[Yl,Yh] = wavexfm(x,4,biort);\n\n% Inverse DWT, one subband at a time, using gain_mask to select subbands.\nz1 = waveifm(Yl*0,Yh,biort,[1 0 0 0]);\nz01 = waveifm(Yl*0,Yh,biort,[0 1 0 0]);\nz001 = waveifm(Yl*0,Yh,biort,[0 0 1 0]);\nz0001 = waveifm(Yl*0,Yh,biort,[0 0 0 1]);\nz0000 = waveifm(Yl,Yh,biort,[0 0 0 0]);\n\n% Check for perfect reconstruction: abs(error) < 1e-12.\nz = z1 + z01 + z001 + z0001 + z0000;\nDWT_error = max(abs(z(:)-x(:)))\n\nsubplot('position',[0.47 0.1 0.3 0.8]);\non = ones(size(x,2)-1,1)/5;\noffset = sc*cumsum([0;on;1;on;1;on;1;on;1;on;1;on]/4).';\nzdwt = [x+0.5 z1 z01 z001 z0001 z0000-0.5] - ones(size(x,1),1)*offset;\ntt = -40:40;\nplot(tt,zdwt(n+8+tt,:),'-r');\naxis off\n% xlabel('(b) Real DWT')\ntext(0,-7*sc,'(b) Real DWT','horiz','c')\n\nreturn\n\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/NSCT_SR/dtcwt_toolbox/shift_test_1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7265915983928187}} {"text": "function h = p13_h ( n, x )\n\n%*****************************************************************************80\n%\n%% P13_H evaluates the Hessian for problem 13.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 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 h = zeros ( n, n );\n\n s1 = sum ( cos ( x(1:n) ) );\n\n for j = 1 : n\n h(j,j) = sin ( x(j) );\n end\n\n s2 = 0.0;\n\n for j = 1 : n\n\n th = cos ( x(j) );\n t = ( n + j ) - h(j,j) - s1 - j * th;\n s2 = s2 + t;\n for k = 1 : j - 1\n h(j,k) = 2.0 * ( sin ( x(k) ) * ( ( n + j + k ) * h(j,j) - th ) - ...\n h(j,j) * cos ( x(k) ) );\n end\n\n h(j,j) = ( j * ( j + 2 ) + n ) * h(j,j) * h(j,j) + th * ...\n ( th - ( 2 * j + 2 ) * h(j,j) ) + t * ( j * th + h(j,j) );\n\n end\n\n for j = 1 : n\n h(j,j) = 2.0 * ( h(j,j) + cos ( x(j) ) * s2 );\n end\n\n for i = 1 : n\n h(i,i+1:n) = h(i+1:n,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/test_opt/p13_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7265915963944504}} {"text": "function Y = fft2_mid0(X)\n% fft2_mid0 -- 2d fft with argument [-pi,pi] (instead of [0,2pi])\n% Usage:\n% Y = fft_mid0(X)\n% Inputs:\n% X\tArray(n) \n% Outputs:\n% Y Array(n)\n% Description:\n% Performs 1d fft with grid (-n/2):(n/2-1) on both time\n% and frequency side. \n%\n% y(k) = sum_{-n/2 <= t1,t2 < n/2} exp(-i 2pi/n (k1 t1 + k2 t2)) x(t1,t2),\n% (-n/2) <= k1,k2 < n/2\n%\n\nY = fftshift(fft2(fftshift(X)));\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/CurveLab-2.1.3/fdct_usfft_matlab/Utilities/fft2_mid0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7265910403730005}} {"text": "function [lat, lon, alt] = ecf_to_geodetic(x, y, z)\n%ECF_TO_GEODETIC Convert ECF coordinates to geodetic\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n%\n% Convert ECF (Earth Centered Fixed) coordinates to geodetic latitude, \n% longitude, and altitude.\n%\n% USAGE:\n% pos_lla = ecf_to_geodetic(pos_ecf)\n% [lat, lon, alt] = geodetic_to_ecf(pos_ecf_x, pos_ecf_y, pos_ecf_z)\n%\n% INPUTS:\n% pos_ecf - required : ecf x, y, z coordinates [m, m, m]\n%\n% OUTPUTS:\n% pos_lla - required : geodetic latitude, longitude, and altitude [deg, deg, m]\n%\n% NOTES:\n% Zhu, J. Conversion of Earth-centered, Earth-fixed coordinates to \n% geodetic coordinates. IEEE Transactions on Aerospace and Electronic\n% Systems, 30, 3 (July 1994), 957-962.\n%\n% VERSION:\n% 1.0\n% - Sean Hatch 20070911\n% - initial version\n% 1.1\n% - Wade Schwartzkopf 20130708\n% - vectorized and componentwise data handling\n%\n% TODO:\n\n% define constants\ne2 = 6.6943799901377997e-3; % eccentricity squared of Earth (WGS 84 value)\na = 6378137.0; % semimajor radius of the Earth (WGS 84 value)\n\n% calculate derived constants\ne4 = e2 .* e2;\nome2 = 1.0 - e2;\na2 = a .* a;\nb = a .* sqrt(ome2); % semiminor radius of the Earth\nb2 = b .* b;\ne_b2 = (a2 - b2) ./ b2;\n\n% Handle different forms in input arguments\nif nargin==3 % Componentwise inputs, separate arguments for X,Y,Z\n % Nothing to do. Processing uses this form.\nelseif size(x,1)==3 % Array of 3-element vectors\n z = x(3,:);\n y = x(2,:);\n x = x(1,:);\nelseif numel(x)==3 % Horizontal 3-element vector\n z = x(3);\n y = x(2);\n x = x(1);\nelse\n error('WGS_84_NORM:INVALID_INPUTS', 'Invalid inputs.');\nend\n\n% calculate intermediates\nz2 = z .* z;\nr2 = (x .* x) + (y .* y);\nr = sqrt(r2);\n\n% Check for invalid solution\nvalid = ((a .* r) .* (a .* r) + (b .* z) .* (b .* z) > (a2 - b2) .* (a2 - b2));\nlon = nan(size(x)); % Default values for invalid solutions\nlat = nan(size(x));\nalt = nan(size(x));\n\n% calculate longitude\nlon(valid) = atan2(y(valid), x(valid))*180/pi; % atan2d not available until MATLAB 2012b\n\n% calculate intermediates\nF = 54.0 .* b2 .* z2;\nG = r2 + ome2 .* z2 - e2 .* (a2 - b2);\nc = e4 .* F .* r2 ./ (G .* G .* G);\ns = (1.0 + c + sqrt(c .* c + 2 .* c)) .^ (1 ./ 3);\ntempl = s + 1.0 ./ s + 1.0;\nP = F ./ (3.0 .* templ .* templ .* G .* G);\nQ = sqrt(1.0 + 2.0 .* e4 .* P);\nr0 = -P .* e2 .* r ./ (1.0 + Q) + ...\n sqrt(abs(0.5 .* a2 .* (1.0 + 1.0 ./ Q) - ...\n P .* ome2 .* z2 ./ (Q .* (1.0 + Q)) - 0.5 .* P .* r2));\ntemp2 = r - e2 .* r0;\nU = sqrt(temp2 .* temp2 + z2);\nV = sqrt(temp2 .* temp2 + ome2 .* z2);\nz0 = b2 .* z ./ (a .* V);\n\n% calculate latitude\nlat(valid) = atan2(z(valid) + e_b2 .* z0(valid), r(valid))*180/pi; % atan2d not available until MATLAB 2012b\n\n% calculate altitude\nalt(valid) = U(valid) .* (1.0 - b2 ./ (a .* V(valid)));\n\nif nargout < 2 % Matrix/vector form, rather than componentwise form, was requested\n lat = [lat; lon; alt];\nend\n\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Geometry/coordinates/ecf_to_geodetic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7265910308668174}} {"text": "% [mu,S] = weighted_mean_cov(x,w)\n% x is n x d, w is n x 1\nfunction [mu,S] = weighted_mean_cov(x,w)\n\n%[n,d] = size(x);\n\nz = sum(w);\nmu = sum(bsxfun(@times,x,w(:)),1)/z;\n\ndiffs = bsxfun(@minus,x,mu);\ndiffs = bsxfun(@times,diffs,sqrt(w));\nS = (diffs'*diffs)/z;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/weighted_mean_cov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.7265910088245788}} {"text": "function [ o, x, w ] = epn_lag_01_1 ( n )\n\n%*****************************************************************************80\n%\n%% EPN_LAG_01_1 implements a precision 1 rule for region EPN_LAG.\n%\n% Discussion:\n%\n% The rule has order O = 1.\n%\n% The rule has precision P = 1.\n%\n% EPN is the N-dimensional positive space [0,+oo)^N with exponential\n% or Laguerre weight function:\n%\n% w(x(1:n)) = exp ( - sum ( x(1:n) ) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 January 2010\n%\n% Author:\n%\n% John Burkardt\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 = 1;\n\n expon = 0;\n value1 = ep1_lag_monomial_integral ( expon );\n volume = value1 ^ n;\n\n expon = 1;\n value2 = ep1_lag_monomial_integral ( expon );\n\n x = zeros ( n, o );\n w = zeros ( o, 1 );\n\n k = 0;\n%\n% 1 point.\n%\n k = k + 1;\n x(1:n,k) = value2 / value1;\n w(k) = 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/epn_lag_01_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7265719873216866}} {"text": "%% computing the bounds from the mean and standard deviations from dynare\nprob=0.9;\nParams={\n\t'alp' , 'beta' , 0.356000, 0.02\t \n\t'bet' , 'beta' , 0.993000, 0.002\t\t\n\t'gam' , 'normal' , 0.008500, 0.003\t\n\t'mst' , 'normal' , 1.000200, 0.007\t\n\t'rho' , 'beta' , 0.129000, 0.223\t\t\n\t'psi' , 'beta' , 0.650000, 0.05\t\t\n\t'del' , 'beta' , 0.010000, 0.005\t\t\n\t'sig_a', 'inv_gamma', 0.035449, inf\t\n\t'sig_m', 'inv_gamma', 0.008862, inf\n\t};\nnpars=size(Params,1);\nbounds=nan(npars,2);\nfor ii=1:npars\n bounds(ii,:)=distributions.find_bounds(Params{ii,2},Params{ii,3},Params{ii,4},prob);\nend\ndisp(bounds)\n%% recover means and standard deviations\nMOMS=nan(npars,2);\nfor ii=1:npars\n [a,b,moments,fval]=distributions.(Params{ii,2})(bounds(ii,1),bounds(ii,2),prob);\n MOMS(ii,1)=moments.mean;\n MOMS(ii,2)=moments.sd;\nend\n%% display and compare\ndisp('================ Means and Standard Deviations ================ ')\ndisp(num2cell(MOMS))\ndisp('================ Discrepancies ================')\ndisp(abs(cell2mat(Params(:,3:end))-MOMS))\n\n", "meta": {"author": "jmaih", "repo": "RISE_toolbox", "sha": "1b2edfa27830c6d522f9d7d2335d33c3e4d84285", "save_path": "github-repos/MATLAB/jmaih-RISE_toolbox", "path": "github-repos/MATLAB/jmaih-RISE_toolbox/RISE_toolbox-1b2edfa27830c6d522f9d7d2335d33c3e4d84285/examples/MomentsToBounds_BoundsToMoments/howto.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.726571974728666}} {"text": "function zi = pwl_interp_2d ( nxd, nyd, xd, yd, zd, ni, xi, yi )\n\n%*****************************************************************************80\n%\n%% PWL_INTERP_2D: piecewise linear interpolant to data defined on a 2D grid.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 October 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NXD, NYD, the number of X and Y data values.\n%\n% Input, real XD(NXD), YD(NYD), the sorted X and Y data.\n%\n% Input, real ZD(NXD,NYD), the Z data.\n%\n% Input, integer NI, the number of interpolation points.\n%\n% Input, real XI(NI), YI(NI), the coordinates of the\n% interpolation points.\n%\n% Output, real ZI(NI), the value of the interpolant.\n%\n zi = zeros ( ni, 1 );\n\n for k = 1 : ni\n\n i = r8vec_bracket5 ( nxd, xd, xi(k) );\n if ( i == -1 )\n zi(k) = r8_huge ( );\n continue\n end\n\n j = r8vec_bracket5 ( nyd, yd, yi(k) );\n if ( j == -1 )\n zi(k) = r8_huge ( );\n continue\n end\n\n if ( yi(k) < yd(j+1) ...\n + ( yd(j) - yd(j+1) ) * ( xi(i) - xd(i) ) / ( xd(i+1) - xd(i) ) )\n\n dxa = xd(i+1) - xd(i);\n dya = yd(j) - yd(j);\n\n dxb = xd(i) - xd(i);\n dyb = yd(j+1) - yd(j);\n\n dxi = xi(k) - xd(i);\n dyi = yi(k) - yd(j);\n\n det = dxa * dyb - dya * dxb;\n\n alpha = ( dxi * dyb - dyi * dxb ) / det;\n beta = ( dxa * dyi - dya * dxi ) / det;\n gamma = 1.0 - alpha - beta;\n\n zi(k) = alpha * zd(i+1,j) + beta * zd(i,j+1) + gamma * zd(i,j);\n\n else\n\n dxa = xd(i) - xd(i+1);\n dya = yd(j+1) - yd(j+1);\n\n dxb = xd(i+1) - xd(i+1);\n dyb = yd(j) - yd(j+1);\n\n dxi = xi(k) - xd(i+1);\n dyi = yi(k) - yd(j+1);\n\n det = dxa * dyb - dya * dxb;\n\n alpha = ( dxi * dyb - dyi * dxb ) / det;\n beta = ( dxa * dyi - dya * dxi ) / det;\n gamma = 1.0 - alpha - beta;\n\n zi(k) = alpha * zd(i,j+1) + beta * zd(i+1,j) + gamma * zd(i+1,j+1);\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/pwl_interp_2d/pwl_interp_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276224, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.72655806283002}} {"text": "% Studies the recovery probability of rank aware thresholding\n% with sparsity level and number of channels in joint recovery.\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 = 32;\n% Number of signals\nSs = [1, 2, 4, 8, 16, 32];\n% Sparsity levels\nKs = 2:30;\nnum_trials = 200;\nnum_ks = length(Ks);\nnum_ss = length(Ss);\nsuccess_with_k = zeros(num_ss, num_ks);\n\n\nsnr_threshold = 100;\n\nfor ns=1:num_ss\n % Current sparsity level\n S = Ss(ns);\n for nk=1:num_ks\n K = Ks(nk);\n num_successes = 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 % Create the solver for rank aware thresholding\n solver = spx.pursuit.joint.RankAwareThresholding(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 = num_successes + success;\n fprintf('S: %d, K=%d, trial=%d, residual: %e, SNR: %f dB\\n'...\n , S, K, nt, cs.cum_difference_norm, snr);\n end\n success_with_k(ns, nk) = num_successes / num_trials;\n end\nend\n\n\nsave ('bin/figure_1_ra_thresholding_success_with_K_S.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/examples/pursuit/joint_recovery/davies2012rank/ex_fig_1_ra_thresholding.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.726534142599617}} {"text": "function circle_segment_test13 ( )\n\n%*****************************************************************************80\n%\n%% CIRCLE_SEGMENT_TEST13 demonstrates GAUSS for quadrature rules.\n%\n% Discussion:\n%\n% Some recursion coefficients ALPHA and BETA are listed in Kautsky\n% and Elhay.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference\n%\n% Jaroslav Kautsky, Sylvan Elhay,\n% Calculation of the Weights of Interpolatory Quadratures,\n% Numerische Mathematik,\n% Volume 40, Number 3, October 1982, pages 407-422.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIRCLE_SEGMENT_TEST13\\n' );\n fprintf ( 1, ' GAUSS computes the points and weights for a\\n' );\n fprintf ( 1, ' Gauss quadrature rule, given the ALPHA and BETA\\n' );\n fprintf ( 1, ' recursion coefficients.\\n' );\n%\n% Legendre rule.\n%\n n = 10;\n\n alpha = zeros ( n, 1 );\n beta = zeros ( n, 1 );\n\n for i = 1 : n\n alpha(i) = 0.0;\n if ( i == 1 )\n beta(i) = 2.0;\n else\n beta(i) = 1.0 / ( 4.0 - 1.0 / ( i - 1.0 )^2 );\n end\n end\n\n ab(1:n,1) = alpha(1:n);\n ab(1:n,2) = beta(1:n);\n\n xw = gauss ( n, ab );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEGENDRE RULE\\n' );\n fprintf ( 1, ' Point Weight\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %12g %12g\\n', xw(i,1), xw(i,2) );\n end\n%\n% Hermite rule.\n%\n n = 10;\n\n alpha = zeros ( n, 1 );\n beta = zeros ( n, 1 );\n\n for i = 1 : n\n alpha(i) = 0.0;\n if ( i == 1 )\n beta(i) = sqrt ( pi );\n else\n beta(i) = ( i - 1 ) / 2;\n end\n end\n\n ab(1:n,1) = alpha(1:n);\n ab(1:n,2) = beta(1:n);\n\n xw = gauss ( n, ab );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' HERMITE RULE\\n' );\n fprintf ( 1, ' Point Weight\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %12g %12g\\n', xw(i,1), xw(i,2) );\n end\n%\n% Laguerre rule.\n%\n n = 10;\n\n alpha = zeros ( n, 1 );\n beta = zeros ( n, 1 );\n\n for i = 1 : n\n alpha(i) = 2.0 * i - 1.0;\n if ( i == 1 )\n beta(i) = 1;\n else\n beta(i) = ( i - 1 )^2;\n end\n end\n\n ab(1:n,1) = alpha(1:n);\n ab(1:n,2) = beta(1:n);\n\n xw = gauss ( n, ab );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LAGUERRE RULE\\n' );\n fprintf ( 1, ' Point Weight\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %12g %12g\\n', xw(i,1), xw(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/circle_segment/circle_segment_test13.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.7264832246103043}} {"text": "% StackExchange Mathematics Q3537129\n% https://math.stackexchange.com/questions/3537129\n% Projection of z onto the Affine Half Space {x∣Ax=b,x≥0}.\n% References:\n% 1. \n% Remarks:\n% 1. sa\n% TODO:\n% \t1. ds\n% Release Notes\n% - 1.0.000 27/12/2020\n% * First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 2088;0; % 500, Very Good!\n% cvx_solver('Gurobi');\n\nhRunTime = tic();\n\ncvx_begin('quiet')\n% cvx_begin()\n % cvx_precision('best');\n variable vX(numCols, 1);\n minimize( 0.5 * sum_square(vX - vZ) );\n subject to\n mA * vX == vB;\n vX >= 0;\ncvx_end\n\nrunTime = toc(hRunTime);\n\n% vX = mX(:);\n\ndisp([' ']);\ndisp([solverString, ' Solution Summary']);\ndisp(['The ', solverString, ' Solver Status - ', cvx_status]);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\nsCvxSol.vXCvx = vX;\nsCvxSol.cvxOptVal = hObjFun(vX);\n\n\n%% Solution by Dykstra's Projection Algorithm\n\nsolverIdx = solverIdx + 1;\ncLegendString{solverIdx} = ['Projected Gradient Method'];\n\nhRunTime = tic();\n\nvX = hP(vZ);\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([cLegendString{solverIdx}, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(vX))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX(:).'), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n\n%% Restore Defaults\n\n% set(0, 'DefaultFigureWindowStyle', 'normal');\n% set(0, 'DefaultAxesLooseInset', defaultLoosInset);\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/Mathematics/Q3537129/Q3537129.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7264776455201083}} {"text": "function res = ssc_W(Y,x,ta,sc,type,opC,rl)\n% PURPOSE: Temporal disaggregation using the dynamic Chow-Lin method\n% proposed by Santos Silva-Cardoso (2001).\n% Without pretesting for intercept\n% ------------------------------------------------------------\n% SYNTAX: res = ssc_W(Y,x,ta,sc,type,opC,rl);\n% ------------------------------------------------------------\n% OUTPUT: res: a structure\n% res.meth ='Santos Silva-Cardoso';\n% res.ta = type of disaggregation\n% res.type = method of estimation\n% res.opC = option related to intercept\n% res.N = nobs. of low frequency data\n% res.n = nobs. of high-frequency data\n% res.pred = number of extrapolations\n% res.sc = frequency conversion between low and high freq.\n% res.p = number of regressors (including intercept)\n% res.Y = low frequency data\n% res.x = high frequency indicators\n% res.y = high frequency estimate\n% res.y_dt = high frequency estimate: standard deviation\n% res.y_lo = high frequency estimate: sd - sigma\n% res.y_up = high frequency estimate: sd + sigma\n% res.u = high frequency residuals\n% res.U = low frequency residuals\n% res.gamma = estimated model parameters (including y(0))\n% res.gamma_sd = estimated model parameters: standard deviation\n% res.gamma_t = estimated model parameters: t ratios\n% res.phi = dynamic parameter phi\n% res.beta = estimated model parameters (excluding y(0))\n% res.beta_sd = estimated model parameters: standard deviation\n% res.beta_t = estimated model parameters: t ratios\n% res.phi = innovational parameter\n% res.aic = Information criterion: AIC\n% res.bic = Information criterion: BIC\n% res.val = Objective function used by the estimation method\n% res.wls = Weighted least squares as a function of phi\n% res.loglik = Log likelihood as a function of phi\n% res.r = grid of innovational parameters used by the estimation method\n% res.et = elapsed time\n% ------------------------------------------------------------\n% INPUT: Y: Nx1 ---> vector of low frequency data\n% x: nxp ---> matrix of high frequency indicators (without intercept)\n% ta: type of disaggregation\n% ta=1 ---> sum (flow)\n% ta=2 ---> average (index)\n% ta=3 ---> last element (stock) ---> interpolation\n% ta=4 ---> first element (stock) ---> interpolation\n% sc: number of high frequency data points for each low frequency data points \n% sc= 4 ---> annual to quarterly\n% sc=12 ---> annual to monthly\n% sc= 3 ---> quarterly to monthly\n% type: estimation method: \n% type=0 ---> weighted least squares \t\n% type=1 ---> maximum likelihood\n% opC: 1x1 option related to intercept\n% opc = 0 : no intercept in hf model\n% opc = 1 : intercept in hf model\n% rl: innovational parameter\n% rl = []: 0x0 ---> rl=[0.05 0.99], 100 points grid\n% rl: 1x1 ---> fixed value of phi parameter\n% rl: 1x2 ---> [r_min r_max] search is performed\n% on this range, using a 200 points grid\n% ------------------------------------------------------------\n% LIBRARY: aggreg, criterion_SSC\n% ------------------------------------------------------------\n% SEE ALSO: chowlin, litterman, fernandez, td_plot, td_print\n% ------------------------------------------------------------\n% REFERENCE: Santos, J.M.C. and Cardoso, F.(2001) \"The Chow-Lin method\n% using dynamic models\",Economic Modelling, vol. 18, p. 269-280.\n% Di Fonzo, T. (2002) \"Temporal disaggregation of economic time series: \n% towards a dynamic extension\", Dipartimento di Scienze Statistiche, \n% Universita di Padova, Working Paper n. 2002-17.\n\n% written by:\n% Enrique M. Quilis\n% Macroeconomic Research Department\n% Ministry of Economy and Competitiveness\n% \n\n% Version 2.1 [April 2012]\n\nt0=clock;\n\n% ------------------------------------------------------------\n% Size of the problem\n\n[N,M] = size(Y); % Size of low-frequency input\n[n,p] = size(x); % Size of p high-frequency inputs (without intercept)\n\n% ------------------------------------------------------------\n% Initial checks\n\nif ((opC ~= 0) & (opC ~= 1))\n error ('*** c has an invalid value ***');\nend\n\n% ------------------------------------------------------------\n% Preparing the X matrix: including an intercept if opC==1\n\nif (opC == 1)\n e=ones(n,1); \n x=[e x]; % Expanding the regressor matrix\n p=p+1; % Number of p high-frequency inputs (plus intercept)\nend\n\n% ------------------------------------------------------------\n% Generating the aggregation matrix\n\nC = aggreg(ta,N,sc);\n\n% -----------------------------------------------------------\n% Expanding the aggregation matrix to perform\n% extrapolation if needed.\n\nif (n > sc * N)\n pred = n - sc*N; % Number of required extrapolations \n C = [C zeros(N,pred)];\nelse\n pred = 0;\nend\n\n% -----------------------------------------------------------\n% Temporal aggregation of the indicators\n\nX = C*x;\n\n% -----------------------------------------------------------\n% Optimization of objective funcion (Lik. or WLS)\n\nnrl = length(rl);\n\nswitch nrl\n case 0 %Default\n rl = [0.05 0.99];\n rex = criterion_SSC(Y,x,ta,type,opC,rl,X,C,N,n,p);\n phi = rex.phi;\n r = rex.r;\n case 1 %Fixed innovational parameter\n phi = rl;\n type = 4;\n case 2\n rex = criterion_SSC(Y,x,ta,type,opC,rl,X,C,N,n,p);\n phi = rex.phi;\n r = rex.r;\n otherwise\n error('*** Grid search on phi is improperly defined. Check rl ***');\nend\n\n% -----------------------------------------------------------\n% Final estimation with optimal phi\n% -----------------------------------------------------------\n\n% Auxiliary matrix useful to simplify computations\n\nI=eye(n); w=I;\nLL = diag(-ones(n-1,1),-1);\n\n% -----------------------------------------------------------\n% Final estimation with optimal phi\n\n% -----------------------------------------------------------\n% Generation of difference matrix D_phi\n\nD_phi = I + phi*LL;\nD_phi(1,1)=sqrt(1-phi^2);\niD_phi = inv(D_phi);\n\n% -----------------------------------------------------------\n% Truncation remainder: q parameter\n\nq=zeros(n,1);\nq(1)=phi;\n\n% -----------------------------------------------------------\n% Expanded set of regressors: high and low frequency\n\nz = [x q];\nz_phi = iD_phi * z;\nZ_phi = C * z_phi;\n\n% -----------------------------------------------------------\n% GLS estimator of gamma\n\nw = inv(D_phi' * D_phi);\nW = C * w * C';\niW = inv(W);\n\ngamma = (Z_phi' * iW * Z_phi) \\ (Z_phi' * iW * Y); % gamma GLS\n\nU = Y - Z_phi * gamma; % Low frequency residuals\nscp = U' * iW * U; % Weighted least squares\nsigma_a = scp/(N-p-1); % sigma_a estimator (p+1 due to lagged endogenous)\nL = w * C' * iW; % Filtering matrix\nu = L * U; % High frequency residuals\n\n% -----------------------------------------------------------\n% Temporally disaggregated time series\n\ny = z_phi * gamma + u;\n\n% -----------------------------------------------------------\n% Information criteria\n% p is expanded to include lagged endogenous\n\naic=log(sigma_a)+2*(p+1)/N;\nbic=log(sigma_a)+log(N)*(p+1)/N;\n\n% -----------------------------------------------------------\n% VCV matrix of high frequency estimates\n\nsigma_gamma = sigma_a * inv(Z_phi' * iW * Z_phi);\n\nVCV_y = sigma_a * (eye(n)-L*C) * w + (z_phi-L*Z_phi) * sigma_gamma * (z_phi-L*Z_phi)';\n\nd_y=sqrt((diag(VCV_y))); % Std. dev. of high frequency estimates\ny_li=y-d_y; % Lower lim. of high frequency estimates\ny_ls=y+d_y; % Upper lim. of high frequency estimates\n\n% -----------------------------------------------------------\n% -----------------------------------------------------------\n% Loading the structure\n\nres.meth='Santos Silva-Cardoso';\n\n% -----------------------------------------------------------\n% Basic parameters\n\nres.ta = ta;\nres.type = type;\nres.N = N;\nres.n = n;\nres.pred = pred;\nres.sc = sc;\nres.p = p;\nres.opC = opC;\nres.rl = rl;\n\n% -----------------------------------------------------------\n% Series\n\nres.Y = Y;\nres.x = x;\nres.y = y;\nres.y_dt = d_y;\nres.y_lo = y_li;\nres.y_up = y_ls;\n\n% -----------------------------------------------------------\n% Residuals\n\nres.u = u;\nres.U = U;\n\n% -----------------------------------------------------------\n% Parameters\n\nres.gamma = gamma;\nres.gamma_sd = sqrt(diag(sigma_gamma));\nres.gamma_t = gamma./sqrt(diag(sigma_gamma));\nres.phi = phi;\n\nres.beta = gamma(1:end-1);\nres.beta_sd = res.gamma_sd(1:end-1);\nres.beta_t = res.gamma_t(1:end-1);\nres.sigma_a = sigma_a;\n\n% -----------------------------------------------------------\n% Information criteria\n\nres.aic = aic;\nres.bic = bic;\n\n% -----------------------------------------------------------\n% Objective function\n\nif (nrl == 1)\n res.val = [];\n res.wls = [];\n res.loglik = [];\n res.r = [];\nelse \n res.val = rex.val;\n res.wls \t = rex.wls;\n res.loglik = rex.loglik;\n res.r = r;\nend\n\n% -----------------------------------------------------------\n% Elapsed time\n\nres.et = etime(clock,t0);\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39770-temporal-disaggregation-library/ssc_W.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7264776415065939}} {"text": "function latLonEnd=directRhumbProbGen(latLonStart,azimuth,dist,height,useHeightApprox,a,f,numSteps4Circ)\n%%DIRECTRHUMBLINEPROBGEN Given a starting location near the surface of the\n% reference ellipsoid as well as a constant heading a\n% distance to travel, determine the location of a vessel\n% traveling at the constant heading after traveling the\n% distance. A constant heading trajectory is a rhumb\n% line (loxodrome) and is usually not the shortest path\n% between two points. This function is general in that\n% it will also solve the direct rhumb problem at a fixed\n% height above the reference ellipsoid, if desired.\n%\n%INPUTS: latLonStart A 2X1 vector of the starting ellipsoidal latitude\n% (North) and longitude (East) in radians.\n% azimuth The constant heading that is to be traveled in\n% radians East of North.\n% dist The distance that is to be traveled on a constant\n% heading course.\n% height The heights above the reference ellipsoid at which the\n% trajectory should be determined. If this parameter\n% is omitted, then the default value of 0 is used.\n% useHeightApprox If true, and the height is not zero, then a distance\n% scaling height approximation is used. An equatorial\n% trajectory traveling a distance dist at a height h\n% above the reference ellipsoid will only travel\n% a/(a+h)*dist over the surface. If useHeightApprox is\n% true, then this scaling applied to any trajectry\n% (including non-equatorial). If useHeightApprox is\n% false, a slow iterative optimization used. The default\n% value if omitted or an empty matrix is passed is\n% false. This parameter is ignored if height=0.\n% a The semi-major axis of the reference ellipsoid. If\n% this 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% numSteps4Circ If height!=0, and useHeightApprox=false, then an\n% algorithm propagating a state in ECEF coordinates\n% around the curved Earth is used. This parameter\n% determines the number of steps that would be needed\n% for a target that circumnavigates the globe around the\n% equator. The default value if this parameter is not\n% provided is 2000. A value of 6000 appears to be about\n% the best number for overall precision. Reducing the\n% number of steps will speed up the function. This\n% parameter is not used if height=0.\n%\n%OUTPUTS: latLonEnd The ellipsoidal latitude and longitude that one will be\n% after starting at latLonStart and traveling a distance\n% of dist at a constant heading on azimuth.\n%\n%For zero-altitude, the directRhumbProb function is called. The solution\n%for a non-zero height is based on [1]. The function is significantly\n%faster if a zero hight is used or if useHeightApprox=true, in which case\n%the approximation described in [2] is used.\n%\n%The algorithm is generally the opposite of indirectRhumbProblem, except\n%when a starting or ending point is at a geographic pole, as discussed in\n%the comments to the indirectRhumbProblem function.\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"Simulating aerial targets in 3D accounting for the\n% Earth's curvature,\" Journal of Advances in Information Fusion, vol.\n% 10, no. 1, Jun. 2015.\n%[2] D. F. Crouse, \"Worldwide Ground Target State Propagation,\" in\n% Proceedings of the 23rd International Conference on Information\n% Fusion, 6-9 Jul. 2020.\n%\n%August 2019 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<8||isempty(numSteps4Circ))\n%This is the number of steps that would be taken to travel a distance of\n%2*pi*a (circumnavigate the globe the long way). This is a design parameter\n%that should be large enough to ensure that the results are accurate.\n%However, if it is too large, finite precision errors will accumulate.\n numSteps4Circ=2000;\nend\n\nif(nargin<7||isempty(f))\n f=Constants.WGS84Flattening;\nend\n\nif(nargin<6||isempty(a))\n a=Constants.WGS84SemiMajorAxis;\nend\n\nif(nargin<5||isempty(useHeightApprox))\n useHeightApprox=false; \nend\n\nif(nargin<4||isempty(height))\n height=0; \nend\n\nif(useHeightApprox)\n %Scale the distance based on the height and then solve the rumb problem\n %with the scaled distance.\n dist=a/(a+height)*dist;\n height=0; \nend\n\nif(height==0)\n latLonEnd=directRhumbProblem(latLonStart,azimuth,dist,0,a,f);\n return\nelse\n %If the height is not zero, then use the algorithm for propagating a\n %level, non-maneuvering dynamic model along a rhumb line forward in\n %time.\n\n %This is the number of Runge-Kutta steps on a curved Earth that will be\n %performed.\n numSteps=ceil(numSteps4Circ*(dist/(2*pi*a)));\n stepSize=1/numSteps;\n \n %We have to calculate the initial location and heading in CARTESIAN\n %ECEF coordinates.\n xyzInit=ellips2Cart([latLonStart;height],a,f);\n \n %The initial heading in the LOCAL East-North-Up tangent-plane\n %coordinate system for level flight.\n uh=[sin(azimuth);cos(azimuth);0];\n \n %The speed of the target is such that it travels a distance of dist in\n %1 unit of time.\n speed=dist;\n \n %The initial target state with the position in the GLOBAL ECEF\n %coordinate system and the velocity in a LOCAL flat-Earth coordinate\n %system.\n xInit=[xyzInit;speed*uh];\n \n aDyn=@(x,t)aPoly(x,t,3);%A constant velocity model.\n\n %When traveling along a rhumb-line, the local coordinate system is\n %known at all times: it is the local ENU coordinate system. The local\n %basis vectors are deterministially known at all places on the Earth.\n uDet=@(x,t)getENUAxes(Cart2Ellipse(x(1:3),[],a,f));\n xList=RungeKCurvedAtTimes(xInit,[],[0;1],aDyn,uDet,stepSize,4);\n plhEnd=Cart2Ellipse(xList(1:3,end),[],a,f);\n latLonEnd=plhEnd(1:2);%The Cartesian location at the end of the\n %trajectory.\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/Navigation/directRhumbProbGen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.726410971456477}} {"text": "function [W, stat] = gsp_learn_graph_log_degrees(Z, a, b, params)\n%GSP_LEARN_GRAPH_LOG_DEGREES Learn graph from pairwise distances using negative log prior on nodes degrees\n% Usage: [W, stat] = gsp_learn_graph_log_degrees(Z, a, b)\n% [W, stat] = gsp_learn_graph_log_degrees(Z, a, b, params)\n%\n% Inputs:\n% Z : Matrix with (squared) pairwise distances of nodes\n% a : Log prior constant (bigger a -> bigger weights in W)\n% b : ||W||_F^2 prior constant (bigger b -> more dense W)\n% params : Optional parameters\n%\n% Outputs:\n% W : Weighted adjacency matrix\n% stat : Optional output statistics (adds small overhead)\n%\n%\n% 'W = gsp_learn_graph_log_degrees(Z, a, b, params)' computes a weighted\n% adjacency matrix $W$ from squared pairwise distances in $Z$, using the\n% smoothness assumption that $\\text{trace}(X^TLX)$ is small, where $X$ is\n% the data (columns) changing smoothly from node to node on the graph and\n% $L = D-W$ is the combinatorial graph Laplacian. See the paper of the\n% references for the theory behind the algorithm.\n%\n% Alternatively, Z can contain other types of distances and use the\n% smoothness assumption that\n%\n% .. sum(sum(W .* Z))\n%\n% .. math:: \\sum_i\\sum_j W_{ij}Z_{ij}\n%\n% is small.\n%\n% The minimization problem solved is\n%\n% .. minimize_W sum(sum(W .* Z)) - a * sum(log(sum(W))) + b * ||W||_F^2/2 + c * ||W-W_0||_F^2/2\n%\n% .. math:: \\min_W \\sum_i\\sum_j W_{ij}Z_{ij} -\\alpha\\sum_i\\log(\\sum_jW_{ij}) + \\frac{\\beta}{2} \\|W\\|_F^2 + c/2 ||W - W0||_F^2\n%\n% subject to $W$ being a valid weighted adjacency matrix (non-negative,\n% symmetric, with zero diagonal).\n%\n% The algorithm used is forward-backward-forward (FBF) based primal dual\n% optimization (see references).\n%\n% Example:::\n%\n% G = gsp_sensor(256);\n% f1 = @(x,y) sin((2-x-y).^2);\n% f2 = @(x,y) cos((x+y).^2);\n% f3 = @(x,y) (x-.5).^2 + (y-.5).^3 + x - y;\n% f4 = @(x,y) sin(3*((x-.5).^2+(y-.5).^2));\n% X = [f1(G.coords(:,1), G.coords(:,2)), f2(G.coords(:,1), G.coords(:,2)), f3(G.coords(:,1), G.coords(:,2)), f4(G.coords(:,1), G.coords(:,2))];\n% figure; subplot(2,2,1); gsp_plot_signal(G, X(:,1)); title('1st smooth signal');\n% subplot(2,2,2); gsp_plot_signal(G, X(:,2)); title('2nd smooth signal');\n% subplot(2,2,3); gsp_plot_signal(G, X(:,3)); title('3rd smooth signal');\n% subplot(2,2,4); gsp_plot_signal(G, X(:,4)); title('4th smooth signal');\n% Z = gsp_distanz(X').^2;\n% % we can multiply the pairwise distances with a number to control sparsity\n% [W] = gsp_learn_graph_log_degrees(Z*25, 1, 1);\n% % clean up zeros\n% W(W<1e-5) = 0;\n% G2 = gsp_update_weights(G, W);\n% figure; gsp_plot_graph(G2); title('Graph with edges learned from above 4 signals');\n%\n%\n% Additional parameters\n% ---------------------\n%\n% * *params.W_init* : Initialization point. default: zeros(size(Z))\n% * *verbosity* : Default = 1. Above 1 adds a small overhead\n% * *maxit* : Maximum number of iterations. Default: 1000\n% * *tol* : Tolerance for stopping criterion. Defaul: 1e-5\n% * *step_size* : Step size from the interval (0,1). Default: 0.5\n% * *max_w* : Maximum weight allowed for each edge (or inf)\n% * *w_0* : Vector for adding prior c/2*||w - w_0||^2\n% * *c* : multiplier for prior c/2*||w - w_0||^2 if w_0 given\n% * *fix_zeros* : Fix a set of edges to zero (true/false)\n% * *edge_mask* : Mask indicating the non zero edges if \"fix_zeros\"\n%\n% If fix_zeros is set, an edge_mask is needed. Only the edges\n% corresponding to the non-zero values in edge_mask will be learnt. This\n% has two applications: (1) for large scale applications it is cheaper to\n% learn a subset of edges. (2) for some applications we don't want some\n% connections to be allowed, for example for locality on images.\n%\n% The cost of each iteration is linear to the number of edges to be\n% learned, or the square of the number of nodes (numel(Z)) if fix_zeros\n% is not set.\n%\n% The function is using the UNLocBoX functions sum_squareform and\n% squareform_sp.\n% The stopping criterion is whether both relative primal and dual\n% distance between two iterations are below a given tolerance.\n%\n% To set the step size use the following rule of thumb: Set it so that\n% relative change of primal and dual converge with similar rates (use\n% verbosity > 1).\n%\n% See also: gsp_learn_graph_l2_degrees gsp_distanz gsp_update_weights\n% squareform_sp sum_squareform gsp_compute_graph_learning_theta\n%\n% References: kalofolias2016learn komodakis2015playing kalofolias2017large\n%\n\n\n% Author: Vassilis Kalofolias\n% Testing: gsp_test_learn_graph\n% Date: June 2015\n\n\n%% Default parameters\nif nargin < 4\n params = struct;\nend\n\nif not(isfield(params, 'verbosity')), params.verbosity = 1; end\nif not(isfield(params, 'maxit')), params.maxit = 1000; end\nif not(isfield(params, 'tol')), params.tol = 1e-5; end\nif not(isfield(params, 'step_size')), params.step_size = .5; end % from (0, 1)\nif not(isfield(params, 'fix_zeros')), params.fix_zeros = false; end\nif not(isfield(params, 'max_w')), params.max_w = inf; end\n\n\n%% Fix parameter size and initialize\nif isvector(Z)\n z = Z; % lazy copying of matlab doesn't allocate new memory for z\nelse\n z = squareform_sp(Z);\nend\n% clear Z % for large scale computation\n\nz = z(:);\nl = length(z); % number of edges\n% n(n-1)/2 = l => n = (1 + sqrt(1+8*l))/ 2\nn = round((1 + sqrt(1+8*l))/ 2); % number of nodes\n\nif isfield(params, 'w_0')\n if not(isfield(params, 'c'))\n error('When params.w_0 is specified, params.c should also be specified');\n else\n c = params.c;\n end\n if isvector(params.w_0)\n w_0 = params.w_0;\n else\n w_0 = squareform_sp(params.w_0);\n end\n w_0 = w_0(:);\nelse\n w_0 = 0;\nend\n\n% if sparsity pattern is fixed we optimize with respect to a smaller number\n% of variables, all included in w\nif params.fix_zeros\n if not(isvector(params.edge_mask))\n params.edge_mask = squareform_sp(params.edge_mask);\n end\n % use only the non-zero elements to optimize\n ind = find(params.edge_mask(:));\n z = full(z(ind));\n if not(isscalar(w_0))\n w_0 = full(w_0(ind));\n end\nelse\n z = full(z);\n w_0 = full(w_0);\nend\n\n\nw = zeros(size(z));\n\n%% Needed operators\n% S*w = sum(W)\nif params.fix_zeros\n [S, St] = sum_squareform(n, params.edge_mask(:));\nelse\n [S, St] = sum_squareform(n);\nend\n\n% S: edges -> nodes\nK_op = @(w) S*w;\n\n% S': nodes -> edges\nKt_op = @(z) St*z;\n\nif params.fix_zeros\n norm_K = normest(S);\n % approximation: \n % sqrt(2*(n-1)) * sqrt(nnz(params.edge_mask) / (n*(n+1)/2)) /sqrt(2)\nelse\n % the next is an upper bound if params.fix_zeros\n norm_K = sqrt(2*(n-1));\nend\n\n%% TODO: Rescaling??\n% we want h.beta == norm_K (see definition of mu)\n% we can multiply all terms by s = norm_K/2*b so new h.beta==2*b*s==norm_K\n\n\n%% Learn the graph\n% min_{W>=0} tr(X'*L*X) - gc * sum(log(sum(W))) + gp * norm(W-W0,'fro')^2, where L = diag(sum(W))-W\n% min_W I{W>=0} + W(:)'*Dx(:) - gc * sum(log(sum(W))) + gp * norm(W-W0,'fro')^2\n% min_W f(W) + g(L_op(W)) + h(W)\n\n% put proximal of trace plus positivity together\nf.eval = @(w) 2*w'*z; % half should be counted\n%f.eval = @(W) 0;\nf.prox = @(w, c) min(params.max_w, max(0, w - 2*c*z)); % all change the same\n\nparam_prox_log.verbose = params.verbosity - 3;\ng.eval = @(z) -a * sum(log(z));\ng.prox = @(z, c) prox_sum_log(z, c*a, param_prox_log);\n% proximal of conjugate of g: z-c*g.prox(z/c, 1/c)\ng_star_prox = @(z, c) z - c*a * prox_sum_log(z/(c*a), 1/(c*a), param_prox_log);\n\nif w_0 == 0\n % \"if\" not needed, for c = 0 both are the same but gains speed\n h.eval = @(w) b * norm(w)^2;\n h.grad = @(w) 2 * b * w;\n h.beta = 2 * b;\nelse\n h.eval = @(w) b * norm(w)^2 + c * norm(w - w_0,'fro')^2;\n h.grad = @(w) 2 * ((b+c) * w - c * w_0);\n h.beta = 2 * (b+c);\nend\n\n%% My custom FBF based primal dual (see [1] = [Komodakis, Pesquet])\n% parameters mu, epsilon for convergence (see [1])\nmu = h.beta + norm_K; %TODO: is it squared or not??\nepsilon = lin_map(0.0, [0, 1/(1+mu)], [0,1]); % in (0, 1/(1+mu) )\n\n% INITIALIZATION\n% primal variable ALREADY INITIALIZED\n%w = params.w_init;\n% dual variable\nv_n = K_op(w);\nif nargout > 1 || params.verbosity > 1\n stat.f_eval = nan(params.maxit, 1);\n stat.g_eval = nan(params.maxit, 1);\n stat.h_eval = nan(params.maxit, 1);\n stat.fgh_eval = nan(params.maxit, 1);\n stat.pos_violation = nan(params.maxit, 1);\nend\nif params.verbosity > 1\n fprintf('Relative change of primal, dual variables, and objective fun\\n');\nend\n\ntic\ngn = lin_map(params.step_size, [epsilon, (1-epsilon)/mu], [0,1]); % in [epsilon, (1-epsilon)/mu]\nfor i = 1:params.maxit\n Y_n = w - gn * (h.grad(w) + Kt_op(v_n));\n y_n = v_n + gn * (K_op(w));\n P_n = f.prox(Y_n, gn);\n p_n = g_star_prox(y_n, gn); % = y_n - gn*g_prox(y_n/gn, 1/gn)\n Q_n = P_n - gn * (h.grad(P_n) + Kt_op(p_n));\n q_n = p_n + gn * (K_op(P_n));\n \n if nargout > 1 || params.verbosity > 2\n stat.f_eval(i) = f.eval(w);\n stat.g_eval(i) = g.eval(K_op(w));\n stat.h_eval(i) = h.eval(w);\n stat.fgh_eval(i) = stat.f_eval(i) + stat.g_eval(i) + stat.h_eval(i);\n stat.pos_violation(i) = -sum(min(0,w));\n end\n rel_norm_primal = norm(- Y_n + Q_n, 'fro')/norm(w, 'fro');\n rel_norm_dual = norm(- y_n + q_n)/norm(v_n);\n \n if params.verbosity > 3\n fprintf('iter %4d: %6.4e %6.4e %6.3e', i, rel_norm_primal, rel_norm_dual, stat.fgh_eval(i));\n elseif params.verbosity > 2\n fprintf('iter %4d: %6.4e %6.4e %6.3e\\n', i, rel_norm_primal, rel_norm_dual, stat.fgh_eval(i));\n elseif params.verbosity > 1\n fprintf('iter %4d: %6.4e %6.4e\\n', i, rel_norm_primal, rel_norm_dual);\n end\n \n w = w - Y_n + Q_n;\n v_n = v_n - y_n + q_n;\n \n if rel_norm_primal < params.tol && rel_norm_dual < params.tol\n break\n end\nend\nstat.time = toc;\nif params.verbosity > 0\n fprintf('# iters: %4d. Rel primal: %6.4e Rel dual: %6.4e OBJ %6.3e\\n', i, rel_norm_primal, rel_norm_dual, f.eval(w) + g.eval(K_op(w)) + h.eval(w));\n fprintf('Time needed is %f seconds\\n', stat.time);\nend\n\n% use the following for testing:\n% g.L = K_op;\n% g.Lt = Kt_op;\n% g.norm_L = norm_K;\n% [w, info] = fbf_primal_dual(w, f, g, h, params);\n% %[w, info] = fb_based_primal_dual(w, f, g, h, params);\n\n\n%%\n\nif params.verbosity > 3\n figure; plot(real([stat.f_eval, stat.g_eval, stat.h_eval])); hold all; plot(real(stat.fgh_eval), '.'); legend('f', 'g', 'h', 'f+g+h');\n figure; plot(stat.pos_violation); title('sum of negative (invalid) values per iteration')\n figure; semilogy(max(0,-diff(real(stat.fgh_eval'))),'b.-'); hold on; semilogy(max(0,diff(real(stat.fgh_eval'))),'ro-'); title('|f(i)-f(i-1)|'); legend('going down','going up');\nend\n\nif params.fix_zeros\n w = sparse(ind, ones(size(ind)), w, l, 1);\nend\n\nif isvector(Z)\n W = w;\nelse\n W = squareform_sp(w);\nend\n\n\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/learn_graph/gsp_learn_graph_log_degrees.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7263928415295253}} {"text": "function f = niederreiter_mccurley4 ( x )\n\n%*****************************************************************************80\n%\n%% NIEDERREITER_MCCURLEY4 evaluates the Niederreiter-McCurley function 4.\n%\n% Discussion:\n%\n% The spatial dimension is taken as 4.\n%\n% The maximum is sought within the unit hypercube.\n%\n% The reported maximum value occurs at approximately\n%\n% X = [ 1, 1, 1, 1 ]\n%\n% with\n%\n% F(X) = 9.196986029286059\n%\n% Note that FMINCON is designed to minimize functions, so we must negate\n% the output value here in order to satisfy FMINCON.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 06 September 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Harald Niederreiter, Kevin McCurley,\n% Optimization of functions by quasi-random search methods,\n% Computing,\n% Volume 22, Number 2, 1979, pages 119-123.\n%\n% Parameters:\n%\n% Input, real X(N), the argument of the objection function.\n%\n% Output, real F, the value of the objective function.\n%\n f = - 100 * prod ( x ) * exp ( - x(4) ) ./ ( 1 + x(1) * x(2) * x(3) ).^2;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fmincon/niederreiter_mccurley4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7263928220940952}} {"text": "function [out] = GLCM_Features4(glcmin,pairs)\n% \n% \n% This is an update of GLCM_Features2 (vectorized) without ismember()\n%\n% GLCM_Features2 helps to calculate the features from the different GLCMs\n% that are input to the function. The GLCMs are stored in a i x j x n\n% matrix, where n is the number of GLCMs calculated usually due to the\n% different orientation and displacements used in the algorithm. Usually\n% the values i and j are equal to 'NumLevels' parameter of the GLCM\n% computing function graycomatrix(). Note that matlab quantization values\n% belong to the set {1,..., NumLevels} and not from {0,...,(NumLevels-1)}\n% as provided in some references\n% http://www.mathworks.com/access/helpdesk/help/toolbox/images/graycomatrix\n% .html\n% \n% This vectorized version of GLCM_FEatures1.m reduces the 19 'for' loops\n% used in the earlier code to 5 'for' loops\n% http://blogs.mathworks.com/loren/2006/07/12/what-are-you-really-measuring\n% /\n% Using tic toc and cputime as in above discussion\n%\n% Although there is a function graycoprops() in Matlab Image Processing\n% Toolbox that computes four parameters Contrast, Correlation, Energy,\n% and Homogeneity. The paper by Haralick suggests a few more parameters\n% that are also computed here. The code is not fully vectorized and hence\n% is not an efficient implementation but it is easy to add new features\n% based on the GLCM using this code. Takes care of 3 dimensional glcms\n% (multiple glcms in a single 3D array)\n% \n% If you find that the values obtained are different from what you expect \n% or if you think there is a different formula that needs to be used \n% from the ones used in this code please let me know. \n% A few questions which I have are listed in the link \n% http://www.mathworks.com/matlabcentral/newsreader/view_thread/239608\n%\n%\n%\n% Features computed \n% Autocorrelation: [2] (out.autoc)\n% Contrast: matlab/[1,2] (out.contr)\n% Correlation: matlab (out.corrm)\n% Correlation: [1,2] (out.corrp)\n% Cluster Prominence: [2] (out.cprom)\n% Cluster Shade: [2] (out.cshad)\n% Dissimilarity: [2] (out.dissi)\n% Energy: matlab / [1,2] (out.energ)\n% Entropy: [2] (out.entro)\n% Homogeneity: matlab (out.homom)\n% Homogeneity: [2] (out.homop)\n% Maximum probability: [2] (out.maxpr)\n% Sum of squares: Variance [1] (out.sosvh)\n% Sum average [1] (out.savgh)\n% Sum variance [1] (out.svarh)\n% Sum entropy [1] (out.senth)\n% Difference variance [1] (out.dvarh)\n% Difference entropy [1] (out.denth)\n% Information measure of correlation1 [1] (out.inf1h)\n% Informaiton measure of correlation2 [1] (out.inf2h)\n% Inverse difference (INV) is homom [3] (out.homom)\n% Inverse difference normalized (INN) [3] (out.indnc) \n% Inverse difference moment normalized [3] (out.idmnc)\n%\n% The maximal correlation coefficient was not calculated due to\n% computational instability \n% http://murphylab.web.cmu.edu/publications/boland/boland_node26.html\n%\n% Formulae from MATLAB site (some look different from\n% the paper by Haralick but are equivalent and give same results)\n% Example formulae: \n% Contrast = sum_i(sum_j( (i-j)^2 * p(i,j) ) ) (same in matlab/paper)\n% Correlation = sum_i( sum_j( (i - u_i)(j - u_j)p(i,j)/(s_i.s_j) ) ) (m)\n% Correlation = sum_i( sum_j( ((ij)p(i,j) - u_x.u_y) / (s_x.s_y) ) ) (p[2])\n% Energy = sum_i( sum_j( p(i,j)^2 ) ) (same in matlab/paper)\n% Homogeneity = sum_i( sum_j( p(i,j) / (1 + |i-j|) ) ) (as in matlab)\n% Homogeneity = sum_i( sum_j( p(i,j) / (1 + (i-j)^2) ) ) (as in paper)\n% \n% Where:\n% u_i = u_x = sum_i( sum_j( i.p(i,j) ) ) (in paper [2])\n% u_j = u_y = sum_i( sum_j( j.p(i,j) ) ) (in paper [2])\n% s_i = s_x = sum_i( sum_j( (i - u_x)^2.p(i,j) ) ) (in paper [2])\n% s_j = s_y = sum_i( sum_j( (j - u_y)^2.p(i,j) ) ) (in paper [2])\n%\n% \n% Normalize the glcm:\n% Compute the sum of all the values in each glcm in the array and divide \n% each element by it sum\n%\n% Haralick uses 'Symmetric' = true in computing the glcm\n% There is no Symmetric flag in the Matlab version I use hence\n% I add the diagonally opposite pairs to obtain the Haralick glcm\n% Here it is assumed that the diagonally opposite orientations are paired\n% one after the other in the matrix\n% If the above assumption is true with respect to the input glcm then\n% setting the flag 'pairs' to 1 will compute the final glcms that would result \n% by setting 'Symmetric' to true. If your glcm is computed using the\n% Matlab version with 'Symmetric' flag you can set the flag 'pairs' to 0\n%\n% References:\n% 1. R. M. Haralick, K. Shanmugam, and I. Dinstein, Textural Features of\n% Image Classification, IEEE Transactions on Systems, Man and Cybernetics,\n% vol. SMC-3, no. 6, Nov. 1973\n% 2. L. Soh and C. Tsatsoulis, Texture Analysis of SAR Sea Ice Imagery\n% Using Gray Level Co-Occurrence Matrices, IEEE Transactions on Geoscience\n% and Remote Sensing, vol. 37, no. 2, March 1999.\n% 3. D A. Clausi, An analysis of co-occurrence texture statistics as a\n% function of grey level quantization, Can. J. Remote Sensing, vol. 28, no.\n% 1, pp. 45-62, 2002\n% 4. http://murphylab.web.cmu.edu/publications/boland/boland_node26.html\n%\n%\n% Example:\n%\n% Usage is similar to graycoprops() but needs extra parameter 'pairs' apart\n% from the GLCM as input\n% I = imread('circuit.tif');\n% GLCM2 = graycomatrix(I,'Offset',[2 0;0 2]);\n% stats = GLCM_features4(GLCM2,0)\n% The output is a structure containing all the parameters for the different\n% GLCMs\n%\n% [Avinash Uppuluri: avinash_uv@yahoo.com: Last modified: 04/05/2010]\n\n% If 'pairs' not entered: set pairs to 0 \nif ((nargin > 2) || (nargin == 0))\n error('Too many or too few input arguments. Enter GLCM and pairs.');\nelseif ( (nargin == 2) ) \n if ((size(glcmin,1) <= 1) || (size(glcmin,2) <= 1))\n error('The GLCM should be a 2-D or 3-D matrix.');\n elseif ( size(glcmin,1) ~= size(glcmin,2) )\n error('Each GLCM should be square with NumLevels rows and NumLevels cols');\n end \nelseif (nargin == 1) % only GLCM is entered\n pairs = 0; % default is numbers and input 1 for percentage\n if ((size(glcmin,1) <= 1) || (size(glcmin,2) <= 1))\n error('The GLCM should be a 2-D or 3-D matrix.');\n elseif ( size(glcmin,1) ~= size(glcmin,2) )\n error('Each GLCM should be square with NumLevels rows and NumLevels cols');\n end \nend\n\n\nformat long e\nif (pairs == 1)\n newn = 1;\n for nglcm = 1:2:size(glcmin,3)\n glcm(:,:,newn) = glcmin(:,:,nglcm) + glcmin(:,:,nglcm+1);\n newn = newn + 1;\n end\nelseif (pairs == 0)\n glcm = glcmin;\nend\n\nsize_glcm_1 = size(glcm,1);\nsize_glcm_2 = size(glcm,2);\nsize_glcm_3 = size(glcm,3);\n\n% checked \nout.autoc = zeros(1,size_glcm_3); % Autocorrelation: [2] \nout.contr = zeros(1,size_glcm_3); % Contrast: matlab/[1,2]\nout.corrm = zeros(1,size_glcm_3); % Correlation: matlab\nout.corrp = zeros(1,size_glcm_3); % Correlation: [1,2]\nout.cprom = zeros(1,size_glcm_3); % Cluster Prominence: [2]\nout.cshad = zeros(1,size_glcm_3); % Cluster Shade: [2]\nout.dissi = zeros(1,size_glcm_3); % Dissimilarity: [2]\nout.energ = zeros(1,size_glcm_3); % Energy: matlab / [1,2]\nout.entro = zeros(1,size_glcm_3); % Entropy: [2]\nout.homom = zeros(1,size_glcm_3); % Homogeneity: matlab\nout.homop = zeros(1,size_glcm_3); % Homogeneity: [2]\nout.maxpr = zeros(1,size_glcm_3); % Maximum probability: [2]\n\nout.sosvh = zeros(1,size_glcm_3); % Sum of sqaures: Variance [1]\nout.savgh = zeros(1,size_glcm_3); % Sum average [1]\nout.svarh = zeros(1,size_glcm_3); % Sum variance [1]\nout.senth = zeros(1,size_glcm_3); % Sum entropy [1]\nout.dvarh = zeros(1,size_glcm_3); % Difference variance [4]\n%out.dvarh2 = zeros(1,size_glcm_3); % Difference variance [1]\nout.denth = zeros(1,size_glcm_3); % Difference entropy [1]\nout.inf1h = zeros(1,size_glcm_3); % Information measure of correlation1 [1]\nout.inf2h = zeros(1,size_glcm_3); % Informaiton measure of correlation2 [1]\n%out.mxcch = zeros(1,size_glcm_3);% maximal correlation coefficient [1]\n%out.invdc = zeros(1,size_glcm_3);% Inverse difference (INV) is homom [3]\nout.indnc = zeros(1,size_glcm_3); % Inverse difference normalized (INN) [3]\nout.idmnc = zeros(1,size_glcm_3); % Inverse difference moment normalized [3]\n\nglcm_sum = zeros(size_glcm_3,1);\nglcm_mean = zeros(size_glcm_3,1);\nglcm_var = zeros(size_glcm_3,1);\n\n% http://www.fp.ucalgary.ca/mhallbey/glcm_mean.htm confuses the range of \n% i and j used in calculating the means and standard deviations.\n% As of now I am not sure if the range of i and j should be [1:Ng] or\n% [0:Ng-1]. I am working on obtaining the values of mean and std that get\n% the values of correlation that are provided by matlab.\nu_x = zeros(size_glcm_3,1);\nu_y = zeros(size_glcm_3,1);\ns_x = zeros(size_glcm_3,1);\ns_y = zeros(size_glcm_3,1);\n\n% checked p_x p_y p_xplusy p_xminusy\np_x = zeros(size_glcm_1,size_glcm_3); % Ng x #glcms[1] \np_y = zeros(size_glcm_2,size_glcm_3); % Ng x #glcms[1]\np_xplusy = zeros((size_glcm_1*2 - 1),size_glcm_3); %[1]\np_xminusy = zeros((size_glcm_1),size_glcm_3); %[1]\n% checked hxy hxy1 hxy2 hx hy\nhxy = zeros(size_glcm_3,1);\nhxy1 = zeros(size_glcm_3,1);\nhx = zeros(size_glcm_3,1);\nhy = zeros(size_glcm_3,1);\nhxy2 = zeros(size_glcm_3,1);\n\ncorm = zeros(size_glcm_3,1);\ncorp = zeros(size_glcm_3,1);\n\nfor k = 1:size_glcm_3\n \n glcm_sum(k) = sum(sum(glcm(:,:,k)));\n glcm(:,:,k) = glcm(:,:,k)./glcm_sum(k); % Normalize each glcm\n glcm_mean(k) = mean2(glcm(:,:,k)); % compute mean after norm\n glcm_var(k) = (std2(glcm(:,:,k)))^2;\n \n for i = 1:size_glcm_1\n \n for j = 1:size_glcm_2\n p_x(i,k) = p_x(i,k) + glcm(i,j,k); \n p_y(i,k) = p_y(i,k) + glcm(j,i,k); % taking i for j and j for i\n %if (ismember((i + j),[2:2*size_glcm_1])) \n p_xplusy((i+j)-1,k) = p_xplusy((i+j)-1,k) + glcm(i,j,k);\n %end\n %if (ismember(abs(i-j),[0:(size_glcm_1-1)])) \n p_xminusy((abs(i-j))+1,k) = p_xminusy((abs(i-j))+1,k) +...\n glcm(i,j,k);\n %end\n end\n end\n \nend\n\n% marginal probabilities are now available [1]\n% p_xminusy has +1 in index for matlab (no 0 index)\n% computing sum average, sum variance and sum entropy:\n\n\n%Q = zeros(size(glcm));\n\ni_matrix = repmat([1:size_glcm_1]',1,size_glcm_2);\nj_matrix = repmat([1:size_glcm_2],size_glcm_1,1);\n% i_index = [ 1 1 1 1 1 .... 2 2 2 2 2 ... ]\ni_index = j_matrix(:);\n% j_index = [ 1 2 3 4 5 .... 1 2 3 4 5 ... ]\nj_index = i_matrix(:);\nxplusy_index = [1:(2*(size_glcm_1)-1)]';\nxminusy_index = [0:(size_glcm_1-1)]';\nmul_contr = abs(i_matrix - j_matrix).^2;\nmul_dissi = abs(i_matrix - j_matrix);\n%div_homop = ( 1 + mul_contr); % used from the above two formulae\n%div_homom = ( 1 + mul_dissi);\n\nfor k = 1:size_glcm_3 % number glcms\n \n out.contr(k) = sum(sum(mul_contr.*glcm(:,:,k)));\n out.dissi(k) = sum(sum(mul_dissi.*glcm(:,:,k)));\n out.energ(k) = sum(sum(glcm(:,:,k).^2));\n out.entro(k) = - sum(sum((glcm(:,:,k).*log(glcm(:,:,k) + eps))));\n out.homom(k) = sum(sum((glcm(:,:,k)./( 1 + mul_dissi))));\n out.homop(k) = sum(sum((glcm(:,:,k)./( 1 + mul_contr))));\n % [1] explains sum of squares variance with a mean value;\n % the exact definition for mean has not been provided in \n % the reference: I use the mean of the entire normalized glcm \n out.sosvh(k) = sum(sum(glcm(:,:,k).*((i_matrix - glcm_mean(k)).^2)));\n out.indnc(k) = sum(sum(glcm(:,:,k)./( 1 + (mul_dissi./size_glcm_1) )));\n out.idmnc(k) = sum(sum(glcm(:,:,k)./( 1 + (mul_contr./(size_glcm_1^2)))));\n out.maxpr(k) = max(max(glcm(:,:,k)));\n \n u_x(k) = sum(sum(i_matrix.*glcm(:,:,k))); \n u_y(k) = sum(sum(j_matrix.*glcm(:,:,k))); \n % using http://www.fp.ucalgary.ca/mhallbey/glcm_variance.htm for s_x\n % s_y : This solves the difference in value of correlation and might be\n % the right value of standard deviations required \n % According to this website there is a typo in [2] which provides\n % values of variance instead of the standard deviation hence a square\n % root is required as done below:\n s_x(k) = (sum(sum( ((i_matrix - u_x(k)).^2).*glcm(:,:,k) )))^0.5;\n s_y(k) = (sum(sum( ((j_matrix - u_y(k)).^2).*glcm(:,:,k) )))^0.5;\n \n corp(k) = sum(sum((i_matrix.*j_matrix.*glcm(:,:,k))));\n corm(k) = sum(sum(((i_matrix - u_x(k)).*(j_matrix - u_y(k)).*glcm(:,:,k)))); \n \n out.autoc(k) = corp(k);\n out.corrp(k) = (corp(k) - u_x(k)*u_y(k))/(s_x(k)*s_y(k));\n out.corrm(k) = corm(k) / (s_x(k)*s_y(k)); \n \n out.cprom(k) = sum(sum(((i_matrix + j_matrix - u_x(k) - u_y(k)).^4).*...\n glcm(:,:,k))); \n out.cshad(k) = sum(sum(((i_matrix + j_matrix - u_x(k) - u_y(k)).^3).*...\n glcm(:,:,k))); \n \n \n\n \n\n out.savgh(k) = sum((xplusy_index + 1).*p_xplusy(:,k));\n % the summation for savgh is for i from 2 to 2*Ng hence (i+1)\n out.senth(k) = - sum(p_xplusy(:,k).*...\n log(p_xplusy(:,k) + eps));\n \n % compute sum variance with the help of sum entropy\n out.svarh(k) = sum((((xplusy_index + 1) - out.senth(k)).^2).*...\n p_xplusy(:,k));\n % the summation for savgh is for i from 2 to 2*Ng hence (i+1) \n \n % compute difference variance, difference entropy,\n % out.dvarh2(k) = var(p_xminusy(:,k));\n % but using the formula in \n % http://murphylab.web.cmu.edu/publications/boland/boland_node26.html\n % we have for dvarh\n out.denth(k) = - sum((p_xminusy(:,k)).*...\n log(p_xminusy(:,k) + eps));\n out.dvarh(k) = sum((xminusy_index.^2).*p_xminusy(:,k));\n \n % compute information measure of correlation(1,2) [1]\n hxy(k) = out.entro(k);\n glcmk = glcm(:,:,k)';\n glcmkv = glcmk(:);\n \n hxy1(k) = - sum(glcmkv.*log(p_x(i_index,k).*p_y(j_index,k) + eps));\n hxy2(k) = - sum(p_x(i_index,k).*p_y(j_index,k).*...\n log(p_x(i_index,k).*p_y(j_index,k) + eps));\n hx(k) = - sum(p_x(:,k).*log(p_x(:,k) + eps));\n hy(k) = - sum(p_y(:,k).*log(p_y(:,k) + eps)); \n \n out.inf1h(k) = ( hxy(k) - hxy1(k) ) / ( max([hx(k),hy(k)]) );\n out.inf2h(k) = ( 1 - exp( -2*( hxy2(k) - hxy(k) ) ) )^0.5;\n \n % eig_Q(k,:) = eig(Q(:,:,k));\n % sort_eig(k,:)= sort(eig_Q(k,:),'descend');\n % out.mxcch(k) = sort_eig(k,2)^0.5;\n % The maximal correlation coefficient was not calculated due to\n % computational instability \n % http://murphylab.web.cmu.edu/publications/boland/boland_node26.html \n \n \nend\n\n\n\n% GLCM Features (Soh, 1999; Haralick, 1973; Clausi 2002)\n% f1. Uniformity / Energy / Angular Second Moment (done)\n% f2. Entropy (done)\n% f3. Dissimilarity (done)\n% f4. Contrast / Inertia (done)\n% f5. Inverse difference \n% f6. correlation\n% f7. Homogeneity / Inverse difference moment\n% f8. Autocorrelation\n% f9. Cluster Shade\n% f10. Cluster Prominence\n% f11. Maximum probability\n% f12. Sum of Squares\n% f13. Sum Average\n% f14. Sum Variance\n% f15. Sum Entropy\n% f16. Difference variance\n% f17. Difference entropy\n% f18. Information measures of correlation (1)\n% f19. Information measures of correlation (2)\n% f20. Maximal correlation coefficient\n% f21. Inverse difference normalized (INN)\n% f22. Inverse difference moment normalized (IDN)\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/22354-glcmfeatures4-m-vectorized-version-of-glcmfeatures1-m-with-code-changes/GLCM_Features4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7262757468082662}} {"text": "function b=num2ibm(x)\n% num2ibm : convert IEEE 754 doubles to IBM 32 bit floating point format\n% b=num2ibm(x)\n% x is a matrix of doubles\n% b is a corresponding matrix of uint32\n%\n% The representations for NaN and inf are arbitrary\n%\n% See also ibm2num\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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n%\n%\n% (C) Brian Farrelly, 22 October 2001\n% mailto:Brian.Farrelly@nho.hydro.com Norsk Hydro Research Centre\n% phone +47 55 99 68 74 ((( Postboks 7190\n% fax +47 55 99 69 70 2oooS N-5020 Bergen\n% home +47 55 13 78 49 HYDRO Norway\n%\n\nb=repmat(uint32(0),size(x));\nerr=zeros(size(x));\n\n%format long\n\nx(x> 7.236998675585915e+75)= inf; % change big numbers to infinity\nx(x<-7.236998675585915e+75)=-inf; % 7.236998675585915e+75 is\n % ibm2num(uint32(hex2dec('7fffffff')) or\n % ibm2num(num2ibm(inf))\n\n[F E]=log2(abs(x));\n\ne=E/4; % exponent of base 16\nec=ceil(e); % adjust upwards to integer\np=ec+64; % offset exponent\n\nf=F.*2.^(-4*(ec-e)); % correct mantissa for fractional part of exponent\nf=round(f*2^24); % convert to integer. Roundoff here can be as large as\n % 0.5/2^20 when mantissa is close to 1/16 so that\n % 3 bits of signifance are lost.\n\np(f==2^24)=p(f==2^24)+1; % Roundoff can cause f to be 2^24 for numbers just under a\nf(f==2^24)=2^20; % power of 16, so correct for this\n\n%format hex\npsi=uint32(p*2^24); % put exponent in first byte of psi.\nphi=uint32(f); % put mantissa into last 3 bytes of phi \n\n% make bit representation\n\nb=bitor(psi,phi); % exponent and mantissa\nb(x<0)=bitset(b(x<0),32); % sign bit \n%format long\n\n% special cases\n\nb(x==0) =uint32(0) ; % bias is incorrect for zero \nb(isnan(x)) =uint32(hex2dec('7fffffff')); % 7.237005145973116e+75 in IBM format\nb(isinf(x) & x>0)=uint32(hex2dec('7ffffff0')); % 7.236998675585915e+75 ,,\nb(isinf(x) & x<0)=uint32(hex2dec('fffffff0')); % -7.236998675585915e+75 ,,\n % Note that NaN > inf in IBM format\n\n% check bit representation for normal cases \n\ncheckx=ibm2num(b); % note that use of base 16 in IBM format\nz=x==0; % can lead to a loss of 3 bits of precision\nerr(z)=0; % compared with an IEEE single.\nq=(checkx(~z)-x(~z))./x(~z);\nerr(~z) = abs(q) > 5e-7; % this is almost reached with numbers\n % of the form 16^n + 0.5*16^(n-5) where\n % the mantissa is 100001 hex. Roundoff\n % error is then 0.5/16^5=0.5/2^20=4.7684e-7\n \n \nif any(err)\n warning('Conversion error in num2ibm for the following:')\n disp(x(logical(err)))\nend \n\n\n\n\n", "meta": {"author": "cultpenguin", "repo": "segymat", "sha": "6470f59fd8184f0fff0d89383265417b461cc1da", "save_path": "github-repos/MATLAB/cultpenguin-segymat", "path": "github-repos/MATLAB/cultpenguin-segymat/segymat-6470f59fd8184f0fff0d89383265417b461cc1da/num2ibm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7262757375262007}} {"text": "function mb = trimeshMeanBreadth(vertices, faces)\n%TRIMESHMEANBREADTH Mean breadth of a triangular mesh.\n%\n% MB = trimeshMeanBreadth(VERTICES, FACES)\n% Computes the mean breadth (proporitonal to the integral of mean\n% curvature) of a triangular mesh.\n%\n% Example\n% [V, F] = createCube;\n% F2 = triangulateFaces(F);\n% MB = trimeshMeanBreadth(V, F2)\n% MB = \n% 1.5000\n%\n% See also\n% meshes3d, trimeshSurfaceArea, trimeshEdgeFaces, polyhedronMeanBreadth\n%\n% References\n% Stoyan D., Kendall W.S., Mecke J. (1995) \"Stochastic Geometry and its\n% Applications\", John Wiley and Sons, p. 26\n% Ohser, J., Muescklich, F. (2000) \"Statistical Analysis of\n% Microstructures in Materials Sciences\", John Wiley and Sons, p.352\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2015-08-19, using Matlab 8.5.0.197613 (R2015a)\n% Copyright 2015 INRA - Cepia Software Platform.\n\n\n%% Check input validity\n\nif size(faces, 2) ~= 3\n error('meshes3d:trimeshMeanBreadth:NonTriangularMesh', ...\n 'Requires a triangular mesh as input');\nend\n \n%% Compute edge and edgeFaces arrays\n% Uses the same code as in trimeshEdgeFaces\n\n% compute vertex indices of each edge (in increasing index order)\nedges = sort([faces(:,[1 2]) ; faces(:,[2 3]) ; faces(:,[3 1])], 2);\n\n% create an array to keep indices of faces \"creating\" each edge\nnFaces = size(faces, 1);\nedgeFaceInds = repmat( (1:nFaces)', 3, 1);\n\n% sort edges, keeping indices\n[edges, ia, ib] = unique(edges, 'rows'); %#ok\nnEdges = size(edges, 1);\n\n% allocate memory for result\nedgeFaces = zeros(nEdges, 2);\n\n% iterate over edges, to identify incident faces\nfor iEdge = 1:nEdges\n inds = find(ib == iEdge);\n edgeFaces(iEdge, 1:length(inds)) = edgeFaceInds(inds);\nend\n\n\n%% Compute dihedral angle for each edge\n\n% compute normal of each face\nnormals = meshFaceNormals(vertices, faces);\n\n% allocate memory for resulting angles\nalpha = zeros(nEdges, 1);\n\n% iterate over edges\nfor iEdge = 1:nEdges\n % indices of adjacent faces\n indFace1 = edgeFaces(iEdge, 1);\n indFace2 = edgeFaces(iEdge, 2);\n \n % normal vector of adjacent faces\n normal1 = normals(indFace1, :);\n normal2 = normals(indFace2, :);\n \n % compute dihedral angle of two vectors\n alpha(iEdge) = vectorAngle3d(normal1, normal2);\nend\n\n\n%% Compute mean breadth\n% integrate the dihedral angles weighted by the length of each edge\n\n% compute length of each edge\nlengths = meshEdgeLength(vertices, edges);\n\n% compute product of length by angles \nmb = sum(alpha .* lengths) / (4*pi);\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/meshes3d/trimeshMeanBreadth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7262464573356965}} {"text": "function diff = getDiffuseness_TV(i_vecs)\n%GETDIFFUSENESS_TV Compute diffuseness from temporal variation of intensity\n%vectors\n% \n% This routine estimates diffuseness using the temporal variation of \n% intensity vectors, as proposed in \n% \n% Ahonen, J. and Pulkki, V., 2009. \n% Diffuseness estimation using temporal variation of intensity vectors. \n% In 2009 IEEE Workshop on Applications of Signal Processing to Audio and Acoustics (WASPAA).\n%\n% also termed coefficient of variation in other works. It is based on the\n% relation sqrt( 1 - ||||/<||Ia||> ), where Ia is the active intensity \n% vector. It is similar to the spherical variance estimator, but it takes \n% into account the magnitude of the DoA vectors, hence giving more weight \n% to strong sound estimates instead of low noisy ones. It is also flexible \n% in the sense that alternative DoA vectors with magnitude that relates \n% to the energy of the sound-field can be used instead of the intensity\n% vector.\n%\n% Inputs:\n% i_vecs: Kx3 matrix of DoA vectors, for K temporal observations\n%\n% Outputs:\n% diff: diffuseness value\n%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% GETDIFFUSENESS_TV.M - 5/10/2016\n% Archontis Politis, archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% mean of active intensity vectors\nmean_i_vecs = mean(i_vecs, 1);\n% norm of mean vector\nnorm_mean_i_vecs = sqrt(sum(mean_i_vecs.^2, 2));\n\n% norm of intensity vectors\nnorm_i_vecs = sqrt(sum(i_vecs.^2, 2));\n% mean of norms\nmean_norm_i_vecs = mean(norm_i_vecs);\n\n% diffuseness\ndiff = sqrt( 1 - norm_mean_i_vecs/mean_norm_i_vecs );\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/getDiffuseness_TV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197771, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.726183642898954}} {"text": "function nu = PoissonRatio(S,x,y)\n% Poisson ratio of an elasticity tensor\n%\n% Syntax\n% nu = PoissonRatio(S,x,y)\n% nu = PoissonRatio(S) % isotropic case\n%\n% Input\n% S - elastic @complianceTensor\n% x - @vector3d tension direction\n% y - @vector3d perpendicular direction\n%\n% Output\n% nu - Poisson ratio\n%\n% Description\n% \n% $$\\nu = \\frac{-S_{ijkl} x_i x_j y_k y_l}{S_{mnop} x_m x_n x_o x_p}$$ \n%\n\n\nif nargin == 1 % isotrpoic theory\n \n S_iso_Voigt = mean(S,uniformODF(S.CS));\n nu = S_iso_Voigt.PoissonRatio(xvector,yvector);\n \n return\nend\n\n% generate a function if required\nif nargin == 1 || isempty(x)\n \n nu = S2FunHarmonicSym.quadrature(@(v) PoissonRatio(S,v,y),'bandwidth',4,S.CS);\n \nelseif nargin <= 2 || isempty(y)\n\n nu = S2FunHarmonicSym.quadrature(@(v) PoissonRatio(S,x,v),'bandwidth',4,S.CS);\n \nelse\n\n % compute tensor product\n nu = -EinsteinSum(S,[-1 -2 -3 -4],x,-1,x,-2,y,-3,y,-4) ./ ...\n EinsteinSum(S,[-1 -2 -3 -4],x,-1,x,-2,x,-3,x,-4);\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/TensorAnalysis/@complianceTensor/PoissonRatio.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768635777511, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7261477760716916}} {"text": "function flux = EulerRoe2D(nx, ny, QM, QP, gamma)\n \n% function flux = EulerRoe2D(nx, ny, QM, QP, gamma)\n% Purpose: compute surface fluxes for Euler's equations using the approximate \n% Riemann solver based on Roe averages\n\n% Rotate \"-\" trace momentum to face normal-tangent coordinates\nrhouM = QM(:,:,2); rhovM = QM(:,:,3);\nQM(:,:,2) = nx.*rhouM + ny.*rhovM; QM(:,:,3) =-ny.*rhouM + nx.*rhovM;\n\n% Rotate \"+\" trace momentum to face normal-tangent coordinates\nrhouP = QP(:,:,2); rhovP = QP(:,:,3);\nQP(:,:,2) = nx.*rhouP + ny.*rhovP; QP(:,:,3) =-ny.*rhouP + nx.*rhovP;\n \n% Compute fluxes and primitive variables in rotated coordinates\n[fxQM,fyQM,rhoM,uM,vM,pM] = EulerFluxes2D(QM, gamma);\n[fxQP,fyQP,rhoP,uP,vP,pP] = EulerFluxes2D(QP, gamma);\nEnerM = QM(:,:,4); EnerP = QP(:,:,4);\n\nNfields = 4;\nHM = (EnerM+pM)./rhoM; cM = sqrt(gamma*pM./rhoM);\nHP = (EnerP+pP)./rhoP; cP = sqrt(gamma*pP./rhoP);\n\n% Compute Roe average variables\nrhoMs = sqrt(rhoM); rhoPs = sqrt(rhoP);\n\nrho = rhoMs.*rhoPs;\nu = (rhoMs.*uM + rhoPs.*uP)./(rhoMs + rhoPs);\nv = (rhoMs.*vM + rhoPs.*vP)./(rhoMs + rhoPs);\nH = (rhoMs.*HM + rhoPs.*HP)./(rhoMs + rhoPs);\n\nc2 = (gamma-1)*(H - 0.5*(u.^2 + v.^2)); c = sqrt(c2);\n\n% Compute estimate of waves speeds\nSL = min(uM-cM, u-c); SR = max(uP+cP, u+c);\n\n% Compute HLL flux\nt1 = (min(SR,0)-min(0,SL))./(SR-SL);\nt2 = 1-t1;\nt3 = (SR.*abs(SL)-SL.*abs(SR))./(2*(SR-SL));\n\nfor n=1:4\n fx(:,:,n) = t1.*fxQP(:,:,n) + t2.*fxQM(:,:,n) - t3.*(QP(:,:,n)-QM(:,:,n));\nend\n\n% rotate flux back into Cartesian coordinates\nflux(:,:,1) = fx(:,:,1);\nflux(:,:,2) = nx.*fx(:,:,2) - ny.*fx(:,:,3);\nflux(:,:,3) = ny.*fx(:,:,2) + nx.*fx(:,:,3);\nflux(:,:,4) = fx(:,:,4);;\nreturn;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/CFD2D/EulerHLL2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768541530197, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.7261477538313895}} {"text": "% solveWirtFlow.m\n%\n% Implementation of the Wirtinger Flow (WF) algorithm proposed in the\n% paper.\n%\n%% I/O\n% Inputs:\n% A: m x n matrix or a function handle to a method that\n% returns A*x. \n% At: The adjoint (transpose) of 'A'. If 'A' is a function handle,\n% 'At' must be provided.\n% b0: m x 1 real,non-negative vector consists of all the measurements.\n% x0: n x 1 vector. It is the initial guess of the unknown signal x.\n% opts: A struct consists of the options for the algorithm. For details,\n% see header in solvePhaseRetrieval.m or the User Guide.\n%\n% Note: When a function handle is used, the\n% value of 'At' (a function handle for the adjoint of 'A') must be \n% supplied.\n% \n% Outputs:\n% sol: n x 1 vector. It is the estimated signal.\n% outs: A struct consists of the convergence info. For details,\n% see header in solvePhaseRetrieval.m or the User Guide.\n% \n% \n% See the script 'testWirtFlow.m' for an example of proper usage of this \n% function.\n%\n%% Notations\n% x is the estimation of the signal. y is the vector of measurements such\n% that yi = ||^2 for i = 1,...,m\n%\n%% Algorithm Description\n% WF successively refines the estimate via an update rule that bears a\n% strong resemblance to a gradient descent scheme. Specifically, at each\n% iteration, x = x + mu/m * gradient log-likelihood of x given y For the\n% detailed formulation of \"gradient log-likelihood of x given y\" and a\n% detailed explanation of the theory, see the WF paper referenced below.\n% \n%% References\n% Paper Title: Phase Retrieval via Wirtinger Flow: Theory and Algorithms\n% Place: Chapter 2.3\n% Authors: Emmanuel Candes, Xiaodong Li, Mahdi Soltanolkotabi\n% arXiv Address: https://arxiv.org/abs/1407.1065\n% \n% PhasePack by Rohan Chandra, Ziyuan Zhong, Justin Hontz, Val McCulloch,\n% Christoph Studer, & Tom Goldstein \n% Copyright (c) University of Maryland, 2017\n\n\n\n\n%% -----------------------------START----------------------------------- \n \nfunction [sol, outs] = solveWirtFlow(A, At, b0, x0, opts) \n innerOpts = struct;\n innerOpts.maxIters = opts.maxIters;\n innerOpts.maxTime = opts.maxTime;\n innerOpts.tol = opts.tol;\n innerOpts.verbose = opts.verbose;\n innerOpts.recordTimes = opts.recordTimes;\n innerOpts.recordResiduals = opts.recordResiduals;\n innerOpts.recordMeasurementErrors = opts.recordMeasurementErrors;\n innerOpts.recordReconErrors = opts.recordReconErrors;\n innerOpts.xt = opts.xt;\n \n innerOpts.searchMethod = opts.searchMethod;\n innerOpts.betaChoice = opts.betaChoice;\n \n [sol, outs] = gradientDescentSolver(A, At, x0, b0, @updateObjective, innerOpts);\n \n function [f, gradf] = updateObjective(~, ~)\n f = @(z) 0.5 * norm(abs(z).^2 - b0.^2)^2;\n gradf = @(z) (abs(z).^2 - b0.^2) .* z;\n end\nend\n", "meta": {"author": "tomgoldstein", "repo": "phasepack-matlab", "sha": "aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9", "save_path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab", "path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab/phasepack-matlab-aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9/solvers/solveWirtFlow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7261420185896132}} {"text": "function [J, grad] = linearRegCostFunction(X, y, theta, lambda)\n%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear \n%regression with multiple variables\n% [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the \n% cost of using theta as the parameter for linear regression to fit the \n% data points in X and y. Returns the cost in J and the gradient in grad\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost and gradient of regularized linear \n% regression for a particular choice of theta.\n%\n% You should set J to the cost and grad to the gradient.\n%\n\n\nh = X*theta;\nhy = h-y;\nJ = sum(hy.^2)/(2*m) + lambda*sum(theta(2:end).^2)/(2*m);\nhyrep = repmat(hy,[1 size(X,2)]);\ngrad = sum(hyrep.*X,1)'/m;\n\ngrad(2:end) = grad(2:end) + lambda.*theta(2:end)/m;\n\n\n\n\n\n\n\n% =========================================================================\n\ngrad = grad(:);\n\nend\n", "meta": {"author": "1094401996", "repo": "machine-learning-coursera", "sha": "e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb", "save_path": "github-repos/MATLAB/1094401996-machine-learning-coursera", "path": "github-repos/MATLAB/1094401996-machine-learning-coursera/machine-learning-coursera-e53d1021a08b0f2ab7e0840d9807ab14e24ea9bb/problem_sets/ex5/linearRegCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7260864845338337}} {"text": "function cdf = beta_binomial_cdf ( x, a, b, c )\n\n%*****************************************************************************80\n%\n%% BETA_BINOMIAL_CDF evaluates the Beta Binomial CDF.\n%\n% Discussion:\n%\n% A simple summing approach is used.\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, integer X, the argument of the CDF.\n%\n% Input, real A, B, parameters of the PDF.\n% 0.0D+00 < A,\n% 0.0D+00 < B.\n%\n% Input, integer C, a parameter of the PDF.\n% 0 <= C.\n%\n% Output, real CDF, the value of the CDF.\n%\n if ( x < 0 )\n\n cdf = 0.0;\n\n elseif ( x < c )\n\n cdf = 0.0;\n for y = 0 : x\n pdf = beta ( a + y, b + c - y ) / ( ( c + 1 ) ...\n * beta ( y + 1, c - y + 1 ) * beta ( a, b ) );\n cdf = cdf + pdf;\n end\n\n elseif ( c <= x )\n\n cdf = 1.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/prob/beta_binomial_cdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7260864779916948}} {"text": "N = 25;\nx = 0:N-1;\nH = zeros(N,1);\n\nfor i = 1:N\n if i == (N+1)/2\n H(i) = 1/6;\n else\n H(i) = sin(pi*(i-(N+1)/2)/6)/(pi*(i-(N+1)/2));\n end;\nend;\nH = H.*blackman(N);\nnewN = 1000;\nH = [H',zeros(1,newN-length(H))];\nY = fft(H);\nY = fftshift(Y);\nW = calculateDiscreteFrequencyIndex(length(Y));\nsubplot(2,1,1);\n%plot(W,abs(Y));\nplot(W,10*log10(abs(Y)));\nsubplot(2,1,2);\nplot(W,angle(Y));\n", "meta": {"author": "VipaiLab", "repo": "Signals-and-Systems-course", "sha": "a48269b0247359ab746cb42bb55c984ed850e437", "save_path": "github-repos/MATLAB/VipaiLab-Signals-and-Systems-course", "path": "github-repos/MATLAB/VipaiLab-Signals-and-Systems-course/Signals-and-Systems-course-a48269b0247359ab746cb42bb55c984ed850e437/信号与系统MATLAB程序示例/8. FIR数字滤波器设计程序/testFilters.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013355, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7259872338733266}} {"text": "function v=v_dlyapsq(a,b)\n%V_DLYAPSQ Solves the discrete Lyapunov equation AV'VA' - V'V + BB' = 0\n% V is upper triangular with real non-negative diagonal entries\n% this is equivalent to v=chol(dlyap(a,b*b')) but better conditioned numerically\n\n% Copyright (C) Mike Brookes 2002\n% Version: $Id: v_dlyapsq.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[q,s]=schur(a');\n[q,s]=rsf2csf(q,s);\n[qd,r]=qr(b'*q,0);\n% save r for testing\nr0=r;\n[m,n]=size(r);\nu=zeros(n,n);\nif m==1\n for i=1:n-1\n in=i+1:n;\n si=s(i,i);\n aa=sqrt(1-si*si');\n u(i,i)=r(1)/aa;\n u(i,in)=(u(i,i)*si'*s(i,in)+aa*r(2:end))/(eye(n-i)-si'*s(in,in));\n r=aa*(u(i,i)*s(i,in)+u(i,in)*s(in,in))-si*r(2:end);\n end\n u(n,n)=r/sqrt(1-s(n,n)*s(n,n)');\n \nelse\n w=zeros(m,1); w(m)=1;\n em=eye(m);\n for i=1:n-m\n in=i+1:n;\n si=s(i,i);\n aa=sqrt(1-si*si');\n u(i,i)=r(1,1)/aa;\n u(i,in)=(u(i,i)*si'*s(i,in)+aa*r(1,2:end))/(eye(n-i)-si'*s(in,in));\n vv=aa*(u(i,i)*s(i,in)+u(i,in)*s(in,in))-si*r(1,2:end);\n rr=zeros(m,n-i);\n rr(1:m-1,:)=r(2:end,2:end);\n [qq,r]=qrupdate(em,rr,w,vv');\n end\n for i=n-m+1:n-1\n in=i+1:n;\n si=s(i,i);\n aa=sqrt(1-si*si');\n u(i,i)=r(1,1)/aa;\n u(i,in)=(u(i,i)*si'*s(i,in)+aa*r(1,2:end))/(eye(n-i)-si'*s(in,in));\n vv=aa*(u(i,i)*s(i,in)+u(i,in)*s(in,in))-si*r(1,2:end);\n rr=zeros(n-i+1,n-i);\n rr(1:n-i,:)=r(2:end,2:end);\n [qq,rr]=qrupdate(eye(n-i+1),rr,w(m-n+i:end),vv');\n r=rr(1:n-i,:);\n end\n \n u(n,n)=r/sqrt(1-s(n,n)*s(n,n)');\n \nend\n\nv=triu(qr(u*q'));\ndv=diag(v);\nix=dv~=0;\nv(ix,:)=diag(abs(dv(ix))./dv(ix))*v(ix,:);\nif isreal(a) & isreal(b)\n v=real(v);\nend\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_dlyapsq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7259872218740023}} {"text": "function x = block_levinson(y, L)\n%BLOCK_LEVINSON Block Levinson recursion for efficiently solving \n%symmetric block Toeplitz matrix equations.\n% BLOCK_LEVINSON(Y, L) solves the matrix equation T * x = y, where T \n% is a symmetric matrix with block Toeplitz structure, and returns the \n% solution vector x. The matrix T is never stored in full (because it \n% is large and mostly redundant), so the input parameter L is actually \n% the leftmost \"block column\" of T (the leftmost d columns where d is \n% the block dimension).\n\n% Author: Keenan Pepper\n% Last modified: 2007-12-23\n\n% References:\n% [1] Akaike, Hirotugu (1973). \"Block Toeplitz Matrix Inversion\".\n% SIAM J. Appl. Math. 24 (2): 234-241\n\ns = size(L);\nd = s(2); % Block dimension\nN = s(1) / d; % Number of blocks\n\nB = reshape(L, [d,N,d]); % This is just to get the bottom block row B\nB = permute(B, [1,3,2]); % from the left block column L\nB = flipdim(B, 3);\nB = reshape(B, [d,N*d]);\n\nf = L(1:d,:)^-1; % \"Forward\" block vector\nb = f; % \"Backward\" block vector\nx = f * y(1:d); % Solution vector\n\nfor n = 2:N\n ef = B(:,(N-n)*d+1:N*d) * [f;zeros(d)];\n eb = L(1:n*d,:)' * [zeros(d);b];\n ex = B(:,(N-n)*d+1:N*d) * [x;zeros(d,1)];\n A = [eye(d),eb;ef,eye(d)]^-1;\n fn = [[f;zeros(d)],[zeros(d);b]] * A(:,1:d);\n bn = [[f;zeros(d)],[zeros(d);b]] * A(:,d+1:end);\n f = fn;\n b = bn;\n x = [x;zeros(d,1)] + b * (y((n-1)*d+1:n*d) - ex);\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/30931-block-levinson-solver/block_levinson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7259872174528395}} {"text": "%\tnufft_tune_gauss\n%\ttune the FWHM for gaussian interpolation in 1D NUFFT\n%\tto minimize the worst-case error\n\nif ~isvar('err_gauss')\n\tN = 2^8;\n\tK_N = 2;\t\t\t\t% oversampling factor\n\tJlist = [2:16];\n\tPlist = linspace(0.2, 0.4, 101);\t% sig = parameter * sqrt(J)\n\trlist = [0:20]'/40;\t\t\t% fractions of gamma\n\n\terr_gauss.zn = zeros([length(rlist) length(Jlist) length(Plist)]);\n\terr_gauss.ft = zeros([length(rlist) length(Jlist) length(Plist)]);\n\n\tfor jj=1:length(Jlist)\n\t\tJ = Jlist(jj);\tprintf('J=%d', J)\n\n\t\tK = K_N * N;\n\t\tgam = 2*pi/K;\n\t\tom = gam * rlist;\n\n\t\t%\n\t\t%\tgaussian with various FWHM\n\t\t%\n\t\tfor ii=1:length(Plist)\n\t\t\tsig = Plist(ii) * sqrt(J);\n\t\t\t[Gfunc, Gfunc_ft] = nufft_gauss('inline', J, sig);\n\n\t\t\t%\n\t\t\t%\tinterpolator worst-case error\n\t\t\t%\n\t\t err_gauss.ft(:,jj,ii) = nufft1_error(om, N, J, K, ...\n\t\t\t\tGfunc, Gfunc_ft);\n\t\t err_gauss.zn(:,jj,ii) = nufft1_error(om, N, J, K, ...\n\t\t\t\tGfunc);\n\t\tend\n\tend\nend\n\nemax.zn = squeeze( max(err_gauss.zn, [], 1) );\t\t% [M,J,F] -> [J,F]\n[emax.zn, ibest.zn] = min(emax.zn, [], 2);\t\t% [J,F] -> J\npbest.zn = Plist(ibest.zn);\n\nemax.ft = squeeze( max(err_gauss.ft, [], 1) );\t\t% [M,J,F] -> [J,F]\n[emax.ft, ibest.ft] = min(emax.ft, [], 2);\t\t% [J,F] -> J\npbest.ft = Plist(ibest.ft);\n\n%\tplot best sig vs J (on log scale!)\nclf\nif 1\n\tlog_J = log(Jlist);\n\tlog_sig.zn = log(pbest.zn .* sqrt(Jlist));\n\tlog_sig.ft = log(pbest.ft .* sqrt(Jlist));\n\n\tsubplot(131)\n\tplot(log_J, log_sig.zn, 'co', log_J, log_sig.ft, 'yx'), axis tight\n\tlsline, legend('zn', 'ft')\n\txlabel log(J), ylabel 'log(sig best)'\n\tpol = polyfit(log_J, log_sig.zn, 1)\n\tprintf('\\\\sigma \\\\approx %g * J^{%g}', exp(pol(2)), pol(1))\n\tpol = polyfit(log_J, log_sig.ft, 1)\n\tprintf('\\\\sigma \\\\approx %g * J^{%g}', exp(pol(2)), pol(1))\nend\n\n%\n%\tplot emax vs J\n%\nif 1\n\tsubplot(132)\n\tsemilogy(Jlist, emax.zn, 'c-o', Jlist, emax.ft, 'y-x')\n\txlabel J, ylabel E_{max}\n title(sprintf('Maximum error for K/N=%g', K/N))\n\tlegend('zn', 'ft')\n\n\tsubplot(133)\n\tplot(emax.zn ./ emax.ft), axis tight, title 'emax: zn / ft'\n%\tsavefig c 'fig_?'\nend\n\n%\n%\tsave both sets of tuned sigma's to \"private\" file\n%\nif 1\n\tJgauss2 = Jlist;\n\tSgauss2.zn = pbest.zn .* sqrt(Jlist);\t\t% tuned sig zn\n\tSgauss2.ft = pbest.ft .* sqrt(Jlist);\t\t% tuned sig ft\n\tsave nufft_gauss2 Jgauss2 Sgauss2\n\tdisp('MOVE TO private!')\nend\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/@NUFFT/private/nufft_tune_gauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7259872095586365}} {"text": "%% B-A Scale-Free Network Generation and Visualization\n% *By Mathew Neil George*\n\n%% Description and Cautions\n% The *SFNG* m-file is used to simulate the B-A algorithm and returns scale-free\n% networks of given node sizes. Understanding the B-A algorithm is key \n% to using this code to its fullest. Due to Matlab resource limitations, it may not be\n% possible to generate networks much larger than 15000 nodes, and increasing the\n% *mlinks* variable increases processing time severely. This code was\n% developed so that one could generate a network of small size, and then\n% use that network as a seed to build a greater sized network, continuing\n% this process until the actual desired network size is reached. This is for\n% processor and time management purposes. However, realize that the initial\n% seed does not have to have scale-free properties, while the later seeds\n% may happen to have these properties. Therefore, it is prudent not to make the\n% initial seed size much larger than a few nodes (most commonly 5\n% interconnected nodes). In addition, the *mlinks* should be kept constant\n% throughout the creation of the scale-free network.\n%\n% The *PLplot* m-file takes a scale-free network in adjacency matrix format\n% and draws a best fit line to the frequency of degrees distribution of the\n% nodes. Degree is the number of links that connect to and from a single node\n% For scale-free networks, the frequency of degrees distribution forms a \n% power-law curve, with an exponent usually between -2 and -3. This code is\n% designed to allow only non-zero frequencies to be graphed in log-log format.\n% The function returns the equation of the power-law fit in a cfit variable.\n%\n% The *CNet* m-file function creats a network graph using the *gplot*\n% function with circular coordinates. It allows for a simple, yet\n% intuitive, visualization of a given network.\n\n%% Parameters\n% *SFNG*\n%\n% * *Nodes* is the desired network size, including the seed network size\n% (i.e. Nodes minus seed network size equals the number of nodes to be\n% added).\n%\n% * *mlinks* controls the number of links a new node can make to the existing\n% network nodes.\n%\n% * *seed* is the original network to which the B-A algorithm links\n% additional nodes with a specific preferential attachment procedure.\n% This undirected adjacency matrix can be created manually, or one could\n% use the *Adjacency Matrix GUI*. Each node must have at least one link.\n% The *seed* variable can be replaced with a developed scale-free network\n% to generate a larger one. Make sure the new *Nodes* variable is greater\n% than the size of the *seed* network.\n% \n% *PLplot*\n%\n% * *Net* is the input network which is to be graphed.\n%\n% *CNet*\n%\n% * *Net* is the input network which is to be graphed.\n%\n% Note that variables *Nodes*, *mlinks*, and *size* must be whole numbers and \n% variables *seed* and *Net* must be undirected adjacency matrices. The \n% diagonol elements of any adjacency matrix used with these functions must\n% all be zero.\n\n%% Sample Output\n% Here is a small example to demonstrate how to use the code. This code\n% creates a seed network of 5 nodes, generates a scale-free network of 300 nodes from\n% the seed network, and then performs the two graphing procedures.\nseed =[0 1 0 0 1;1 0 0 1 0;0 0 0 1 0;0 1 1 0 0;1 0 0 0 0]\nNet = SFNG(300, 1, seed);\nPL_Equation = PLplot(Net)\nCNet(Net)\n\n%% References\n% One explanation of the B-A Algorithm can be found on this PDF website\n% http://arxiv.org/PS_cache/cond-mat/pdf/0107/0107420.pdf\n%\n% Undirected Adjecency Matrices are defined on Wikipedia.org\n% http://en.wikipedia.org/wiki/Adjacency_matrix\n%\n% The *Adjacency Matrix GUI* file by Steve Chuang can be found on the Matlab File Exchange\n% http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=6937&objectType=file\n\n%% Acknowledgements\n% Special thanks to Mark Ballerini with the Massapequa High School Science \n% Research Program and Zoltan Dezso at the University of Notre Dame for \n% their invaluable help in researching network theory as well as to my \n% family for providing motivation and encouragement in pursuing science.", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/11947-b-a-scale-free-network-generation-and-visualization/pubfile.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7258904628031229}} {"text": "function s=norm(a,P)\n%norm: Matrix or vector norm of vector/matrix of mp-type\n\n% For matrices...\n% NORM(X) is the largest singular value of X, max(svd(X)).\n% NORM(X,2) is the same as NORM(X).\n% NORM(X,1) is the 1-norm of X, the largest column sum,\n% = max(sum(abs(X))).\n% NORM(X,inf) is the infinity norm of X, the largest row sum,\n% = max(sum(abs(X'))).\n% NORM(X,'fro') is the Frobenius norm, sqrt(sum(diag(X'*X))).\n% NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'.\n% \n% For vectors...\n% NORM(V,P) = sum(abs(V).^P)^(1/P).\n% NORM(V) = norm(V,2).\n% NORM(V,inf) = max(abs(V)).\n% NORM(V,-inf) = min(abs(V)).\n% \n% See also COND, RCOND, CONDEST, NORMEST.\n\nif nargin<2,P=2;end\nif isa(P,'mp')\n error(['Second parameter should not be of mp-type'])\nend\nif min(size(a))==1\n %is a vector\n if isinf(P) | strcmp(lower(P),'inf')\n if P>0\n s=max(abs(a));\n else\n s=min(abs(a));\n end\n return\n end\n A=max(abs(a(:)));a=a/A;\n if P==2\n %naive implementation\n s=A*sqrt(sum(a.*a));\n else\n s=A*(sum(a.^P))^(1/P);\n end\nelse\n %is a matrix\n if isinf(P) | strcmp(lower(P),'inf')\n s=max(sum(abs(a')));\n return\n end\n if ischar(P)\n if strcmp(lower(P),'fro')\n s=sqrt(sum(diag(a'*a)));\n else\n error(['Second parameter is not recognized as an option: ' P])\n end\n return\n end\n switch P\n case 1\n s=max(sum(abs(a)));\n case 2\n s=max(svd(a));\n otherwise\n error(['NORM(X,P) is available for matrix X only if P is 1, 2, inf or ' setstr(39) 'fro' setstr(39) '.'])\n end\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/external/analysis/mptoolbox/@mp/norm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.72581245587321}} {"text": "function [all_theta] = oneVsAll(X, y, num_labels, lambda)\n%ONEVSALL trains multiple logistic regression classifiers and returns all\n%the classifiers in a matrix all_theta, where the i-th row of all_theta \n%corresponds to the classifier for label i\n% [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels\n% logisitc regression classifiers and returns each of these classifiers\n% in a matrix all_theta, where the i-th row of all_theta corresponds \n% to the classifier for label i\n\n% Some useful variables\nm = size(X, 1);\nn = size(X, 2);\n\n% You need to return the following variables correctly \nall_theta = zeros(num_labels, n + 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: You should complete the following code to train num_labels\n% logistic regression classifiers with regularization\n% parameter lambda. \n%\n% Hint: theta(:) will return a column vector.\n%\n% Hint: You can use y == c to obtain a vector of 1's and 0's that tell use \n% whether the ground truth is true/false for this class.\n%\n% Note: For this assignment, we recommend using fmincg to optimize the cost\n% function. It is okay to use a for-loop (for c = 1:num_labels) to\n% loop over the different classes.\n%\n% fmincg works similarly to fminunc, but is more efficient when we\n% are dealing with large number of parameters.\n%\n% Example Code for fmincg:\n%\n% % Set Initial theta\n% initial_theta = zeros(n + 1, 1);\n% \n% % Set options for fminunc\n% options = optimset('GradObj', 'on', 'MaxIter', 50);\n% \n% % Run fmincg to obtain the optimal theta\n% % This function will return theta and the cost \n% [theta] = ...\n% fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...\n% initial_theta, options);\n%\n\nfor c = 1:num_labels\n\n% Set initial theta\ninitial_theta=zeros(n+1,1);\n%initial_theta=zeros(num_labels, n + 1);\n\n% Set options for fminunc\noptions = optimset('GradObj', 'on', 'MaxIter', 50);\n\n% Run fmincg to obtain the optimal theta\n% This function will return theta and the cost \n[theta]=fmincg(@(t)(lrCostFunction(t,X, (y == c), lambda)), initial_theta, options);\n\n% Updating theta to overall all_theta\nif (c==1)\n\thistory_theta=theta';\nelse\n\thistory_theta=[history_theta; theta'];\nend\n\nend\n\nall_theta=history_theta;\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "yhyap", "repo": "machine-learning-coursera", "sha": "fb33f0ad54ff2104660c86b0d26456b15029a798", "save_path": "github-repos/MATLAB/yhyap-machine-learning-coursera", "path": "github-repos/MATLAB/yhyap-machine-learning-coursera/machine-learning-coursera-fb33f0ad54ff2104660c86b0d26456b15029a798/mlclass-ex3/oneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8499711813581708, "lm_q1q2_score": 0.725801231403168}} {"text": "function triangle_symq_rule_test02 ( degree, numnodes, vert1, vert2, vert3 )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_SYMQ_RULE_TEST02 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 exactness\n% 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_TEST02\\n' );\n fprintf ( 1, ' Symmetric quadrature rule for a triangle.\\n' );\n fprintf ( 1, ' Polynomial exactness degree DEGREE = %d\\n', degree );\n\n area = triangle_area ( vert1, vert2, vert3 );\n%\n% Retrieve and print a symmetric quadrature rule.\n%\n [ rnodes, weights ] = triasymq ( degree, vert1, vert2, vert3, numnodes );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NUMNODES = %d', numnodes );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' J W X Y\\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : numnodes\n fprintf ( 1, ' %4d %14.6g %14.6g %14.6g\\n', ...\n j, weights(j), rnodes(1,j), rnodes(2,j) );\n end\n\n d = sum ( weights(1:numnodes) );\n\n fprintf ( 1, ' Sum %14.6g\\n', d );\n fprintf ( 1, ' Area %14.6g\\n', area );\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/triangle_symq_rule/triangle_symq_rule_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.8539127566694178, "lm_q1q2_score": 0.7258012296953058}} {"text": "function X = randnd(beta,varargin)\n%% X = randnd(beta,varargin)\n% This function is a \"decorator\" for the Matlab in-build 'randn' function.\n% It takes an additional first argument (beta) which shapes the spectral\n% characteristic of the data (in all dimensions) as f^beta. The output data\n% is scaled to zero mean and unit standard deviation.\n%\n% For help on 'varargin' go to Matlab help for the 'randn' function.\n%\n% EXAMPLE 1 - Input robustness\n% A = randnd(-1,[2^5+1 1]); % Handle odd dimensionality\n% A = randnd((rand-0.5)*4,[134 12 1 1 1 26 1 9]); % Handle large number of dimentions\n% A = randnd(-1,[1 0 3]); % Handle 0's\n% A = randnd(2,[1 1 1 256]); % Handle leading singleton dimensions\n%\n% EXAMPLE 2 - Pink map\n% A = randnd(-1,2^8); % Generate 256 x 256 grid with random 1/f (pink) noise\n% contourf(A,'edgecolor','none'); axis square; % Display it as a contour plot\n%\n% EXAMPLE 3 - Brownian cube\n% A = randnd(-2,[2^4 2^4 2^4]); % Generate 16 x 16 x 16 cube of f^-2 (Brownian) noise\n% [X,Y,Z] = meshgrid(1:2^4); % Generate 3d meshgrid\n% scatter3(X(:),Y(:),Z(:),100,A(:),'filled');\n% axis vis3d; axis off;\n%\n% EXAMPLE 4 - Single blue noise\n% p = single(magic(10)); % Single precision matrix of interest\n% A = randnd(1,size(p),'like',p); % Generate f (blue) noise 'like' p\n% isa(A,'single') % X is also a single precision random number\n%\n% EXAMPLE 5 - Proof that beta scales power spectral density correctly\n% beta = -2;\n% A = randnd(beta,[1 2^11]);\n% Afft = abs(fft(A.^2)); % Get the magnitude of power (i.e. signal^2) spectrum\n% Afft = Afft(2:length(Afft)/2); % Get the spectrum between DC and Nyquist\n% k = 1:length(Afft); % Create wavenumber (frequency) vector\n% P = polyfit(log(k),log(Afft),1); % Fit a straight line to the loglog plot\n% loglog(k,Afft,'.',k,exp(P(2))*k.^P(1),'-'); grid on; % Plot on loglog axis\n% xlim([min(k) max(k)]); title(['Beta = ',num2str(beta),'; Slope = ',num2str(P(1))]);\n%\n%\n% Based on similar functions by Jon Yearsley and Hristo Zhivomirov\n% Written by Marcin Konowalczyk\n% Timmel Group @ Oxford University\n \n%% Parse the input\nnarginchk(0,Inf); nargoutchk(0,1);\n \nif nargin < 2 || isempty(beta); beta = 0; end % Default to white noise\nassert(isnumeric(beta) && isequal(size(beta),[1 1]),'''beta'' must be a number');\nassert(-2 <= beta && beta <= 2,'''beta'' out of range'); % Put on reasonable bounds\n \n%% Generate N-dimensional white noise with 'randn'\nX = randn(varargin{:});\nif isempty(X); return; end; % Usually happens when size vector contains zeros\n \n% Squeeze prevents an error if X has more than one leading singleton dimension\n% This is a slight deviation from the pure functionality of 'randn'\nX = squeeze(X);\n \n% Return if white noise is requested\nif beta == 0; return; end;\n \n%% Generate corresponding N-dimensional matrix of multipliers\nN = size(X);\n% Create matrix of multipliers (M) of X in the frequency domain\nM = []; \nfor j = 1:length(N)\n n = N(j);\n \n if (rem(n,2)~=0) % if n is odd\n % Nyquist frequency bin does not show up in odd-numbered fft\n k = ifftshift(-(n-1)/2:(n-1)/2);\n else\n k = ifftshift(-n/2:n/2-1);\n end\n \n % Spectral multipliers\n m = (k.^2)';\n \n if isempty(M);\n M = m;\n else\n % Create the permutation vector\n M_perm = circshift(1:length(size(M))+1,1,2);\n % Permute a singleton dimension to the beginning of M\n M = permute(M,M_perm);\n % Add m along the first dimension of M\n M = bsxfun(@plus,M,m);\n end\nend\nclear j M_perm k n m\n% Reverse M to match X (since new dimensions were being added form the left)\nM = permute(M,length(size(M)):-1:1);\nassert(isequal(size(M),size(X)),'Bad programming error'); % This should never occur\n \n% Shape the amplitude multipliers by (beta/2) which corresponds to shaping\n% the power by beta\nM = M.^(beta/2);\n \n% Set the DC component to zero\nM(1,1) = 0;\n \n%% Multiply X by M in frequency domain\nXstd = std(X(:));\nXmean = mean(X(:));\nX = real(ifftn(fftn(X).*M));\n \n% Force zero mean unity standard deviation\nX = X - mean(X(:));\nX = X./std(X(:));\n \n% Restore the standard deviation and mean from before the spectral shaping.\n% This ensures the random sample from randn is truly random. After all, if\n% the mean was always exactly zero it would not be all that random.\nX = X + Xmean;\nX = X.*Xstd;\nend", "meta": {"author": "zwx8981", "repo": "DBCNN", "sha": "64f6e3e86f1a055b387fc170c93aa2dd994a5256", "save_path": "github-repos/MATLAB/zwx8981-DBCNN", "path": "github-repos/MATLAB/zwx8981-DBCNN/DBCNN-64f6e3e86f1a055b387fc170c93aa2dd994a5256/distortion_generator/randnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544448, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7257967893327237}} {"text": "function SR = getInitialSRImage(W, LRImages, photoParams)\n% GETINITIALSRIMAGE Initial guess for super-resolved image\n% GETINITIALSRIMAGE computes a rough estimate for the super-resolved\n% image from given model parameters.\n%\n% X = GETINITIALSRIMAGE(W, Y, PHOTOPARAMS) computes the \"average image\" X\n% as initial guess based on the system matrix W, the low-resolution data \n% Y and the photometric parameters PHOTOPARAMS.\n%\n% See David P. Capel, Image Mosaicing and Super-resolution, PhD thesis,\n% 2001 for details.\n\n if nargin > 2 && ~isempty(photoParams)\n numFrames = length(photoParams.mult);\n numLRPixel = length(LRImages) / numFrames;\n \n % Compose photometric parameters into additive and multiplicative term.\n bm = zeros(size(LRImages));\n ba = zeros(size(LRImages));\n for k = 1:numFrames\n bm( ((k-1)*numLRPixel + 1):(k*numLRPixel) ) = repmat(photoParams.mult(k), numLRPixel, 1);\n ba( ((k-1)*numLRPixel + 1):(k*numLRPixel) ) = repmat(photoParams.add(k), numLRPixel, 1);\n end\n bm_invmat = spdiags(1./bm(:), 0, length(bm), length(bm));\n \n % Compute \"average image\" from low-resolution observtions, system\n % matrix and phtometric parameters.\n SR = (W' * bm_invmat * (LRImages - ba .* ones(size(LRImages)))) ./ (sum(W, 1)' + 1e-4);\n else\n % Compute \"average image\" without photometric parameters\n SR = (W' * LRImages) ./ (sum(W, 1)' + 1e-4);\n end", "meta": {"author": "thomas-koehler", "repo": "SupER", "sha": "d8c6f2e4b26db002ff55bc2beba18639f1d0bb49", "save_path": "github-repos/MATLAB/thomas-koehler-SupER", "path": "github-repos/MATLAB/thomas-koehler-SupER/SupER-d8c6f2e4b26db002ff55bc2beba18639f1d0bb49/matlab/algorithms/SRAlgorithms/SRToolbox/algorithms/MAP/getInitialSRImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572635, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7257365091114466}} {"text": "function [out] = baseflow_3(S,Smax)\n%baseflow_3 \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: Empirical non-linear outflow from a reservoir\n% Constraints: None specified\n% @(Inputs): S - current storage [mm]\n% Smax - maximum contributing storage [mm]\n\nout = Smax^(-4)/(4)*(S^5);\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/baseflow_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.7257364984624177}} {"text": "function crackFVMP2\n%% CRACK Problem\n%\n% crack solves the Poisson equation $-\\Delta u =f$ in $\\Omega$ and $u =\n% g_D$ on $\\partial \\Omega$ in a crack domain\n% $\\Omega=\\{|x|+|y|<1\\}\\backslash \\{0<= x <=1, y=0\\}$\n% using adaptive finite element method (AFEM). We choose f=1 and g_D such\n% that the exact solution is $u = r^{\\beta}\\sin(\\beta\\theta)-0.25r^2,\n% \\beta = 1/2$ in the polar coordinate.\n%\n% EXAMPLE\n%\n% crack \n%\n% See also crack_performance, Lshape\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclose all;clc;clear;\n%% Parameters\nmaxN = 2e3; theta = 0.5; maxIt = 50; \nN = zeros(maxIt,1); err = zeros(maxIt,3); \n%% Generate an initial mesh\nnode = [1,0; 0,1; -1,0; 0,-1; 0,0; 1,0]; % nodes\nelem = [5,1,2; 5,2,3; 5,3,4; 5,4,6]; % elements\nelem = label(node,elem); % label the mesh\nbdEdge = setboundary(node,elem,'Dirichlet'); % Dirichlet boundary condition\nshowmesh(node,elem); % plot mesh\nfindelem(node,elem); % plot element indices\nfindnode(node,1:5); % plot node indices\nfindedge(node,[1 5; 5 6],1); % plot the crack edge\ntext(node(6,1)+0.05,node(6,2)+0.075,int2str(6), ...\n 'FontSize',14,'FontWeight','bold');\n%% \n% node 1 and node 6 are the same point (1,0)\n\n%% Get a fine mesh by uniform bisection\nfor k = 1:2\n [node,elem,bdEdge] = uniformbisect(node,elem,bdEdge);\nend\nclf; showmesh(node,elem);\n%% Set up PDE data\npde.f = @f;\npde.exactu = @exactu;\npde.g_D = @exactu;\npde.Du=@Du;\npde.d=[];\n%% Adaptive Finite Element Method\n% *SOLVE* -> *ESTIMATE* -> *MARK* -> *REFINE*\nfor k = 1:maxIt\n % Step 1: SOLVE\n [u,A,~,~,edge] = PoissonP2FVM(node,elem,[],@pde.f,@pde.g_D);\n % Plot mesh and solution\n figure(1); showresult(node,elem,u(1:size(node,1)),[-7,12]); \n % Step 2: ESTIMATE\n % eta = estimaterecovery(node,elem,u); % recovery type % need eta^2 for mark\n eta = recoverFlux2(node,elem,pde,bdEdge,u);\n % Record error and number of vertices\n uI = pde.exactu([node; (node(edge(:,1),:)+node(edge(:,2),:))/2]);\n err(k,1) = sqrt((u-uI)'*A*(u-uI)); \n err(k,2) = getL2error(node,elem,@exactu,u);\n err(k,3) = getH1error(node,elem,@pde.Du,u);\n N(k) = size(node,1);\n if (N(k)>maxN), break; end \n % Step 3: MARK\n markedElem = mark(elem,eta,theta);\n % Step 4: REFINE\n [node,elem,bdEdge] = bisect(node,elem,markedElem,bdEdge);\nend\n\n%% Plot convergence rates\nN= N(1:k); \nerruIuh= err(1:k,1); errL2 = err(1:k,2); errH1 = err(1:k,3); \nfigure(2);\nr1 = showrate(N,erruIuh,5,'-*');\nhold on;\nr2 = showrate(N,errL2,5,'k-+');\nr3 = showrate(N,errH1,10,'r-+');\nlegend('||Du_I-Du_h||',['cN^{' num2str(r1) '}'], ...\n '||u-u_h||',['cN^{' num2str(r2) '}'], ...\n '||Du-Du_h||',['cN^{' num2str(r3) '}'], ...\n 'LOCATION','Best');\n%%\n% Using AFEM, we obtain optimal rate of convergence the error in the energy\n% norm ($N^{-0.5}$) and in the $L^2$ norm ($N^{-1}$).\nend % End of function CRACK\n\n\n%% Data of CRACK\nfunction z = f(p) % load data (right hand side function)\nz = ones(size(p,1),1);\nend\n\nfunction z = exactu(p) % exact solution\nr = sqrt(sum(p.^2,2));\nz = sqrt(0.5*(r-p(:,1)))-0.25*r.^2;\nend\n\nfunction z = Du(p) % derivative of the exact solution\nr = sqrt(sum(p.^2,2));\nz(:,1) = (p(:,1)./r-1)./sqrt(8*(r-p(:,1)))-0.5*p(:,1); % u_x\nz(:,2) = p(:,2)./r./sqrt(8*(r-p(:,1)))-0.5*p(:,2); % u_y\nend", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fvm/crackFVMP2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.725736485336748}} {"text": "function y = circle_characteristic ( m, n, x )\n\n%*****************************************************************************80\n%\n%% CIRCLE_CHARACTERISTIC evaluates the characteristic function of a circle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points to check.\n%\n% Input, real X(M,N), the coordinates of points to be checked.\n%\n% Output, real Y(N,1), is 1 if the point is inside, 0 otherwise.\n%\n y = sqrt ( sum ( x.^2, 1 ) );\n\n y = y';\n\n y = ( y < 1.0 );\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/hypersphere_surface/circle_characteristic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.7257341804987968}} {"text": "function r8plu_inverse_test ( )\n\n%*****************************************************************************80\n%\n%% R8PLU_INVERSE_TEST tests R8PLU_INVERSE;\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 n = 5;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8PLU_INVERSE_TEST\\n' );\n fprintf ( 1, ' R8PLU_INVERSE determines the inverse of a matrix\\n' );\n fprintf ( 1, ' from its compressed PLU factors.\\n' );\n fprintf ( 1, ' Using initial random number seed = %d\\n', seed );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n%\n% Set the matrix.\n%\n [ a, seed ] = r8mat_uniform_01 ( n, n, seed );\n\n r8mat_print ( n, n, a, ' The matrix A:' );\n%\n% Factor the matrix.\n%\n [ pivot, lu, info ] = r8mat_to_r8plu ( n, a );\n\n if ( info ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST0852 - Fatal error!\\n' );\n fprintf ( 1, ' R8MAT_TO_R8PLU declares the matrix is singular!\\n' );\n fprintf ( 1, ' The value of INFO is %d\\n', info );\n return\n end\n%\n% Compute the inverse.\n%\n b = r8plu_inverse ( n, pivot, lu );\n\n r8mat_print ( n, n, b, ' The inverse matrix B:' );\n%\n% Compute the product C = A * B.\n%\n c(1:n,1:n) = a(1:n,1:n) * b(1:n,1:n);\n\n r8mat_print ( n, n, c, ' The product matrix C = A * B:' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8plu_inverse_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7257341770400516}} {"text": "function g = year_to_golden_number ( y )\n\n%*****************************************************************************80\n%\n%% YEAR_TO_GOLDEN_NUMBER returns the golden number of a Common year.\n%\n% Discussion:\n%\n% Nineteen solar years are very close to 235 lunations. Calendars\n% that try to keep track of both the sun and moon often make use of\n% this fact, ascribed to the Greek astronomer Meton.\n%\n% While trying to determine a formula for Easter, Dionysus Exiguus\n% symbolized the place of each year in its Metonic cycle by a\n% \"golden number\" between 1 and 19. The numbering began with the\n% year 1 BC, assigned the golden number of 1. The following year,\n% 1 AD, got the golden number of 2, and after that it gets easier.\n%\n% The same golden year calculation is done for years in the Julian\n% or Gregorian calendar.\n%\n% Example:\n%\n% Year Golden Number\n%\n% 1 BC 1\n% 1 AD 2\n% 2 AD 3\n% 18 AD 19\n% 19 AD 1\n% 20 AD 2\n% 1066 AD 3\n% 1900 AD 1\n% 1919 AD 1\n% 1938 AD 1\n% 1957 AD 1\n% 1976 AD 1\n% 1995 AD 1\n% 2014 AD 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer Y, the year.\n%\n% Output, integer G, the golden number, between 1 and 19. This\n% records the position of the year in the 19 year Metonic cycle.\n%\n if ( y == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'YEAR_TO_GOLDEN_NUMBER - Fatal error!\\n' );\n fprintf ( 1, ' Illegal input Y = 0.\\n' );\n error ( 'YEAR_TO_GOLDEN_NUMBER - Fatal error!' );\n end\n%\n% We assume that BC years come in as negative numbers, and that\n% the year before 1 AD is 1 BC. So add 1 to any negative value\n% so that the arithmetic works.\n%\n y2 = y_common_to_astronomical ( y );\n\n g = i4_wrap ( y2 + 1, 1, 19 );\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/year_to_golden_number.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7257341723634526}} {"text": "function R=return_Rt_matrix(alpha,beta,gamma,tx,ty,tz)\n\n% Copyright (C) <2007> \n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the version 3 of the GNU General Public License\n% as published by the Free Software Foundation.\n% \n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n% General Public License for more details. \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% Francesc Moreno-Noguer, CVLab-EPFL, September 2007.\n% fmorenoguer@gmail.com, http://cvlab.epfl.ch/~fmoreno/ \n\nR(1,1)=cos(alpha)*cos(gamma)-cos(beta)*sin(alpha)*sin(gamma);\nR(2,1)=cos(gamma)*sin(alpha)+cos(alpha)*cos(beta)*sin(gamma);\nR(3,1)=sin(beta)*sin(gamma);\nR(4,1)=0;\n\nR(1,2)=-cos(beta)*cos(gamma)*sin(alpha)-cos(alpha)*sin(gamma);\nR(2,2)=cos(alpha)*cos(beta)*cos(gamma)-sin(alpha)*sin(gamma);\nR(3,2)=cos(gamma)*sin(beta);\nR(4,2)=0;\n\nR(1,3)=sin(alpha)*sin(beta);\nR(2,3)=-cos(alpha)*sin(beta);\nR(3,3)=cos(beta);\nR(4,3)=0;\n\nR(:,4)=[tx,ty,tz,1]';\n\n", "meta": {"author": "cvlab-epfl", "repo": "EPnP", "sha": "f9d27b186d9c754b72e076b3843f47ad136e9799", "save_path": "github-repos/MATLAB/cvlab-epfl-EPnP", "path": "github-repos/MATLAB/cvlab-epfl-EPnP/EPnP-f9d27b186d9c754b72e076b3843f47ad136e9799/matlab/data/return_Rt_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660923657093, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.7256349359660538}} {"text": "function [lx, r0, ux] = get_rate_grid_boundaries( model, modparam, t, gamma)\n% Retrive lower and upper boundaries for variance grid, based on first two moments of variance process\n% model : see below\n% modparam : container with each of the model parameters required\n% t: time to maturity used for the vairance grid\n% gamma: grid mult param, rougly centered around +/- gamma standard deviations of the variance process\n\nif model == 1 %CIR (eta, theta, Rho, Sigmar, r0)\n eta = modparam.eta; theta = modparam.theta; Sigmar = modparam.Sigmar; r0 = modparam.r0; \n\n mu_H = exp(-eta*t)*r0 + theta*(1-exp(-eta*t));\n sig2_H = Sigmar^2/eta*r0*(exp(-eta*t)-exp(-2*eta*t)) +theta*Sigmar^2/(2*eta)*(1-2*exp(-eta*t)+exp(-2*eta*t));\n \nelseif model == 2 %VASICEK ( in SV this is STEIN STEIN / same moments as SCOTT) ... (eta, theta, Rho, Sigmar, r0)\n eta = modparam.eta; theta = modparam.theta; Sigmar = modparam.Sigmar; r0 = modparam.r0; \n \n mu_H = exp(-eta*t)*r0 + theta*(1-exp(-eta*t));\n sig2_H = Sigmar^2/(2*eta)*(1 -exp(-2*eta*t));\n \nelseif model == 3 % Merton\n lambda = modparam.lambda; Sigmar = modparam.Sigmar; r0 = modparam.r0; \n \n mu_H = r0 + lambda*t;\n sig2_H = Sigmar^2*t;\n \nelseif model == 4 % Dothan\n a = modparam.a; Sigmar = modparam.Sigmar; r0 = modparam.r0; \n \n mu_H = r0*exp(a*t);\n sig2_H = r0^2*exp(2*a*t)*(exp(Sigmar^2*t) - 1);\n \nend \n\nux = mu_H + gamma*sqrt(sig2_H); %variance grid upper bound\nlx = mu_H - gamma*sqrt(sig2_H);\n\nif model == 1 || model == 4\n lx = max(0.00001,lx); %variance grid lower bound\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/PROJ/STOCHASTIC_INTEREST/Helper_Functions/get_rate_grid_boundaries.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7256134066179035}} {"text": "function [fa,md,rd,ad] = dtiComputeFA(eigVal)\n% Computes fractional anisotropy (FA) from tensor eigenvalues\n%\n% [fa,md,rd,ad] = dtiComputeFA(eigVal)\n%\n% eigVal XxYxZx3xN (or nx3xN) array of tensor eigenvalues (N is No. of subjects)\n% fa XxYxZxN (or nxN) array of FA values\n% md XxYxZxN (or nxN) array of Mean Diffusivity values (10^-^6 mm^2/sec)\n% rd XxYxZxN (or nxN) array of Radial Diffusivity values\n%\n% HISTORY: \n% 2003.12.04 ASH (armins@stanford.edu) wrote it.\n% 2003.12.04 RFD (bob@white.stanford.edu) added check to avoid divide-by-zero.\n% 2004.02.19 ASH added extra dimension for subjects\n% 2005.05.02 RFD: added option to pass in a dt6 array.\n% 2006.07.12 ASH added indexed format\n% 2006.07.13 RFD: fixed the features that ASH so rudely clobbered yesterday.\n% 2007.02.28 RFD: added rd return arg. \n\n% Programming: Since this returns MD as an option, how about renaming the\n% function. Or giving it a flag about which to return. Or something.\n\n% Check inputs\nif (ndims(eigVal)==2)\n Ind = 1; % eigVal in indexed nx3 format\n eigVal = shiftdim(eigVal, -2);\nelseif(ndims(eigVal)==3),\n if(size(eigVal,2)==3 && size(eigVal,3)~=3)\n Ind = 1; % Data in indexed nx3xN format\n eigVal = shiftdim(eigVal, -2);\n else\n Ind = 2; % Data in XxYx3 format\n eigVal = shiftdim(eigVal, -1);\n end\nelse\n Ind = 0; % eigVal in XxYxZx3xN format\nend\nif (ndims(eigVal)<4 || ndims(eigVal)>5),\n error('Wrong input format');\nend\n\nif(size(eigVal,4) ~= 3),\n if(size(eigVal,4)==6)\n [eigVec, eigVal] = dtiEig(eigVal);\n clear eigVec;\n else\n error('Wrong input format');\n end\nend\n\n% Main\nepsilon = 1e-10; % Avoid division by zero\n\n% Mean diffusivity\nmd = sum(eigVal,4)/3;\n\n%\nstdevDiffusivity = sqrt(sum((eigVal-repmat(md,[1,1,1,3,1])).^2,4));\nnormDiffusivity = sqrt(sum(eigVal.^2,4));\nnz = normDiffusivity > epsilon;\n\n% Formula for fractional anisotropy\nfa = repmat(NaN, size(md));\nfa(nz) = sqrt(3/2).*(stdevDiffusivity(nz)./normDiffusivity(nz));\nfa = squeeze(fa);\n\n% Mean diffusivity\nmd = squeeze(md);\n\n% If requested, return rd and ad\nif(nargout>2)\n % Radial diffusivity is the average of the two smaller eigenvalues\n rd = squeeze((eigVal(:,:,:,2)+eigVal(:,:,:,3))/2);\nend\nif(nargout>3)\n % Axial diffusivity - the largest eigenvalue\n ad = squeeze(eigVal(:,:,:,1));\nend\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/mrDiffusion/statistics/dtiComputeFA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.7256133921489597}} {"text": "function flag = checkinterfacemesh3(node, elem, interfaceData)\n%% CHECKINTERFACEMESH3 check the validity of the polyhedra mesh generated\n% by interfacemesh3.\n%\n% Here we check validity of the polyhedra mesh by the Euler formla: \n% F - E + V = 2 \n% where F, E and V are the number of faces, edges and vertices of a simply\n% closed polyhedron.\n%\n% Author: Huayi Wei , based on discussion with Long Chen.\n%\n% See also: interfacemesh3\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nface = interfaceData.face;\nface2elem = interfaceData.face2elem;\nN = size(node,1);\nNF = size(face,1);\n\nNP = max(face2elem);\nisCutPoly = false(NP, 1);\nisCutPoly(face2elem) = true;\ncutPolyIdx = zeros(NP, 1);\nNP = sum(isCutPoly);\ncutPolyIdx(isCutPoly) = 1:NP;\nface2elem = cutPolyIdx(face2elem);\n\nisTriFace = face(:,4) == 0;\nedge = 4*ones(NF,1);\nedge(isTriFace) = 3;\nE = accumarray(face2elem, edge)/2;\nF = accumarray(face2elem, ones(NF,1));\n\npoly2node = sparse(face2elem(isTriFace)*ones(1,3), face(isTriFace, 1:3), 1, NP,N)...\n+ sparse(face2elem(~isTriFace)*ones(1,4), face(~isTriFace, 1:4), 1, NP,N);\npoly2node = poly2node > 0;\nNV = poly2node*ones(N,1);\n\nisBdPoly = ((F - E + NV) ~= 2);\n\nif ~isempty(find(isBdPoly,1))\n figure\n showmesh(node, face(isTriFace & isBdPoly(face2elem),1:3));\n sface = face(~isTriFace & isBdPoly(face2elem),1:4);\n hold on\n tsface = [sface(:, 1:3);sface(:,[3, 4,1])];\n showmesh(node, tsface, 'Facecolor','y');\n \n% bdPolyIdx = find(isBdPoly);\n% figure\n% for i = 1:size(bdPolyIdx)\n% sface = face(~isTriFace & face2elem == bdPolyIdx(i),1:4);\n% tsface = [sface(:, 1:3);sface(:,[3, 4,1])];\n% showmesh(node, [face(isTriFace & face2elem == bdPolyIdx(i),1:3);tsface]);\n% end\n flag = false;\nelse\n flag = true;\nend\n\n\n\n\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/mesh/checkinterfacemesh3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7256133876748831}} {"text": "function y = perform_windowed_fourier_transform(x,w,q,n, options)\n\n% perform_windowed_fourier_transform - compute a local Fourier transform\n%\n% Forward transform:\n% MF = perform_windowed_fourier_transform(M,w,q,n, options);\n% Backward transform:\n% M = perform_windowed_fourier_transform(MF,w,q,n, options);\n%\n% w is the width of the window used to perform local computation.\n% q is the spacing betwen each window.\n%\n% MF(:,:,,i,j) contains the spectrum around point ((i-1)*q,(j-1)*q)+1.\n%\n% A typical use, for an redundancy of 2x2 could be w=2*q+1\n%\n% options.bound can be either 'per' or 'sym'\n%\n% options.normalization can be set to\n% 'tightframe': tight frame transform, with energy conservation.\n% 'unit': unit norm basis vectors, usefull to do thresholding\n%\n% Copyright (c) 2006 Gabriel Peyre\n\noptions.null = 0;\nif size(x,3)>1\n dir = -1;\n if nargin<4\n % assume power of 2 size\n n = q*size(x,3);\n n = 2^floor(log2(n));\n end\nelse\n dir = 1;\n n = size(x,1);\nend\n\nif isfield(options, 'bound')\n bound = options.bound;\nelse\n bound = 'sym';\n bound = 'per';\nend\n\nif isfield(options, 'transform_type')\n transform_type = options.transform_type;\nelse\n transform_type = 'fourier';\nend\n\nif isfield(options, 'normalization')\n normalization = options.normalization;\nelse\n normalization = 'tightframe';\nend\n\n% perform sampling\nt = 1:q:n+1;\n[Y,X] = meshgrid(t,t);\np = size(X,1);\n\nif mod(w,2)==1\n% w = ceil((w-1)/2)*2+1;\n w1 = (w-1)/2;\n t = -w1:w1;\nelse\n t = -w/2+1:w/2;\nend\n[dY,dX] = meshgrid(t,t);\n\nX = reshape(X,[1 1 p p]);\nY = reshape(Y,[1 1 p p]);\nX = repmat( X, [w w 1 1] );\nY = repmat( Y, [w w 1 1] );\ndX = repmat( dX, [1 1 p p] );\ndY = repmat( dY, [1 1 p p] );\n\nX1 = X+dX;\nY1 = Y+dY;\n\nswitch lower(bound)\n case 'sym'\n X1(X1<1) = 1-X1(X1<1);\n X1(X1>n) = 2*n+1-X1(X1>n);\n Y1(Y1<1) = 1-Y1(Y1<1);\n Y1(Y1>n) = 2*n+1-Y1(Y1>n);\n case 'per'\n X1 = mod(X1-1,n)+1;\n Y1 = mod(Y1-1,n)+1;\nend\n \n\n% build a weight function\nif isfield(options, 'window_type')\n window_type = options.window_type;\nelse\n window_type = 'sin';\nend\nif isfield(options, 'eta')\n eta = options.eta;\nelse\n eta = 1;\nend\n\nif strcmp(window_type, 'sin')\n t = linspace(0,1,w);\n W = sin(t(:)*pi).^2;\n W = W * W';\nelseif strcmp(window_type, 'constant')\n W = ones(w);\nelse\n error('Unkwnown winow.');\nend\n\nI = X1 + (Y1-1)*n;\n\n%% renormalize the windows\nweight = zeros(n);\nfor i=1:p\n for j=1:p\n weight(I(:,:,i,j)) = weight(I(:,:,i,j)) + W.^2;\n end\nend\nweight = sqrt(weight);\nWeight = repmat(W, [1 1 p p]);\nfor i=1:p\n for j=1:p\n Weight(:,:,i,j) = Weight(:,:,i,j) ./ weight(I(:,:,i,j));\n end\nend\n\n\nif strcmp(normalization, 'unit')\n if strcmp(transform_type, 'fourier')\n % for Fourier it is easy\n Renorm = sqrt( sum( sum( Weight.^2, 1 ), 2 ) )/w;\n else\n % for DCT it is less easy ...\n % take a typical window in the middle of the image\n weight = Weight(:,:,round(end/2),round(end/2));\n % compute diracs\n [X,Y,fX,fY] = ndgrid(0:w-1,0:w-1,0:w-1,0:w-1);\n A = 2 * cos( pi/w * ( X+1/2 ).*fX ) .* cos( pi/w * ( Y+1/2 ).*fY ) / w;\n A(:,:,1,:) = A(:,:,1,:) / sqrt(2); % scale zero frequency\n A(:,:,:,1) = A(:,:,:,1) / sqrt(2); \n A = A .* repmat( weight, [1 1 w w] );\n Renorm = sqrt( sum( sum( abs(A).^2, 1 ),2 ) );\n end\n Renorm = reshape( Renorm, w,w );\nend\n \n%% compute the transform\nif dir==1\n y = zeros(eta*w,eta*w,p,p);\n if mod(w,2)==1\n m = (eta*w+1)/2; w1 = (w-1)/2;\n sel = m-w1:m+w1;\n else\n m = (eta*w)/2+1; w1 = w/2;\n sel = m-w1:m+w1-1;\n end\n y(sel,sel,:,:) = x(I) .* Weight;\n % perform the transform\n y = my_transform( y, +1, transform_type );\n % renormalize if necessary\n if strcmp(normalization, 'unit')\n y = y ./ repmat( Renorm, [1 1 p p] );\n end\nelse\n if strcmp(normalization, 'unit')\n x = x .* repmat( Renorm, [1 1 p p] );\n end\n x = my_transform( x, -1, transform_type );\n x = real( x.*Weight );\n y = zeros(n);\n for i=1:p\n for j=1:p\n y(I(:,:,i,j)) = y(I(:,:,i,j)) + x(:,:,i,j);\n end\n end\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction y = my_transform(x,dir,transform_type)\n\n% my_transform - perform either FFT or DCT with energy conservation.\n% Works on array of size (w,w,a,b) on the 2 first dimensions.\n\nw = size(x,1);\nif strcmp(transform_type, 'fourier')\n % normalize for energy conservation\n if dir==1\n y = fftshift( fft2(x) ) / w;\n else\n y = ifft2( ifftshift(x*w) );\n end\nelseif strcmp(transform_type, 'dct')\n for i=1:size(x,3)\n for j=1:size(x,4)\n y(:,:,i,j) = perform_dct_transform(x(:,:,i,j),dir);\n end\n end\nelse\n error('Unknown transform');\nend\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_sparsity/toolbox/perform_windowed_fourier_transform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7256133858346193}} {"text": "%................................................................\n\n% MATLAB codes for Finite Element Analysis\n% problem16vibrationsSchultz.m\n% Timoshenko beam in free vibrations\n% Lee/Schultz problem\n% antonio ferreira 2008\n\n% clear memory\nclear all\n\n% E; modulus of elasticity\n% G; shear modulus\n% I: second moments of area\n% L: length of beam\n% thickness: thickness of beam\nE=10e7; poisson = 0.30;L = 1;thickness=0.1;\nI=thickness^3/12;\nEI=E*I;\nkapa=5/6;\nrho=1;\nA=1*thickness;\n% \n\nP = -1; % uniform pressure\n% constitutive matrix\nG=E/2/(1+poisson);\nC=[ EI 0; 0 kapa*thickness*G];\n\n% mesh\nnumberElements = 40; \nnodeCoordinates=linspace(0,L,numberElements+1);\nxx=nodeCoordinates';x=xx';\nfor i=1:size(nodeCoordinates,2)-1\n elementNodes(i,1)=i; \n elementNodes(i,2)=i+1\nend\n% generation of coordinates and connectivities\nnumberNodes=size(xx,1);\n\n% GDof: global number of degrees of freedom\nGDof=2*numberNodes; \n\n% computation of the system stiffness, force, mass\n[stiffness,force,mass]=...\n formStiffnessMassTimoshenkoBeam(GDof,numberElements,...\n elementNodes,numberNodes,xx,C,P,rho,I,thickness);\n\n% boundary conditions (CC)\nfixedNodeW =find(xx==min(nodeCoordinates(:))...\n | xx==max(nodeCoordinates(:)));\nfixedNodeTX=fixedNodeW;\nprescribedDof=[fixedNodeW; fixedNodeTX+numberNodes];\n\n% solution\ndisplacements=solution(GDof,prescribedDof,stiffness,force);\n\n% output displacements/reactions\noutputDisplacementsReactions(displacements,stiffness,...\n GDof,prescribedDof)\n\n% free vibration problem\nactiveDof=setdiff([1:GDof]',[prescribedDof]);\n[V,D]=eig(stiffness(activeDof,activeDof),...\n mass(activeDof,activeDof));\nD = diag(sqrt(D)*L*L*sqrt(rho*thickness/E/I));D=sqrt(D) ;\n[D,ii] = sort(D); \n \n \n% lee,schultz paper\nmodeNumber=4;\nV1=zeros(GDof,1);\nV1(activeDof,1:modeNumber)=V(:,1:modeNumber);\n\n% drawing eigenmodes\ndrawEigenmodes1D(modeNumber,numberNodes,V1,xx,x)", "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/FEM/Timoshenko_beam/Timoshenko_Schultz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308054739519, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7255556451420812}} {"text": "function y = mg(DataDuration)\n\n% Mackey-Glass chaotic time series generator. \n\nNumOfSamples = DataDuration;\ndiscarded = 350;\nx = zeros(NumOfSamples + discarded + 1);\ny = zeros(1,NumOfSamples); % Each column represents different time instants.\nTs = 1;\nx(1) = 1.2;\ntau = 17;\n\nfor n = tau+1:(NumOfSamples + discarded)\n x(n+1) = Ts*(0.2*x(n-tau)/( 1 + (x(n-tau))^10)) + (1 - 0.1*Ts)*x(n);\nend\n\n% plot(x);\n% title('Mackey-Glass Chaotic Time Series');\n% xlabel('Time Sample');\n% ylabel('Estimated Value');\n\n\nfor k=1:NumOfSamples\n y(k) = x(discarded+k);\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/36098-adaptive-neuro-fuzzy-inference-systems-anfis-library-for-simulink/NFA_Demos/Utilities/mg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.7255189102876946}} {"text": "% Generate a set of covariance matrices according to a Wishart distrib.\n% Inputs :\n% N : the size of the matrices\n% I : the number of matrices\n% Df : the degee of freedom\n% Sig : the parameter of the wishart disrib \n%\n% Outputs :\n% COV : a set of I covariance matrices\n% Sig : the parameter of the wishart disrib \nfunction [COV Sig] = generate_wishart_set(N,I,Df,Sig)\n\n if nargin<4\n [Q,~] = qr(randn(N));\n Sig = Q'*diag(5*rand(N,1))*Q;\n end\n\n COV = zeros(N,N,I);\n for i=1:I\n COV(:,:,i) = wishrnd(Sig,Df);\n end", "meta": {"author": "alexandrebarachant", "repo": "covariancetoolbox", "sha": "f1c088566eda2b2b63857b6563d7be5525ea4768", "save_path": "github-repos/MATLAB/alexandrebarachant-covariancetoolbox", "path": "github-repos/MATLAB/alexandrebarachant-covariancetoolbox/covariancetoolbox-f1c088566eda2b2b63857b6563d7be5525ea4768/lib/simulation/generate_wishart_set.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.7879312006227323, "lm_q1q2_score": 0.7255189079950031}} {"text": "function bi = evalBSpline(xi,deg)\n% evalBSpline: evaluate BSpline basis function\n% usage: bi = evalBSpline(xi,deg);\n%\n% arguments:\n% xi (N-D arrary) - positions at which to evaluate BSpline basis function\n% deg (scalar) - degree of desired basis function\n%\n% Note: no error checking is performed for speed\n%\n\n% author: Nathan D. Cahill\n% email: ndcahill@gmail.com\n% date: 18 April 2008\n\nswitch deg\n case 0\n bi = (xi>=(-1/2))&(xi<(1/2));\n case 1\n bi = zeros(size(xi));\n k = (xi>=0) & (xi<1);\n bi(k) = 1 - xi(k);\n k(:) = (xi>=-1) & (xi<0);\n bi(k) = 1 + xi(k);\n case 2\n bi = zeros(size(xi));\n x2 = xi.*xi;\n k = (xi>=1/2) & (xi<3/2);\n bi(k) = (9/8) - (3/2).*xi(k) + (1/2).*x2(k);\n k = (xi>=-1/2) & (xi<1/2);\n bi(k) = (3/4) - x2(k);\n k = (xi>=-3/2) & (xi<-1/2);\n bi(k) = (9/8) + (3/2).*xi(k) + (1/2).*x2(k);\n case 3\n bi = zeros(size(xi));\n x2 = xi.*xi; x3 = x2.*xi;\n k = (xi>=1) & (xi<2);\n bi(k) = 4/3 - 2.*xi(k) + x2(k) - (1/6).*x3(k);\n k(:) = (xi>=0) & (xi<1);\n bi(k) = 2/3 - x2(k) + (1/2).*x3(k);\n k(:) = (xi>=-1) & (xi<0);\n bi(k) = 2/3 - x2(k) - (1/2).*x3(k);\n k(:) = (xi>=-2) & (xi<-1);\n bi(k) = 4/3 + 2.*xi(k) + x2(k) + (1/6).*x3(k);\n case 4\n bi = zeros(size(xi));\n x2 = xi.*xi; x3 = x2.*xi; x4 = x3.*xi;\n k = (xi>=3/2) & (xi<5/2);\n bi(k) = 625/384 - (125/48).*xi(k) + (25/16).*x2(k) - (5/12).*x3(k) + (1/24).*x4(k);\n k = (xi>=1/2) & (xi<3/2);\n bi(k) = 55/96 + (5/24).*xi(k) - (5/4).*x2(k) + (5/6).*x3(k) - (1/6).*x4(k);\n k = (xi>=-1/2) & (xi<1/2);\n bi(k) = 115/192 - (5/8).*x2(k) + (1/4).*x4(k);\n k = (xi>=-3/2) & (xi<-1/2);\n bi(k) = 55/96 - (5/24).*xi(k) - (5/4).*x2(k) - (5/6).*x3(k) - (1/6).*x4(k);\n k = (xi>=-5/2) & (xi<-3/2);\n bi(k) = 625/384 + (125/48).*xi(k) + (25/16).*x2(k) + (5/12).*x3(k) + (1/24).*x4(k);\n case 5\n bi = zeros(size(xi));\n x2 = xi.*xi; x3 = x2.*xi; x4 = x3.*xi; x5 = x4.*xi;\n k = (xi>=2) & (xi<3);\n bi(k) = 81/40 - (27/8).*xi(k) + (9/4).*x2(k) - (3/4).*x3(k) + (1/8).*x4(k) - (1/120).*x5(k);\n k = (xi>=1) & (xi<2);\n bi(k) = 17/40 + (5/8).*xi(k) - (7/4).*x2(k) + (5/4).*x3(k) - (3/8).*x4(k) + (1/24).*x5(k);\n k = (xi>=0) & (xi<1);\n bi(k) = 11/20 - (1/2).*x2(k) + (1/4).*x4(k) - (1/12).*x5(k);\n k = (xi>=-1) & (xi<0);\n bi(k) = 11/20 - (1/2).*x2(k) + (1/4).*x4(k) + (1/12).*x5(k);\n k = (xi>=-2) & (xi<-1);\n bi(k) = 17/40 - (5/8).*xi(k) - (7/4).*x2(k) - (5/4).*x3(k) - (3/8).*x4(k) - (1/24).*x5(k);\n k = (xi>=-3) & (xi<-2);\n bi(k) = 81/40 + (27/8).*xi(k) + (9/4).*x2(k) + (3/4).*x3(k) + (1/8).*x4(k) + (1/120).*x5(k);\n case 6\n bi = zeros(size(xi));\n x2 = xi.*xi; x3 = x2.*xi; x4 = x3.*xi; x5 = x4.*xi; x6 = x5.*xi;\n k = (xi>=5/2) & (xi<7/2);\n bi(k) = 117649/46080 - (16807/3840).*xi(k) + (2401/768).*x2(k) - (343/288).*x3(k) + (49/192).*x4(k) - (7/240).*x5(k) + (1/720).*x6(k);\n k = (xi>=3/2) & (xi<5/2);\n bi(k) = 1379/7680 + (1267/960).*xi(k) - (329/128).*x2(k) + (133/72).*x3(k) - (21/32).*x4(k) + (7/60).*x5(k) - (1/120).*x6(k);\n k = (xi>=1/2) & (xi<3/2);\n bi(k) = 7861/15360 - (7/768).*xi(k) - (91/256).*x2(k) - (35/288).*x3(k) + (21/64).*x4(k) - (7/48).*x5(k) + (1/48).*x6(k);\n k = (xi>=-1/2) & (xi<1/2);\n bi(k) = 5887/11520 - (77/192).*x2(k) + (7/48).*x4(k) - (1/36).*x6(k);\n k = (xi>=-3/2) & (xi<-1/2);\n bi(k) = 7861/15360 + (7/768).*xi(k) - (91/256).*x2(k) + (35/288).*x3(k) + (21/64).*x4(k) + (7/48).*x5(k) + (1/48).*x6(k);\n k = (xi>=-5/2) & (xi<-3/2);\n bi(k) = 1379/7680 - (1267/960).*xi(k) - (329/128).*x2(k) - (133/72).*x3(k) - (21/32).*x4(k) - (7/60).*x5(k) - (1/120).*x6(k);\n k = (xi>=-7/2) & (xi<-5/2);\n bi(k) = 117649/46080 + (16807/3840).*xi(k) + (2401/768).*x2(k) + (343/288).*x3(k) + (49/192).*x4(k) + (7/240).*x5(k) + (1/720).*x6(k);\n case 7\n bi = zeros(size(xi));\n x2 = xi.*xi; x3 = x2.*xi; x4 = x3.*xi; x5 = x4.*xi; x6 = x5.*xi; x7 = x6.*xi;\n k = (xi>=3) & (xi<4);\n bi(k) = 6405119470038039/1970324836974592 - (672537544353994073/118219490218475520).*xi(k) + (64/15).*x2(k) - (16/9).*x3(k) + (4/9).*x4(k) - (1/15).*x5(k) + (1/180).*x6(k) - (1/5040).*x7(k);\n k = (xi>=2) & (xi<3);\n bi(k) = -2173612320154509/9851624184872960 + (855120979246972939/354658470655426560).*xi(k) - (23/6).*x2(k) + (49/18).*x3(k) - (19/18).*x4(k) + (7/30).*x5(k) - (1/36).*x6(k) + (1/720).*x7(k);\n k = (xi>=1) & (xi<2);\n bi(k) = 103/210 - (7/90).*xi(k) - (1/10).*x2(k) - (7/18).*x3(k) + (1/2).*x4(k) - (7/30).*x5(k) + (1/20).*x6(k) - (1/240).*x7(k);\n k = (xi>=0) & (xi<1);\n bi(k) = 151/315 - (1/3).*x2(k) + (1/9).*x4(k) - (1/36).*x6(k) + (1/144).*x7(k);\n k = (xi>=-1) & (xi<0);\n bi(k) = 151/315 - (1/3).*x2(k) + (1/9).*x4(k) - (1/36).*x6(k) - (1/144).*x7(k);\n k = (xi>=-2) & (xi<-1);\n bi(k) = 103/210 + (7/90).*xi(k) - (1/10).*x2(k) + (7/18).*x3(k) + (1/2).*x4(k) + (7/30).*x5(k) + (1/20).*x6(k) + (1/240).*x7(k);\n k = (xi>=-3) & (xi<-2);\n bi(k) = -2173612320154509/9851624184872960 - (855120979246972939/354658470655426560).*xi(k) - (23/6).*x2(k) - (49/18).*x3(k) - (19/18).*x4(k) - (7/30).*x5(k) - (1/36).*x6(k) - (1/720).*x7(k);\n k = (xi>=-4) & (xi<-3);\n bi(k) = 6405119470038039/1970324836974592 + (672537544353994073/118219490218475520).*xi(k) + (64/15).*x2(k) + (16/9).*x3(k) + (4/9).*x4(k) + (1/15).*x5(k) + (1/180).*x6(k) + (1/5040).*x7(k);\n otherwise\n bi = ((xi + ((deg+1)/2)).*evalBSpline(xi+(1/2),deg-1) + ...\n (((deg+1)/2) - xi).*evalBSpline(xi-(1/2),deg-1))./deg;\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/19632-n-dimensional-bsplines/@bsarray/private/evalBSpline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699845, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7255189005369345}} {"text": "% 迭代法求解方程\nclear;\nformat long;\ntol = 1e-5;\nN = 100;\nx0 = 10.5;\n\nphi = @(x) exp(-x);\nfor k = 1 : N\n x1 = phi(x0);\n if abs(x1 - x0) < tol\n fprintf('方程的正根: %10.8f\\n', x1);\n fprintf('迭代次数: %d\\n', k);\n break;\n end\n x0 = x1;\nend\nif k == N\n fprintf('迭代方法失败\\n');\nend", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第五章 方程求根的迭代法/example_4_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7255022478279038}} {"text": "function pts = intersectPolylines(poly1, varargin)\n%INTERSECTPOLYLINES Find the common points between 2 polylines\n%\n% INTERS = intersectPolylines(POLY1, POLY2)\n% Returns the intersection points between two polylines. Each polyline is\n% defined by a N-by-2 array representing coordinates of its vertices: \n% [X1 Y1 ; X2 Y2 ; ... ; XN YN]\n% INTERS is a NP-by-2 array containing coordinates of intersection\n% points.\n%\n% INTERS = intersectPolylines(POLY1)\n% Compute self-intersections of the polyline.\n%\n% Example\n% % Compute intersection points between 2 simple polylines\n% poly1 = [20 10 ; 20 50 ; 60 50 ; 60 10];\n% poly2 = [10 40 ; 30 40 ; 30 60 ; 50 60 ; 50 40 ; 70 40];\n% pts = intersectPolylines(poly1, poly2);\n% figure; hold on; \n% drawPolyline(poly1, 'b');\n% drawPolyline(poly2, 'm');\n% drawPoint(pts);\n% axis([0 80 0 80]);\n%\n% This function is largely based on the 'interX' function, found on the\n% FileExchange:\n% https://fr.mathworks.com/matlabcentral/fileexchange/22441-curve-intersections\n% \n% See also\n% polygons2d, polylineSelfIntersections, intersectLinePolygon\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2009-06-15, using Matlab 7.7.0.471 (R2008b)\n% Copyright 2009 INRA - Cepia Software Platform.\n\n% The code is a slight rewritting of the interX function, consisting in\n% avoiding argument transposition in the begining of the function. Comment\n% of original submission are kept here for information.\n%\n%INTERX Intersection of curves\n% P = INTERX(L1,L2) returns the intersection points of two curves L1 \n% and L2. The curves L1,L2 can be either closed or open and are described\n% by two-row-matrices, where each row contains its x- and y- coordinates.\n% The intersection of groups of curves (e.g. contour lines, multiply \n% connected regions etc) can also be computed by separating them with a\n% column of NaNs as for example\n%\n% L = [x11 x12 x13 ... NaN x21 x22 x23 ...;\n% y11 y12 y13 ... NaN y21 y22 y23 ...]\n%\n% P has the same structure as L1 and L2, and its rows correspond to the\n% x- and y- coordinates of the intersection points of L1 and L2. If no\n% intersections are found, the returned P is empty.\n%\n% P = INTERX(L1) returns the self-intersection points of L1. To keep\n% the code simple, the points at which the curve is tangent to itself are\n% not included. P = INTERX(L1,L1) returns all the points of the curve \n% together with any self-intersection points.\n% \n% Example:\n% t = linspace(0,2*pi);\n% r1 = sin(4*t)+2; x1 = r1.*cos(t); y1 = r1.*sin(t);\n% r2 = sin(8*t)+2; x2 = r2.*cos(t); y2 = r2.*sin(t);\n% P = InterX([x1;y1],[x2;y2]);\n% plot(x1,y1,x2,y2,P(1,:),P(2,:),'ro')\n%\n% Author : NS\n% Version: 3.0, 21 Sept. 2010\n%\n% Two words about the algorithm: Most of the code is self-explanatory.\n% The only trick lies in the calculation of C1 and C2. To be brief, this\n% is essentially the two-dimensional analog of the condition that needs\n% to be satisfied by a function F(x) that has a zero in the interval\n% [a,b], namely\n% F(a)*F(b) <= 0\n% C1 and C2 exactly do this for each segment of curves 1 and 2\n% respectively. If this condition is satisfied simultaneously for two\n% segments then we know that they will cross at some point. \n% Each factor of the 'C' arrays is essentially a matrix containing \n% the numerators of the signed distances between points of one curve\n% and line segments of the other.\n\n\n% Check number of inputs\nnarginchk(1, 2);\n\n% Specific init depending on number of inputs\nif nargin == 1\n % Compute self-intersections \n % -> Avoid the inclusion of common points\n poly2 = poly1;\n hF = @lt;\nelse\n % Compute intersections between distinct lines\n poly2 = varargin{1}; \n hF = @le;\nend\n\n% Get coordinates of polyline vertices\nx1 = poly1(:,1); \nx2 = poly2(:,1)';\ny1 = poly1(:,2); \ny2 = poly2(:,2)';\n\n% differentiate coordinate arrays\ndx1 = diff(x1); dy1 = diff(y1);\ndx2 = diff(x2); dy2 = diff(y2);\n\n% Determine 'signed distances'\nS1 = dx1 .* y1(1:end-1) - dy1 .* x1(1:end-1);\nS2 = dx2 .* y2(1:end-1) - dy2 .* x2(1:end-1);\n\nC1 = feval(hF, D(bsxfun(@times,dx1,y2) - bsxfun(@times,dy1,x2), S1), 0);\nC2 = feval(hF, D((bsxfun(@times,y1,dx2) - bsxfun(@times,x1,dy2))', S2'), 0)';\n\n% Obtain the segments where an intersection is expected\n[i, j] = find(C1 & C2); \n\n% Process case of no intersection\nif isempty(i)\n pts = zeros(0, 2);\n return;\nend\n\n% Transpose and prepare for output\ni=i'; dx2=dx2'; dy2=dy2'; S2 = S2';\nL = dy2(j).*dx1(i) - dy1(i).*dx2(j);\n\n% Avoid divisions by zero\ni = i(L~=0);\nj = j(L~=0);\nL = L(L~=0);\n\n% Solve system of eqs to get the common points\nres = [dx2(j).*S1(i) - dx1(i).*S2(j), dy2(j).*S1(i) - dy1(i).*S2(j)] ./ [L L];\npts = unique(res, 'rows');\n\n% Innre function computing a kind of cross-product\nfunction u = D(x,y)\n u = bsxfun(@minus, x(:,1:end-1), y) .* bsxfun(@minus, x(:,2:end), y);\nend\n\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/polygons2d/intersectPolylines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7255022287879641}} {"text": "function varargout = cylinderMesh(cyl, varargin)\n%CYLINDERMESH Create a 3D mesh representing a cylinder.\n%\n% [V, F] = cylinderMesh(CYL)\n% Computes vertex coordinates and face vertex indices of a mesh\n% representing a 3D cylinder given as [X1 Y1 Z1 X2 Y2 Z2 R].\n% \n% [V, F] = cylinderMesh(..., OPT)\n% with OPT = 'open' (0) (default) or 'closed' (1), specify if the bases \n% of the cylinder should be included.\n% \n% [V, F] = cylinderMesh(..., NAME, VALUE);\n% Specifies one or several options using parameter name-value pairs.\n% Available options are:\n% 'nPerimeter' the number of circles represeting the perimeter\n% 'nRho' the number of circles along the hight\n%\n% Example\n% % Draw a rotated cylinder\n% cyl = [0 0 0 10 20 30 5];\n% [v, f] = cylinderMesh(cyl);\n% figure;drawMesh(v, f, 'FaceColor', 'r');\n% view(3); axis equal;\n%\n% % Draw three mutually intersecting cylinders\n% p0 = [30 30 30];\n% p1 = [90 30 30];\n% p2 = [30 90 30];\n% p3 = [30 30 90];\n% [v1 f1] = cylinderMesh([p0 p1 25]);\n% [v2 f2] = cylinderMesh([p0 p2 25]);\n% [v3 f3] = cylinderMesh([p0 p3 25],'closed','nPeri',40,'nRho',20);\n% figure; hold on;\n% drawMesh(v1, f1, 'FaceColor', 'r');\n% drawMesh(v2, f2, 'FaceColor', 'g');\n% drawMesh(v3, f3, 'FaceColor', 'b');\n% view(3); axis equal\n% set(gcf, 'renderer', 'opengl')\n% \n% See also \n% drawCylinder, torusMesh, sphereMesh\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inra.fr\n% Created: 2012-10-25, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012-2022 INRA - Cepia Software Platform\n\nparser = inputParser;\naddRequired(parser, 'cyl', @(x) validateattributes(x, {'numeric'},...\n {'size',[1 7],'real','finite','nonnan'}));\ncapParValidFunc = @(x) (islogical(x) ...\n || isequal(x,1) || isequal(x,0) || any(validatestring(x, {'open','closed'})));\naddOptional(parser,'cap','open', capParValidFunc);\naddParameter(parser, 'nPerimeter', 20, @(x) validateattributes(x,{'numeric'},...\n {'integer','scalar','>=',4}));\naddParameter(parser, 'nRho', 10, @(x) validateattributes(x,{'numeric'},...\n {'integer','scalar','>=',2}));\nparse(parser,cyl,varargin{:});\ncyl=parser.Results.cyl;\ncap=lower(parser.Results.cap(1));\nNoPP=parser.Results.nPerimeter;\nnRho=parser.Results.nRho;\n\n% extract cylinder data\np1 = cyl(:, 1:3);\np2 = cyl(:, 4:6);\nr = cyl(:, 7);\n\n% compute length and orientation\n[theta, phi, rho] = cart2sph2d(p2 - p1);\n\n% parametrisation on x\nt = linspace(0, 2*pi, NoPP);\nlx = r * cos(t);\nly = r * sin(t);\n\n% parametrisation on z\nlz = linspace(0, rho, nRho);\n\n% generate surface grids\nx = repmat(lx, [length(lz) 1]);\ny = repmat(ly, [length(lz) 1]);\nz = repmat(lz', [1 length(t)]);\n\n% transform points \ntrans = localToGlobal3d(p1, theta, phi, 0);\n[x, y, z] = transformPoint3d(x, y, z, trans);\n\n% convert to FV mesh\n[vertices, faces] = surfToMesh(x, y, z, 'xPeriodic', true);\n\n% Close cylinder\nif cap == 'c' || cap == 1\n toe.vertices = [x(1,1:NoPP-1); y(1,1:NoPP-1); z(1,1:NoPP-1)]';\n toe.vertices(NoPP,:) = transformPoint3d([0 0 0], trans);\n toe.faces = [repmat(NoPP, 1, NoPP-1); [2:NoPP-1 1]; 1:NoPP-1]';\n \n top.vertices = [x(end,1:NoPP-1); y(end,1:NoPP-1); z(end,1:NoPP-1)]';\n top.vertices(NoPP,:) = transformPoint3d([0 0 rho], trans);\n top.faces = fliplr(toe.faces);\n \n [vertices, faces] = concatenateMeshes(vertices, triangulateFaces(faces), ...\n toe.vertices, toe.faces, top.vertices, top.faces);\nend\n\n% format output\nvarargout = formatMeshOutput(nargout, vertices, faces);\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/cylinderMesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.7255022203503783}} {"text": "function result = pyramid_unit_o06_3d ( func )\n\n%*****************************************************************************80\n%\n%% PYRAMID_UNIT_O06_3D approximates an integral inside the unit pyramid in 3D.\n%\n% Discussion:\n%\n% A 6 point formula is used.\n%\n% The (X,Y,Z) integration region can be represented as:\n%\n% - ( 1 - Z ) <= X <= 1 - Z\n% - ( 1 - Z ) <= Y <= 1 - Z\n% 0 <= Z <= 1.\n%\n% When Z is zero, the integration region is a square lying in the (X,Y)\n% plane, centered at (0,0,0) with \"radius\" 1. As Z increases to 1, the\n% radius of the square diminishes, and when Z reaches 1, the square has\n% contracted to the single point (0,0,1).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 April 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Carlos Felippa,\n% A compendium of FEM integration formulas for symbolic work,\n% Engineering Computation,\n% Volume 21, Number 8, 2004, pages 867-890.\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the user supplied function which\n% evaluates F(X,Y,Z), of the form\n% function value = func ( x, y, z )\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n order = 6;\n\n w = [ ...\n 0.21000000000000000000, ...\n 0.21000000000000000000, ...\n 0.21000000000000000000, ...\n 0.21000000000000000000, ...\n 0.06000000000000000000, ...\n 0.10000000000000000000 ]';\n x = [ ...\n -0.48795003647426658968, ...\n 0.48795003647426658968, ...\n 0.48795003647426658968, ...\n -0.48795003647426658968, ...\n 0.00000000000000000000, ...\n 0.00000000000000000000 ]';\n y = [ ...\n -0.48795003647426658968, ...\n -0.48795003647426658968, ...\n 0.48795003647426658968, ...\n 0.48795003647426658968, ...\n 0.00000000000000000000, ...\n 0.00000000000000000000 ]';\n z = [ ...\n 0.16666666666666666667, ...\n 0.16666666666666666667, ...\n 0.16666666666666666667, ...\n 0.16666666666666666667, ...\n 0.58333333333333333333, ...\n 0.75000000000000000000 ]';\n%\n% Quadrature.\n%\n quad = 0.0;\n for i = 1 : order\n quad = quad + w(i) * feval ( func, x(i), y(i), z(i) );\n end\n%\n% Volume.\n%\n volume = pyramid_unit_volume_3d ( );\n%\n% Result.\n%\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/pyramid_unit_o06_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7254957956382597}} {"text": "function [x, c, funVal, ValueL]=fusedLogisticR(A, y, lambda, opts)\n%\n%%\n% Function fusedLogisticR\n% Logistic Loss with the Fused Lasso Penalty\n%\n%% Problem\n%\n% min f(x,c) = - weight_i * log (p_i) + lambda * ||x||_1 + lambda_2 ||Rx||_1\n% + 1/2 rsL2 * ||x||_2^2\n%\n% By default, rsL2=0.\n% When rsL2 is nonzero, this correspons the well-know elastic net.\n%\n% a_i denotes a training sample,\n% and a_i' corresponds to the i-th row of the data matrix A\n%\n% y_i (either 1 or -1) is the response\n%\n% p_i= 1/ (1+ exp(-y_i (x' * a_i + c) ) ) denotes the probability\n%\n% weight_i denotes the weight for the i-th sample\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% lambda - Lq/L1 norm regularization parameter (lambda >=0)\n% opts- Optional inputs (default value: opts=[])\n%\n%% Output parameters:\n% x- The obtained weight of size n x 1\n% c- The obtained intercept (scalar)\n% funVal- Function value during iterations\n%\n%% Copyright (C) 2009-2010 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 February 18, 2010.\n%\n%% Related papers\n%\n% [1] Jun Liu, Lei Yuan, and Jieping Ye, An Efficient Algorithm for \n% a Class of Fused Lasso Problems, KDD, 2010.\n%\n%% Related functions\n%\n% sll_opts, initFactor, pathSolutionLeast\n% LogisticC, nnLogisticR, nnLogisticC\n%\n%%\n\n%% Verify and initialize the parameters\n%%\nif (nargin <3)\n error('\\n Inputs: A, y, and lambda 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 (lambda<=0)\n error('\\n lambda should be positive!\\n');\nend\n\nopts=sll_opts(opts); % run sll_opts to set default values (flags)\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% The parameter 'weight' contains the weight for each training sample.\n% See the definition of the problem above.\n% The summation of the weights for all the samples equals to 1.\nif (isfield(opts,'sWeight'))\n sWeight=opts.sWeight;\n\n if ( length(sWeight)~=2 || sWeight(1) <=0 || sWeight(2) <= 0)\n error('\\n Check opts.sWeight, which contains two positive values');\n end\n\n % we process the weight, so that the summation of the weights for all\n % the samples is 1.\n\n p_flag=(y==1); % the indices of the postive samples\n m1=sum(p_flag) * sWeight(1); % the total weight for the positive samples\n m2=sum(~p_flag) * sWeight(2); % the total weight for the positive samples\n\n weight(p_flag,1)=sWeight(1)/(m1+m2);\n weight(~p_flag,1)=sWeight(2)/(m1+m2);\nelse\n weight=ones(m,1)/m; % if not specified, we apply equal weight\nend\n\n%% Starting point initialization\n\n% process the regularization parameter\n\n% L2 norm regularization\nif isfield(opts,'rsL2')\n rsL2=opts.rsL2;\n if (rsL2<0)\n error('\\n opts.rsL2 should be nonnegative!');\n end\nelse\n rsL2=0;\nend\n\np_flag=(y==1); % the indices of the postive samples\nm1=sum(weight(p_flag)); % the total weight for the positive samples\nm2=1-m1; % the total weight for the positive samples\n\n% L1 norm regularization\nif (opts.rFlag==0)\n lambda=lambda;\nelse % lambda here is the scaling factor lying in [0,1]\n if (lambda<0 || lambda>1)\n error('\\n opts.rFlag=1, and lambda should be in [0,1]');\n end\n\n % we compute ATb for computing lambda_max, when the input lambda is a ratio\n\n b(p_flag,1)=m2; b(~p_flag,1)=-m1;\n b=b.*weight;\n\n % compute AT b\n if (opts.nFlag==0)\n ATb =A'*b;\n elseif (opts.nFlag==1)\n ATb= A'*b - sum(b) * mu'; ATb=ATb./nu;\n else\n invNu=b./nu; ATb=A'*invNu-sum(invNu)*mu';\n end\n\n lambda_max=max(abs(ATb));\n lambda=lambda*lambda_max;\n \n if ~isfield(opts,'fusedPenalty')\n lambda2=0;\n else\n lambda2=lambda_max * opts.fusedPenalty;\n end \n\n rsL2=rsL2*lambda_max; % the input rsL2 is a ratio of lambda_max\nend\n\n% initialize a starting point\nif opts.init==2\n x=zeros(n,1); c=log(m1/m2);\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=zeros(n,1);\n end\n\n if isfield(opts,'c0')\n c=opts.c0;\n else\n c=log(m1/m2);\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\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\n%% The main program\n\nz0=zeros(n-1,1);\n% z0 is the starting point for flsa\n\n%% The Armijo Goldstein line search scheme + accelearted gradient descent\n\nif (opts.mFlag==0 && opts.lFlag==0)\n\n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1/m + rsL2; % the intial guess of the Lipschitz continuous gradient\n\n weighty=weight.*y;\n % the product between weight and y\n\n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,1);\n cp=c; ccp=0;\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; sc=c + beta* ccp;\n\n % --------------------------- step 2 ---------------------------\n % line search for L and compute the new approximate solution x\n\n % compute As=A*s\n As=Ax + beta* (Ax-Axp);\n\n % aa= - diag(y) * (A * s + sc)\n aa=- y.*(As+ sc);\n\n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_s= weight' * ( log( exp(-bb) + exp(aa-bb) ) + bb )+...\n rsL2/2 * s'*s;\n\n % compute prob=[p_1;p_2;...;p_m]\n prob=1./( 1+ exp(aa) );\n\n % b= - diag(y.* weight) * (1 - prob)\n b= -weighty.*(1-prob);\n\n gc=sum(b); % the gradient of c\n\n % compute g= AT b, the gradient of x\n if (opts.nFlag==0)\n g=A'*b;\n elseif (opts.nFlag==1)\n g=A'*b - sum(b) * mu'; g=g./nu;\n else\n invNu=b./nu; g=A'*invNu-sum(invNu)*mu';\n end\n\n g=g+ rsL2 * s; % add the squared L2 norm regularization term\n\n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n cp=c;\n\n while (1)\n % let s walk in a step in the antigradient of s to get v\n % and then do the Lq/L1-norm regularized projection\n v=s-g/L; c= sc- gc/L;\n \n [x, z, infor]=flsa(v, z0,...\n lambda / L, lambda2 / L, n,...\n 1000, 1e-8, 1, 6);\n z0=z;\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 % aa= - diag(y) * (A * x + c)\n aa=- y.*(Ax+ c);\n\n % fun_x is the logistic loss at the new approximate solution\n bb=max(aa,0);\n fun_x= weight'* ( log( exp(-bb) + exp(aa-bb) ) + bb ) +...\n rsL2/2 * x'*x;\n\n r_sum= (v'*v + (c-sc)^2) / 2;\n l_sum=fun_x - fun_s - v'* g - (c-sc)* gc;\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 fun_x <= fun_s + v'* g + c * gc\n % + L/2 * (v'*v + (c-sc)^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=%e, r_sum=%e',L, r_sum);\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 ValueL(iterStep)=L;\n % store values for L\n \n xxp=x-xp; ccp=c-cp;\n funVal(iterStep)=fun_x + lambda* sum(abs(x)) +...\n lambda2 * sum( abs( x(2:n) -x(1:(n-1)) ));\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 =1;\n end\n end\nelse\n error('\\n This function only supports opts.mFlag=0 & opts.lFlag=0');\nend\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_SLEP/SLEP/functions/fusedLasso/fusedLogisticR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7254957913863108}} {"text": "function [ n_data, n, fn ] = i4_factorial_values ( n_data )\n\n%*****************************************************************************80\n%\n%% I4_FACTORIAL_VALUES returns values of the factorial function.\n%\n% Discussion:\n%\n% 0! = 1\n% I! = Product ( 1 <= J <= I ) I\n%\n% In Mathematica, the function can be evaluated by:\n%\n% n!\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, integer N, the argument of the function.\n%\n% Output, integer FN, the value of the function.\n%\n n_max = 13;\n\n fn_vec = [ ...\n 1, ...\n 1, ...\n 2, ...\n 6, ...\n 24, ...\n 120, ...\n 720, ...\n 5040, ...\n 40320, ...\n 362880, ...\n 3628800, ...\n 39916800, ...\n 479001600 ];\n\n n_vec = [ ...\n 0, 1, 2, 3, ...\n 4, 5, 6, 7, ...\n 8, 9, 10, 11, ...\n 12 ];\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 fn = 0;\n else\n n = n_vec(n_data);\n fn = fn_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/combo/i4_factorial_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7254660380014387}} {"text": "function dq = line2dq(v,r)\n\n% LINE2DQ Transforms a line position expressed in vector notation into \n% its dual quaternion representation.\n%\n% DQ = LINE2DQ(V,R) transforms the line position, specified by the\n% line orientation V and the coordinates of any point of the line, R,\n% into its dual quaternion representation. V and R must have the same\n% size. V (resp. R) is either a vector of size 3 or an array of size\n% 3*N (column i represents the orientation (resp. coordinates of a \n% point) of Line i) where N is the number of lines. DQ is either a\n% vector of size 8, either an array of size (8*N) depending on V\n% format. Each column of DQ represents the dual quaternion\n% representation of the corresponding line position.\n%\n% See also POS2DQ, VEL2DQ, LINEVEL2DQ, DQ2LINE\n\nsv = size(v);\nsr = size(r);\nif sv == [1 3]\n v = v.';\n sv = size(v);\nend\nif sr == [1 3]\n r = r.';\n sr = size(r);\nend\n\n% check that v and r have the same size\nif sv ~= sr\n error('DualQuaternion:line2dquat:sizesDoNotMatch',...\n 'Arrays v and r should be the same size. Size of v matrix is [%d %d] while size of r matrix is [%d %d]',sv(1),sv(2),sr(1),sr(2));\nend\n% if the format is wrong\nif sv(1) ~= 3 \n error('DualQuaternion:line2dquat:wrongsize',...\n '%d rows in the V and R array. 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; \n\n% construction of the line dual quaternion\ndq = sym(zeros(8,n));\ndq(2:4,:) = v;\ndq(6:8,:) = cross(r,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/line2dq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7254188073482187}} {"text": "%HCLUST hierarchical clustering\n% \n% [LABELS, DENDROGRAM] = HCLUST(D,TYPE,K)\n% DENDROGRAM = HCLUST(D,TYPE)\n% \n% INPUT\n% D dissimilarity matrix\n% TYPE string name of clustering criterion (optional)\n% - 's' or 'single' : single linkage (default)\n% - 'c' or 'complete' : complete linkage\n% - 'a' or 'average' : average linkage (weighted over cluster sizes)\n% K number of clusters (optional)\n%\n% OUTPUT\n% LABELS vector with labels\n% DENDROGRAM matrix with dendrogram\n%\n% DESCRIPTION \n% Computation of cluster labels and a dendrogram between the clusters for\n% objects with a given distance matrix D. K is the desired number of\n% clusters. The dendrogram is a 2*K matrix. The first row yields all\n% cluster sizes. The second row is the cluster level on which the set of\n% clusters starting at that position is merged with the set of clusters\n% just above it in the dendrogram. A dendrogram may be plotted by PLOTDG.\n%\n% DENDROGRAM = HCLUST(D,TYPE)\n%\n% As in this case no clustering level is supplied, just the entire\n% dendrogram is returned. The first row now contains the object indices.\n%\n% EXAMPLE\n% a = gendats([25 25],20,5); % 50 points in 20 dimensional feature space\n% d = sqrt(distm(a)); % Euclidean distances\n% dendg = hclust(d,'complete'); % dendrogram\n% plotdg(dendg)\n% lab = hclust(d,'complete',2); % labels\n% confmat(lab,getlabels(a)); % confusion matrix\n%\n% SEE ALSO (PRTools Guide)\n% PLOTDG, PRKMEANS, KCENTRES, MODESEEK, EMCLUST\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: hclust.m,v 1.3 2008/02/14 11:54:43 duin Exp $\n\nfunction [labels, dendrogram] = hclust(D,type,k) \n\t\t\n\tif nargin < 3, k = []; end\n\tif nargin < 2, type = 's'; end\n\t[m,m1] = size(D);\n\tif m ~= m1\n\t\terror('Input matrix should be square')\n\tend\n\tD = D + diag(inf*ones(1,m)); % set diagonal at infinity.\n\tW = [1:m+1]; % starting points of clusters in linear object set.\n\tV = [1:m+2]; % positions of objects in final linear object set.\n\tF = inf * ones(1,m+1); % distance of next cluster to previous cluster to be stored at first point of second cluster\n\tZ = ones(1,m); % number of samples in a cluster (only for average linkage)\n\n t = sprintf('Analysing %i cluster levels: ',m);\n prwaitbar(m,t);\n\tfor n = 1:m-1\n prwaitbar(m,n,[t int2str(n)]);\n\t\t% find minimum distance D(i,j) i j, j1 = j; j = i; i = j1; end\n\t\t% combine clusters i,j\n\t\tswitch type\n\t\tcase {'s','single'}\n\t\t\tD(i,:) = min(D(i,:),D(j,:));\n\t\tcase {'c','complete'}\n\t\t\tD(i,:) = max(D(i,:),D(j,:));\n\t\tcase {'a','average'}\n\t\t\tD(i,:) = (Z(i)*D(i,:) + Z(j)*D(j,:))/(Z(i)+Z(j));\n\t\t\tZ(i:j-1) = [Z(i)+Z(j),Z(i+1:j-1)]; Z(j) = [];\n\t\totherwise\n\t\t\terror('Unknown clustertype desired')\n\t\tend\n\t\tD(:,i) = D(i,:)';\n\t\tD(i,i) = inf;\n\t\tD(j,:) = []; D(:,j) = [];\n\t\t% store cluster distance\n\t\tF(V(j)) = dj;\n\t\t% move second cluster in linear ordering right after first cluster\n\t\tIV = [1:V(i+1)-1,V(j):V(j+1)-1,V(i+1):V(j)-1,V(j+1):m+1];\n\t\tW = W(IV); F = F(IV); \n\t\t% keep track of object positions and cluster distances\n\t\tV = [V(1:i),V(i+1:j) + V(j+1) - V(j),V(j+2:m-n+3)];\n end\n prwaitbar(0);\n\tif ~isempty(k) | nargout == 2\n\t\tif isempty(k), k = m; end\n\t\tlabels = zeros(1,m); \n\t\t[S,J] = sort(-F); % find cluster level\n\t\tI = sort(J(1:k+1)); % find all indices where cluster starts\n\t\tfor i = 1:k % find for all objects cluster labels\n\t\t\tlabels(W(I(i):I(i+1)-1)) = i * ones(1,I(i+1)-I(i));\n\t\tend % compute dendrogram\n\t\tdendrogram = [I(2:k+1) - I(1:k); F(I(1:k))];\n\t\tlabels = labels';\n\telse\n\t\tlabels = [W(1:m);F(1:m)]; % full dendrogram\n\tend\nreturn\n\t\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/hclust.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7254187904787726}} {"text": "function ls = logsum(xx,dim)\n% ls = logsum(x,dim)\n%\n% returns the log of sum of logs\n% computes ls = log(sum(exp(x),dim))\n% but in a way that tries to avoid underflow/overflow\n%\n% basic idea: shift before exp and reshift back\n% log(sum(exp(x))) = alpha + log(sum(exp(x-alpha)));\n%\n% This program was originally written by Sam Roweis\n\nif(length(xx(:))==1) ls=xx; return; end\n\nxdims=size(xx);\nif(nargin<2) \n dim=find(xdims>1);\nend\n\nalpha = max(xx,[],dim)-log(realmax)/2;\nrepdims=ones(size(xdims)); repdims(dim)=xdims(dim);\nls = alpha+log(sum(exp(xx-repmat(alpha,repdims)),dim));\n\n", "meta": {"author": "mars920314", "repo": "DeepFi", "sha": "9e7f99c181616d9aa4db18973c08675bdb714e8c", "save_path": "github-repos/MATLAB/mars920314-DeepFi", "path": "github-repos/MATLAB/mars920314-DeepFi/DeepFi-9e7f99c181616d9aa4db18973c08675bdb714e8c/Restricted Boltzmann Machines/logsum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7253558446817261}} {"text": "function [ magSpect_oct, freqVec_oct ] = octaveBandMean( magSpect, freqVec, octSpace, centerFreq )\n% Given a magnitude spectrum this function will calculate the average (single, third, nth) octave band magnitude\n% \n% Syntax:\t[ MAGSPECT_OCT, FREQVEC_OCT ] = OCTAVEBANDMEAN( MAGSPECT, FREQVEC, OCTSPACE, CENTERFREQ )\n% \n% Inputs: \n% \tmagSpect - An arbitrary magnitude spectrum as a vector\n% \tfreqVec - The corresponding frequencies for each magnitude value\n% \toctSpace - A single value between 0 and 1 specifying the octave spacing\n% \tcenterFreq - The center frequency for the octave band\n% \n% Outputs: \n% \tmagSpect_oct - The magnitude spectrum averaged per octave band\n% \tfreqVec_oct - The corresponding frequencies for the output magnitude vector\n% \n% See also: \n\n% Author: Jacob Donley\n% University of Wollongong\n% Email: jrd089@uowmail.edu.au\n% Copyright: Jacob Donley 2016, 2017\n% Date: 8 July 2016\n% Revision: 0.2 (29 March 2017)\n% \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif nargin < 4\n centerFreq=1e3;\nend\nif nargin < 3\n octSpace = 1/3;\nend\n\nif size(magSpect,2) > size(magSpect,1), magSpect = magSpect.'; end\nif size(freqVec,2) > size(freqVec,1), freqVec = freqVec.'; end\n\nfreqVec_ = nonzeros(freqVec); %remove zero values\n\nn = floor(log(freqVec_( 1 )/centerFreq)/log(2)/octSpace): ...\n floor(log(freqVec_(end)/centerFreq)/log(2)/octSpace);\n\nfreqVec_oct = centerFreq * (2 .^ (n*octSpace));\nif freqVec_oct(end) ~= freqVec_(end)\n % This may happen if there is no octave band that is centered at the\n % Nyquist frequency (fs/2)\n freqVec_oct(end+1) = freqVec_(end); % So we find an average at the \n % Nyquist frequency that is of the same width as the other octave bands\n warning(['The sampling frequency used does not have a Nyquist ' ...\n 'frequency that, after division by the centre frequency, is a ' ...\n 'power of two. ' ...\n 'i.e. (' num2str(freqVec_(end)*2) '/2)/' num2str(centerFreq) ' is ' ... \n 'not a power of two.']);\nend\nfd = 2^(octSpace/2);\nfupper = freqVec_oct * fd;\nflower = freqVec_oct / fd;\n\noctBands = [flower' fupper'];\n\n[~, oBandInds] = min(abs( ...\n repmat(freqVec,1,2,length(octBands)) ...\n - repmat(permute(octBands,[3 2 1]),length(freqVec),1,1) ));\n\noBandInds = permute(oBandInds, [3 2 1]);\n\nmagSpect_oct = zeros(1,length(freqVec_oct));\nfor band = 1:length(freqVec_oct)\n magSpect_oct(band+1) = mean( ...\n magSpect( oBandInds(band,1):oBandInds(band,2) ) );\nend\n\nmagSpect_oct(1) = magSpect(1);\nfreqVec_oct = [0 freqVec_oct];\nend\n\n", "meta": {"author": "jtkim-kaist", "repo": "Speech-enhancement", "sha": "84f1a3c1273fb4952522b911dd62cbb4476a534d", "save_path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement", "path": "github-repos/MATLAB/jtkim-kaist-Speech-enhancement/Speech-enhancement-84f1a3c1273fb4952522b911dd62cbb4476a534d/SE/lib/sub_lib/SoundZone_Tools-master/SoundZone_Tools-master/octaveBandMean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7253558407381808}} {"text": "function [xroot, froot] = brent (f, x1, x2, rtol)\n\n% solve for a single real root of a nonlinear equation\n\n% Brent's method\n\n% input\n\n% f = objective function coded as y = f(x)\n% x1 = lower bound of search interval\n% x2 = upper bound of search interval\n% rtol = algorithm convergence criterion\n\n% output\n\n% xroot = real root of f(x) = 0\n% froot = function value at f(x) = 0\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal iter;\n\n% machine epsilon\n\neps = 2.23e-16;\n\ne = 0;\n\na = x1;\nb = x2;\n\nfa = feval(f, a);\n\nfb = feval(f, b);\n\nfc = fb;\n\nfor iter = 1:1:50 \n \n if (fb * fc > 0)\n c = a;\n fc = fa;\n d = b - a;\n e = d;\n end\n\n if (abs(fc) < abs(fb))\n a = b;\n b = c;\n c = a;\n fa = fb;\n fb = fc;\n fc = fa;\n end\n\n tol1 = 2 * eps * abs(b) + 0.5 * rtol;\n\n xm = 0.5 * (c - b);\n\n if (abs(xm) <= tol1 || fb == 0)\n break;\n end\n\n if (abs(e) >= tol1 && abs(fa) > abs(fb))\n s = fb / fa;\n \n if (a == c)\n p = 2 * xm * s;\n q = 1 - s;\n else\n q = fa / fc;\n r = fb / fc;\n p = s * (2 * xm * q * (q - r) - (b - a) * (r - 1));\n q = (q - 1) * (r - 1) * (s - 1);\n end\n\n if (p > 0)\n q = -q;\n end\n\n p = abs(p);\n\n min = abs(e * q);\n \n tmp = 3 * xm * q - abs(tol1 * q);\n \n if (min < tmp)\n min = tmp;\n end\n\n if (2 * p < min)\n e = d;\n d = p / q;\n else\n d = xm;\n e = d;\n end\n else\n d = xm;\n e = d;\n end\n\n a = b;\n fa = fb;\n\n if (abs(d) > tol1)\n b = b + d;\n else\n b = b + sign(xm) * tol1;\n end\n\n fb = feval(f, b);\n\nend\n\nxroot = b;\nfroot = fb;\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/brent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7253558358615195}} {"text": "function [u_norm, coeffs, u] = smallestinconvexhull(M, x, U, tol)\n% Computes a minimal norm convex combination of given tangent vectors in Manopt.\n%\n% function [u_norm, coeffs, u] = smallestinconvexhull(M, x, U)\n% function [u_norm, coeffs, u] = smallestinconvexhull(M, x, U, tol)\n%\n% M is a manifold as returned by a Manopt factory.\n% x is a point on this manifold.\n% U is a cell containing N tangent vectors U{1} to U{N} at x.\n% tol (default: 1e-8): tolerance for solving the quadratic program.\n% \n% This function computes u, a tangent vector at x contained in the convex\n% hull spanned by the N vectors U{i}, with minimal norm (according to the\n% Riemannian metric on M). This is obtained by solving a convex quadratic\n% program involving the Gram matrix of the given tangent vectors.\n% The quadratic program is solved using Matlab's built-in quadprog,\n% which requires the optimization toolbox. If this toolbox is not\n% available, consider replacing with CVX for example.\n%\n%\n% u_norm is the norm of the smallest vector u.\n% coeffs is a vector of length N with entries in [0, 1] summing to 1.\n% u is the sought vector: u = coeffs(1)*U{1} + ... + coeffs(N)*U{N}.\n%\n% Nicolas Boumal, Feb. 19, 2013\n% Modified April 6, 2016 to work with Manopt.\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, June 28, 2016.\n% Contributors: \n% Change log: \n%\n% June 28, 2016 (NB):\n% Adapted for Manopt from original code by same author (Feb. 19, 2013)\n\n% Example code: pick a manifold, a point, and a collection of tangent\n% vectors at that point, then get the smallest vector in the convex hull\n% of those:\n% \n% M = spherefactory(5);\n% x = M.rand();\n% N = 3;\n% U = cell(N,1);\n% for k = 1 : N, U{k} = M.randvec(x); end\n% [u_norm, coeffs, u] = smallestinconvexhull(M, x, U)\n\n % We simply need to solve the following quadratic program:\n % minimize ||u||^2 such that u = sum_i s_i U_i, 0 <= s_i <= 1\n % and sum_i s_i = 1\n %\n % This is equivalent to solving:\n % min s'*G*s s.t. 0 <= s <= 1, s'*ones = 1, with G(i, j) = (Gram matrix)\n % Then our solution is s_1 U_1 + ... + s_N U_N.\n \n \n % Compute the Gram matrix of the given tangent vectors\n N = numel(U);\n G = grammatrix(M, x, U);\n \n % Solve the quadratic program.\n % If the optimization toolbox is not available, consider replacing with\n % CVX.\n \n if ~exist('tol', 'var') || isempty(tol)\n tol = 1e-8;\n end\n \n opts = optimset('Display', 'off', 'TolFun', tol);\n [s_opt, cost_opt] ...\n = quadprog(G, zeros(N, 1), ... % objective (squared norm)\n [], [], ... % inequalities (none)\n ones(1, N), 1, ... % equality (sum to 1)\n zeros(N, 1), ... % lower bounds (s_i >= 0)\n ones(N, 1), ... % upper bounds (s_i <= 1)\n [], ... % we do not specify an initial guess\n opts);\n\n % Norm of the smallest tangent vector in the convex hull:\n u_norm = real(sqrt(2*cost_opt));\n\n % Keep track of optimal coefficients\n coeffs = s_opt;\n \n % If required, construct the vector explicitly.\n if nargout >= 3\n u = lincomb(M, x, U, coeffs);\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/smallestinconvexhull.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7253558349284032}} {"text": "function a = daub8_matrix ( n )\n\n%*****************************************************************************80\n%\n%% DAUB8_MATRIX returns the DAUB8 matrix.\n%\n% Discussion:\n%\n% The DAUB8 matrix is the Daubechies wavelet transformation matrix\n% with 8 coefficients.\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_MATRIX - Fatal error!\\n' );\n fprintf ( 1, ' N must be at least 6 and a multiple of 2.\\n' );\n error ( 'DAUB8_MATRIX - 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/wavelet/daub8_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7253558348228629}} {"text": "function value = r8_gamic ( a, x )\n\n%*****************************************************************************80\n%\n%% R8_GAMIC evaluates the complementary incomplete gamma function.\n%\n% Discussion:\n%\n% GAMIC = integral ( x <= t < oo ) exp(-t) * t^(a-1) dt\n%\n% GAMIC is evaluated for arbitrary real values of A and non-negative\n% values X (even though GAMIC is defined for X < 0.0), except that\n% for X = 0 and A <= 0.0, GAMIC is undefined.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 October 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% Walter Gautschi,\n% A Computational Procedure for Incomplete Gamma Functions,\n% ACM Transactions on Mathematical Software,\n% Volume 5, Number 4, December 1979, pages 466-481.\n%\n% Parameters:\n%\n% Input, real A, the parameter.\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of the incomplete gamma function.\n%\n persistent alneps\n persistent bot\n persistent eps\n persistent sqeps\n\n if ( isempty ( eps ) )\n eps = 0.5 * r8_mach ( 3 );\n sqeps = sqrt ( r8_mach ( 4 ) );\n alneps = - log ( 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_GAMIC - Fatal error!\\n' );\n fprintf ( 1, ' X < 0.\\n' );\n error ( 'R8_GAMIC - Fatal error!' )\n end\n\n if ( x == 0.0 )\n\n if ( a <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_GAMIC - Fatal error!\\n' );\n fprintf ( 1, ' X = 0 and A <= 0.\\n' );\n error ( 'R8_GAMIC - Fatal error!' )\n end\n\n value = exp ( r8_lngam ( a + 1.0 ) - log ( a ) );\n\n return\n end\n\n alx = log ( x );\n if ( a < 0.0 )\n sga = - 1.0;\n else\n sga = + 1.0;\n end\n\n ainta = r8_aint ( a + 0.5 * sga );\n aeps = a - ainta;\n\n izero = 0;\n\n if ( x < 1.0 )\n\n if ( a <= 0.5 && abs ( aeps ) <= 0.001 )\n\n if ( - ainta <= 1.0 )\n e = 2.0;\n else\n e = 2.0 * ( - ainta + 2.0 ) / ( ainta * ainta - 1.0 );\n end\n\n e = e - alx * x^( - 0.001 );\n\n if ( e * abs ( aeps ) <= eps )\n value = r8_gmic ( a, x, alx );\n return\n end\n\n end\n\n [ algap1, sgngam ] = r8_lgams ( a + 1.0 );\n gstar = r8_gmit ( a, x, algap1, sgngam, alx );\n\n if ( gstar == 0.0 )\n izero = 1;\n else\n alngs = log ( abs ( gstar ) );\n sgngs = r8_sign ( gstar );\n end\n\n else\n\n if ( a < x )\n value = exp ( r8_lgic ( a, x, alx ) );\n return\n end\n\n sgngam = 1.0;\n algap1 = r8_lngam ( a + 1.0 );\n sgngs = 1.0;\n alngs = r8_lgit ( a, x, algap1 );\n\n end\n\n h = 1.0;\n\n if ( izero ~= 1 )\n\n t = a * alx + alngs;\n\n if ( alneps < t )\n sgng = - sgngs * sga * sgngam;\n t = t + algap1 - log ( abs ( a ) );\n value = sgng * exp ( t );\n return\n end\n\n if ( - alneps < t )\n h = 1.0 - sgngs * exp ( t );\n end\n\n end\n\n sgng = r8_sign ( h ) * sga * sgngam;\n t = log ( abs ( h ) ) + algap1 - log ( abs ( a ) );\n value = sgng * exp ( 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/fn/r8_gamic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.8175744717487329, "lm_q1q2_score": 0.7253558294796436}} {"text": "function determ = jordan_determinant ( n, alpha )\n\n%*****************************************************************************80\n%\n%% JORDAN_DETERMINANT returns the determinant of the JORDAN matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Input, real ALPHA, the eigenvalue of the Jordan matrix.\n%\n% Output, real DETERM, the determinant.\n%\n determ = alpha^n;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/jordan_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8418256512199032, "lm_q1q2_score": 0.7252649582195237}} {"text": "function [ ml, mu, m ] = bandwidth ( element_order, element_num, element_node )\n\n%*****************************************************************************80\n%\n%% BANDWIDTH determines the bandwidth associated with the finite element mesh.\n%\n% Discussion:\n%\n% The quantity computed here is the \"geometric\" bandwidth determined\n% by the finite element mesh alone.\n%\n% If a single finite element variable is associated with each node\n% of the mesh, and if the nodes and variables are numbered in the\n% same way, then the geometric bandwidth is the same as the bandwidth\n% of a typical finite element matrix.\n%\n% The bandwidth M is defined in terms of the lower and upper bandwidths:\n%\n% M = ML + 1 + MU\n%\n% where\n%\n% ML = maximum distance from any diagonal entry to a nonzero\n% entry in the same row, but earlier column,\n%\n% MU = maximum distance from any diagonal entry to a nonzero\n% entry in the same row, but later column.\n%\n% Because the finite element node adjacency relationship is symmetric,\n% we are guaranteed that ML = MU.\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 ELEMENT_ORDER, the order of the elements.\n%\n% Input, integer ELEMENT_NUM, the number of elements.\n%\n% Input, integer ELEMENT_NODE(ELEMENT_ORDER,ELEMENT_NUM);\n% ELEMENT_NODE(I,J) is the global index of local node I in element J.\n%\n% Output, integer ML, MU, the lower and upper bandwidths of the matrix.\n%\n% Output, integer M, the bandwidth of the matrix.\n%\n ml = 0;\n mu = 0;\n\n for element = 1 : element_num\n\n for local_i = 1 : element_order\n global_i = element_node(local_i,element);\n\n for local_j = 1 : element_order\n global_j = element_node(local_j,element);\n\n mu = max ( mu, global_j - global_i );\n ml = max ( ml, global_i - global_j );\n\n end\n end\n end\n\n m = ml + 1 + mu;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quad_mesh/bandwidth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7252649453961921}} {"text": "function grads = imLocalGradient(img, pos, sigma)\n% Compute gradient for chosen locations within image.\n%\n% The aim of this function is to compute gradient within images at\n% specified positions without requiring to compute the whole gradient\n% image. This greatly saves memory when image is large and number of\n% position is small.\n%\n% GRAD = imLocalGradient(IMG, POS)\n% Evaluates the gradient within the image IMG at the specified position\n% POS. The result GRAD is a 1-by-2 row vector containing gradient along\n% the x and y diections.\n% If POS is a N-by-2 array of coordinates, the result is a N-by-2 array\n% of vector components.\n%\n% GRAD = imLocalGradient(IMG, POS, SIGMA)\n% Also specifies the sigma parameter for computing gradient.\n%\n% Example\n% imLocalGradient\n%\n% See also\n% imGradientFilter, imLaplacian, gradientKernels, gradientKernels3d\n%\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% INRAE - BIA Research Unit - BIBS Platform (Nantes)\n% Created: 2022-06-01, using Matlab 9.9.0.1570001 (R2020b) Update 4\n% Copyright 2022 INRAE.\n\n\n%% Input arguments\n\n% process optional inputs\nif nargin == 2\n sigma = 2;\nend\n\n% compute output dimensions from input arguments\nnPos = size(pos, 1);\nnd = ndims(img);\n\n% allocate memory for result\ngrads = zeros(nPos, nd);\n\n\n%% Main processing\n\nif nd == 2\n % create gradient kernels\n [kx, ky] = gradientKernels(sigma);\n \n % computation will be performed using point-wise multiplication, so we need\n % to use the symetric kernels\n kx = kx(end:-1:1, end:-1:1);\n ky = ky(end:-1:1, end:-1:1);\n \n % size of the kernels along each dimension\n ks1 = size(kx, 1);\n ks2 = size(kx, 2);\n kr1 = floor((ks1 - 1) / 2);\n kr2 = floor((ks2 - 1) / 2);\n \n % iterate over position\n for iPos = 1:nPos\n % position in array indexing (position is x,y indexing)\n pos1 = round(pos(iPos, 2));\n pos2 = round(pos(iPos, 1));\n \n % clamp indexing of sub-image\n inds1 = max(min(pos1-kr1:pos1+kr1, size(img, 1)), 1);\n inds2 = max(min(pos2-kr2:pos2+kr2, size(img, 2)), 1);\n \n % extract region to process (using replication of borders if necessary)\n sub = double(img(inds1, inds2));\n \n % evaluate gradient by multiplying with gradient kernels\n gx = sub .* kx;\n gy = sub .* ky;\n grads(iPos, :) = [sum(gx(:)) sum(gy(:))];\n end\n \nelse\n % create gradient kernels\n [kx, ky, kz] = gradientKernels3d(sigma);\n \n % computation will be performed using point-wise multiplication, so we need\n % to use the symetric kernels\n kx = kx(end:-1:1, end:-1:1, end:-1:1);\n ky = ky(end:-1:1, end:-1:1, end:-1:1);\n kz = kz(end:-1:1, end:-1:1, end:-1:1);\n \n % size of the kernels along each dimension\n ks1 = size(kx, 1);\n ks2 = size(kx, 2);\n ks3 = size(kx, 3);\n kr1 = floor((ks1 - 1) / 2);\n kr2 = floor((ks2 - 1) / 2);\n kr3 = floor((ks3 - 1) / 2);\n \n % iterate over position\n for iPos = 1:nPos\n % position in array indexing (position is x,y indexing)\n pos1 = round(pos(iPos, 2));\n pos2 = round(pos(iPos, 1));\n pos3 = round(pos(iPos, 3));\n \n % clamp indexing of sub-image\n inds1 = max(min(pos1-kr1:pos1+kr1, size(img, 1)), 1);\n inds2 = max(min(pos2-kr2:pos2+kr2, size(img, 2)), 1);\n inds3 = max(min(pos3-kr3:pos3+kr3, size(img, 3)), 1);\n \n % extract region to process (using replication of borders if necessary)\n sub = double(img(inds1, inds2, inds3));\n \n % evaluate gradient by multiplying with gradient kernels\n gx = sub .* kx;\n gy = sub .* ky;\n gz = sub .* kz;\n grads(iPos, :) = [sum(gx(:)) sum(gy(:)) sum(gz(:))];\n end \nend\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/imLocalGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.7252468057929087}} {"text": "function loglikelihood = ComputeLogLikelihood(P, G, dataset)\n% returns the (natural) log-likelihood of data given the model and graph structure\n%\n% Inputs:\n% P: struct array parameters (explained in PA description)\n% G: graph structure and parameterization (explained in PA description)\n%\n% NOTICE that G could be either 10x2 (same graph shared by all classes)\n% or 10x2x2 (each class has its own graph). your code should compute\n% the log-likelihood using the right graph.\n%\n% dataset: N x 10 x 3, N poses represented by 10 parts in (y, x, alpha)\n% \n% Output:\n% loglikelihood: log-likelihood of the data (scalar)\n%\n% Copyright (C) Daphne Koller, Stanford Univerity, 2012\n\nN = size(dataset,1); % number of examples\nK = length(P.c); % number of classes\n\nloglikelihood = 0;\n% You should compute the log likelihood of data as in eq. (12) and (13)\n% in the PA description\n% Hint: Use lognormpdf instead of log(normpdf) to prevent underflow.\n% You may use log(sum(exp(logProb))) to do addition in the original\n% space, sum(Prob).\n% assuming data = [y x alpha]\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% YOUR CODE HERE\n% function val = lognormpdf(x, mu, sigma);\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\tloglikelihood += log(sum(exp(log1)+exp(log2)));\nend\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\n\n\n\n\n\n\n\n\n\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/ComputeLogLikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7252467957113644}} {"text": "%% mri_example2.m\n%|\n%| Example illustrating regularized iterative reconstruction for MRI\n%| from nonuniform k-space samples.\n%| This script generates the k-space data analytically (no inverse crime).\n%| (This example does not include field inhomogeneity or relaxation.)\n%|\n%| More generally, this shows how to go from nonuniform samples\n%| in the frequency domain back to uniform samples in the space domain\n%| by an interative algorithm.\n%|\n%| Copyright 2004-4-20, Jeff Fessler, University of Michigan\n\n\n%% functions for true object and its Fourier space\nif ~isvar('xtrue'), printm 'setup object'\n\tfov = 250; % mm FOV\n\n\tNdisp = 256; % display images with many pixels...\n\tx1d = [-Ndisp/2:Ndisp/2-1] / Ndisp * fov;\n\t[x1dd, x2dd] = ndgrid(x1d, x1d);\n\n\tobj = mri_objects('case1'); % analytical description\n\txtrue = obj.image(x1dd, x2dd);\n\tclear x1dd x2dd\n\n\tim clf, pl = @(it,j) subplot(5, 3, 3*it+j);\n\tclim = [0 2];\n\tif im\n\t\tpl(0,1); im(x1d, x1d, xtrue, 'x true', clim), cbar\n\tend\nprompt\nend\n\n\n%% Coarse object\nif 1 && ~isvar('xcoarse')\n\tN = [32 28];\n\tx1d = [-N(1)/2:N(1)/2-1] / N(1) * fov;\n\tx2d = [-N(2)/2:N(2)/2-1] / N(2) * fov;\n\t[x1dd, x2dd] = ndgrid(x1d, x2d);\n\txcoarse = obj.image(x1dd, x2dd);\n\tif im\n\t\tpl(0,3); im(xcoarse, 'x coarse', clim), cbar\n\t\taxis equal\n\tend\n\tclear x1dd x2dd\nprompt\nend\n\n\n%% trajectories\nlist.type = {'cartesian', 'radial', 'spiral1'}; %, 'epi-sin'};\n%list.type = {'radial'};\nlist.arg = {{}, {}, {}}; % , {2}\nlist.dens = {{}, {'voronoi'}, {'voronoi'}};\n\n\n%% loop over trajectory types\nif ~isvar('xpcg')\n for it=1:length(list.type)\n\ttraj_type = list.type{it};\n\n\t[kspace, omega, wi_traj] = mri_trajectory(traj_type, list.arg{it}, ...\n\t\tN, fov, list.dens{it});\n\n\tif im\n\t\tpl(it,1);\n\t\tplot(omega(1:1:end,1), omega(1:1:end,2), '.')\n\t\ttitlef('%s: %d', traj_type, size(omega,1))\n\t\taxis_pipi, axis square\n\tend\n\n\t% create Gnufft class object\n\tprintm 'setup system objects'\n\tJ = [6 6];\n\tnufft_args = {N, J, 2*N, N/2, 'table', 2^10, 'minmax:kb'};\n\tmask = true(N);\n\tAm = Gmri(kspace, mask, 'fov', fov, 'nufft', nufft_args, ...\n\t\t'basis', {'dirac*dx'});\n\t%\t'basis', {'rect'});\n\n\tprintm 'setup data'\n\tytrue = obj.kspace(kspace(:,1), kspace(:,2));\n\n\tif 0 % cheat and use discrete data for testing\n%\t\ttmp = zeros(N); tmp(end/4+1,end/4+1) = 1;\n\t\tminmax(ytrue)\n\t\tytrue = Am * xcoarse(mask);\n\t\tminmax(ytrue)\n\tend\n\n\t% add noise\n\trng(0)\n\tyi = ytrue + 0 * randn(size(ytrue));\n\n\twi_basis = wi_traj ./ Am.arg.basis.transform;\n\n\tprintm 'conj. phase reconstruction'\n\txcp = Am' * (wi_basis .* yi);\n\txcp = embed(xcp, mask);\n%\tplot([abs(xcp(:,end/2)) xcoarse(:,end/2)]), prompt % check scale\n\n\tif im\n\t\tpl(it,2); im(abs(xcp), 'Conj. Phase Recon'), cbar, drawnow\n\tend\n\n\tbeta = 2^-7 * size(omega,1); % good for quadratic\n%\tC = Cdiff(sqrt(beta) * mask, 'edge_type', 'tight'); % obsolete\n\tR = Reg1(mask, 'beta', beta);\n\tC = R.C;\n\n\tif 0 % example PSF\n\t\tqpwls_psf(Am, C, 1, mask);\n\t\tcontinue\n\tend\n\n\tif 0 % todo: explore new fast approach with MA\n\t\txnew = qpwls_psf(Am, C, 1, mask, 1, 'yb', yi(:));\t\n\tend\n\n\tprintm 'PCG with quadratic regularizer'\n\tniter = 10;\n\txpcg = qpwls_pcg(0*xcp(:), Am, 1, yi(:), 0, C, 1, niter);\n\txpcg = embed(xpcg(:,end), mask);\n\n\tif im\n\t\tpl(it,3); im(abs(xpcg), '$|x|$ pcg quad', clim), cbar, drawnow\n\tend\n end\nend\n\n\n%% PCG edge preserving\nif 1 || ~isvar('xh'), printm 'PCG with edge-preserving regularizer'\n\tR = Reg1(mask, 'beta', 2^20*beta, 'pot_arg', {'hyper3', 0.05}, ...\n\t\t'type_penal', 'mat', ... % because complex\n\t\t'type_denom', 'matlab');\n\txh = pwls_pcg1(xpcg(:), Am, 1, yi(:), R, 'niter', niter);\n\txh = embed(xh, mask);\n\t[magn, angn] = mag_angle_real(xh);\n\tif im\n\t\tpl(it+1,3), im(magn, '$|x|$ pcg edge', clim), cbar\n%\t\tpl(it+1,2), im(angn.*mask, '\\angle x pcg edge', plim), cbar\n\tend\nend\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/example/mri_example2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7252467895800924}} {"text": "function A = whtmtx(N)\n%WHTMTX Generates sequency-ordered Walsh-Hadamard transformation matrix.\n% A = WHTMTX(N) returns the sequency-ordered transformation matrix for\n% a Walsh-Hadamard transform of dimension N, where N is a power of 2.\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\nbits = log2(N);\nif rem(bits,1) > 0\n error('N must be a power of 2!');\nend\n\n% Scale MATLAB's naturally ordered Hadamard functions\nH = hadamard(N) ./ sqrt(N);\n\n% Create a vector of row numbers in binary. Subtract character '0' to make\n% the vector of type logical rather than character.\nrows = dec2bin(0:N-1,bits) - '0';\n\n% Gray code the row numbers. Note that we are working from the most to\n% least significant bit. That is, column 1 of gray contains the MSB.\ngray = rows;\nfor i = 2:1:bits\n gray(:,i) = xor(rows(:,i),rows(:,i-1));\nend\n\n% Bit-reverse the gray coded row numbers and convert to new decimal row\n% numbers. Then rearrange the rows.\nrows = fliplr(gray) * pow2((bits-1:-1:0)');\nA = H(rows+1,:);\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/whtmtx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7252079881542948}} {"text": "function X = kr(U,varargin)\n%KR Khatri-Rao product.\n% kr(A,B) returns the Khatri-Rao product of two matrices A and B, of \n% dimensions I-by-K and J-by-K respectively. The result is an I*J-by-K\n% matrix formed by the matching columnwise Kronecker products, i.e.,\n% the k-th column of the Khatri-Rao product is defined as\n% kron(A(:,k),B(:,k)).\n%\n% kr(A,B,C,...) and kr({A B C ...}) compute a string of Khatri-Rao \n% products A x B x C x ..., where x denotes the Khatri-Rao product.\n%\n% See also kron.\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\nif ~iscell(U), U = [{U} varargin]; end\n[J,K] = size(U{end});\nif any(cellfun('size',U,2) ~= K)\n error('kr:U','Input matrices should have the same number of columns.');\nend\n\nX = reshape(U{end},[J 1 K]);\nfor n = length(U)-1:-1:1\n I = size(U{n},1);\n A = reshape(U{n},[1 I K]);\n X = reshape(bsxfun(@times,A,X),[I*J 1 K]);\n J = I*J;\nend\nX = reshape(X,[size(X,1) K]);\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/kr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7250192775680451}} {"text": "function mono_total_enum_test ( )\n\n%*****************************************************************************80\n%\n%% MONO_TOTAL_ENUM_TEST tests MONO_TOTAL_ENUM.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONO_TOTAL_ENUM_TEST\\n' );\n fprintf ( 1, ' MONO_TOTAL_ENUM can enumerate the number of monomials\\n' );\n fprintf ( 1, ' in M variables, of total degree N.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N:' );\n for n = 0 : 8\n fprintf ( 1, ' %4d', n );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' M +------------------------------------------------------\\n' );\n for m = 1 : 8\n fprintf ( 1, ' %2d |', m );\n for n = 0 : 8\n v = mono_total_enum ( m, n );\n fprintf ( 1, ' %4d', v );\n end\n fprintf ( 1, '\\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/monomial/mono_total_enum_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.7250192702463769}} {"text": "function [ y, m, d, f ] = jed_to_ymdf_islamic_b ( jed )\n\n%*****************************************************************************80\n%\n%% JED_TO_YMDF_ISLAMIC_B converts a JED to an Islamic B YMDF date.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 July 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Edward Richards,\n% Algorithm F,\n% Mapping Time, The Calendar and Its History,\n% Oxford, 1999, pages 324-325.\n%\n% Parameters:\n%\n% Input, real JED, the Julian Ephemeris Date.\n%\n% Output, integer Y, M, D, real F, the YMDF date.\n%\n\n%\n% Determine the computational date (Y'/M'/D').\n%\n j = floor ( jed + 0.5 );\n f = ( jed + 0.5 ) - j;\n\n j_prime = j + 7664;\n\n y_prime = floor ( ( 30 * j_prime + 15 ) / 10631 );\n t_prime = floor ( mod ( 30 * j_prime + 15, 10631 ) / 30 );\n m_prime = floor ( ( 100 * t_prime + 10 ) / 2951 );\n d_prime = floor ( mod ( 100 * t_prime + 10, 2951 ) / 100 );\n%\n% Convert the computational date to a calendar date.\n%\n d = d_prime + 1;\n m = mod ( m_prime, 12 ) + 1;\n y = y_prime - 5519 + floor ( ( 12 - m ) / 12 );\n\n return\nend\n", "meta": {"author": "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/jed_to_ymdf_islamic_b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7956581097540518, "lm_q1q2_score": 0.7249875237951721}} {"text": "function BC=betweenness_bin(G)\n%BETWEENNESS_BIN Node betweenness centrality\n%\n% BC = betweenness_bin(A);\n%\n% Node betweenness centrality is the fraction of all shortest paths in \n% the network that contain a given node. Nodes with high values of \n% betweenness centrality participate in a large number of shortest paths.\n%\n% Input: A, binary (directed/undirected) connection matrix.\n%\n% Output: BC, node betweenness centrality vector.\n%\n% Note: Betweenness centrality may be normalised to the range [0,1] as\n% BC/[(N-1)(N-2)], where N is the number of nodes in the network.\n%\n% Reference: Kintali (2008) arXiv:0809.1906v2 [cs.DS]\n% (generalization to directed and disconnected graphs)\n%\n%\n% Mika Rubinov, UNSW/U Cambridge, 2007-2012\n\n\nn=length(G); %number of nodes\nI=eye(n)~=0; %logical identity matrix\nd=1; \t%path length\nNPd=G; %number of paths of length |d|\nNSPd=NPd; \t%number of shortest paths of length |d|\nNSP=NSPd; NSP(I)=1; \t%number of shortest paths of any length\nL=NSPd; L(I)=1; \t%length of shortest paths\n\n%calculate NSP and L\nwhile find(NSPd,1)\n d=d+1;\n NPd=NPd*G;\n NSPd=NPd.*(L==0);\n NSP=NSP+NSPd;\n L=L+d.*(NSPd~=0);\nend\nL(~L)=inf; L(I)=0; %L for disconnected vertices is inf\nNSP(~NSP)=1; %NSP for disconnected vertices is 1\n\nGt=G.';\nDP=zeros(n); \t%vertex on vertex dependency\ndiam=d-1; \t%graph diameter\n\n%calculate DP\nfor d=diam:-1:2\n DPd1=(((L==d).*(1+DP)./NSP)*Gt).*((L==(d-1)).*NSP);\n DP=DP + DPd1; %DPd1: dependencies on vertices |d-1| from source\nend\n\nBC=sum(DP,1); %compute betweenness", "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/betweenness_bin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7249875235067137}} {"text": "function [gd,relres,iter] = gabconvexopt(g,a,M,varargin)\n%GABCONVEXOPT Compute a window using convex optimization\n% Usage: gout=gabconvexopt(g,a,M);\n% gout=gabconvexopt(g,a,M, varagin);\n%\n% Input parameters:\n% g : Window function /initial point (tight case)\n% a : Time shift\n% M : Number of Channels\n%\n% Output parameters:\n% gout : Output window\n% iter : Number of iterations\n% relres : Reconstruction error\n%\n% `gabconvexopt(g,a,M)` computes a window *gout* which is the optimal\n% solution of the convex optimization problem below\n%\n% .. gd = argmin_x || alpha x||_1 + || beta Fx||_1 \n%\n% .. + || omega (x -g_l) ||_2^2 + delta || x ||_S0\n%\n% .. + gamma || nabla F x ||_2^2 + mu || nabla x ||_2^2\n%\n% .. such that x satifies the constraints\n%\n% .. math:: \\begin{split} \\text{gd} = & \\text{arg} \\min_x \\| \\alpha x \\|_1 + \\| \\beta \\mathcal{F}x\\|_1 \\\\ & + \\| \\omega (x - g_l) \\|_2^2 \\\\ & \\delta \\| x \\|_{S0}+ \\mu \\| \\nabla x \\|_2^2 +\\gamma \\| \\nabla \\mathcal{F} x \\|_2^2 \\\\ & \\text{such that } x \\text{ satisfies the constraints} \\end{split}\n%\n% Three constraints are possible:\n% \n% * *x* is dual with respect of g\n%\n% * *x* is tight\n%\n% * *x* is compactly supported on Ldual\n%\n% **Note**: This function require the unlocbox. You can download it at\n% ``_\n%\n% The function uses an iterative algorithm to compute the approximate.\n% The algorithm can be controlled by the following flags:\n%\n% 'alpha',alpha Weight in time. If it is a scalar, it represent the\n% weights of the entire L1 function in time. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L1 norm (length: Ldual).\n% Default value is $\\alpha=0$.\n% **Warning**: this value should not be too big in order to\n% avoid the the L1 norm proximal operator kill the signal.\n% No L1-time constraint: $\\alpha=0$\n%\n% 'beta',beta Weight in frequency. If it is a scalar, it represent the\n% weights of the entire L1 function in frequency. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L1 norm in frequency. (length: Ldual).\n% Default value is $\\beta=0$.\n% **Warning**: this value should not be too big in order to\n% avoid the the L1 norm proximal operator kill the signal.\n% No L1-frequency constraint: $\\beta=0$\n%\n% 'omega',omega Weight in time of the L2-norm. If it is a scalar, it represent the\n% weights of the entire L2 function in time. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L2 norm (length: Ldual).\n% Default value is $\\omega=0$.\n% No L2-time constraint: $\\omega=0$\n%\n% 'glike',g_l $g_l$ is a windows in time. The algorithm try to shape\n% the dual window like $g_l$. Normalization of $g_l$ is done\n% automatically. To use option omega should be different\n% from 0. By default $g_d=0$.\n%\n% 'mu', mu Weight of the smooth constraint Default value is 1. \n% No smooth constraint: $\\mu=0$\n% \n% 'gamma', gamma Weight of the smooth constraint in frequency. Default value is 1. \n% No smooth constraint: $\\gamma=0$\n% \n% 'delta', delta Weight of the S0-norm. Default value is 0. \n% No S0-norm: $\\delta=0$\n%\n% 'support' Ldual Add a constraint on the support. The windows should\n% be compactly supported on Ldual.\n%\n% 'tight' Look for a tight windows\n%\n% 'dual' Look for a dual windows (default)\n%\n% 'painless' Construct a starting guess using a painless-case\n% approximation. This is the default\n%\n% 'zero' Choose a starting guess of zero.\n%\n% 'rand' Choose a random starting phase.\n%\n% 'tol',t Stop if relative residual error is less than the \n% specified tolerance. \n%\n% 'maxit',n Do at most n iterations. default 200\n%\n% 'print' Display the progress.\n%\n% 'debug' Display all the progresses.\n%\n% 'quiet' Don't print anything, this is the default.\n%\n% 'fast' Fast algorithm, this is the default.\n%\n% 'slow' Safer algorithm, you can try this if the fast algorithm\n% is not working. Before using this, try to iterate more.\n%\n% 'printstep',p If 'print' is specified, then print every p'th\n% iteration. Default value is p=10;\n%\n% 'hardconstraint' Force the projection at the end (default)\n%\n% 'softconstaint' Do not force the projection at the end\n%\n% See also: gaboptdual, gabdual, gabtight, gabfirtight, gabopttight\n \n\n\n% Author: Nathanael Perraudin\n% Date : 18 Feb 2014\n\n\nif nargin<4\n error('%s: Too few input parameters.',upper(mfilename));\nend;\n\nif numel(g)==1\n error('g must be a vector (you probably forgot to supply the window function as input parameter.)');\nend;\n\ndefinput.keyvals.L=[];\ndefinput.keyvals.lt=[0 1];\ndefinput.keyvals.tol=1e-6;\ndefinput.keyvals.maxit=200;\ndefinput.keyvals.printstep=10;\ndefinput.flags.print={'quiet','print','debug'};\ndefinput.flags.algo={'fast','slow'};\ndefinput.flags.constraint={'hardconstraint','softconstaint'};\ndefinput.flags.startphase={'painless','zero','rand'};\ndefinput.flags.type={'dual','tight'};\n\ndefinput.keyvals.alpha=0;\ndefinput.keyvals.omega=0;\ndefinput.keyvals.beta=0;\ndefinput.keyvals.mu=1;\ndefinput.keyvals.gamma=1;\ndefinput.keyvals.vart=0;\ndefinput.keyvals.varf=0;\ndefinput.keyvals.var2t=0;\ndefinput.keyvals.var2f=0;\ndefinput.keyvals.support=0;\ndefinput.keyvals.delta=0;\ndefinput.keyvals.deltaw=0;\ndefinput.keyvals.glike=zeros(size(g));\n\n[flags,kv]=ltfatarghelper({'L','tol','maxit'},definput,varargin);\n\n% Determine the window. The window /must/ be an FIR window, so it is\n% perfectly legal to specify L=[] when calling gabwin\n[g,info]=gabwin(g,a,M,[],kv.lt,'callfun',upper(mfilename));\n\nif kv.support\n Ldual=kv.support;\n % Determine L. L must be longer than L+Ldual+1 to make sure that no convolutions are periodic\n L=dgtlength(info.gl+Ldual+1,a,M);\nelse\n L=length(g);\n Ldual=L;\nend\n\nb=L/M;\n\n% Determine the initial guess\nif flags.do_zero\n gd_initial=zeros(Ldual,1);\nend;\n\nif flags.do_rand\n gd_initial=rand(size(g));\nend;\n\nif flags.do_painless\n gsmall=long2fir(g,M);\n gdsmall=gabdual(gsmall,a,M);\n gd_initial=fir2long(gdsmall,Ldual);\nend;\n\n% -------- do the convex optimization stuff\n\n% Define the long original window\nglong=fir2long(g,L);\n\n\n\n\n%gabframebounds(g,a,M)\n\n\n% Initial point\nxin=gd_initial;\nxin=fir2long(xin,L);\n\n\n% -- * Setting the different prox for ppxa *--\n% ppxa will minimize all different proxes\n\n% value test for the selection constraint\nnb_priors=0;\n\n% - variance -\n if kv.vart % constraint in time\n if flags.do_debug\n param_l1.verbose=1; % display the results\n else\n param_l1.verbose=0; % do not display anything\n end\n \n % alpha is a scalar\n if mod(L,2)\n w=[0:1:(L-1)/2,(L-1)/2:-1:1]';\n else\n w=[0:1:L/2-1,L/2:-1:1]';\n end\n w=w.^2/L;\n \n param_l1.weights=w;\n nb_priors=nb_priors+1;\n g11.prox= @(x,T) prox_l1(x,kv.vart*T,param_l1); % define the prox_l1 as operator\n g11.eval= @(x) kv.vart*norm(w.*x,1); % the objectiv function is the l1 norm\n else % no L1 in time constraint\n g11.prox= @(x,T) x; \n g11.eval= @(x) 0; \n end\n\n% - variance -\n if kv.varf % constraint in time\n \n param_l1_fourier.A= @(x) 1/sqrt(L)*fft(x); % Fourier operator\n param_l1_fourier.At= @(x) sqrt(L)*ifft(x); % adjoint of the Fourier operator\n if flags.do_debug\n param_l1_fourier.verbose=1; % display the results\n else\n param_l1_fourier.verbose=0; % do not display anything\n end\n \n if mod(L,2)\n w=[0:1:(L-1)/2,(L-1)/2:-1:1]';\n else\n w=[0:1:L/2-1,L/2:-1:1]';\n end\n w=w.^2/L;\n \n param_l1_fourier.weights=w;\n nb_priors=nb_priors+1;\n g12.prox= @(x,T) prox_l1(x,kv.varf*T,param_l1_fourier); % define the prox_l1 as operator\n g12.eval= @(x) kv.varf*norm(w.*x,1); % the objectiv function is the l1 norm\n else % no L1 in time constraint\n g12.prox= @(x,T) x; \n g12.eval= @(x) 0; \n end \n\n% - variance2 -\n if kv.var2t % constraint in time\n if flags.do_debug\n param_l2.verbose=1; % display the results\n else\n param_l2.verbose=0; % do not display anything\n end\n \n % alpha is a scalar\n if mod(L,2)\n w=[0:1:(L-1)/2,(L-1)/2:-1:1]';\n else\n w=[0:1:L/2-1,L/2:-1:1]';\n end\n w=w/sqrt(L);\n \n param_l2.weights=w;\n nb_priors=nb_priors+1;\n g13.prox= @(x,T) prox_l2(x,kv.var2t*T,param_l2); % define the prox_l1 as operator\n g13.eval= @(x) kv.var2t*norm(w.*x,2)^2; % the objectiv function is the l1 norm\n else % no L1 in time constraint\n g13.prox= @(x,T) x; \n g13.eval= @(x) 0; \n end\n\n% - variance2 -\n if kv.var2f % constraint in time\n \n param_l2_fourier.A= @(x) 1/sqrt(L)*fft(x); % Fourier operator\n param_l2_fourier.At= @(x) sqrt(L)*ifft(x); % adjoint of the Fourier operator\n if flags.do_debug\n param_l2_fourier.verbose=1; % display the results\n else\n param_l2_fourier.verbose=0; % do not display anything\n end\n \n if mod(L,2)\n w=[0:1:(L-1)/2,(L-1)/2:-1:1]';\n else\n w=[0:1:L/2-1,L/2:-1:1]';\n end\n w=w/sqrt(L);\n \n param_l2_fourier.weights=w;\n nb_priors=nb_priors+1;\n g14.prox= @(x,T) prox_l2(x,kv.var2f*T,param_l2_fourier); % define the prox_l1 as operator\n g14.eval= @(x) kv.var2f*norm(w.*x,2)^2; % the objectiv function is the l1 norm\n else % no L1 in time constraint\n g14.prox= @(x,T) x; \n g14.eval= @(x) 0; \n end \n \n% - small L1 norm in coefficient domain -\n if kv.alpha % constraint in time\n if flags.do_debug\n param_l1.verbose=1; % display the results\n else\n param_l1.verbose=0; % do not display anything\n end\n \n if length(kv.alpha)==1 % alpha is a scalar\n kv.alpha=ones(size(xin))*kv.alpha;\n end\n param_l1.weights=kv.alpha;\n nb_priors=nb_priors+1;\n g1.prox= @(x,T) prox_l1(x,T,param_l1); % define the prox_l1 as operator\n g1.eval= @(x) norm(kv.alpha.*x,1); % the objectiv function is the l1 norm\n else % no L1 in time constraint\n g1.prox= @(x,T) x; \n g1.eval= @(x) 0; \n end\n\n% - small L1 norm in Fourier domain -\n if kv.beta %frequency constraint\n param_l1_fourier.A= @(x) 1/sqrt(L)*fft(x); % Fourier operator\n param_l1_fourier.At= @(x) sqrt(L)*ifft(x); % adjoint of the Fourier operator\n if flags.do_debug\n param_l1_fourier.verbose=1; % display the results\n else\n param_l1_fourier.verbose=0; % Do not display anything\n end\n \n \n\n if length(kv.beta)==1 % alpha is a scalar\n kv.beta=ones(size(xin))*kv.beta;\n end\n\n param_l1_fourier.weights=kv.beta;\n % Here are the step for the prox\n % 2) go into the Fourier domain (prox_l1)\n % 3) soft thresholding (prox_l1)\n % 4) back in the time domain (prox_l1)\n nb_priors=nb_priors+1;\n g3.prox= @(x,T) prox_l1(x,T,param_l1_fourier); \n\n g3.eval= @(x) norm(kv.beta.*fft(x),1); % objectiv function\n else % no L1 in frequency constraint\n g3.prox= @(x,T) x; \n g3.eval= @(x) 0; % objectiv function\n \n end\n\n\n% - DUAL OR TIGHT?- \nif flags.do_tight\n % tight windows\n g2.prox= @(x,T) gabtight(x,a,M); % set the prox\n g2.eval= @(x) norm(x-gabdual(x,a,M,L)); % objectiv function\nelse\n% - projection on a B2 ball -\n % Frame-type matrix of the adjoint lattice\n %G=tfmat('dgt',glong,M,a);\n Fal=frame('dgt',glong,M,a);\n G=framematrix(Fal,L);\n d=[a/M;zeros(a*b-1,1)];\n \n % Using a B2 ball projection\n % || Gcut' x - b ||_2 < epsilon\n% param_proj.A = @(x) G'*x; % forward operator\n% param_proj.At = @(x) G*x; % adjoint operator\n% param_proj.y = d; \n% param_proj.maxit = 200; % maximum of iteration\n% param_proj.tight=0; % not a tight frame\n% param_proj.nu=norm(G)^2; % frame bound on Gcut'\n% param_proj.verbose=0; % diplay summary at the end\n% param_proj.epsilon=10*eps; % radius of the B2 ball\n% g2.prox= @(x,T) fast_proj_b2(x,T,param_proj); % set the prox\n\n % Using a direct projection (better solution)\n param_proj.verbose=flags.do_debug;\n param_proj.y=d;\n param_proj.A=G';\n param_proj.AAtinv=(G'*G)^(-1);\n g2.prox= @(x,T) proj_dual(x,T,param_proj); % set the prox\n g2.eval= @(x) norm(G'*x-d); % objectiv function\nend\n \n\n% SUPPORT CONSTRAINT\nif kv.support\n% - set null coefficient \n g4.prox = @(x,T) forceeven(fir2long(long2fir(x,Ldual),L));\n g4.eval = @(x) 0;\n\n% - function apply the two projections thanks to a poc algorithm.\n if flags.do_tight\n\n G={g2,g4};\n paramPOCS.tol=20*eps;\n paramPOCS.maxit=5000;\n paramPOCS.verbose=flags.do_print+flags.do_debug;\n paramPOCS.abs_tol=1;\n g5.prox = @(x,T) pocs(x,G,paramPOCS);\n % g5.prox = @(x,T) ppxa(x,G,paramPOCS);\n % g5.prox = @(x,T) douglas_rachford(x,g2,g4,paramPOCS);\n % g5.prox = @(x,T) pocs2(x,g2,g4,20*eps,2000, flags.do_print+flags.do_debug);\n g5.eval = @(x) 0;\n\n else\n Fal=frame('dgt',glong,M,a);\n G=framematrix(Fal,L);\n d=[a/M;zeros(a*b-1,1)];\n Lfirst=ceil(Ldual/2);\n Llast=Ldual-Lfirst;\n Gcut=G([1:Lfirst,L-Llast+1:L],:);\n param_proj2.verbose=flags.do_debug;\n param_proj2.y=d;\n param_proj2.A=Gcut';\n param_proj2.AAtinv=pinv(Gcut'*Gcut);\n g5.prox= @(x,T) fir2long(proj_dual(long2fir(x,Ldual),T,param_proj2),L); % set the prox\n g5.eval= @(x) norm(G'*x-d); % objectiv function\n end\n \nelse\n g4.prox= @(x,T) x; \n g4.eval= @(x) 0; % objectiv function\n g5=g2;\nend\n% - function apply the two projections thanks to a douglas rachford algorithm.\n% param_douglas.verbose=1;\n% param_douglas.abs_tol=1;\n% param_douglas.maxit=2000;\n% param_douglas.tol=20*eps;\n% g6.prox = @(x,T) douglas_rachford(x,g2,g4,param_douglas);\n% g6.eval = @(x) 0;\n\n\n\n% - small gradient norm - \n% this is the smoothing parameter\n if kv.mu\n if flags.do_debug\n param_l2grad.verbose=1; % display the results\n else\n param_l2grad.verbose=0; % Do not display anything\n end\n nb_priors=nb_priors+1;\n g7.prox = @(x,T) prox_l2grad(fir2long(x,L),kv.mu*T,param_l2grad);\n g7.eval = @(x) norm(gradient(x))^2;\n else\n g7.prox = @(x,T) x;\n g7.eval = @(x) 0;\n end\n\n \n \n% - small gradient norm in fourrier- \n% this is the smoothing parameter\n if kv.gamma\n if flags.do_debug\n param_l2grad.verbose=1; % display the results\n else\n param_l2grad.verbose=0; % Do not display anything\n end\n nb_priors=nb_priors+1;\n g9.prox = @(x,T) prox_l2gradfourier(fir2long(x,L),kv.gamma*T,param_l2grad);\n g9.eval = @(x) norm(gradient(1/sqrt(L)*fft(x)))^2;\n else\n g9.prox = @(x,T) x;\n g9.eval = @(x) 0;\n end\n \n \n \n% - small L2 norm in coefficient domain -\n if kv.omega % constraint in time\n if flags.do_debug\n param_l2.verbose=1; % display the results\n else\n param_l2.verbose=0; % do not display anything\n end\n \n if length(kv.omega)==1 % alpha is a scalar\n kv.alpha=ones(size(xin))*kv.omega;\n end\n param_l2.weights=kv.omega;\n if sum(kv.glike)\n kv.glike=fir2long(kv.glike,L);\n\n glike=kv.glike/norm(kv.glike)*norm(gabdual(g,a,M));\n param_l2.y=fir2long(glike,L);\n end\n nb_priors=nb_priors+1;\n g8.prox= @(x,T) prox_l2(x,T,param_l2); % define the prox_l2 as operator\n g8.eval= @(x) norm(kv.omega.*x-kv.glike,'fro')^2; % the objectiv function is the l2 norm\n else % no L1 in time constraint\n g8.prox= @(x,T) x; \n g8.eval= @(x) 0; \n end \n\n\n \n \n% - small S0 norm -\n if kv.delta %frequency constraint\n gauss=pgauss(L,1);\n\n [A,B]=gabframebounds(gauss,1,L);\n AB=(A+B)/2;\n param_S0.A= @(x) dgt(x,gauss,1,L)/sqrt(AB);\n param_S0.At= @(x) idgt(x,gauss,1,L)/sqrt(AB);\n if flags.do_debug\n param_S0.verbose=1; % display the results\n else\n param_S0.verbose=0; % Do not display anything\n end\n \n nb_priors=nb_priors+1;\n g10.prox= @(x,T) prox_l1(x,T*kv.delta,param_S0); \n\n g10.eval= @(x) kv.delta*norm(reshape(dgt(x,gauss,1,L),[],1),1); % objectiv function\n else % no L1 in frequency constraint\n g10.prox= @(x,T) x; \n g10.eval= @(x) 0; % objectiv function\n \n end\n \n% - small weighted S0 norm -\n if kv.deltaw %frequency constraint\n gauss=pgauss(L,1);\n\n [A,B]=gabframebounds(gauss,1,L);\n AB=(A+B)/2;\n param_S0.A= @(x) dgt(x,gauss,1,L)/sqrt(AB);\n param_S0.At= @(x) idgt(x,gauss,1,L)/sqrt(AB);\n if flags.do_debug\n param_S0.verbose=1; % display the results\n else\n param_S0.verbose=0; % Do not display anything\n end\n \n if mod(L,2)\n w=[0:1:(L-1)/2,(L-1)/2:-1:1]';\n else\n w=[0:1:L/2-1,L/2:-1:1]';\n end\n w=w/sqrt(L);\n \n %W=w*w';\n \n W=repmat(w,1,L).^2+repmat(w',L,1).^2;\n \n \n W=sqrt(W);\n \n param_S0.weights=W;\n nb_priors=nb_priors+1;\n g15.prox= @(x,T) prox_l1(x,T*kv.deltaw,param_S0); \n\n g15.eval= @(x) kv.deltaw*norm(reshape(dgt(x,gauss,1,L),[],1),1); % objectiv function\n else % no L1 in frequency constraint\n g15.prox= @(x,T) x; \n g15.eval= @(x) 0; % objectiv function\n \n end\n \n \n \n% -- * PPXA function, the solver * --\n\n\n% parameter for the solver\n param.maxit=kv.maxit; % maximum number of iteration\n param.tol=kv.tol;\n if flags.do_quiet\n param.verbose=0;\n end\n \n % Definition of the function f (the order is important)\n if flags.do_fast && flags.do_tight\n F={g1, g3,g7,g9,g8, g2, g4,g10,g11,g12,g13,g14,g15}; \n \n else\n F={g1, g3,g7,g9,g8, g5,g10,g11,g12,g13,g14,g15};\n end\n\n \n % solving the problem\n \n if nb_priors\n [gd,iter,~]=ppxa(xin,F,param);\n \n % Force the hard constraint\n if flags.do_hardconstraint\n % In case of use of the douglas rachford algo instead of POCS\n % gd=g6.prox(gd,0); % force the constraint\n\n gd=g5.prox(gd,0);\n end\n else\n fprintf( ' Warning!!! No prior selected! -- Only perform a projection. \\n')\n gd=g5.prox(xin,0);\n end\n \n % compute the error\n if flags.do_tight\n relres=gabdualnorm(gd,gd,a,M,L);\n else\n relres=gabdualnorm(g,gd,a,M,L);\n end\n \n\n if kv.support\n % set the good size\n gd=long2fir(gd,Ldual);\n end\n\nend\n\n\n% function x=pocs2(x,g1,g2,tol,maxii,flagp)\n% % this function implement a POCS algorithm, projection onto convex Set\n% % using the differents projection of the algorithm.\n% tola=1;\n% ii=0;\n% tola_old=tola;\n% while (tola>tol)\n% x=g2.prox(g1.prox(x,0),0);\n% tola=g1.eval(x);\n% ii=ii+1;\n% if (logical(1-logical(mod(ii,50))) && flagp)\n% fprintf(' POCS sub-iteration: %i -- Tol : %g\\n',ii,tola)\n% end\n% if ii> maxii\n% break;\n% end\n% if abs(tola_old-tola)/tola 0.0 ) );\n\n D = D( D > 0.0 );\n%\n% Truncate the potential.\n%\n D2 = D .* ( D <= pi2 ) + pi2 * ( D > pi2 );\n%\n% Accumulate the potential energy.\n%\n pot = pot + 0.5 * sum ( sin ( D2 ).^2 );\n%\n% Compute force on particle I.\n%\n f( :, i) = Ri * ( sin ( 2*D2 ) ./ D )';\n\n end\n%\n% Compute the kinetic energy.\n%\n kin = 0.5 * mass * sum ( sum ( vel.^2 ) );\n\n return\nend\nfunction [ pos, vel, acc, seed ] = initialize ( np, nd, box, seed )\n\n%*****************************************************************************80\n%\n%% INITIALIZE initializes the positions, velocities, and accelerations.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 July 2008\n%\n% Author:\n%\n% Original FORTRAN90 version by Bill Magro.\n% MATLAB version by John Burkardt.\n%\n% Parameters:\n%\n% Input, integer NP, the number of particles.\n%\n% Input, integer ND, the number of spatial dimensions.\n%\n% Input, real BOX(ND), specifies the maximum position\n% of particles in each dimension.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real POS(ND,NP), the position of each particle.\n%\n% Output, real VEL(ND,NP), the velocity of each particle.\n%\n% Output, real ACC(ND,NP), the acceleration of each particle.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n\n%\n% Start by setting the positions to random numbers between 0 and 1.\n%\n pos(1:nd,1:np) = rand ( nd, np );\n%\n% Use these random values as scale factors to pick random locations\n% inside the box.\n%\n for i = 1 : nd\n pos(i,1:np) = box(i) * pos(i,1:np);\n end\n%\n% Velocities and accelerations.\n%\n vel(1:nd,1:np) = randn ( nd, np );\n acc(1:nd,1:np) = 0.0;\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\nfunction [ pos, vel, acc ] = update ( np, nd, pos, vel, f, acc, mass, dt )\n\n%*****************************************************************************80\n%\n%% UPDATE updates positions, velocities and accelerations.\n%\n% Discussion:\n%\n% The time integration is fully parallel.\n%\n% A velocity Verlet algorithm is used for the updating.\n%\n% x(t+dt) = x(t) + v(t) * dt + 0.5 * a(t) * dt * dt\n% v(t+dt) = v(t) + 0.5 * ( a(t) + a(t+dt) ) * dt\n% a(t+dt) = f(t) / m\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 July 2008\n%\n% Author:\n%\n% Original FORTRAN90 version by Bill Magro.\n% MATLAB version by John Burkardt.\n%\n% Parameters:\n%\n% Input, integer NP, the number of particles.\n%\n% Input, integer ND, the number of spatial dimensions.\n%\n% Input, real POS(ND,NP), the position of each particle.\n%\n% Input, real VEL(ND,NP), the velocity of each particle.\n%\n% Input, real F(ND,NP), the force on each particle.\n%\n% Input, real ACC(ND,NP), the acceleration of each\n% particle.\n%\n% Input, real MASS, the mass of each particle.\n%\n% Input, real DT, the time step.\n%\n% Output, real POS(ND,NP), the updated position of each particle.\n%\n% Output, real VEL(ND,NP), the updated velocity of each particle.\n%\n% Output, real ACC(ND,NP), the updated acceleration of each\n% particle.\n%\n rmass = 1.0 / mass;\n\n pos(1:nd,1:np) = pos(1:nd,1:np) + vel(1:nd,1:np) * dt ...\n + 0.5 * acc(1:nd,1:np) * dt * dt;\n\n vel(1:nd,1:np) = vel(1:nd,1:np) ...\n + 0.5 * dt * ( f(1:nd,1:np) * rmass + acc(1:nd,1:np) );\n\n acc(1:nd,1:np) = f(1:nd,1:np) * rmass;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/md_fast/md_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.7249875061348728}} {"text": "classdef SPX_CGLeastSquare < handle\n% Conjugate gradient algorithm for least squares or\n% normal equations implementation\n% We are solving the problem minimize \\| A x - b \\|_2^2.\n% A is of size M x N. \n% M > N.\n% A^T A is of size N x N.\n% b is of size M x 1.\n% x is of size N x 1.\n% A is full rank. Rank(A) = N.\n% We assume that A is well conditioned.\n% We can simultaneously solve S problems.\n\n\n properties\n % Settable and gettable properties\n\n % Maximum number of iterations for which the algorithm can run\n MaxIterations\n % Threshold of norm (in terms of percentage)\n NormThreshold\n end\n\n\n properties(SetAccess=private)\n % Gettable properties\n\n % The full rank tall matrix operator M x N\n A\n % The vectors to be solved M x S\n B\n % Measurements dimension\n M\n % Problem dimension\n N\n % Number of equations to be solved\n S\n % Number of iterations taken for solving the problem\n Iterations\n % The solution vectors\n X\n % Residual vectors in the CG algorithm\n CGResiduals\n % Residual norms at the end of the corresponding CG problem.\n CGResidualNorms\n % Residual vectors of the LS problem\n LSResiduals\n % Norms of the LS residuals at the end\n LSResidualNorms\n % Indicates if the problems converged\n % This would be false only if the algorithm crossed max iterations\n Converged\n end\n\n methods\n % Public methods\n function self = SPX_CGLeastSquare(A, B)\n % Constructor\n if isa(A, 'spx.dict.Operator')\n self.A = A;\n elseif ismatrix(A)\n self.A = spx.dict.MatrixOperator(A); \n else\n error('Unsupported operator.');\n end\n [self.M, self.N] = size(A);\n if self.M < self.N\n error('Only over-determined systems are supported')\n end\n % Ideally we should check the rank too.\n % But that would be too time consuming.\n [bm, self.S] = size(B);\n if bm ~= self.M\n error('Dimensions mismatch.');\n end\n self.B = B;\n self.MaxIterations = self.N ;\n self.NormThreshold = 1e-6;\n end\n\n function result = solve(self)\n aa = self.A; % M x N\n % We compute A' B in advance.\n atbb = self.A.apply_ctranspose(self.B); % N x S\n % Initial estimate vectors are all zeros\n xx = zeros(self.N, self.S); % N x S\n result = xx;\n self.Iterations = zeros(self.S, 1);\n self.CGResidualNorms = zeros(self.S, 1);\n self.Converged = false(self.S, 1);\n % Initial residual vectors\n rr = atbb - aa.apply_ctranspose(aa.apply(xx)); % N x S\n self.CGResiduals = rr;\n % Norm squared of initial residual vectors\n deltas = spx.norm.inner_product_cw(rr, rr);\n % The factor with which the norm needs to be reduced\n epsilon = self.NormThreshold;\n % Target limits on norm squared of residuals\n limits = epsilon^2 * deltas;\n % Maximum number of iterations for which the algorithm \n % is allowed to run\n imax = self.MaxIterations;\n % Number of problems being solved\n ns = self.S;\n for s=1:ns\n % Initialize iteration counter\n i = 0;\n % The quantities for this problem\n limit = limits(s);\n delta = deltas(s);\n % First residual\n r = rr(:, s); % N x 1.\n % First estimate\n x = xx(:, s); % N x 1.\n % Target b\n atb = atbb(:, s); % N x 1.\n % First direction\n d = r;\n while i < imax && delta > limit\n % Compute the intermediate variable\n p = aa.apply(d); % M x 1\n q = aa.apply_ctranspose(p); % N x 1\n % the line search scale factor in current direction\n % Note that d' * q = p' * p.\n alpha = delta / (p' * p);\n % Update estimate in current direction\n x = x + alpha * d;\n if mod(i , 50) == 0\n % In order to avoid propagation of floating point\n % errors, we will recompute the value of residual\n r = atb - aa.apply_ctranspose(aa.apply(x));\n else\n % Otherwise we use a shortcut\n r = r - alpha * q;\n end\n % hold the current residual norm squared\n delta_old = delta;\n % Update residual norm squared\n delta = r' * r;\n % Compute the ratio\n beta = delta / delta_old;\n % choose the new direction\n d = r + beta * d;\n % Increase iteration counter\n i = i + 1;\n end\n % The problem has been solved\n result(:, s) = x;\n % Number of iterations taken to solve this problem\n self.Iterations(s) = i;\n self.CGResidualNorms(s) = sqrt(delta);\n self.CGResiduals(:, s) = r;\n self.Converged(s) = delta <= limit;\n end\n % Maintain the result for reference\n self.X = result;\n % Compute the corresponding LS residuals\n self.LSResiduals = self.B - aa.apply(self.X);\n self.LSResidualNorms = spx.norm.norms_l2_cw(self.LSResiduals);\n end\n\n function result = hasConverged(self)\n % Returns if all the solutions have converged\n result = all(self.Converged);\n end\n\n function printResults(self)\n ns = self.S;\n nn = self.N;\n mm = self.N;\n for s = 1:ns\n fprintf('Problem: %d\\n', s);\n fprintf('Iterations: %d\\n', self.Iterations(s));\n fprintf('CG Residual norm: %.2f, LS Residual norm: %.2f, Converged: %d\\n', ...\n self.CGResidualNorms(s), self.LSResidualNorms(s), self.Converged(s));\n if nn < 10\n % We will print the solutions too\n fprintf('Solution vector: ');\n fprintf('%.4f ', self.X(:, s));\n fprintf('\\n');\n fprintf('CG Residual vector: ');\n fprintf('%.4f ', self.CGResiduals(:, s));\n fprintf('\\n');\n end\n if mm < 10\n fprintf('LS Residual vector: ');\n fprintf('%.4f ', self.LSResiduals(:, s));\n fprintf('\\n');\n end\n end\n end\n end\n\n\n methods(Access=private)\n % Private methods\n\n end\n\n\n\n methods(Static)\n % Public static methods\n\n\n end\n\n\nend\n", "meta": {"author": "indigits", "repo": "sparse-plex", "sha": "43cae2978f62938d001baaa03308a2a717ee6c9b", "save_path": "github-repos/MATLAB/indigits-sparse-plex", "path": "github-repos/MATLAB/indigits-sparse-plex/sparse-plex-43cae2978f62938d001baaa03308a2a717ee6c9b/library/+spx/+opt/convex_optimization/conjugate_gradient/SPX_CGLeastSquare.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.7249569256899041}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n% \n% \n% \n% problem 5 - convolution of x(t) and h(t) \n\n\nt1=0:.1:.9;\nt2=1:.1:3;\nt3=3.1:.1:5;\nx1=zeros(size(t1));\nx2=t2;\nx3=ones(size(t3));\nx=[x1 x2 x3];\nh1=zeros(size(t1));\nh2=exp(-t2);\nh3=zeros(size(t3));\nh=[h1 h2 h3];\ny=conv(x,h)*0.1;\nplot(0:.1:10,y);\nlegend('y(t)')\n\n\nfigure\nth=1:.01:3;\nh=exp(-th);\ntx1=1:.01:3;\nx1=tx1;\ntx2=3.01:.01:5;\nx2=ones(size(tx2));\nx=[x1 x2];\ny=conv(x,h)*0.01;\nplot(2:.01:8,y);\nlegend('y(t)')\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/4/c412e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7249569224610312}} {"text": "function D = mahalDist(x, m, C, use_log)\n% p=gaussian_prob(x, m, C, use_log)\n%\n% Evaluate the multi-variate density with mean vector m and covariance\n% matrix C for the input vector x.\n% Vectorized version: Here X is a matrix of column vectors, and p is \n% a vector of probabilities for each vector.\n\nif nargin<4, use_log = 0; end\n\nd = length(m);\n\nif size(x,1)~=d\n x=x';\nend\nN = size(x,2);\n\nm = m(:);\nM = m*ones(1,N);\ndenom = (2*pi)^(d/2)*sqrt(abs(det(C)));\ninvC = inv(C);\nmahal = sum(((x-M)'*invC).*(x-M)',2); % Chris Bregler's trick\n\nswitch use_log,\ncase 2,\n D = mahal;\ncase 1,\n D = -0.5*mahal - log(denom);\ncase 0,\n numer = exp(-0.5*mahal);\n D = numer/denom;\notherwise\n error('Unsupported log type')\nend\n\n", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/_internal/metrics/mahalDist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.724956917527753}} {"text": "function [spath,mpath,stdpath,fwd,stdfwd,xpath,epath,r1,r2]=schwartzsmithsim(start,param,ftemp,T,rmatrix,sim)\nkappa=param(1);\nmue=param(2);\nsigmax=param(3);\nsigmae=param(4);\nlambdae=param(5);\nlambdax=param(6);\npxe=param(7);\nx0=param(8);\ne0=param(9);\n \n \niter=start;\nfor k=1:length(T)\n loc=mod(iter,12);\n \n if loc==0\n f(k)=ftemp(12);\n else\n f(k)=ftemp(loc);\n end\n iter=iter+1;\nend\n \nfor i=1:length(T)\n explns(i,1)=exp(-kappa*T(i))*x0+e0-((1-exp(-kappa*T(i)))*lambdax/kappa)+(mue-lambdae)*T(i);\n varlns(i,1)=((1-exp(-2*kappa*T(i)))*sigmax^2/(2*kappa))+sigmae^2*T(i)+2*(1-exp(-kappa*T(i)))*pxe*sigmax*sigmae/kappa;\n fwd(i,1)=f(i)*exp(explns(i,1)+.5*varlns(i,1));\n varlnfwd(i,1)= T(i)*(sigmae)^2 + (1-exp(-2*kappa*T(i)))*(sigmax^2)/(2*kappa) + 2*(1-exp(-kappa*T(i)))*pxe*sigmax*sigmae/kappa;\n stdfwd(i,1)=f(i)*sqrt((exp(varlnfwd(i,1))-1)*exp(2*explns(i,1)+varlnfwd(i,1)));\n stdspot(i,1)=f(i)*sqrt((exp(varlnfwd(i,1))-1)*exp(2*explns(i,1)+varlnfwd(i,1)));\n ve(i,1)=sigmae^2*T(i);\n vx(i,1)=(1-exp(-2*kappa*T(i)))*(.5*sigmax^2)/kappa;\nend\n\n\nm=length(T);\n\nr1(:,:)=rmatrix;\nr2(:,:)=pxe.*r1(:,:)+sqrt(1-pxe^2).*randn(sim,m); \n \nfor i=1:sim\n \nx(1)=x0-lambdax*T(1)-kappa*x0*T(1)+sigmax*sqrt(T(1))*r1(i,1);\ne(1)=e0+(mue-lambdae)*T(1)+sigmae*sqrt(T(1))*r2(i,1);\ns(1)=f(1)*exp(e(1)+x(1));\n\nfor t=1:m-1\n x(t+1)=x(t)-lambdax*(T(t+1)-T(t))-kappa*x(t)*(T(t+1)-T(t))+sigmax*sqrt((T(t+1)-T(t)))*r1(i,t+1);\n e(t+1)=e(t)+(mue-lambdae)*(T(t+1)-T(t))+sigmae*sqrt((T(t+1)-T(t)))*r2(i,t+1);\n s(t+1)=f(t+1)*exp(e(t+1)+x(t+1));\nend\nepath(i,:)=e(1:end);\nxpath(i,:)=x(1:end);\nspath(i,:)=s(1:end);\nlspath(i,:)=log(s(1:end));\nc(i)=corr(r1(i,:)',r2(i,:)');\nc2(i)=corr(xpath(i,:)',epath(i,:)');\nend\nevar = var(epath)';\nxvar = var(xpath)';\n \n%E(S(T))=E(F(T,T))\nmpath=mean(spath)'; \n%V(ln(S(T)))=V[ln(F(T,T)]\nvarlnpath=var(lspath)';\n%E(ln(S(T)))=E[ln(F(T,T)]\nmlnpath=mean(lspath)';\nstdpath=sqrt((exp(varlnpath)-1).*exp(2*mlnpath+varlnpath));\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/31381-calibration-of-forward-price-volatility-and-correlations-across-multiple-assets/MultiAsset Calibration/schwartzsmithsim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948494, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7249569053320067}} {"text": "function inurbs = nrbdegelev(nurbs, ntimes) \n% \n% Function Name: \n% \n% nrbdegelev - Elevate the degree of the NURBS curve or surface. \n% \n% Calling Sequence: \n% \n% ecrv = nrbdegelev(crv,utimes); \n% esrf = nrbdegelev(srf,{utimes,vtimes}); \n% \n% Parameters: \n% \n% crv\t\t: NURBS curve, see nrbmak. \n% \n% srf\t\t: NURBS surface, see nrbmak. \n% \n% utimes\t: Increase the degree along U direction utimes. \n% \n% vtimes\t: Increase the degree along V direction vtimes. \n% \n% ecrv\t: new NURBS structure for a curve with degree elevated. \n% \n% esrf : new NURBS structure for a surface with degree elevated. \n% \n% \n% Description: \n% \n% Degree elevates the NURBS curve or surface. This function uses the \n% B-Spline function bspdegelev, which interface to an internal 'C' \n% routine. \n% \n% Examples: \n% \n% Increase the NURBS surface twice along the V direction. \n% esrf = nrbdegelev(srf, 0, 1); \n% \n% See: \n% \n% bspdegelev \n \n% D.M. Spink \n% Copyright (c) 2000. \n \nif nargin < 2 \n error('Input argument must include the NURBS and degree increment.'); \nend \n \nif ~isstruct(nurbs) \n error('NURBS representation is not structure!'); \nend \n \nif ~strcmp(nurbs.form,'B-NURBS') \n error('Not a recognised NURBS representation'); \nend \n \ndegree = nurbs.order-1; \n \nif iscell(nurbs.knots) \n % NURBS represents a surface \n [dim,num1,num2] = size(nurbs.coefs); \n \n % Degree elevate along the v direction \n if ntimes(2) == 0 \n coefs = nurbs.coefs; \n knots{2} = nurbs.knots{2}; \n else \n coefs = reshape(nurbs.coefs,4*num1,num2); \n [coefs,knots{2}] = bspdegelev(degree(2),coefs,nurbs.knots{2},ntimes(2)); \n num2 = size(coefs,2); \n coefs = reshape(coefs,[4 num1 num2]); \n end \n \n % Degree elevate along the u direction \n if ntimes(1) == 0 \n knots{1} = nurbs.knots{1}; \n else \n coefs = permute(coefs,[1 3 2]); \n coefs = reshape(coefs,4*num2,num1); \n [coefs,knots{1}] = bspdegelev(degree(1),coefs,nurbs.knots{1},ntimes(1)); \n coefs = reshape(coefs,[4 num2 size(coefs,2)]); \n coefs = permute(coefs,[1 3 2]); \n end \n \nelse \n \n % NURBS represents a curve \n if isempty(ntimes) \n coefs = nurbs.coefs; \n knots = nurbs.knots; \n else \n [coefs,knots] = bspdegelev(degree,nurbs.coefs,nurbs.knots,ntimes); \n end \n \nend \n \n% construct new NURBS \ninurbs = nrbmak(coefs,knots); \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/26390-nurbs-toolbox-by-d-m-spink/nurbs_toolbox/nrbdegelev.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.72492406793683}} {"text": "function determ = gk324_determinant ( n, x )\n\n%*****************************************************************************80\n%\n%% GK324_DETERMINANT returns the determinant of the GK324 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 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, real X(N-1), the first N-1 entries of the\n% last row.\n%\n% Output, real DETERM, the determinant.\n%\n determ = prod ( 1.0 - x(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_mat/gk324_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7249240585873917}} {"text": "% Figure 3.24 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%script to generate Fig. 3.24\n\n\nclf;\nzeta=.5;\nk=1/zeta;\nden=[1 1 1];\n\na=10;\nnum=[k/a 1];\nt=0:.1:10;\ny1=step(num,den,t);\n\na=4;\nnum=[k/a 1];\nt=0:.1:10;\ny2=step(num,den,t);\n\na=2;\nnum=[k/a 1];\nt=0:.1:10;\ny3=step(num,den,t);\n\na=1;\nnum=[k/a 1];\nt=0:.1:10;\ny4=step(num,den,t);\n\nplot(t,y1,'-',t,y2,'-',t,y3,'-',t,y4,'-'),grid\ntitle('Fig. 3.24 Step response with \\xi = 0.5')\nxlabel('\\omega_n t')\nylabel('Step response of H(s)')\ntext(.1,.9,'\\alpha=')\ntext(.6,.9,'1')\ntext(1.1,.9,'2')\ntext(1.5,.85,'4')\ntext(1.8,.8,'100')", "meta": {"author": "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/fig3_24.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.7853085834000791, "lm_q1q2_score": 0.7248705802049182}} {"text": "function [y,deriv] = neg_gaussll_taylor(w,x)\n% This is an MV2DF. See MV2DF_API_DEFINITION.readme.\n% This function represents the part of log N(x|0,W) that is dependent on \n% W = reshape(w,...), where w is variable and x is given. \n%\n% y = -0.5*x'*inv(W)*x - 0.5*log(det(W)), where W is positive definite and W = reshape(w,...)\n\n\nif nargin==0\n test_this();\n return;\nend\n\nif isempty(w)\n y = @(w)neg_gaussll_taylor(w,x);\n return;\nend\n\nif isa(w,'function_handle')\n outer = neg_gaussll_taylor([],x);\n y = compose_mv(outer,w,[]);\n return;\nend\n\ndim = length(x);\nW = reshape(w,dim,dim);\n\n[inv_map,logdet] = invchol_taylor(W);\nz = inv_map(x);\ny = 0.5*x'*z + 0.5*logdet;\nderiv = @(dy) deriv_this(dy,z,inv_map);\n\nend\n\nfunction [g,hess,linear] = deriv_this(dy,z,inv_map)\nG1 = z*z.';\nG2 = inv_map(eye(length(z)));\ngrad = 0.5*(G2(:)-G1(:));\ng = dy*grad;\nlinear = false;\nhess = @(d) hess_this(grad,z,inv_map,dy,d);\nend\n\n\nfunction [h,Jd] = hess_this(grad,z,inv_map,dy,d)\ndim = sqrt(length(d));\nD = reshape(d,dim,dim);\nH1 = inv_map(D*z)*z' + z*inv_map(D'*z)';\nH2 = inv_map(inv_map(D)');\nh = 0.5*dy*(H1(:)-H2(:));\nif nargout>1 \n Jd = grad.'*d(:);\nend\nend\n\n\n\nfunction test_this()\nm = 3;\nn = 10;\n\nw = [];\nA = UtU(w,n,m); %A is m-by-m\nx = randn(m,1);\n\nf = neg_gaussll_taylor(A,x);\nw = randn(m*n,1);\n\ntest_MV2DF(f,w,true);\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/Optimization_Toolkit/MV2DF/function_library/scalar/neg_gaussll_taylor.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7248705758736024}} {"text": "function [P,Gvec] = autoGen_getPoints(q1,q2,q3,q4,q5,l1,l2,l3,l4,l5,c1,c2,c3,c4,c5)\n%AUTOGEN_GETPOINTS\n% [P,GVEC] = AUTOGEN_GETPOINTS(Q1,Q2,Q3,Q4,Q5,L1,L2,L3,L4,L5,C1,C2,C3,C4,C5)\n\n% This function was generated by the Symbolic Math Toolbox version 6.2.\n% 22-Oct-2015 19:14:40\n\nt2 = sin(q1);\nt3 = cos(q1);\nt4 = l1.*t3;\nt5 = sin(q2);\nt6 = cos(q2);\nt7 = l2.*t6;\nt8 = sin(q4);\nt9 = l4.*t8;\nt10 = cos(q4);\nt11 = sin(q3);\nt12 = cos(q3);\nt13 = l3.*t12;\nt14 = sin(q5);\nt15 = cos(q5);\nP = [-l1.*t2;t4;-l1.*t2-l2.*t5;t4+t7;-l1.*t2-l2.*t5-l3.*t11;t4+t7+t13;t9-l1.*t2-l2.*t5;t4+t7-l4.*t10;t9-l1.*t2-l2.*t5+l5.*t14;t4+t7-l4.*t10-l5.*t15];\nif nargout > 1\n Gvec = [c1.*t2-l1.*t2;t4-c1.*t3;c2.*t5-l1.*t2-l2.*t5;t4+t7-c2.*t6;c3.*t11-l1.*t2-l2.*t5-l3.*t11;t4+t7+t13-c3.*t12;c4.*t8-l1.*t2-l2.*t5;t4+t7-c4.*t10;t9+c5.*t14-l1.*t2-l2.*t5;t4+t7-c5.*t15-l4.*t10];\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/fiveLinkBiped/autoGen_getPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7248705712356609}} {"text": "function [ x, w ] = laguerre_ek_compute ( n )\n\n%*****************************************************************************80\n%\n%% LAGUERRE_EK_COMPUTE: Laguerre quadrature rule by the Elhay-Kautsky method.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 April 2011\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer N, the order.\n%\n% Output, real X(N), the abscissas.\n%\n% Output, real W(N), the weights.\n%\n\n%\n% Define the zero-th moment.\n%\n zemu = 1.0;\n%\n% Define the Jacobi matrix.\n%\n bj = zeros ( n, 1 );\n\n for i = 1 : n\n bj(i) = i;\n end\n\n x = zeros ( n, 1 );\n for i = 1 : n\n x(i) = 2 * i - 1;\n end\n\n w = zeros ( n, 1 );\n w(1) = sqrt ( zemu );\n%\n% Diagonalize the Jacobi matrix.\n%\n [ x, w ] = imtqlx ( n, x, bj, w );\n\n w(1:n) = w(1:n).^2;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule/laguerre_ek_compute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.724823046055107}} {"text": "function zi=interptri(tri,x,y,z,xi,yi)\n% INTERPTRI Interpolate Triangulation.\n% Zi = INTERPTRI(TRI,X,Y,Z,Xi,Yi) linearly interpolates the scattered data\n% in vectors X,Y,Z as described by the triangulation TRI as returned by\n% DELAUNAY at the individual pairs of points in Xi and Yi. That is, Zi(k)\n% is the linear interpolation at the point (Xi(k),Yi(k)). Xi and Yi are not\n% MESHGRIDed as they are in GRIDDATA when Xi is a row vector and and Yi is\n% a column vector. Use MESHGRID when desired. For example,\n% [Xii,Yii] = MESHGRID(Xi,Yi); % meshgrid yourself\n% Zi = INTERPTRI(TRI,x,y,z,Xii,Yii);\n% is the same as Zi = GRIDDATA(x,y,z,Xi(:).',Yi(:));\n% \n% INTERPTRI is faster than GRIDDATA when the same data is interpolated more\n% than once because the triangulation TRI is precomputed and passed into\n% INTERPTRI, whereas it is computed within GRIDDATA each time it is called.\n%\n% See also GRIDDATA, MESHGRID, DELAUNAY, TRIPLOT, TRIMESH, TRISURF, TSEARCH\n\n% D.C. Hanselman, University of Maine, Orono, ME 04469\n% MasteringMatlab@yahoo.com\n% Mastering MATLAB 7\n% 2006-05-03\n\nif nargin~=6\n error('Six Input Arguments Required.')\nend\nx=x(:); % make input data into vectors\ny=y(:);\nz=z(:).';\nxlen=length(x);\nif ~isequal(xlen,length(y),length(z))\n error('X, Y, and Z Must Have the Same Number of Elements.')\nend\nif size(tri,2)~=3 || any(tri(:)<0) || any(tri(:)>xlen)\n error('TRI Must Be a Valid Triangulation of the Data in X, Y, Z.')\nend\n\nzisiz=size(xi);\nxi=xi(:);\nyi=yi(:);\nif length(xi)~=length(yi)\n error('Xi and Yi Must Have the Same Number of Elements.')\nend\n%ti=tsearch(x,y,tri,xi,yi); % find triangle associated with each data point.\n\n% use tsearchn because tsearch is now gone\nti=tsearchn([x y],tri,[xi yi]);\n\ntinan=isnan(ti); % True for xi, yi outside the convex hull\nti(tinan)=1; % point nan points to triangle one for now\ntri=tri(ti,:); % keep only those triangles where xi and yi exist\n\nx1=x(tri(:,1)); % x data at vertices\nx2=x(tri(:,2));\nx3=x(tri(:,3));\ny1=y(tri(:,1)); % y data at vertices\ny2=y(tri(:,2));\ny3=y(tri(:,3));\n\nA2=(x2-x1).*(y3-y1) - (x3-x1).*(y2-y1); % shape functions\nN(:,3)=((x1-xi).*(y2-yi) - (x2-xi).*(y1-yi))./A2;\nN(:,2)=((x3-xi).*(y1-yi) - (x1-xi).*(y3-yi))./A2;\nN(:,1)=((x2-xi).*(y3-yi) - (x3-xi).*(y2-yi))./A2;\nN(tinan,:)=0; % give zero weight to nan data\nzi = sum(z(tri).*N,2); % interpolate\nzi(tinan)=nan; % poke in nans where needed\nzi=reshape(zi,zisiz); % reshape output to match xi and yi input", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Other/Utilities/interptri/interptri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7248179185606274}} {"text": "function [ x, w ] = tetrahedron_arbq ( degree, n )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_ARBQ returns a quadrature rule for a tetrahedron.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 July 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This 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 degree of exactness.\n% 1 <= DEGREE <= 15.\n%\n% Input, integer N, the number of points in the rule.\n% This value should be requested first from TETRAHEDRON_ARBQ_SIZE.\n%\n% Output, real X(3,N), the quadrature nodes.\n%\n% Output, real W(N), the quadrature weights.\n%\n if ( degree == 1 )\n [ x, w ] = rule01 ( n );\n elseif ( degree == 2 )\n [ x, w ] = rule02 ( n );\n elseif ( degree == 3 )\n [ x, w ] = rule03 ( n );\n elseif ( degree == 4 )\n [ x, w ] = rule04 ( n );\n elseif ( degree == 5 )\n [ x, w ] = rule05 ( n );\n elseif ( degree == 6 )\n [ x, w ] = rule06 ( n );\n elseif ( degree == 7 )\n [ x, w ] = rule07 ( n );\n elseif ( degree == 8 )\n [ x, w ] = rule08 ( n );\n elseif ( degree == 9 )\n [ x, w ] = rule09 ( n );\n elseif ( degree == 10 )\n [ x, w ] = rule10 ( n );\n elseif ( degree == 11 )\n [ x, w ] = rule11 ( n );\n elseif ( degree == 12 )\n [ x, w ] = rule12 ( n );\n elseif ( degree == 13 )\n [ x, w ] = rule13 ( n );\n elseif ( degree == 14 )\n [ x, w ] = rule14 ( n );\n elseif ( degree == 15 )\n [ x, w ] = rule15 ( n );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TETRAHEDRON_ARBQ - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of DEGREE.\\n' );\n error ( 'TETRAHEDRON_ARBQ - Fatal error!' );\n end\n\n d = sum ( w(1:n) );\n\n volume = sqrt ( 8.0 ) / 3.0;\n w(1:n) = w(1:n) * volume / 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/tetrahedron_arbq_rule/tetrahedron_arbq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.724817912724832}} {"text": "function value = conex2_condition ( alpha )\n\n%*****************************************************************************80\n%\n%% CONEX2_CONDITION returns the L1 condition of the CONEX1 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 February 2015\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.\n%\n% Output, real VALUE, the L1 condition.\n%\n c1 = 1.0;\n c2 = abs ( 1.0 - 1.0 / alpha^2 ) + 1.0 / abs ( alpha );\n c3 = 3.0 + 1.0 / abs ( alpha );\n a_norm = max ( c1, max ( c2, c3 ) );\n c1 = 1.0;\n c2 = abs ( ( 1.0 - alpha * alpha ) / alpha ) + abs ( alpha );\n c3 = abs ( ( 1.0 + alpha * alpha ) / alpha ^ 2 ) + 2.0;\n b_norm = max ( c1, max ( c2, c3 ) );\n value = a_norm * b_norm;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/conex2_condition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7248179118988312}} {"text": "function fx = p14_fx ( x )\n\n%*****************************************************************************80\n%\n%% P14_FX evaluates the Camel.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 July 2011\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 FX(*), the value of the function at X.\n%\n fx = 1.0 ./ ( ( x - 0.3 ).^2 + 0.01 ) ...\n + 1.0 ./ ( ( x - 0.9 ).^2 + 0.04 ) ...\n + 2.0 * x - 5.2;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_zero/p14_fx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.724817909953566}} {"text": "function stage = BOPointInPolygon( P, q )\n%% BOPointInPolygon - find point in polygon\n% \n% REFERENCE:\n% This code is described in \"Computational Geometry in C\", Chapter 7. \n% The Matlab version is based on C code written by Joseph O'Rourke, \n% contributions by Min Xu, June 1997. \n%\n% INPUT:\n% P - input vector Nx2\n% q - input query vector 1x2\n%\n% OUTPUT:\n% stage - output stage:\n% 'v' - q is a vertex\n% 'i' - q is inside\n% 'o' - q is outside\n% 'e' - q on the edge\n% USAGE:\n% t = 0:0.6:6.28;\n% seedx = 100; seedy = 100; scalefactor = 20;\n% P(:,1) = (seedx(1) + scalefactor*cos(t))';\n% P(:,2) = (seedy(1) + scalefactor*sin(t))';\n% PP = [P; P(1,:)];\n% plot(PP(:,1),PP(:,2),'-bs'); hold on\n% q = PP(10,:);\n% plot(q(:,1),q(:,2),'r*');\n% stage = BOPointInPolygon(PP,q);\n% \n% AUTHOR:\n% Boguslaw Obara, http://boguslawobara.net/\n%\n% VERSION:\n% 0.1 - 25/05/2008 First implementation\n% \n\n%% \n% i, i1 - point index; i1 = i-1 mod n\n% d - dimension index\n% x - x intersection of e with ray\n% Rcross - number of right edge/ray crossings\n% Lcross - number of left edge/ray crossings\n%%\nRcross = 0; Lcross = 0;\nn = length(P);\n%%\n% Shift so that q is the origin. Note this destroys the polygon.\nfor i=1:n\n for d=1:2\n P(i,d) = P(i,d) - q(d);\n end\nend\n%%\t\n% For each edge e=(i-1,i), see if crosses ray.\nfor i=1:n\n % First see if q=(0,0) is a vertex.\n if P(i,1)==0 && P(i,2)==0 \n stage = 'v';\n return; \n end\n i1 = mod((i + n - 2), n) + 1;\n \n % if e \"straddles\" the x-axis... \n % The commented-out statement is logically equivalent to the one following. \n % if( ((P(i,2)>0) && (P(i1,2)<=0)) || ((P(i1,2)>0) && (P(i,2)<=0)) \n\n if (P(i,2)>0) ~= (P(i1,2)>0)\n % e straddles ray, so compute intersection with ray.\n x = (P(i,1) * P(i1,2) - P(i1,1) * P(i,2)) / (P(i1,2) - P(i,2));\n \n % crosses ray if strictly positive intersection.\n if x>0\n Rcross = Rcross + 1; \n end\n end\n \n % if e straddles the x-axis when reversed...\n % if ((P(i,2)<0) && (P(i1,2)>=0)) || ((P(i1,2)<0) && (P(i,2)>=0) \n \n if (P(i,2) < 0) ~= (P(i1,2) < 0) \n % e straddles ray, so compute intersection with ray.\n x = (P(i,1) * P(i1,2) - P(i1,1) * P(i,2)) / (P(i1,2) - P(i,2));\n % crosses ray if strictly positive intersection.\n if (x < 0) \n Lcross = Lcross + 1;\n end\n end\nend\t\n%% \n% q on the edge if left and right cross are not the same parity.\nif mod(Rcross,2) ~= mod(Lcross,2)\n stage = 'e';\n return;\nend\n% q inside if an odd number of crossings.\nif mod(Rcross,2) == 1\n stage = 'i';\n return;\nelse\n stage = 'o';\n return;\nend\n%%\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/21621-find-point-position-in-2d-polygon/BOPointInPolygon/BOPointInPolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.7248179029985061}} {"text": "function [x_g,w_g,phi,p_x,p_y] = twod_shapeiso(x_local,r,s,w)\n%-----------------------------------------------------------------------\n% twod_shapeiso.m - computes test functions and derivatives on an\n% element given element coordinates and Gauss points.\n% \n% ! Note: specifically set up for isoparametric\n% ! elements. Use `twod_shape' for linear elements.\n%\n% Copyright (c) 2001, Jeff Borggaard, Virginia Tech\n% Version: 1.0\n%\n% Usage: [x_g,w_g,phi,p_x,p_y] = twod_shapeiso(x_local,r,w)\n%\n% Variables: x_local\n% Coordinates of the element nodes\n% (r,s)\n% Coordinates of Gauss points in unit triangle\n% w\n% Gauss weights associated with (r,s)\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% First spatial derivatives of phi\n% p_xx\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 2\n rule = length(r);\n \n if (n == 6)\n % Transform coordinates for quadratic element\n c0 = x(1,:);\n c1 =-3.*x(1,:) - x(2,:) + 4.*x(4,:);\n c2 =-3.*x(1,:) - x(3,:) + 4.*x(6,:);\n c3 = 2.*x(1,:) + 2.*x(2,:) - 4.*x(4,:);\n c4 = 4.*x(1,:) - 4.*x(4,:) + 4.*x(5,:) - 4.*x(6,:);\n c5 = 2.*x(1,:) + 2.*x(3,:) - 4.*x(6,:);\n \n x_g(:,1) = c0(1) + c1(1)*r + c2(1)*s + c3(1)*r.*r +...\n c4(1)*r.*s + c5(1)*s.*s;\n xr = c1(1) + 2.*c3(1)*r + c4(1)*s;\n xs = c2(1) + c4(1)*r + 2.*c5(1)*s;\n \n x_g(:,2) = c0(2) + c1(2)*r + c2(2)*s + c3(2)*r.*r +...\n c4(2)*r.*s + c5(2)*s.*s;\n yr = c1(2) + 2.*c3(2)*r + c4(2)*s;\n ys = c2(2) + c4(2)*r + 2.*c5(2)*s;\n \n w_g = (xr.*ys-yr.*xs).*w;\n\n % Compute the Jacobian of the (r,s) -> (x,y) transformation\n jac = 1./( xr.*ys - yr.*xs );\n rx = ys.*jac;\n sx =-yr.*jac;\n ry =-xs.*jac;\n sy = xr.*jac;\n\n % Compute shape function and derivatives at Gauss points\n phi = zeros(rule,n);\n phi(:,1) = 1. - 3.*r - 3.*s + 2.*r.*r + 4.*r.*s + 2.*s.*s;\n phi(:,2) = - 1.*r + 2.*r.*r ;\n phi(:,3) = - 1.*s + 2.*s.*s;\n phi(:,4) = 4.*r - 4.*r.*r - 4.*r.*s ;\n phi(:,5) = 4.*r.*s ;\n phi(:,6) = 4.*s - 4.*r.*s - 4.*s.*s;\n \n p_x = zeros(rule,n);\n p_x(:,1) = ( -3. + 4.*r + 4.*s ).*rx + ( -3. + 4.*r + 4.*s ).*sx;\n p_x(:,2) = ( -1. + 4.*r ).*rx ;\n p_x(:,3) = ( -1. + 4.*s ).*sx;\n p_x(:,4) = ( 4. - 8.*r - 4.*s ).*rx + ( - 4.*r ).*sx;\n p_x(:,5) = ( 4.*s ).*rx + ( 4.*r ).*sx;\n p_x(:,6) = ( - 4.*s ).*rx + ( 4. - 4.*r - 8.*s ).*sx;\n \n p_y = zeros(rule,n);\n p_y(:,1) = ( -3. + 4.*r + 4.*s ).*ry + ( -3. + 4.*r + 4.*s ).*sy;\n p_y(:,2) = ( -1. + 4.*r ).*ry ;\n p_y(:,3) = ( -1. + 4.*s ).*sy;\n p_y(:,4) = ( 4. - 8.*r - 4.*s ).*ry + ( - 4.*r ).*sy;\n p_y(:,5) = ( 4.*s ).*ry + ( 4.*r ).*sy;\n p_y(:,6) = ( - 4.*s ).*ry + ( 4. - 4.*r - 8.*s ).*sy;\n else\n fprintf('element not supported');\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/twod/twod_shapeiso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533144915913, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7247958367166509}} {"text": "\n% PartitionTable.m by David Terr, Raytheon, 6-7-04\n\n% Given nonnegative integer n, compute the unrestricted partition function p(k) for k<=n.\nfunction pt = partitiontable(n)\n\nif n==0 \n pt = 1;\n return;\nend\n\npt = zeros( n+1, 2 );\npt( n+1, 1 ) = n;\n\n% Precompute tables of (-1)^k and k*(3k +/- 1)/2.\ns = sqrt( 24*n + 1 );\nkp = floor( ( s - 1 ) / 6 );\nkm = floor( ( s + 1 ) / 6 );\ntp = zeros( kp );\ntm = zeros( km );\n\nfor k = 1:kp\n tp( k ) = k*(3*k+1)/2;\nend\n\nfor k = 1:km\n tm( k ) = k*(3*k-1)/2;\nend\n\n% Compute p(m) for all m <= n.\npt( 1, 2 ) = 1;\n\nfor m=1:n\n pt(m,1) = m-1;\n s = sqrt( 24*m + 1 );\n kp = floor( ( s - 1 ) / 6 );\n km = floor( ( s + 1 ) / 6 );\n \n for k = 1:kp\n pt( m+1, 2 ) = pt( m+1, 2 ) + (-1)^(k+1) * pt( m + 1 - tp(k), 2 );\n end\n \n for k = 1:km\n pt( m+1, 2 ) = pt( m+1, 2 ) + (-1)^(k+1) * pt( m + 1 - tm(k), 2 );\n end\nend\n \n \n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/5154-partitiontable-m/PartitionTable.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7247802147665274}} {"text": "function f = spm_Dpdf(x,a)\n% Probability Density Function (PDF) of Dirichlet distribution\n% FORMAT f = spm_Dpdf(x,a)\n% \n% x - Dirichlet variate\n% a - Dirichlet parameters (a>0)\n% f - PDF of Dirichlet-distribution at point x\n%__________________________________________________________________________\n%\n% spm_Dpdf implements the Probability Density Function for Dirichlet \n% distribution.\n%\n% Definition:\n%--------------------------------------------------------------------------\n% See http://en.wikipedia.org/wiki/Dirichlet_distribution\n%\n% Algorithm:\n%--------------------------------------------------------------------------\n% Direct computation using logs and MATLAB's implementation of the log of \n% the gamma function (gammaln).\n%__________________________________________________________________________\n% Copyright (C) 2008-2011 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny\n% $Id: spm_Dpdf.m 4182 2011-02-01 12:29:09Z guillaume $\n\n%-Check enough arguments\n%--------------------------------------------------------------------------\nif nargin<2, error('Insufficient arguments'), end\n\n%-Computation\n%--------------------------------------------------------------------------\na = a(:);\nx = x(:);\n\nf = exp( gammaln(sum(a)) + sum((a-1).*log(x+eps)) - sum(gammaln(a)) );\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_Dpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7247802068640953}} {"text": "function y = log_normcdf( x, approx ) %#ok\n\n%LOG_NORMCDF Logarithm of the cumulative normal distribution.\n% Y = LOG_NORMCDF(X) is the logarithm of the CDF of the normal\n% distribution at the point X.\n%\n% 1 / x\n% LOG_NORMCDF(X) = LOG( ------- | exp(-t^2/2) dt )\n% sqrt(2) / -Inf\n%\n% For numeric X, LOG_NORMCDF(X) is computed using the equivalent \n% expression LOG(0.5*ERFC(-X*SQRT(0.5))). When X is a CVX variable, a \n% a piecewise quadratic *approximation* is employed instead. This\n% approximation gives good results when -4 <= x <= 4, and will be\n% improved in future releases of CVX.\n%\n% For array values of X, the LOG_NORMCDF returns an array of identical\n% size with the calculation applied independently to each element.\n%\n% X must be real.\n%\n% Disciplined convex programming information:\n% LOG_NORMCDF is concave and nondecreasing in X. Therefore, when used\n% in CVX specifications, X must be concave.\n\nnarginchk(1,2);\nif ~isreal( x ),\n error( 'Argument must be real.' );\nend\nif nargin > 1,\n % For debugging purposes only\n y = cvx_constant(log_normcdf(cvx(x)));\nelse\n y = log(0.5*erfc(-x*sqrt(0.5)));\nend\n\n% Copyright 2005-2016 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/functions/log_normcdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7247802032529568}} {"text": "function [vOut,data]=getNextMultipartition(data)\n%%GETNEXTMULTIPARTITION Get the next multipartition of a set of elements\n% with possible repeats, or get the first multipartition in the\n% sequence. The multipartitions are given in decreasing\n% lexicographic order.\n%\n%INPUTS: data If the first multipartition is desired, then this is an mX1\n% or 1Xm vector containing how many times each element in the\n% set to be partitioned is repeated. For example, if one wishes\n% to partition the set (1,2,3,4), then this is [1;1;1;1]. For\n% the set [1;2;2;2;3;3;4], then this is [1;3;2;1]. Otherwise,\n% if one wishes to get the next multipartition in the sequence,\n% then this is the data variable returned from the previous\n% call to this function.\n%\n%OUTPUTS: vOut This is the current multipartition, or an empty vector if\n% one has passed the final multipartition in the sequence. The\n% multipartition is an mXnumParts matrix. The number of\n% columns is the number of parts of the partition. Each column\n% has the number of repeats of each item (corresponding to the\n% positions in the original data passed). See the examples\n% below for more explanation.\n% data This is a structure that can be passed to this function to\n% get the next multipartition in the sequence.\n% \n%This function implements Algorithm M of Chapter 7.2.1.5 of [1].\n%\n%As an example, there are nine multipartitions of the set (1,1,2,2). These\n%are\n%(1,1,2,2); (1,1,2),(2); (1,1),(2,2); (1,1),(2),(2); (1,2,2),(1);\n%(1,2),(1,2); (1,2),(1),(2); (1),(1),(2,2); (1),(1),(2),(2)\n%However, represented in terms of the output vOut, we have 9 matrices:\n% [2; [2,0; [2,0; [2,0,0; [1,1; [1,1; [1,1,0; [1,1,0; [1,1,0,0\n% 2] 1,1] 0,2] 0,1,1] 2,0] 1,1] 1,0,1] 0,0,2] 0,0,1,1]\n%The example below shows how to use this function and how to display the\n%outputs in a more recognizable form as partitions.\n%\n%EXAMPLE:\n%Here, we display all multipartitions of 1123, which means that n=[2;1;1].\n% vTotal=[1;1;2;3];\n% vUnique=unique(vTotal);\n% n=[2;1;1];\n% m=length(n);\n% [vOut,data]=getNextMultipartition(n);\n% while(~isempty(vOut))\n% %Display the current multipartition.\n% %We will build a string showing the partitions. of [1,1,2,3].\n% strDisp=[];\n% \n% numParts=size(vOut,2);\n% for curPart=1:numParts\n% strDisp=[strDisp,sprintf('(')];\n% for k=1:m\n% for i=1:vOut(k,curPart)\n% strDisp=[strDisp,sprintf('%i',vUnique(k))];\n% end\n% end\n% strDisp=[strDisp,sprintf(')')];\n% end\n% disp(strDisp)\n% \n% %Get the next one.\n% [vOut,data]=getNextMultipartition(data);\n% end\n%\n%REFERENCES:\n%[1] D. E. Knuth, The Art of Computer Programming. Vol. 4, Fascicle 3:\n% Generating all Combinations and Partitions, Upper Saddle River, NJ:\n% Addison-Wesley, 2009.\n%\n%February 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%If the first multipartition is desired.\nif(~isstruct(data))\n n=data;\n data=[];\n\n m=length(n);\n nSum=sum(n);\n \n data.nSum=nSum;\n data.m=m;\n\n %Allocate space\n f=zeros(nSum+1,1);\n c=zeros(m*nSum+1,1);\n u=zeros(m*nSum+1,1);\n v=zeros(m*nSum+1,1);\n\n %Step M1\n c(1:m)=1:m;\n u(1:m)=n(1:m);\n v(1:m)=n(1:m);\n f(0+1)=0;\n a=0;\n l=0;\n\n f(1+1)=m;\n b=m;\nelse\n %If the algorithm is finished.\n if(data.algFinished)\n vOut=[];\n return;\n end\n \n f=data.f;\n c=data.c;\n u=data.u;\n v=data.v;\n a=data.a;\n b=data.b;\n l=data.l;\n m=data.m;\n nSum=data.nSum;\nend\n\nwhile(1)\n %Step M2\n j=a;\n k=b;\n x=0;\n\n while(jb)\n a=b;\n b=k;\n l=l+1;\n f(l+1+1)=b;\n continue;%Return to M2\n end\n\n %Step M4, visit the partition\n numOut=0;\n vOut=zeros(m,nSum);%Allocate the maximum possible space needed.\n for k=0:l\n numOut=numOut+1;\n for j=f(k+1):(f(k+1+1)-1)\n vOut(c(j+1),numOut)=v(j+1);\n end\n end\n vOut=vOut(:,1:numOut);\n \n %Step M5\n while(1)\n \n j=b-1;\n while(v(j+1)==0)\n j=j-1; \n end\n\n if(~(j==a&&v(j+1)==1))\n v(j+1)=v(j+1)-1;\n\n for k=(j+1):(b-1)\n v(k+1)=u(k+1); \n end\n\n %Return to M2 to visit the next one, so return from this\n %function.\n data.f=f;\n data.c=c;\n data.u=u;\n data.v=v;\n data.a=a;\n data.b=b;\n data.l=l;\n data.algFinished=false;\n return\n end\n\n %Step M6\n if(l==0)%All multiset partitions have been found.\n %There is no need to update the other things in data, because\n %there are no more multipartitions to find.\n data.algFinished=true;\n return;\n end\n\n l=l-1;\n b=a;\n a=f(l+1);\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/Combinatorics/getNextMultipartition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276224, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.724728966638023}} {"text": "%% \"Spirograph\" Code\n% Jonathan Jamieson - September 2013\n% unigamer@gmail.com\n% www.jonathanjamieson.com\n\nfunction [P_x_global,P_y_global ] = CalculatePenPosition(A_x_global,A_y_global,C_x_global,C_y_global,extension )\n\ndx = C_x_global-A_x_global;\ndy = C_y_global-A_y_global;\n\ntheta = atan2(dy,dx);\n\nP_x_global = extension*cos(theta)+C_x_global;\nP_y_global = extension*sin(theta)+C_y_global;\n\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/38828-rotordraw/CalculatePenPosition.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.724642298607259}} {"text": "function dist_signed = quad_point_dist_signed_2d ( q, p )\n\n%*****************************************************************************80\n%\n%% QUAD_POINT_DIST_SIGNED_2D: signed distanct ( quadrilateral, point ) in 2D.\n%\n% Discussion:\n%\n% The quadrilateral must be convex. DIST_SIGNED is actually the maximum\n% of the signed distances from the point to each of the four lines that\n% make up the quadrilateral.\n%\n% Essentially, if the point is outside the convex quadrilateral,\n% only one of the signed distances can be positive, or two can\n% be positive and equal.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real Q(2,4), the vertices of the quadrilateral.\n%\n% Input, real P(2,1), the point which is to be checked.\n%\n% Output, real DIST_SIGNED, the signed distance from the\n% point to the convex quadrilateral. If DIST_SIGNED is\n% 0.0, the point is on the boundary;\n% negative, the point is in the interior;\n% positive, the point is in the exterior.\n%\n\n%\n% Compare the signed distance from each line segment to the point,\n% with the signed distance to the midpoint of the opposite line.\n%\n% The signed distances should all be negative if the point is inside.\n%\n% Side 12\n%\n dis12 = line_exp_point_dist_signed_2d ( q(1:2,1), q(1:2,2), p );\n\n pm(1:2,1) = 0.5 * ( q(1:2,3) + q(1:2,4) );\n\n dis = line_exp_point_dist_signed_2d ( q(1:2,1), q(1:2,2), pm );\n\n if ( 0.0 < dis )\n dis = -dis;\n dis12 = -dis12;\n end\n%\n% Side 23\n%\n dis23 = line_exp_point_dist_signed_2d ( q(1:2,2), q(1:2,3), p );\n\n pm(1:2,1) = 0.5 * ( q(1:2,4) + q(1:2,1) );\n\n dis = line_exp_point_dist_signed_2d ( q(1:2,2), q(1:2,3), pm );\n\n if ( 0.0 < dis )\n dis = -dis;\n dis23 = -dis23;\n end\n%\n% Side 34\n%\n dis34 = line_exp_point_dist_signed_2d ( q(1:2,3), q(1:2,4), p );\n\n pm(1:2,1) = 0.5 * ( q(1:2,1) + q(1:2,2) );\n\n dis = line_exp_point_dist_signed_2d ( q(1:2,3), q(1:2,4), pm );\n\n if ( 0.0 < dis )\n dis = -dis;\n dis34 = -dis34;\n end\n%\n% Side 41\n%\n dis41 = line_exp_point_dist_signed_2d ( q(1:2,4), q(1:2,1), p );\n\n pm(1:2,1) = 0.5 * ( q(1:2,2) + q(1:2,3) );\n\n dis = line_exp_point_dist_signed_2d ( q(1:2,4), q(1:2,1), pm );\n\n if ( 0.0 < dis )\n dis = -dis;\n dis41 = -dis41;\n end\n\n dist_signed = max ( dis12, max ( dis23, max ( dis34, dis41 ) ) );\n\n return\nend\n", "meta": {"author": "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/quad_point_dist_signed_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7246422926447271}} {"text": "function value = r8_gamma_sample ( a, r )\n\n%*****************************************************************************80\n%\n%% R8_GAMMA_SAMPLE generates a Gamma random deviate.\n%\n% Discussion:\n%\n% This procedure generates random deviates from the gamma distribution whose\n% density is (A^R)/Gamma(R) * X^(R-1) * Exp(-A*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% Joachim Ahrens, Ulrich Dieter,\n% Computer Methods for Sampling from Gamma, Beta, Poisson and\n% Binomial Distributions,\n% Computing,\n% Volume 12, Number 3, September 1974, pages 223-246.\n%\n% Parameters:\n%\n% Input, real A, the rate parameter.\n%\n% Input, real R, the shape parameter.\n%\n% Output, real VALUE, a random deviate \n% from the distribution.\n%\n value = r8_gamma_01_sample ( r ) / a;\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/pdflib/r8_gamma_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676514011486, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7246422851877518}} {"text": "function [G]=TabulateGenGam2dft(Rksi,Rgam,nu);\n% function [G]=TabulateGenGam1dft(Rksi,Rgam,nu,K);\n% This function tabulates the gain functions G for MMSE estimation\n% of speech DFT coefficients, under the assumption of a\n% Generalized Gamma speech amplitude prior with gamma=2. For explanations,\n% derivations and motivations, see:\n% J.S. Erkelens, R.C. Hendriks, R. Heusdens, and J. Jensen,\n% \"Minimum mean-square error estimation of discrete Fourier coefficients\n% with Generalized Gamma priors\", IEEE Trans. Audio, Speech and Language\n% Processing, August 2007.\n% and\n%J.S. Erkelens, R.C. Hendriks and R. Heusdens\n%\"On the Estimation of Complex Speech DFT Coefficients without Assuming Independent Real and Imaginary Parts\", \n%IEEE signal processing letters 2008.\n%\n% INPUT variables:\n% Rksi: Array of \"a priori\" SNR (SNRprior) values for which the gains are\n% computed. NOTE: The values must be in dBs.\n% Rgam: Array of \"a posteriori\" SNR (SNRpost) values for which the gains\n% are computed. NOTE: The values must be in dBs.\n% 'nu': parameter of the Generalized Gamma distribution.\n% \n% OUTPUT variables:\n% G: Matrix with gain values for speech DFT estimation,\n% evaluated at all combinations of a priori and a posteriori SNR in the\n% input variables Rksi and Rgam. To be multiplied with the noisy complex DFT coefficient.\n% \n%\n% Copyright 2007: Delft University of Technology, Information and\n% Communication Theory Group. The software is free for non-commercial use.\n% This program comes WITHOUT ANY WARRANTY.\n%\n% Last modified: 22-11-2007.\n\n\nRgam=10.^(Rgam(:)'/10);%Rksi and Rgam are in dBs.\nRksi=10.^(Rksi/10);\nG=zeros(length(Rksi),length(Rgam));\nfor k=1:length(Rgam)\n [g]=gam2gains(nu,Rgam(k),Rksi);\n G(:,k)=g(:);\nend\n\nfunction [G]=gam2gains(nu,gamm,ksi);\n\nQ=ksi./(nu+ksi);\nTeller=ConflHyperGeomFun(nu+1,2,Q.*gamm);%evaluate the confluent hypergeometric functions\nNoemer=ConflHyperGeomFun(nu,1,Q.*gamm); \nG=(nu.*Q).*Teller./Noemer;\n% asymptotic result for Q.*gamm>700 (A&S, 13.5.1) For very high values of nu and a posteriori SNR a value lower than 700 might be more appropriate.\n\nI=find(Q.*gamm>700);\nG(I)=Q(I);\n%limit G for problematic cases\nI=find(~isfinite(G));\nG(I)=1;\nI=find(G>1e4);\nG(I)=1e4;\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/27312-mmse-based-noise-psd-tracking-algorithm/TabGenGam/TabulateGenGam2dft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7246150489406563}} {"text": "function pde = Lshapedata3\n%% LSHAPEDATA data of Lshape Problem\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n\npde = struct('f',0,'exactu',@exactu,'g_D',@exactu,'Du',@Du);\n\n \n function u = exactu(p) % exact solution\n x = p(:,1); y = p(:,2);\n r = sqrt(x.^2+y.^2);\n theta = atan2(p(:,2),p(:,1));\n theta = (theta>=0).*theta + (theta<0).*(theta+2*pi);\n u = r.^(2/3).*sin(2*theta/3);\n end\n\n function uprime = Du(p) % exact solution\n x = p(:,1); y = p(:,2);\n r = sqrt(x.^2+y.^2);\n theta = atan2(y,x);\n theta = (theta>=0).*theta + (theta<0).*(theta+2*pi);\n uprime(:,1) = 2/3*r.^(-1/3).*sin(2*theta/3).*x./r ...\n - 2/3*r.^(2/3).*cos(2*theta/3).*y./r.^2;\n uprime(:,2) = 2/3*r.^(-1/3).*sin(2*theta/3).*y./r ...\n + 2/3*r.^(2/3).*cos(2*theta/3).*x./r.^2;\n uprime(:,3) = 0;\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/Lshapedata3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849805, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7246150489406562}} {"text": "function varargout = goldsteinprice(X)\n% Goldstein-Price function\n%\n% GOLDSTEINPRICE([x1, x2]) returns the value of the value of the \n% Goldstein-Price function at the specified points. [x1] and [x2] \n% may be vectors. The search domain is\n%\n% -2 < x_i < 2\n%\n% The golbal minimum is\n%\n% f(x1, x2) = f(0, -1) = 3.\n \n% Author: Rody P.S. Oldenhuis\n% Delft University of Technology\n% E-mail: oldenhuis@dds.nl\n% Last edited 20/Jul/2009\n\n % if no input is given, return dimensions, bounds and minimum\n if (nargin == 0)\n varargout{1} = 2; % # dims\n varargout{2} = [-2, -2]; % LB\n varargout{3} = [+2, +2]; % UB\n varargout{4} = [0, -1]; % solution\n varargout{5} = 3; % function value at solution\n \n % otherwise, output function value\n else\n\n % keep values in the search domain\n X(X < -2) = inf; X(X > 2) = inf;\n \n % split input vector X into x1, x2\n if size(X, 1) == 2\n x1 = X(1, :); x2 = X(2, :);\n else\n x1 = X(:, 1); x2 = X(:, 2);\n end\n \n % output function value\n varargout{1} = (1 + (x1 + x2 + 1).^2.*(19 - 14*x1 + 3*x1.^2 - 14*x2 + 6*x1.*x2 + 3*x2.^2)).*...\n (30 + (2*x1 - 3*x2).^2.*(18 - 32*x1 + 12*x1.^2 + 48*x2 - 36*x1.*x2 + 27*x2.^2));\n \n end\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/23147-many-testfunctions-for-global-optimizers/single-objective/goldsteinprice.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7246150402639738}} {"text": "function y = lnCumGaussSum(u1, u2, w1, w2)\n\n% LNCUMGAUSSSUM The log of the weighted sum of two cumulative Gaussians.\n% FORMAT\n% DESC returns the logarithm of the weighted sum of two cumulative\n% Gaussians.\n% ARG u1 : argument of the first cumulative Gaussian.\n% ARG u2 : argument of the second cumulative Gaussian.\n% ARG w1 : weight of the first cumulative Gaussian.\n% ARG w2 : weight of the second cumulative Gaussian.\n%\n% SEEALSO : cumGaussian, lnCumGaussian, lnDiffCumGaussian\n%\n% COPYRIGHT : Neil D. Lawrence, 2004\n\n% NDLUTIL\n\ny = zeros(size(u1));\nsafeCond = u1 > 0 & u2 > 0;\nindex = find(safeCond);\nif ~isempty(index)\n y(index) = log(w1.*cumGaussian(u1(index)) ...\n + w2*cumGaussian(u2(index)));\nend\nindex = find(~safeCond & u1>u2);\nif ~isempty(index)\n y(index) = log(w1) + lnCumGaussian(u1(index))...\n + log(1 + w2/w1*exp(lnCumGaussian(u2(index))...\n -lnCumGaussian(u1(index))));\nend\nindex = find(~safeCond & u2>=u1);\nif ~isempty(index)\n y(index) = log(w2) + lnCumGaussian(u2(index))...\n + log(1 + w1/w2*exp(lnCumGaussian(u1(index))...\n -lnCumGaussian(u2(index))));\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ndlutil/lnCumGaussSum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.952574122783325, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.7245761385556756}} {"text": "function op = prox_hinge( q , r, y)\n\n%PROX_HINGE Hinge-loss function.\n% OP = PROX_HINGE( q , r, y ) implements the nonsmooth function\n% OP(X) = q * sum( max( r - y.*x, 0 ) ).\n% Q is optional; if omitted, Q=1 is assumed. But if Q is supplied,\n% then it must be a positive real scalar.\n% R is also optional; if omitted, R = 1 is assumed. R may be any real number.\n% Y is also optional; if omitted, Y = 1 is assumed. Y may be any scalar\n% or vector of the same size as X\n% Dual: prox_hingeDual.m\n%\n% See also PROX_HINGEDUAL\n\nif nargin < 3\n y = [];\nelseif ~isempty(y) && ( ~isnumeric(y) || ~isreal(y) )\n error( 'Argument 3 must be a real vector');\nend\nif nargin < 2\n\tr = 1;\nelseif ~isnumeric( r ) || ~isreal( r ) %|| numel( r ) ~= 1\n\terror( 'Argument 2 must be real.' );\nend\nif nargin < 1\n\tq = 1;\nelseif ~isnumeric( q ) || ~isreal( q ) || numel( q ) ~= 1 || q <= 0,\n\terror( 'Argument 1 must be positive.' );\nend\n\nif isempty(y) \n op = tfocs_prox( @(x)hinge(x,r,q), @(x,t)prox_hinge(x,t,r,q) );\nelse\n ry = r./y;\n op = tfocs_prox( @(x)hingeY(x,r,q,y), @(x,t)prox_hingeY(x,t,r,q,ry,y) );\nend\n\n\n% -- the actual functions --\n\nfunction v = hingeY(x,r,q,y)\n if ~isscalar(r), assert( numel(r) == numel(x),'r is wrong size' ); end\n if ~isscalar(y), assert( numel(y) == numel(x),'y is wrong size'); end\n v = q*sum( max( r(:) - y(:).*x(:), 0 ) );\nend\nfunction v = hinge(x,r,q)\n if ~isscalar(r), assert( numel(r) == numel(x),'r is wrong size' ); end\n v = q*sum( max( r(:) - x(:), 0 ) );\nend\n\n\n% PROX_F( Y, t ) = argmin_X F(X) + 1/(2*t)*|| X - Y ||^2\nfunction x = prox_hinge(x,t,r,q) \n tq = t * q;\n x = r + (x-r).*( x > r ) + (x + tq - r).*( x + tq < r );\nend\n%{\n in the q = r = t = 1 case, the prox is:\nprox(x) = { x, if x > 1\n 1, if x <= 1, and x > 0\n x + q, if x <= 0\n%}\n\nfunction x = prox_hingeY(x,t,r,q,ry,y) \n tq = t * q;\n x = ry + (x-ry).*( y.*x > r ) + (x + tq*y - ry).*( y.*(x + tq*y) < r );\nend\n\n\nend\n\n% Added Feb, 2011; modified Dec, 2011\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/prox_hinge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7245565353880176}} {"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, 'focus', 'latent', 'output', 'mlpd');\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', 'param', 'output', 'mlpd');\n[DIC2(2), p_eff2(2)] = gp_dic(rfull, x, y, 'focus', 'all', 'output', 'mlpd');\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', 'param', 'output', 'mlpd');\n[DIC2(3), p_eff2(3)] = gp_dic(gp_array, x, y, 'focus', 'all', 'output', 'mlpd');\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, 'focus', 'latent', 'output', 'mlpd');\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', 'param', 'output', 'mlpd');\n[DIC2(5), p_eff2(5)] = gp_dic(rfic, x, y, 'focus', 'all', 'output', 'mlpd');\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', 'param', 'output', 'mlpd');\n[DIC2(6), p_eff2(6)] = gp_dic(gpfic_array, x, y, 'focus', 'all', 'output', 'mlpd');\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, 'focus', 'latent', 'output', 'mlpd');\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', 'param', 'output', 'mlpd');\n[DIC2(8), p_eff2(8)] = gp_dic(rpic, x, y, 'focus', 'all', 'output', 'mlpd');\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', 'param', 'output', 'mlpd');\n[DIC2(9), p_eff2(9)] = gp_dic(gppic_array, x, y, 'focus', 'all', 'output', 'mlpd');\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": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/gp/demo_modelassesment1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7245450532605163}} {"text": "function [x cutvalue cutvalue_upperbound Y] = maxcut(L, r)\n% Algorithm to (try to) compute a maximum cut of a graph, via SDP approach.\n% \n% function x = maxcut(L)\n% function [x cutvalue cutvalue_upperbound Y] = maxcut(L, r)\n%\n% L is the Laplacian matrix describing the graph to cut. The Laplacian of a\n% graph is L = D - A, where D is the diagonal degree matrix (D(i, i) is the\n% sum of the weights of the edges adjacent to node i) and A is the\n% symmetric adjacency matrix of the graph (A(i, j) = A(j, i) is the weight\n% of the edge joining nodes i and j). If L is sparse, this will be\n% exploited.\n%\n% If the graph has n nodes, then L is nxn and the output x is a vector of\n% length n such that x(i) is +1 or -1. This partitions the nodes of the\n% graph in two classes, in an attempt to maximize the sum of the weights of\n% the edges that go from one class to the other (MAX CUT problem).\n%\n% cutvalue is the sum of the weights of the edges 'cut' by the partition x.\n%\n% If the algorithm reached the global optimum of the underlying SDP\n% problem, then it produces an upperbound on the maximum cut value. This\n% value is returned in cutvalue_upperbound if it is found. Otherwise, that\n% output is set to NaN.\n%\n% If r is specified (by default, r = n), the algorithm will stop at rank r.\n% This may prevent the algorithm from reaching a globally optimal solution\n% for the underlying SDP problem (but can greatly help in keeping the\n% execution time under control). If a global optimum of the SDP is reached\n% before rank r, the algorithm will stop of course.\n%\n% Y is a matrix of size nxp, with p <= r, such that X = Y*Y' is the best\n% solution found for the underlying SDP problem. If cutvalue_upperbound is\n% not NaN, then Y*Y' is optimal for the SDP and cutvalue_upperbound is its\n% cut value.\n% \n% By Goemans and Williamson 1995, it is known that if the optimal value of\n% the SDP is reached, then the returned cut, in expectation, is at most at\n% a fraction 0.878 of the optimal cut. (This is not exactly valid because\n% we do not use random projection here; sign(Y*randn(size(Y, 2), 1)) will\n% give a cut that respects this statement -- it's usually worse though).\n%\n% The algorithm is essentially that of:\n% Journee, Bach, Absil and Sepulchre, 2010\n% Low-rank optimization on the code of positive semidefinite matrices.\n%\n% It is itself based on the famous SDP relaxation of MAX CUT:\n% Goemans and Williamson, 1995\n% Improved approximation algorithms for maximum cut and satisfiability\n% problems using semidefinite programming.\n\n% This file is part of Manopt and is copyrighted. See the license file.\n%\n% Main author: Nicolas Boumal, July 18, 2013\n% Contributors:\n%\n% Change log:\n% \n\n\n % If no inputs are provided, generate a random Laplacian.\n % This is for illustration purposes only.\n if ~exist('L', 'var') || isempty(L)\n n = 20;\n A = triu(randn(n) <= .4, 1);\n A = A+A';\n D = diag(sum(A, 2));\n L = D-A;\n end\n\n\n n = size(L, 1);\n assert(size(L, 2) == n, 'L must be square.');\n\n if ~exist('r', 'var') || isempty(r) || r > n\n r = n;\n end\n \n % We will let the rank increase. Each rank value will generate a cut.\n % We have to go up in the rank to eventually find a certificate of SDP\n % optimality. This in turn will give us an upperbound on the MAX CUT\n % value and assure us that we're doing well, according to Goemans and\n % Williamson's argument. In practice though, the good cuts often come\n % up for low rank values, so we better keep track of the best one.\n best_x = ones(n, 1);\n best_cutvalue = 0;\n cutvalue_upperbound = NaN;\n \n time = [];\n cost = [];\n \n for rr = 2 : r\n \n manifold = elliptopefactory(n, rr);\n \n if rr == 2\n \n % At first, for rank 2, generate a random point.\n Y0 = manifold.rand();\n \n else\n \n % To increase the rank, we could just add a column of zeros to\n % the Y matrix. Unfortunately, this lands us in a saddle point.\n % To escape from the saddle, we may compute an eigenvector of\n % Sy associated to a negative eigenvalue: that will yield a\n % (second order) descent direction Z. See Journee et al ; Sy is\n % linked to dual certificates for the SDP.\n Y0 = [Y zeros(n, 1)];\n LY0 = L*Y0;\n Dy = spdiags(sum(LY0.*Y0, 2), 0, n, n);\n Sy = (Dy - L)/4;\n % Find the smallest (the \"most negative\") eigenvalue of Sy.\n [v, s] = eigs(Sy, 1, 'SA');\n % If there is no negative eigenvalue for Sy, than we are not at\n % a saddle point: we're actually done!\n if s >= -1e-8\n % We can stop here: we found the global optimum of the SDP,\n % and hence the reached cost is a valid upper bound on the\n % maximum cut value.\n cutvalue_upperbound = max(-[info.cost]);\n break;\n end\n \n % This is our escape direction.\n Z = manifold.proj(Y0, [zeros(n, rr-1) v]);\n \n % % These instructions can be uncommented to see what the cost\n % % function looks like at a saddle point. But will require the\n % % problem structure which is not defined here: see the helper\n % % function.\n % plotprofile(problem, Y0, Z, linspace(-1, 1, 101));\n % drawnow; pause;\n \n % Now make a step in the Z direction to escape from the saddle.\n % It is not obvious that it is ok to do a unit step ... perhaps\n % need to be cautious here with the stepsize. It's not too\n % critical though: the important point is to leave the saddle\n % point. But it's nice to guarantee monotone decrease of the\n % cost, and we can't do that with a constant step (at least,\n % not without a proper argument to back it up).\n stepsize = 1;\n Y0 = manifold.retr(Y0, Z, stepsize);\n \n end\n \n % Use the Riemannian optimization based algorithm lower in this\n % file to reach a critical point (typically a local optimizer) of\n % the max cut cost with fixed rank, starting from Y0.\n [Y info] = maxcut_fixedrank(L, Y0);\n \n % Some info logging.\n thistime = [info.time];\n if ~isempty(time)\n thistime = time(end) + thistime;\n end\n time = [time thistime]; %#ok\n cost = [cost [info.cost]]; %#ok\n\n % Time to turn the matrix Y into a cut.\n % We can either do the random rounding as follows:\n % x = sign(Y*randn(rr, 1));\n % or extract the \"PCA direction\" of the points in Y and cut\n % orthogonally to that direction, as follows:\n [u, ~, ~] = svds(Y, 1);\n x = sign(u);\n\n cutvalue = (x'*L*x)/4;\n if cutvalue > best_cutvalue\n best_x = x;\n best_cutvalue = cutvalue;\n end\n \n end\n \n x = best_x;\n cutvalue = best_cutvalue;\n \n plot(time, -cost, '.-');\n xlabel('Time [s]');\n ylabel('Relaxed cut value');\n title('The relaxed cut value is an upper bound on the optimal cut value.');\n\nend\n\n\nfunction [Y info] = maxcut_fixedrank(L, Y)\n% Try to solve the (fixed) rank r relaxed max cut program, based on the\n% Laplacian of the graph L and an initial guess Y. L is nxn and Y is nxr.\n\n [n r] = size(Y);\n assert(all(size(L) == n));\n \n % The fixed rank elliptope geometry describes symmetric, positive\n % semidefinite matrices of size n with rank r and all diagonal entries\n % are 1.\n manifold = elliptopefactory(n, r);\n \n % % If you want to compare the performance of the elliptope geometry\n % % against the (conceptually simpler) oblique manifold geometry,\n % % uncomment this line.\n % manifold = obliquefactory(r, n, true);\n \n problem.M = manifold;\n \n % % For rapid prototyping, these lines suffice to describe the cost\n % % function and its gradient and Hessian (here expressed using the\n % % Euclidean gradient and Hessian).\n % problem.cost = @(Y) -trace(Y'*L*Y)/4;\n % problem.egrad = @(Y) -(L*Y)/2;\n % problem.ehess = @(Y, U) -(L*U)/2;\n \n % Instead of the prototyping version, the functions below describe the\n % cost, gradient and Hessian using the caching system (the store\n % structure). This alows to execute exactly the required number of\n % multiplications with the matrix L. These multiplications are counted\n % using the Lproducts_counter and registered for each iteration in the\n % info structure outputted by solvers, via the statsfun function.\n % Notice that we do not use the store structure to count: this does not\n % behave well in general and is not advised.\n \n Lproducts_counter = 0;\n\n % For every visited point Y, we will need L*Y. This function makes sure\n % the quantity L*Y is available, but only computes it if it wasn't\n % already computed.\n function store = prepare(Y, store)\n if ~isfield(store, 'LY')\n store.LY = L*Y;\n Lproducts_counter = Lproducts_counter + 1;\n end\n end\n\n problem.cost = @cost;\n function [f store] = cost(Y, store)\n store = prepare(Y, store);\n LY = store.LY;\n f = -(Y(:)'*LY(:))/4; % = -trace(Y'*LY)/4;\n end\n\n problem.grad = @grad;\n function [g store] = grad(Y, store)\n store = prepare(Y, store);\n LY = store.LY;\n g = manifold.egrad2rgrad(Y, -LY/2);\n end\n\n problem.hess = @hess;\n function [h store] = hess(Y, U, store)\n store = prepare(Y, store);\n LY = store.LY;\n LU = L*U;\n Lproducts_counter = Lproducts_counter + 1;\n h = manifold.ehess2rhess(Y, -LY/2, -LU/2, U);\n end\n\n % statsfun is called exactly once after each iteration (including after\n % the evaluation of the cost at the initial guess). We then register\n % the value of the Lproducts counter (which counts how many product\n % were needed since the last iteration), and reset it to zero.\n options.statsfun = @statsfun;\n function stats = statsfun(problem, Y, stats, store) %#ok\n stats.Lproducts = Lproducts_counter;\n Lproducts_counter = 0;\n end\n \n\n % % Diagnostics tools: to make sure the gradient and Hessian are\n % % correct during the prototyping stage.\n % checkgradient(problem); pause;\n % checkhessian(problem); pause;\n \n % % To investigate the effect of the rotational invariance when using\n % % the oblique or the elliptope geometry, or to study the saddle point\n % % issue mentioned above, it is sometimes interesting to look at the\n % % spectrum of the Hessian. For large dimensions, this is slow!\n % stairs(sort(hessianspectrum(problem, Y)));\n % drawnow; pause;\n \n \n % % When facing a saddle point issue as described in the master\n % % function, and when no sure mechanism exists to find an escape\n % % direction, it may be helpful to set useRand to true and raise\n % % miniter to more than 1, when using trustregions. This will tell the\n % % solver to not stop before at least miniter iterations were\n % % accomplished (thus disregarding the zero gradient at the saddle\n % % point) and to use random search directions to kick start the inner\n % % solve (tCG) step. It is not as efficient as finding a sure escape\n % % direction, but sometimes it's the best we have.\n % options.useRand = true;\n % options.miniter = 5;\n \n options.verbosity = 2;\n Lproducts_counter = 0;\n [Y Ycost info] = trustregions(problem, Y, options); %#ok\n \n % fprintf('Products with L: %d\\n', sum([info.Lproducts]));\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/examples/maxcut.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7245450472348524}} {"text": "function [min_width, min_angle] = minimumCaliperDiameter(points)\n%MINIMUMCALIPERDIAMETER Minimum caliper diameter of a set of points.\n%\n% WIDTH = minimumCaliperDiameter(POINTS)\n% Computes the minimum width of a set of points. As polygons and\n% polylines are represented as point lists, this function works also for\n% polygons and polylines.\n%\n% [WIDTH THETA] = minimumCaliperDiameter(POINTS)\n% Also returns the direction of minimum width. The direction corresponds\n% to the horizontal angle of the edge that minimizes the width. THETA is\n% given in radians, between 0 and PI.\n%\n%\n% Example\n% % Compute minimal caliper diameter, and check coords of rotated points\n% % have expected extent\n% points = randn(30, 2);\n% [width theta] = minimumCaliperDiameter(points);\n% points2 = transformPoint(points, createRotation(-theta));\n% diff = max(points2) - min(points2);\n% abs(width - diff(2)) < 1e-10\n% ans =\n% 1\n%\n% References\n% Algorithms use rotating caliper. Implementation was based on that of\n% Wikipedia:\n% http://en.wikipedia.org/wiki/Rotating_calipers\n%\n% See also \n% polygons2d, convexHull, orientedBox\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2011-04-08, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011-2022 INRA - Cepia Software Platform\n\n% first, compute convex hull of the polygon\ninds = convhull(points(:,1), points(:,2));\nhull = points(inds, :);\n\n% if first and last points are the same, remove the last one\nif inds(1) == inds(end)\n hull = hull(1:end-1, :);\nend\n\n% number of hull vertices\nnV = size(hull, 1);\n\n% default values\nrotated_angle = 0;\nmin_width = inf;\nmin_angle = 0;\n\n% avoid degenerated cases\nif nV < 3\n return;\nend\n\n[tmp, p_a] = min(hull(:, 2)); %#ok\n[tmp, p_b] = max(hull(:, 2)); %#ok\n\ncaliper_a = [ 1 0]; % Caliper A points along the positive x-axis\ncaliper_b = [-1 0]; % Caliper B points along the negative x-axis\n\nwhile rotated_angle < pi\n % compute the direction vectors corresponding to each edge\n ind_a2 = mod(p_a, nV) + 1;\n vector_a = hull(ind_a2, :) - hull(p_a, :);\n \n ind_b2 = mod(p_b, nV) + 1;\n vector_b = hull(ind_b2, :) - hull(p_b, :);\n \n % Determine the angle between each caliper and the next adjacent edge\n % in the polygon \n angle_a = vectorAngle(caliper_a, vector_a);\n angle_b = vectorAngle(caliper_b, vector_b);\n \n % Determine the smallest of these angles\n minAngle = min(angle_a, angle_b);\n \n % Rotate the calipers by the smallest angle\n caliper_a = rotateVector(caliper_a, minAngle);\n caliper_b = rotateVector(caliper_b, minAngle);\n \n rotated_angle = rotated_angle + minAngle;\n \n % compute current width, and update opposite vertex\n if angle_a < angle_b\n line = createLine(hull(p_a, :), hull(ind_a2, :));\n width = distancePointLine(hull(p_b, :), line);\n p_a = mod(p_a, nV) + 1;\n \n else\n line = createLine(hull(p_b, :), hull(ind_b2, :));\n width = distancePointLine(hull(p_a, :), line);\n p_b = mod(p_b, nV) + 1;\n\n end\n \n % update minimum width and corresponding angle if needed\n if width < min_width\n min_width = width;\n min_angle = rotated_angle;\n end\n\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/minimumCaliperDiameter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7245450464615723}} {"text": "%% Using Cook's Distance to Detect Outliers\n% Copyright (c) 2011, The MathWorks, Inc.\n\n% Create a vector of X values\nclear all\nclc\nhold off\n\nX = 1:100;\nX = X';\n\n% Create a noise vector\nnoise = randn(100,1);\n\n% Create a second noise value where sigma is much larger\nnoise2 = 10*randn(100,1);\n\n% Substitute noise2 for noise1 at obs# (11, 31, 51, 71, 91)\n% Many of these points will have an undue influence on the model \n\nnoise(11:20:91) = noise2(11:20:91);\n\n% Specify Y = F(X)\nY = 3*X + 2 + noise;\n\n% Cook's Distance for a given data point measures the extent to \n% which a regression model would change if this data point \n% were excluded from the regression. Cook's Distance is \n% sometimes used to suggest whether a given data point might be an outlier.\n\n% Use regstats to calculate Cook's Distance\nstats = regstats(Y,X,'linear');\n\n% if Cook's Distance > n/4 is a typical treshold that is used to suggest\n% the presence of an outlier\npotential_outlier = stats.cookd > 4/length(X);\n\n% Display the index of potential outliers and graph the results\nX(potential_outlier)\nscatter(X,Y, 'b.')\nhold on\nscatter(X(potential_outlier),Y(potential_outlier), 'r.')\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/30869-fitting-with-matlab-statistics-optimization-and-curve-fitting/Detect_Outliers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7245450396626277}} {"text": "function [gJacobMat] = gJacob(p_pc_c, calibParams)\n%GJACOBMAT Returns the 4x3 Jacobian of the observation model with respect\n%to the feature position in the camera frame\n\n%Redefine local shorthand notation\nx = p_pc_c(1);\ny = p_pc_c(2);\nz = p_pc_c(3);\n\nc_u = calibParams.c_u;\nc_v = calibParams.c_v;\nf_u = calibParams.f_u;\nf_v = calibParams.f_v;\nb = calibParams.b;\n\n%Evaluate the Jacobian\ngJacobMat = [f_u/z, 0, -(1/z^2)*(f_u*x )\n 0, f_v/z, -(1/z^2)*(f_v*y )\n f_u/z, 0, -(1/z^2)*(f_u*(x-b) )\n 0, f_v/z, -(1/z^2)*(f_v*y )];\nend", "meta": {"author": "yuzhou42", "repo": "MSCKF", "sha": "d95d90c85b24f27001bd0ecdce8739b6e602b6df", "save_path": "github-repos/MATLAB/yuzhou42-MSCKF", "path": "github-repos/MATLAB/yuzhou42-MSCKF/MSCKF-d95d90c85b24f27001bd0ecdce8739b6e602b6df/swf/utils/gJacob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465062370313, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.7245038573007447}} {"text": "function [ x, y, z, w ] = ld0014 ( )\n\n%*****************************************************************************80\n%\n%% LD0014 computes the 14 point Lebedev angular grid.\n%\n% Modified:\n%\n% 14 September 2010\n%\n% Author:\n%\n% Dmitri Laikov\n%\n% Reference:\n%\n% Vyacheslav Lebedev, Dmitri Laikov,\n% A quadrature formula for the sphere of the 131st\n% algebraic order of accuracy,\n% Russian Academy of Sciences Doklady Mathematics,\n% Volume 59, Number 3, 1999, pages 477-481.\n%\n% Parameters:\n%\n% Output, real X(N), Y(N), Z(N), W(N), the coordinates\n% and weights of the points.\n%\n n = 0;\n x = zeros(14,1);\n y = zeros(14,1);\n z = zeros(14,1);\n w = zeros(14,1);\n a = 0.0;\n b = 0.0;\n v = 0.6666666666666667E-01;\n [ n, x, y, z, w ] = gen_oh ( 1, n, a, b, v, x, y, z, w );\n v = 0.7500000000000000E-01;\n [ n, x, y, z, w ] = gen_oh ( 3, n, a, b, v, x, y, z, 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/sphere_lebedev_rule/ld0014.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7243990686245193}} {"text": "function value = nco_abscissa ( order, i )\n\n%*****************************************************************************80\n%\n%% NCO_ABSCISSA returns the I-th abscissa for the Newton Cotes open rule.\n%\n% Discussion:\n%\n% Our convention is that the abscissas are numbered from left to\n% right.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 May 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the rule.\n% 1 <= ORDER.\n%\n% Input, integer I, the index of the desired abscissa. \n% 1 <= I <= ORDER.\n%\n% Output, real VALUE, the value of the I-th \n% abscissa in the Newton Cotes open rule of order ORDER.\n%\n x_min = -1.0;\n x_max = +1.0;\n\n if ( order < 1 )\n value = - Inf;\n return\n end\n\n if ( i < 1 | order < i )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NCO_ABSCISSA - Fatal error!\\n' );\n fprintf ( 1, ' 1 <= I <= ORDER is required.\\n' );\n error ( 'NCO_ABSCISSA - Fatal error!' );\n end\n\n value = ( ( order - i + 1 ) * x_min ...\n + ( i ) * x_max ) ...\n / ( order + 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/sparse_grid_open/nco_abscissa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034367, "lm_q2_score": 0.867035771827307, "lm_q1q2_score": 0.7243941134414867}} {"text": "function [ yval, ypval ] = spline_quadratic_val ( ndata, tdata, ydata, tval )\n\n%*****************************************************************************80\n%\n%% SPLINE_QUADRATIC_VAL evaluates a piecewise quadratic spline at a point.\n%\n% Discussion:\n%\n% Because of the simple form of a piecewise quadratic spline,\n% the raw data points ( TDATA(I), YDATA(I)) can be used directly to\n% evaluate the spline at any point. No processing of the data\n% is required.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, int NDATA, the number of data points defining the spline.\n% NDATA should be odd.\n%\n% Input, real TDATA(NDATA), YDATA(NDATA), the values of the independent\n% and dependent variables at the data points. The values of TDATA should\n% be distinct and increasing.\n%\n% Input, real TVAL, the point at which the spline is to be evaluated.\n%\n% Output, real YVAL, YPVAL, the value of the spline and its first\n% derivative dYdT at TVAL. YPVAL is not reliable if TVAL is exactly\n% equal to TDATA(I) for some I.\n%\n if ( mod ( ndata, 2 ) == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPLINE_QUADRATIC_VAL - Fatal error!\\n' );\n fprintf ( 1, ' NDATA must be odd.\\n' );\n error ( 'SPLINE_QUADRATIC_VAL - Fatal error!' );\n end\n%\n% Find the interval [ TDATA(LEFT), TDATA(RIGHT) ] that contains, or is\n% nearest to, TVAL.\n%\n [ left, right ] = r8vec_bracket ( ndata, tdata, tval );\n%\n% Force LEFT to be odd.\n%\n if ( mod ( left, 2 ) == 0 )\n left = left - 1;\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, 'SPLINE_QUADRATIC_VAL - Fatal error!\\n' );\n fprintf ( 1, ' T2 <= T1 or T3 <= T2.\\n' );\n error ( 'SPLINE_QUADRATIC_VAL - Fatal error!' );\n end\n%\n% Construct and evaluate a parabolic interpolant for the data\n% in each dimension.\n%\n y1 = ydata(left);\n y2 = ydata(left+1);\n y3 = ydata(left+2);\n\n dif1 = ( y2 - y1 ) / ( t2 - t1 );\n\n dif2 = ( ( y3 - y1 ) / ( t3 - t1 ) ...\n - ( y2 - y1 ) / ( t2 - t1 ) ) / ( t3 - t2 );\n\n yval = y1 + ( tval - t1 ) * ( dif1 + ( tval - t2 ) * dif2 );\n ypval = dif1 + dif2 * ( 2.0E+00 * tval - t1 - t2 );\n\n return\nend\n", "meta": {"author": "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_quadratic_val.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070838, "lm_q2_score": 0.8670357580842941, "lm_q1q2_score": 0.7243940984077413}} {"text": "function center = graphCenter(v, e, l)\n%GRAPHCENTER Center of a graph\n%\n% CENTER = graphCenter(V, E)\n% Computes the center of the graph given by V and E. The center of the\n% graph is the set of vertices whose eccentricity is minimal. The\n% function returns indices of center vertices.\n%\n% CENTER = graphCenter(V, E, L)\n% Specifies the weight of each edge for computing the distances. Default\n% is to consider a weight of 1 for each edge.\n%\n% Example\n% nodes = [20 20;20 50;20 80;50 50;80 20;80 50;80 80];\n% edges = [1 2;2 3;2 4;4 6;5 6;6 7];\n% figure; drawGraph(nodes, edges);\n% axis([0 100 0 100]); axis equal; hold on\n% C = graphCenter(nodes, edges)\n% C = \n% 4 \n%\n% See Also\n% grPropagateDistance, grVertexEccentricity\n% graphRadius, graphDiameter, graphPeripheralVertices\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-09-07, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% ensure there is a valid length array\nif nargin<3\n l = ones(size(e,1), 1);\nend\n\ng = grVertexEccentricity(v, e, l);\n\ncenter = find(g==min(g));\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/graphs/graphCenter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7243940941019682}} {"text": "function tri = triangulatePolygon(poly)\n%TRIANGULATEPOLYGON Compute a triangulation of the polygon\n%\n% TRI = triangulatePolygon(POLY)\n% Computes a triangulation TRI of the polygon defined by POLY\n% POLY contains the polygon vertices, as a Nv-by-2 array of double. \n% TRI is a Nt-by-3 array containing indices of vertices forming the\n% triangles. \n%\n% Example\n% % creates a simple polygon and computes its Delaunay triangulation\n% poly = [0 0 ; 10 0;5 10;15 15;5 20;-5 10];\n% figure;drawPolygon(poly); axis equal\n% tri = triangulatePolygon(poly);\n% figure;\n% % patch('Faces', tri, 'Vertices', poly, 'facecolor', 'c');\n% drawMesh(poly, tri, 'facecolor', 'c');\n% axis equal\n%\n% % Another example for which constrains were necessary\n% poly2 = [10 10;80 10; 140 20;30 20; 80 30; 140 30; 120 40;10 40];\n% tri2 = triangulatePolygon(poly2);\n% figure; drawMesh(poly2, tri2);\n% hold on, drawPolygon(poly2, 'linewidth', 2);\n% axis equal\n% axis([0 150 0 50])\n%\n% See also\n% delaunayTriangulation, drawMesh, patch\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 INRA - Cepia Software Platform.\n\n% compute constraints\nnv = size(poly, 1);\ncons = [(1:nv)' [2:nv 1]'];\n\nif verLessThan('matlab', '8.1')\n % Code for versions before R2013a\n \n % delaunay triangulation\n dt = DelaunayTri(poly(:,1), poly(:, 2), cons); %#ok\n \n % find which triangles are contained in polygon\n centers = incenters(dt);\n inds = isPointInPolygon(centers, poly);\n \n % keep selected triangles\n tri = dt.Triangulation(inds, :);\n\nelse\n % Code for versions R2013a and later\n\n % delaunay triangulation \n % dt = DelaunayTri(poly(:,1), poly(:, 2), cons);\n dt = delaunayTriangulation(poly(:,1), poly(:, 2), cons);\n\n % find which triangles are contained in polygon\n % centers = incenters(dt);\n centers = incenter(dt);\n inds = isPointInPolygon(centers, poly);\n\n % keep selected triangles\n % tri = dt.Triangulation(inds, :);\n tri = dt.ConnectivityList(inds, :);\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/polygons2d/triangulatePolygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.7243940905502837}} {"text": "%% Setting of the problem\nglobal s\npde = fonedata; % f = 1;\noption.theta = 0.3;\noption.estType = 'star';\noption.maxIt = 18;\noption.maxN = 2e4;\noption.solver = 'mg';\noption.tol = 1e-6;\n[node,elem] = squaremesh([-1,1,-1,1],0.5);\n[node,elem] = delmesh(node,elem,'x>0 & y<0');\nbdFlag = setboundary(node,elem,'Dirichlet');\n\n%% s = 0.2\ns = 0.2; %#ok<*NASGU>\nerr1 = afemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.4\ns = 0.4;\nerr2 = afemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.6\ns = 0.6;\nerr3 = afemfracLap(node,elem,pde,bdFlag,option);\n\n%% s = 0.8\ns = 0.8;\nerr4 = afemfracLap(node,elem,pde,bdFlag,option);\n\n%% save data and plot the table\n% save Lshapencf err1 err2 err3 err4\nload Lshapencf\nfigure; \nplot_error_table(err1.N,err1.energyError,err2.N,err2.energyError,...\n err3.N,err3.energyError,err4.N,err4.energyError);\nsaveas(gcf, 'error_Lshapencf', 'pdf') \nfigure;\nplot_error_table(err1.N,err1.eta,err2.N,err2.eta,err3.N,err3.eta,err4.N,err4.eta);\nylabel('Estimator','interpreter','latex', 'FontSize', 22)\nsaveas(gcf, 'eta_Lshapencf', 'pdf') ", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/fracLaplacian/afemratefracLapLshapencf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.8056321796478255, "lm_q1q2_score": 0.7243611127602076}} {"text": "function [gt,relres,iter]=gabopttight(g,a,M,varargin)\n%GABOPTTIGHT Compute a optimized tight window\n% Usage: gt=gabopttight(Ltight,g,a,M);\n% gt=gabopttight(Ltight,g,a,M, varagin);\n%\n% Input parameters:\n% g : Initial window function\n% a : Time shift\n% M : Number of Channels\n%\n% Output parameters:\n% gt : Tight window\n%\n% `gabopttight(g,a,M)` computes a tight window *gt* for a frame of\n% parameter a and M\n%\n% This function solves a convex optimization problem that can be written\n% as:\n%\n% .. gd = argmin_x || alpha x||_1 + || beta Fx||_1 \n%\n% .. + || omega (x -g_l) ||_2^2 + delta || x ||_S0\n%\n% .. + gamma || nabla F x ||_2^2 + mu || nabla x ||_2^2\n%\n% .. such that x is a tight window\n%\n% .. math:: \\begin{split} \\text{gd} = & \\text{arg} \\min_x \\| \\alpha x \\|_1 + \\| \\beta \\mathcal{F}x\\|_1 \\\\ & + \\| \\omega (x - g_l) \\|_2^2 \\\\ & \\delta \\| x \\|_{S0}+ \\mu \\| \\nabla x \\|_2^2 +\\gamma \\| \\nabla \\mathcal{F} x \\|_2^2 \\\\ & \\text{such that } x \\text{ is tight window}g \\end{split}\n%\n% **Note**: This function require the unlocbox. You can download it at\n% ``_\n%\n% The function uses an iterative algorithm to compute the approximate\n% optimized tight window. Warning The algorithm solve a non convex\n% problem and might be stack in bad local minima. The algorithm can be\n% controlled by the following flags: \n%\n% 'alpha',alpha Weight in time. If it is a scalar, it represent the\n% weights of the entire L1 function in time. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L1 norm (length: Ldual).\n% Default value is $\\alpha=0$.\n% **Warning**: this value should not be too big in order to\n% avoid the the L1 norm proximal operator kill the signal.\n% No L1-time constraint: $\\alpha=0$\n%\n% 'beta',beta Weight in frequency. If it is a scalar, it represent the\n% weights of the entire L1 function in frequency. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L1 norm in frequency. (length: Ldual).\n% Default value is $\\beta=0$.\n% **Warning**: this value should not be too big in order to\n% avoid the the L1 norm proximal operator kill the signal.\n% No L1-frequency constraint: $\\beta=0$\n%\n% 'omega',omega Weight in time of the L2-norm. If it is a scalar, it represent the\n% weights of the entire L2 function in time. If it is a \n% vector, it is the associated weight assotiated to each\n% component of the L2 norm (length: Ldual).\n% Default value is $\\omega=0$.\n% No L2-time constraint: $\\omega=0$\n%\n% 'glike',g_l $g_l$ is a windows in time. The algorithm try to shape\n% the dual window like $g_l$. Normalization of $g_l$ is done\n% automatically. To use option omega should be different\n% from 0. By default $g_d=0$.\n%\n% 'mu', mu Weight of the smooth constraint Default value is 1. \n% No smooth constraint: $\\mu=0$\n% \n% 'gamma', gamma Weight of the smooth constraint in frequency. Default value is 1. \n% No smooth constraint: $\\gamma=0$\n% \n% 'delta', delta Weight of the S0-norm. Default value is 0. \n% No S0-norm: $\\delta=0$\n%\n% 'dual' Look for a dual windows (default)\n%\n% 'painless' Construct a starting guess using a painless-case\n% approximation. This is the default\n%\n% 'zero' Choose a starting guess of zero.\n%\n% 'rand' Choose a random starting phase.\n%\n% 'tol',t Stop if relative residual error is less than the \n% specified tolerance. \n%\n% 'maxit',n Do at most n iterations. default 200\n%\n% 'print' Display the progress.\n%\n% 'debug' Display all the progresses.\n%\n% 'quiet' Don't print anything, this is the default.\n%\n% 'fast' Fast algorithm, this is the default.\n%\n% 'slow' Safer algorithm, you can try this if the fast algorithm\n% is not working. Before using this, try to iterate more.\n%\n% 'printstep',p If 'print' is specified, then print every p'th\n% iteration. Default value is p=10;\n%\n% 'hardconstraint' Force the projection at the end (default)\n%\n% 'softconstaint' Do not force the projection at the end\n%\n% See also: gabfirdual, gabdual, gabtight, gaboptdual, gabconvexopt\n \n\n\n% Author: Nathanael Perraudin\n% Date : 18 Feb 2014\n\nif nargin<3\n error('%s: Too few input parameters.',upper(mfilename));\nend;\n\nif 0\n gt=g;\n for ii=1:50\n gt=gabconvexopt(gt,a,M,varargin{:},'quiet','dual');\n figure(1);\n plot(abs(gt));\n drawnow\n \n fprintf('Error at iteration %i: %g\\n',ii,gabdualnorm(gt,gt,a,M,length(gt)));\n end\n gt=gabconvexopt(g,a,M,'alpha',0,'beta',0,'gamma',0,'mu',0,'omega',0, 'tight');\nelse\n\n[gt,relres,iter]=gabconvexopt(g,a,M,varargin{:}, 'tight');\n\nend\nend\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/gabor/gabopttight.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.724346452542534}} {"text": "function [D] = biharmonic_distance(V,F,i,dim,p)\n % BIHARMONIC_DISTANCE Takes a mesh (V,F) and returns a distance field D from\n % all points in V to the ith vertex, according to the biharmonic embedding\n %\n % [D] = biharmonic_distance(V,F,i,dim)\n % [D] = biharmonic_distance(V,F,i,dim,p)\n %\n % Input:\n % V #V by dim list of vertex positions\n % F #F by 3 list of triangle indices\n % i index of vertex from which to calculate distances\n % dim requested dimension of the embedding\n % Optional:\n % p exponent above eigen values\n % 0.5 \"semi-harmonic\" embedding\n % 1 commute time embedding, \"harmonic\"\n % 2 biharmonic {default}\n % 3 \"triharmonic\" embedding\n % Output:\n % D biharmonic distance field \n % \n\n % if index not given then use n/2th point\n if(~exist('i','var'))\n i = ceil(size(V,1)/2 + sqrt(size(V,1))/2);\n end\n \n % if dimension is not specfied use 4\n if(~exist('dim','var'))\n dim = 4;\n end\n\n % if power is not specfied use 2\n if(~exist('p','var'))\n p = 2;\n end\n\n B = biharmonic_embedding(V,F,dim,p);\n %B = biharmonic_embedding_yaron(V,F);\n D = sqrt(sum((repmat(B(i,:),size(B,1),1)-B(:,:)).^2,2));\n\n %tsurf(F,[V(:,1) V(:,2) D]);\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/biharmonic_distance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505273888291, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7243464355183683}} {"text": "% ir_deblur_gcv1.m\n% Edge-preserving regularized image deblurring (restoration)\n% using (nonlinear!) generalized cross validation GCV (NGCV)\n% to select the regularization parameter automatically\n% 2013-10-01 Jeff Fessler, University of Michigan\n\nif ~isvar('xtrue')\n\tig = image_geom('nx', 100, 'ny', 128, 'dx', 2, 'down', 2);\n\txell = [0 0 85 115 0 100;\n\t\t0 -60 30 20 0 -80; % mouth\n\t\t30 20 25 35 30 20; % eyes\n\t\t-30 20 25 35 -30 20;\n\t\t35 25 7 7 0 -100; % pupils\n\t\t-15 25 7 7 0 -100;\n\t\t0 75 60 15 0 -50; % hat\n\t\t]; % it is not north park, it is ...\n\txtrue = ellipse_im(ig, xell, 'oversample', 3);\n\txtrue = single(xtrue);\nend\n\nif ~isvar('y')\n\tpsf = ones(3)/9;\n\tA = Gblur(ig.mask, 'psf', psf);\n\tytrue = A * xtrue;\n\n\t%% add noise\n\trng(0)\n\tsnr = 20; % specify desired SNR of data in dB\n\tsig = 10^(-snr/20) * norm(ytrue(:)) / sqrt(numel(ytrue));\n\ty = ytrue + sig * randn(size(ytrue));\n\n\tsnr_fun = @(x, xtrue) 20*log10(norm(xtrue(:)) / norm(x(:) - xtrue(:)));\n\tpr 'snr_fun(y, ytrue)'\n\tpr 'snr_fun(y, xtrue)'\n\n\t[nx ny] = size(y);\n\tnd = nx * ny; % # of data points\n%\tC = Cdiffs([], 'mask', ig.mask, 'offsets', [1 nx], 'type_diff', 'circshift');\n\n\tim plc 2 3\n\tclim = [-10 130]; % display all images on same gray scale\n\tim(xtrue, clim)\n\tim(ytrue, clim)\n\tim(y, clim)\nprompt\nend\n\n\ndelta = 5; % small compared to max(y) - min(y)\n%dpot = @(t) t ./ sqrt(1 + (t / delta).^2); % derivative of potential\nniter = 200; % max # of iter\ntol = 1e-5; % stop tolerance for change in x\n\n%% try several values of the regularization parameter\n\nsig = 1; % pretend we don't know the noise level, using sigma=1\n\nreglist = 2 .^ [-3:0.5:2];\nnr = numel(reglist);\ngcv = nan(nr,1);\nrss = nan(nr,1);\nsnr = nan(nr,1); % solver only\ngcv_best = inf;\nx_best = [];\nir_best = [];\n\n% emperically it seems better to generate w once outside the loop\n% instead of making a new random bernoulli for every beta\nw = 2 * (rand(nx,ny) > 0.5) - 1; % bernoulli +/- 1\nweps = 0.05 * norm(y(:)) / norm(w(:));\n\nfor ir=1:nr\n\treg = reglist(ir);\n\tstep = sum(psf(:)) / (1 + reg * 8);\n\n\tR = Reg1(ig.mask, 'offsets', [1 nx], ...\n\t\t'beta', reg, 'pot_arg', {'hyper3', delta});\n\n\t% first run of PCG\n\txinit = y;\n\tx = pwls_pcg1(xinit(ig.mask), A, 1, y(:), R, ...\n\t\t'niter', niter, 'stop_diff_tol', tol);\n\tx = ig.embed(x);\n\n\tsnr(ir) = snr_fun(x, xtrue);\n\n\t% second run of PCG, now with a random perturbation\n\txe = pwls_pcg1(xinit(ig.mask), A, 1, col(y + weps * w), R, ...\n\t\t'niter', niter, 'stop_diff_tol', tol);\n\txe = ig.embed(xe);\n\n\t% todo: find reference for thie NGCV formula\n\ttr_ngcv = (1/nd) * ir_dot_double(w, A * (xe - x) / weps); % NGCV\n\n\trss(ir) = norm(col(A*x) - y(:))^2 / sig^2; % RSS\n\tgcv(ir) = rss(ir) / (1 - tr_ngcv)^2;\n\n\tif gcv(ir) < gcv_best\n\t\tgcv_ir_best = ir;\n\t\tgcv_best = gcv(ir);\n\t\tx_best = x;\n\tend\n\n\n\tim(x, clim)\n\txlabelf('$\\log_2(\\beta)$ = %4.1f', log2(reg))\n\n%\tim subplot 5\n%\tplot(log2(reglist), rss, '-o')\n%\ttitlef 'RSS', xlabelf '$\\log_2(\\beta)$'\n\n\tim subplot 5\n\tplot(log2(reglist), snr, '-o', ...\n\t\tlog2(reglist(gcv_ir_best)), snr(gcv_ir_best), '*')\n\ttitlef 'SNR', xlabelf '$\\log_2(\\beta)$'\n\n\tim subplot 6\n\tplot(log2(reglist), gcv, '-o', ...\n\t\tlog2(reglist(gcv_ir_best)), gcv(gcv_ir_best), '*')\n\ttitlef 'NGCV', xlabelf '$\\log_2(\\beta)$'\n\n\tdrawnow\nend\n\n\tim(4, x_best, clim)\n\txlabelf('$\\log_2(\\beta)$ = %4.1f', log2(reglist(gcv_ir_best)))\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/example/ir_deblur_gcv1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7242313454203181}} {"text": "function [tfr,t,f,wt]=tfrscalo(X,time,wave,fmin,fmax,N,trace);\n%TFRSCALO Scalogram, for Morlet or Mexican hat wavelet.\n%\t[TFR,T,F,WT]=TFRSCALO(X,T,WAVE,FMIN,FMAX,N,TRACE) computes \n%\tthe scalogram (squared magnitude of a continuous wavelet\n%\ttransform). \n%\n%\tX : signal (in time) to be analyzed (Nx=length(X)). Its\n%\t analytic version is used (z=hilbert(real(X))). \n%\tT : time instant(s) on which the TFR is evaluated \n%\t \t\t\t\t\t(default : 1:Nx).\n%\tWAVE : half length of the Morlet analyzing wavelet at coarsest \n% \t scale. If WAVE = 0, the Mexican hat is used. WAVE can also be\n% a vector containing the time samples of any bandpass\n% function, at any scale. \t(default : sqrt(Nx)). \n%\tFMIN,FMAX : respectively lower and upper frequency bounds of \n%\t the analyzed signal. These parameters fix the equivalent\n%\t frequency bandwidth (expressed in Hz). When unspecified, you\n%\t have to enter them at the command line from the plot of the\n%\t spectrum. FMIN and FMAX must be >0 and <=0.5.\n%\tN : number of analyzed voices.\n%\tTRACE : if nonzero, the progression of the algorithm is shown\n%\t \t(default : 0).\n%\tTFR : time-frequency matrix containing the coefficients of the\n%\t decomposition (abscissa correspond to uniformly sampled time,\n%\t and ordinates correspond to a geometrically sampled\n%\t frequency). First row of TFR corresponds to the lowest \n%\t frequency. When called without output arguments, TFRSCALO\n%\t runs TFRQVIEW.\n%\tF : vector of normalized frequencies (geometrically sampled \n%\t from FMIN to FMAX).\n%\tWT : Complex matrix containing the corresponding wavelet\n%\t transform. The scalogram TFR is the square modulus of WT.\n%\n%\tExample : \n%\t sig=altes(64,0.1,0.45); tfrscalo(sig); \n%\n%\tSee also all the time-frequency representations listed in\n%\tthe file CONTENTS (TFR*)\n\n%\tP. Goncalves, October 1995 - O. Lemoine, June 1996. \n%\tCopyright (c) 1995 Rice University - CNRS 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 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 one parameter required');\nend;\n\n[xrow,xcol] = size(X);\nif nargin<=6, trace=0; end\n\nif (nargin == 1),\n time=1:xrow; wave=sqrt(xrow);\nelseif (nargin == 2),\n wave=sqrt(xrow);\nelseif (nargin==4),\n disp('FMIN will not be taken into account. Determine it with FMAX');\n disp(' from the following plot of the spectrum.'); \nelseif nargin==5,\n N=xrow;\nend;\n\n[trow,tcol] = size(time);\nif (xcol==0)|(xcol>2),\n error('X must have one or two columns');\nelseif (trow~=1),\n error('TIME must only have one row'); \nelseif wave<0,\n error('WAVE must be positive');\nend; \n\ns = (real(X) - mean(real(X)))'; \nz = hilbert(s) ;\n\nif trace, disp('Scalogram distribution'); end;\n\nif nargin<=4\t\t % fmin,fmax,N unspecified\n STF = fft(fftshift(z(min(time):max(time)))); Nstf=length(STF);\n sp = (abs(STF(1:round(Nstf/2)))).^2; Maxsp=max(sp);\n f = linspace(0,0.5,round(Nstf/2)+1) ; f = f(1:round(Nstf/2));\n plot(f,sp) ; grid;\n xlabel('Normalized frequency');\n title('Analyzed signal energy spectrum');\n indmin=min(find(sp>Maxsp/100));\n indmax=max(find(sp>Maxsp/100));\n fmindflt=max([0.01 0.05*fix(f(indmin)/0.05)]);\n fmaxdflt=0.05*ceil(f(indmax)/0.05);\n txtmin=['Lower frequency bound [',num2str(fmindflt),'] : '];\n txtmax=['Upper frequency bound [',num2str(fmaxdflt),'] : '];\n fmin = input(txtmin); fmax = input(txtmax);\n if isempty(fmin), fmin=fmindflt; end\n if isempty(fmax), fmax=fmaxdflt; end\n txt=['Number of frequency samples [',num2str(2^nextpow2(xrow)),'] : ']; \n N=input(txt); \n if isempty(N), N=2^nextpow2(xrow); end\nend\n\nfmin_s=num2str(fmin); fmax_s=num2str(fmax); \nN_s=num2str(N);\n\nif fmin >= fmax\n error('FMAX must be greater or equal to FMIN');\nelseif fmin<=0.0 | fmin>0.5,\n error('FMIN must be > 0 and <= 0.5');\nelseif fmax<=0.0 | fmax>0.5,\n error('FMAX must be > 0 and <= 0.5');\nend\nif trace,\n disp(['Frequency runs from ',fmin_s,' to ',fmax_s,' with ',N_s,' points']);\nend\n\nf = logspace(log10(fmin),log10(fmax),N);\na = logspace(log10(fmax/fmin),log10(1),N); \n\n\nwt =zeros(N,tcol);\ntfr=zeros(N,tcol);\n\nif wave > 0\n if trace, disp(['using a Morlet wavelet']) ; end\n for ptr=1:N,\n if trace, disprog(ptr,N,10); end\n nha = wave*a(ptr);\n tha = -round(nha) : round(nha);\n ha = exp(-(2*log(10)/nha^2)*tha.^2).*exp(i*2*pi*f(ptr)*tha); \n detail = conv(z,ha)./sqrt(a(ptr));\n detail = detail(round(nha)+1:length(detail)-round(nha)) ;\n wt(ptr,:) = detail(time) ;\n tfr(ptr,:) = detail(time).*conj(detail(time)) ;\n end\nelseif wave == 0\n if trace, disp(['using a Mexican hat wavelet']) ; end\n for ptr = 1:N\n if trace, disprog(ptr,N,10); end\n ha = mexhat(f(ptr)) ;\n nha = (length(ha)-1)/2 ;\n detail = conv(z,ha)./sqrt(a(ptr));\n detail = detail(round(nha)+1:length(detail)-round(nha)) ;\n wt(ptr,:) = detail(time);\n tfr(ptr,:) = detail(time).*conj(detail(time)) ;\n end \nelseif length(wave) > 1\n [rwav,cwav]=size(wave);\n if cwav>rwav, wave=wave.'; end\n wavef = fft(wave) ;\n nwave = length(wave) ;\n f0 = find(abs(wavef(1:nwave/2)) == max(abs(wavef(1:nwave/2))));\n f0 = mean((f0-1).*(1/nwave));\n if trace, disp(['mother wavelet centered at f0 = ',num2str(f0)]); end\n a = logspace(log10(f0/fmin),log10(f0/fmax),N);\n B = 0.99;\n R = B/((1.001)/2); \n nscale = max(128,round((B*nwave*(1+2/R)*log((1+R/2)/(1-R/2)))/2));\n if trace, disp('Scale computation :'); end\n wts = scale(wave,a,fmin,fmax,nscale,trace);\n for ptr = 1:N, \n clear detail\n if trace, disprog(ptr,N,10); end\n ha = wts(ptr,:);\n nha = length(ha)/2;\n detail = conv(z,ha)./sqrt(a(ptr));\n detail = detail(fix(nha):length(detail)-round(nha));\n wt(ptr,:) = detail(time);\n tfr(ptr,:) = detail(time).*conj(detail(time));\n end\nend\n\n\nt = time;\nf = f';\n\n% Normalization\nSP = fft(z); \nindmin = 1+round(fmin*(xrow-2));\nindmax = 1+round(fmax*(xrow-2));\nSPana=SP(indmin:indmax);\ntfr=tfr*norm(SPana)^2/integ2d(tfr,t,f)/N;\n\nif (nargout==0),\n tfrqview(tfr,hilbert(real(X)),t,'tfrscalo',wave,N,f);\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/tfrscalo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.7242313324885048}} {"text": "function rotMatrix = fick2rotMatrix(vfick,varargin)\n\n% FICK2ROTMATRIX transforms Fick coordinates into a 3*3 rotation matrix\n%\n% ROTMATRIX = FICK2ROTMATRIX(VFICK) returns the rotation matrix ROTMATRIX\n% corresponding to the Fick coordinates VFICK [deg].\n% - VFICK is a 3-vector or a 3*N array (column i represents \n% rotation i) where N is the number of rotations. The 3-D\n% vector VFICK (or VFICK(:,i)) can be written as VFICK = [H V T]\n% where (from the subject's perspective):\n% - H is the horizontal fick angle (positive when to the left)\n% - V is the vertical fick angle (around the inter-aural axis).\n% It is positive when down.\n% - T is the torsional fick angle (around the line of signt). It\n% is positive when clockwise.\n% - ROTMATRIX is a 3*3 array or a 3*3*N tensor (in which case,\n% ROTMATRIX(:,:,ii) is a 3*3 matrix representing the rotation\n% matrix corresponding to rotation ii. \n%\n% ROTMATRIX = FICK2ROTMATRIX(VFICK,OPTION) returns the rotation matrix\n% ROTMATRIX under the form specified by the OPTION string:\n% - 'tensor': ROTMATRIX is a 3*3*N tensor (the default)\n% - 'cell': ROTMATRIX is a 1*N cell and each cell component\n% ROTMATRIX{1,ii} is the 3*3 rotation matrix of rotation\n% ii\n%\n% Useful reference: T. Haslwanter (1995), Mathematics of three-dimensional \n% eye rotations, Vision research, 35(12), 1727-39 \n%\n% See also ROTMATRIX2DQUAT, DQUAT2ROTMATRIX, ROTMATRIX2FICK\n\nsv = size(vfick);\nif sv == [1 3], vfick = vfick'; sv = size(vfick); end\n\n% wrong format\nif sv(1) ~= 3 \n error('DualQuaternion:fick2rotMatrix:wrongsize',...\n '%d rows in the VFICK array. It should be 3.',sv(1));\nend\nvfick = vfick./180.*pi; % expressed in radians\nn = sv(2);\n\n% rotation matrix components (in Fick convention)\nt = vfick(1,:); % Horizontal angle : + when to the left (see Haslwanter95)\nf = vfick(2,:); % Vertical angle: + when down\np = vfick(3,:); % Torsional angle: + when clockwise\n\na11 = cos(t).*cos(f);\na22 = sin(t).*sin(f).*sin(p)+cos(t).*cos(p);\na33 = cos(f).*cos(p);\na23 = sin(t).*sin(f).*cos(p) - cos(t).*sin(p);\na32 = cos(f).*sin(p);\na31 = -sin(f);\na13 = cos(t).*sin(f).*cos(p) + sin(t).*sin(p);\na12 = cos(t).*sin(f).*sin(p)-sin(t).*cos(p);\na21 = sin(t).*cos(f);\n\nchoice = 0;\nsoptargin = size(varargin);\nif soptargin(2) > 1\n error('DualQuaternion:fick2rotMatrix:toomanyInputs',...\n 'Too Many Inputs');\nelseif soptargin(2) == 1\n opt = varargin{1,1};\n if strcmp(opt,'cell') % option is 'cell'\n choice = 1;\n end\nend\n\nif choice == 0 % tensor\n rotMatrix = zeros(3,3,n);\n rotMatrix(1,1,:) = a11;\n rotMatrix(1,2,:) = a12;\n rotMatrix(1,3,:) = a13;\n rotMatrix(2,1,:) = a21;\n rotMatrix(2,2,:) = a22;\n rotMatrix(2,3,:) = a23;\n rotMatrix(3,1,:) = a31;\n rotMatrix(3,2,:) = a32;\n rotMatrix(3,3,:) = a33;\nelseif choice == 1 % cell\n rotMatrix = cell(1,n);\n for ii=1:n\n rotMatrix{1,ii} = [a11(ii) a12(ii) a13(ii);...\n a21(ii) a22(ii) a23(ii);...\n a31(ii) a32(ii) a33(ii)]; \n end\nend\n \n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39288-dual-quaternion-toolbox/Dual quaternion toolbox v2/fick2rotMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.7242124351699875}} {"text": "function [OUT, lags] = CrossCorrelation(X,Y,lag,do_plot,Yname)\n% =======================================================================\n% Computes the cross-correlation between the vector X (Tx1) and each \n% column of the matrix Y (TxN). If specified, it plots it\n% =======================================================================\n% [OUT lags] = CrossCorrelation(X,Y,lag,chart,row,col,)\n% -----------------------------------------------------------------------\n% INPUT\n% - X = vector (Tx1) of interest [double]\n% - Y = matrix (TxN) to correlate X with [double]\n% - lag = length of lags to consider [double]\n% -----------------------------------------------------------------------\n% OPTIONAL INPUT:\n% - do_plot = 1 for plot [dflt 0]\n% - Yname = array (1xN) name of Y [dflt Y#]\n% -----------------------------------------------------------------------\n% OUTPUT\n% - OUT = matrix (2*lag+1,N) of cross-correlations, where every column\n% is a variable [double]\n% - lags = vector of lags used [double]\n% -----------------------------------------------------------------------\n% EXAMPLE\n% X = rand(50,1);\n% Y = rand(50,2);\n% [OUT lags] = CrossCorrelation(X,Y,5,1,{'Consumption','Investment'})\n% =======================================================================\n% VAR Toolbox 3.0\n% Ambrogio Cesa-Bianchi\n% ambrogiocesabianchi@gmail.com\n% March 2012. Updated November 2020\n% -----------------------------------------------------------------------\n\n\n%% Check inputs\n%==========================================================================\n[a, b] = size(X);\n[c, d] = size(Y);\nif a ~= c\n disp('Error: vectors must have the same lenght')\n return\nelseif b > 1\n disp('Error: X must be a Tx1 vector')\n return\nelseif lag >= a-2\n disp('Error: too few observations. Reduce the number of lags')\n return\nend\nif exist('do_plot','var')==0\n do_plot = 0;\nelse\nend\n\n%% Compute the cross correlation with the max amount of observations\n%==========================================================================\n% Lead corr(Xt-1,Yt)\nm = 1;\nfor jj=1:lag\n for ii=1:d\n OUT(m,ii) = corr(X(1:end-lag-1+jj),Y(1+lag+1-jj:end,ii));\n end\n m = m+1;\nend\n\n% Contemporaneous correlation\nfor ii=1:d\n OUT(m,ii) = corr(X,Y(:,ii));\nend\nm = m+1;\n\n% Lag correlation corr(Xt+1,Yt)\nfor jj=1:lag\n for ii=1:d\n OUT(m,ii) = corr(X(1+jj:end),Y(1:end-jj,ii));\n end\n m = m+1;\nend\n\nlags = -lag:1:lag;\n\n%% Plot an istogram with the cross correlations\n%==========================================================================\nif do_plot\n \n % If there are no Yname, create Yname (Y1, Y2,...)\n if ~exist('Yname','var')\n aux1 = 'Y';\n Yname(1,d) = {[]}; \n for ii=1:d\n Yname(1,ii) = {[aux1 num2str(ii)]};\n end\n clear aux1 \n end\n \n % Dimension of the matrix to plot\n dim=size(OUT);\n ntotlags = dim(1);\n ntotvars = dim(2);\n row = round(sqrt(ntotvars));\n col = ceil(sqrt(ntotvars));\n \n % Plot\n for jj=1:row*col\n if jj>ntotvars; break; end\n subplot(row,col,jj);\n stem(lags,OUT(:,jj),'*k','fill','LineWidth',1)\n grid off;\n title(Yname(jj));\n set(gca, 'XTick', -lag:lag); % set the number of ticks\n end\nend\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/v3dot0/Stats/CrossCorrelation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.724204628906167}} {"text": "function [ce_mean_p, ce_mean_ps, ce_mean_s, ce_mean_sn, ce_mean_n] = interpolateElectrolyteConcentration(ce,param)\n%\tinterpolateElectrolyteConcentration interpolates the value of electrolyte concentration at the edges of control volumes using harmonic mean.\n\n% This file is part of the LIONSIMBA Toolbox\n%\n%\tOfficial web-site: \thttp://sisdin.unipv.it/labsisdin/lionsimba.php\n% \tOfficial GitHUB: \thttps://github.com/lionsimbatoolbox/LIONSIMBA\n%\n% LIONSIMBA: A Matlab framework based on a finite volume model suitable for Li-ion battery design, simulation, and control\n% Copyright (C) 2016-2018 :Marcello Torchio, Lalo Magni, Davide Raimondo,\n% University of Pavia, 27100, Pavia, Italy\n% Bhushan Gopaluni, Univ. of British Columbia, \n% Vancouver, BC V6T 1Z3, Canada\n% Richard D. Braatz, \n% Massachusetts Institute of Technology, \n% Cambridge, Massachusetts 02142, USA\n% \n% Main code contributors to LIONSIMBA 2.0:\n% Ian Campbell, Krishnakumar Gopalakrishnan,\n% Imperial college London, London, UK\n%\n% LIONSIMBA is a free Matlab-based software distributed with an MIT\n% license.\n\n%% Electrolyte concentration interpolation\n\n% Interpolation within the positive electrode\nbeta_ce_p = 0.5;\nce_mean_p = ce(1:param.Np-1).*ce(2:param.Np)./ (beta_ce_p*ce(2:param.Np) + (1-beta_ce_p)*ce(1:param.Np-1));\n\n% Interpolation on the interface between separator and positive electrode\nbeta_ce_ps = param.deltax_p*param.len_p/2 / (param.deltax_p*param.len_p/2 + param.deltax_s*param.len_s/2);\nce_mean_ps = ce(param.Np)*ce(param.Np+1)/(beta_ce_ps*ce(param.Np+1) + (1-beta_ce_ps)*ce(param.Np));\n\n% Interpolation within the separator\nbeta_ce_s = 0.5;\nce_mean_s = ce(param.Np+1:param.Np+param.Ns-1).*ce(param.Np+2:param.Np+param.Ns)./ (beta_ce_s*ce(param.Np+2:param.Np+param.Ns) + (1-beta_ce_s)*ce(param.Np+1:param.Np+param.Ns-1));\n\n% Interpolation on the interface between separator and negative electrode\nbeta_ce_sn = param.deltax_s*param.len_s/2 / (param.deltax_n*param.len_n/2 + param.deltax_s*param.len_s/2);\nce_mean_sn = ce(param.Np+param.Ns)*ce(param.Np+param.Ns+1)/(beta_ce_sn*ce(param.Np+param.Ns+1) + (1-beta_ce_sn)*ce(param.Np+param.Ns));\n\n% Interpolation within the negative electrode\nbeta_ce_n = 0.5;\nce_mean_n = ce(param.Np+param.Ns+1:end-1).*ce(param.Np+param.Ns+2:end)./ (beta_ce_n*ce(param.Np+param.Ns+2:end) + (1-beta_ce_n)*ce(param.Np+param.Ns+1:end-1));\n\nend", "meta": {"author": "lionsimbatoolbox", "repo": "LIONSIMBA", "sha": "d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66", "save_path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA", "path": "github-repos/MATLAB/lionsimbatoolbox-LIONSIMBA/LIONSIMBA-d1cf29a4dcfa8e7824fc2416ac3e6ec760bb9b66/battery_model_files/interpolation_scripts/interpolateElectrolyteConcentration.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7242046267283018}} {"text": "function [ vW ] = LmsFilter( vW, mY, vD, numSamples, stepSize, normalizeMode )\n% ----------------------------------------------------------------------------------------------- %\n% [ vW ] = LmsFilter( vY, vD, stepSize, vW, paramN, paramM, paramL, normalizeMode )\n% Applies the Least Mean Squares Adaptive Filter for optimal 'vW' weights\n% given the reference signal vD.\n% Input:\n% - vW - Filter Taps.\n% The adaptive filter taps (To be updated).\n% Structure: Vector (paramL x 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - vY - Input Signal.\n% The signal to be filtered to by the adaptive\n% filter to match the reference signal.\n% Structure: Vector (numSamples x 1.\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - vD - Reference Signal.\n% The reference signal\n% Structure: Vector (numSamples x 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% - paramL - Number of Taps.\n% Number of taps of the adaptive filter.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, 3, ...}.\n% - numSamples - Number of Samples.\n% Number of samples of the input vector 'vY' and\n% 'vD'.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {1, 2, 3, ..., min(length(vY), length(vD)}.\n% - stepSize - Step Size\n% The step size (paramMu) of the LMS filter.\n% Basically the SGD step size.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: (0, inf).\n% - normalizeMode - Normalize Mode.\n% Normalizes the step size by the norm of the\n% samples.\n% Structure: Scalar.\n% Type: 'Single' / 'Double'.\n% Range: {0, 1} / {OFF, ON}.\n% Output:\n% - vW - Filter Taps.\n% The updated adaptive filter taps.\n% Structure: Vector (paramL x 1).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% References:\n% 1. A\n% Remarks:\n% 1. The values of the step size must be in the range (0, 2 / lambdaMax)\n% where lambdaMax is the maximum eigen value of the samples\n% covariance.\n% 2. In case of normalization it is usually will converge for stepSize\n% within the range [0, 2).\n% TODO:\n% 1. C\n% Release Notes:\n% - 1.0.000 07/08/2020 Royi Avital\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\nDELTA_PARAM = 1e-5;\n\n% mW = zeros(length(vW), numSamples);\n% mW(:, 1) = vW;\n\nfor ii = 2:numSamples\n vY = reshape(mY(ii, :), [], 1);\n dSample = vD(ii);\n \n zSample = vW.' * vY;\n \n eSample = dSample - zSample;\n \n if(normalizeMode == ON)\n vW(:) = vW + (stepSize * eSample * vY);\n else\n vW(:) = vW + ((stepSize / ((vY.' * vY) + DELTA_PARAM)) * eSample * vY);\n end\n\n% mW(:, ii) = vW;\n \nend\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/SignalProcessing/Q81138/LmsFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.7242046187263879}} {"text": "% Figure 6.61 Feedback Control of Dynamic Systems, 6e\n% Franklin, Powell, Emami\n% \n\nclear all\n%close all\nclf\n\nnum=9;\nden=conv([1 0.5],[1 1]);\nden=conv(den,[1 2]);\nw=logspace(-1,1,500);\n[mag,phas]=bode(num,den,w);\n[OLGM,OLPM,OLWcg,OLWcp]=margin(mag,phas,w)\n\n%Lead compensator, first guess\nnuml=[1 1];\ndenl=0.333*[1 3];\nnumc=conv(num,numl);\ndenc=conv(den,denl);\n[magc,phasc]=bode(numc,denc,w);\n[D1GM,D1PM,D1Wcg,D1Wcp]=margin(magc,phasc,w)\ndencl=denc+[0 0 0 numc];\nt=0:.1:20;\ny=step(numc,dencl,t);\n%Design Iteration, next guess\nnuml=[1 1.5];\ndenl=0.1*[1 15];\nnumcc=conv(num,numl);\ndencc=conv(den,denl);\n[magcc,phascc]=bode(numcc,dencc,w);\n[D2GM,D2PM,D2Wcg,D2Wcp]=margin(magcc,phascc,w)\n%subplot(2,1,1)\n%loglog(w,mag,'-',w,magc,'--',w,magcc,'-.',w,ones(500,1),'-');\n%grid;\n%xlabel('w (rad/sec)');\n%ylabel('Magnitude');\n%title('Fig. 6.60 Bode Plot for lead-compensation design (a) magnitude');\n%subplot(2,1,2)\n%semilogx(w,phas,'-',w,phasc,'--',w,phascc,'-.',w,-180*ones(500,1));\n%grid;\n%xlabel('w (rad/sec)');\n%ylabel('phase (deg)');\n%title('Fig. 6.60 (b) phase');\ndencl=dencc+[0 0 0 numcc];\nt=0:.1:20;\nyy=step(numcc,dencl,t);\nplot(t,y,'--',t,yy,'-');\nxlabel('Time (sec)');\nylabel('y');\ntitle('Fig. 6.61 Step Response');\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/fig6_61.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7242046181942274}} {"text": "function nrgf = rgf_enum ( m )\n\n%*****************************************************************************80\n%\n%% RGF_ENUM enumerates the restricted growth functions on M.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 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 M, the domain of the RGF is the integers\n% from 1 to M. M must be positive. However, for the enumeration routine\n% only, it is legal to call with any value of M.\n%\n% Output, integer NRGF, the number of restricted growth\n% functions.\n%\n if ( m < 0 )\n\n nrgf = 0;\n\n elseif ( m == 0 )\n\n nrgf = 1;\n\n else\n\n b = zeros ( m + 1, 1 );\n offset = 1;\n b(0+offset) = 1;\n for j = 1 : m\n b(j+offset) = 0;\n for i = 0 : j - 1\n b(j+offset) = b(j+offset) + i4_choose ( j - 1, i ) * b(i+offset);\n end\n end\n\n nrgf = b(m+offset);\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/combo/rgf_enum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.7241817907730395}} {"text": "function [Maxima,MaxPos,Minima,MinPos]=MinimaMaxima3D(Input,Robust,LookInBoundaries,numbermax,numbermin)\n% V 1.0 Dec 13, 07\n% Author Sam Pichardo.\n% This function finds the local minima and maxima in a 3D Cartesian data. \n% It's assumed that the data is uniformly distributed.\n% The minima and maxima are calculated using a multi-directional derivation. \n%\n% Use:\n% \n% [Maxima,MaxPos,Minima,MinPos]=MinimaMaxima3D(Input,[Robust],[LookInBoundaries],[numbermax],[numbermin])\n% \n% where Input is the 3D data and Robust (optional and with a default value\n% of 1) indicates if the multi-directional derivation should include the\n% diagonal derivations. \n%\n% Input has to have a size larger or equal than [3 x 3 x 3]\n% \n% If Robust=1, the total number of derivations taken into account are 26: 6\n% for all surrounding elements colliding each of the faces of the unit cube; \n% 10 for all the surrounding elements in diagonal.\n% \n% If Robust =0, then only the 6 elements of the colliding faces are considered\n% \n% The function returns in Maxima and MaxPos, respectively, \n% the values (numbermax) and subindexes (numbermax x 3) of local maxima\n% and position in Input. Maxima (and the subindexes) are sorted in\n% descending order.\n% Similar situation for Minima and MinimaPos witn a numbermin elements but \n% with the execption of being sorted in ascending order.\n% \n% IMPORTANT: if numbermin or numbermax are not specified, ALL the minima\n% or maxima will be returned. This can be a useless for highly\n% oscillating data\n% \n% LookInBoundaries (default value of 0) specifies if a search of the minima/maxima should be\n% done in the boundaries of the matrix. This situation depends on the\n% the desire application. When it is not activated, the algorithm WILL NOT\n% FIND ANY MINIMA/MAXIMA on the 6 layers of the boundaries.\n% When it is activated, the finding minima and maxima on the boundaries is done by\n% replicating the extra layer as the layer 2 (or layer N-1, depending of the boundary)\n% By example (and using a 2D matrix for simplicity reasons):\n% For the matrix \n% [ 4 1 3 7\n% 5 7 8 8\n% 9 9 9 9\n% 5 6 7 9]\n% \n% the calculation of the partial derivate following the -x direction will be done by substrascting\n% [ 5 7 8 8\n% 4 1 3 7\n% 5 7 8 8\n% 9 9 9 9]\n% to the input. And so on for the other dimensions.\n% Like this, the value \"1\" at the coordinate (1,2) will be detected as a\n% minima. Same situation for the value \"5\" at the coordinate (4,1)\n\n\nif nargin <1\n test=load('temp.mat');\n pf=test.uresTot(test.EvalLims(2,1):test.EvalLims(2,2));\n pf=reshape(pf,length(test.EvalCoord{2}.Ry),length(test.EvalCoord{2}.Rx),length(test.EvalCoord{2}.Rz));\n Input = abs(pf)*1.5e6;\n clear test;\n clear pf;\n Robust =1;\nend\n\nAsize=size(Input);\n\nif length(Asize)<3\n error('MinimaMaxima3D can only works with 3D matrices ');\nend\n \n\nif (Asize(1)<3 || Asize(2)<3 || Asize(3)<3)\n error('MinimaMaxima3D can only works with matrices with dimensions equal or larger to [3x3x3]');\nend\n\nif ~isreal(Input)\n warning('ATTENTION, complex values detected!!, using abs(Input)');\n Input=abs(Input);\nend\n\nif ~exist('Robust','var')\n Robust=1;\nend\n\nif ~exist('LookInBoundaries','var')\n LookInBoundaries=0;\nend\n\nif ~exist('numbermax','var')\n numbermax=0;\nend\n\nif ~exist('numbermin','var')\n numbermin=0;\nend\n\n[xx_base,yy_base,zz_base]=ndgrid(1:Asize(1),1:Asize(2),1:Asize(3));\n\n\nIndBase=sub2ind(Asize,xx_base(:),yy_base(:),zz_base(:));\n\nif Robust ~= 0\n Numbder_dd=26;\nelse\n Numbder_dd=6;\nend\n\nif LookInBoundaries==0\n lx=1:Asize(1);\n lx_p1=[2:Asize(1),Asize(1)];\n lx_m1=[1,1:Asize(1)-1];\n ly=1:Asize(2);\n ly_p1=[2:Asize(2),Asize(2)];\n ly_m1=[1,1:Asize(2)-1];\n lz=1:Asize(3);\n lz_p1=[2:Asize(3),Asize(3)];\n lz_m1=[1,1:Asize(3)-1];\nelse\n lx=1:Asize(1);\n lx_p1=[2:Asize(1),Asize(1)-1]; %We replicate the layer N-1 as the layer N+1\n lx_m1=[2,1:Asize(1)-1]; %We replicate the layer 2 as the layer -1\n ly=1:Asize(2);\n ly_p1=[2:Asize(2),Asize(2)-1]; %We replicate the layer N-1 as the layer N+1\n ly_m1=[2,1:Asize(2)-1]; %We replicate the layer 2 as the layer -1\n lz=1:Asize(3);\n lz_p1=[2:Asize(3),Asize(3)-1]; %We replicate the layer N-1 as the layer N+1\n lz_m1=[2,1:Asize(3)-1];%We replicate the layer 2 as the layer -1\nend\n\nfor n_dd=1:Numbder_dd\n switch n_dd\n case 1\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x+1)\n [xx,yy,zz]=ndgrid(lx_p1,ly,lz);\n\n case 2\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x-1)\n [xx,yy,zz]=ndgrid(lx_m1,ly,lz);\n\n case 3\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(y)-elem(y+1)\n [xx,yy,zz]=ndgrid(lx,ly_p1,lz);\n\n case 4\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(y)-elem(y-1)\n [xx,yy,zz]=ndgrid(lx,ly_m1,lz);\n\n case 5\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(z)-elem(z+1)\n [xx,yy,zz]=ndgrid(lx,ly,lz_p1);\n\n case 6\n %%%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(z)-elem(z-1)\n [xx,yy,zz]=ndgrid(lx,ly,lz_m1);\n case 7\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x+1,y+1)\n [xx,yy,zz]=ndgrid(lx_p1,ly_p1,lz);\n case 8\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x+1,y-1)\n [xx,yy,zz]=ndgrid(lx_p1,ly_m1,lz);\n case 9\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x-1,y-1)\n [xx,yy,zz]=ndgrid(lx_m1,ly_m1,lz);\n case 10\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x-1,y+1)\n [xx,yy,zz]=ndgrid(lx_m1,ly_p1,lz);\n case 11\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x+1,z+1)\n [xx,yy,zz]=ndgrid(lx_p1,ly,lz_p1);\n case 12\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x+1,z-1)\n [xx,yy,zz]=ndgrid(lx_p1,ly,lz_m1);\n case 13\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x-1,z-1)\n [xx,yy,zz]=ndgrid(lx_m1,ly,lz_m1);\n case 14\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x-1,z+1)\n [xx,yy,zz]=ndgrid(lx_m1,ly,lz_p1);\n case 15\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(y+1,z+1)\n [xx,yy,zz]=ndgrid(lx,ly_p1,lz_p1);\n case 16\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(y+1,z-1)\n [xx,yy,zz]=ndgrid(lx,ly_p1,lz_m1);\n case 17\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(y-1,z-1)\n [xx,yy,zz]=ndgrid(lx,ly_m1,lz_m1);\n case 18\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(y-1,z+1)\n [xx,yy,zz]=ndgrid(lx,ly_m1,lz_p1);\n case 19\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x+1,y+1,z+1)\n [xx,yy,zz]=ndgrid(lx_p1,ly_p1,lz_p1);\n case 20\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x+1,y+1,z-1)\n [xx,yy,zz]=ndgrid(lx_p1,ly_p1,lz_m1);\n case 21\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x+1,y-1,z+1)\n [xx,yy,zz]=ndgrid(lx_p1,ly_m1,lz_p1);\n case 22\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x+1,y-1,z-1)\n [xx,yy,zz]=ndgrid(lx_p1,ly_m1,lz_m1);\n case 23\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x-1,y+1,z+1)\n [xx,yy,zz]=ndgrid(lx_m1,ly_p1,lz_p1);\n case 24\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x-1,y+1,z-1)\n [xx,yy,zz]=ndgrid(lx_m1,ly_p1,lz_m1);\n case 25\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x-1,y-1,z+1)\n [xx,yy,zz]=ndgrid(lx_m1,ly_m1,lz_p1);\n case 26\n %%%%%%%%%%%%%%%%%% %% This index is used to calculated elem(x)-elem(x-1,y-1,z-1)\n [xx,yy,zz]=ndgrid(lx_m1,ly_m1,lz_m1); \n\n end\n\n Ind_dd=sub2ind(Asize,xx(:),yy(:),zz(:)); \n \n part_deriv = Input(IndBase)-Input(Ind_dd);\n \n if n_dd >1\n MatMinMax= (sign_Prev_deriv==sign(part_deriv)).*MatMinMax;\n else\n MatMinMax=sign(part_deriv);\n end\n\n sign_Prev_deriv=sign(part_deriv);\nend\n\n%Well , now the easy part, all values MatMinMax ==1 are local maximum and\n%the values MatMinMax ==-1 are minimun\n\nAllMaxima=find(MatMinMax==1);\nAllMinima=find(MatMinMax==-1);\n\nif numbermax ==0\n nmax=length(AllMaxima);\nelse\n nmax=numbermax;\nend\nnmax=min([nmax,length(AllMaxima)]);\nsmax=1:nmax;\n\nif numbermin ==0\n nmin=length(AllMinima);\nelse\n nmin=numbermin;\nend\n\nnmin=min([nmin,length(AllMinima)]);\n\nsmin=1:nmin;\n\n[Maxima,IndMax]=sort(Input(AllMaxima),'descend');\nMaxima=Maxima(smax);\nIndMax=AllMaxima(IndMax(smax));\n\nMaxPos=zeros(nmax,3);\n[MaxPos(:,1),MaxPos(:,2),MaxPos(:,3)]=ind2sub(Asize,IndMax);\n\n[Minima,IndMin]=sort(Input(AllMinima));\nMinima=Minima(smin);\nIndMin=AllMinima(IndMin(smin));\n\nMinPos=zeros(nmin,3);\n[MinPos(:,1),MinPos(:,2),MinPos(:,3)]=ind2sub(Asize,IndMin);\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/17997-minimamaxima3d/MinimaMaxima3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7241817753370005}} {"text": "function varargout = pexp(varargin)\n%PEXP\n%\n% y = PEXP(x)\n%\n% Defines perspective exp, x(1)*exp(x(2)/x(1)) on x(1)>0\n% \n% Alternatively\n%\n% y = PEXP(x,y) to define x*exp(y/x) on x>0\n%\n% Implemented as either evalutation based-nonlinear operator, or\n% represented using exponential cones depending on solver. Hence, the\n% convexity of this function is exploited to perform convexity analysis and\n% rigorous modelling. \n%\n% See also ENTROPY, LOGSUMEXP, CROSSENTROPY, KULLBACKLEIBLER, EXPCONE\n\nswitch class(varargin{1})\n \n case 'double'\n \n if nargin == 2\n varargin{1} = [varargin{1};varargin{2}];\n end\n if nargin == 1 && ~isequal(prod(size(varargin{1})),2)\n error('PEXP only defined for 2x1 arguments');\n end\n x = varargin{1};\n \n varargout{1} = x(1)*exp(x(2)/x(1));\n\n\n case 'sdpvar'\n \n if nargin == 2\n varargin{1} = [varargin{1};varargin{2}];\n end \n if ~isequal(prod(size(varargin{1})),2)\n error('PEXP only defined for 2x1 arguments');\n else\n varargout{1} = yalmip('define',mfilename,varargin{1});\n end\n\n case 'char'\n \n operator = CreateBasicOperator('convex','positive','callback');\n operator.range = [0 inf]; \n operator.derivative = @derivative;\n operator.convexhull = @convexhull;\n operator.bounds = @bounds;\n \n varargout{1} = [varargin{3}(1) >= 0];\n varargout{2} = operator;\n varargout{3} = varargin{3};\n\n otherwise\n error([upper(mfilename) ' called with weird argument']);\nend\n\nfunction [L,U] = bounds(xL,xU)\nx1 = [xL(1);xL(2)];\nx2 = [xU(1);xL(2)];\nx3 = [xL(1);xU(2)];\nx4 = [xU(1);xU(2)];\nL = min([pexp(x1) pexp(x2) pexp(x3) pexp(x4)]);\nU = max([pexp(x1) pexp(x2) pexp(x3) pexp(x4)]);\n\nfunction dp = derivative(x)\nz = x(2)/x(1);\ndp = [exp(z)-z*exp(z);exp(z)];\n\nfunction [Ax,Ay,b,K] = convexhull(xL,xU)\nx1 = [xL(1);xL(2)];\nx2 = [xU(1);xL(2)];\nx3 = [xL(1);xU(2)];\nx4 = [xU(1);xU(2)];\nx5 = (xL+xU)/2;\nf1 = pexp(x1);\nf2 = pexp(x2);\nf3 = pexp(x3);\nf4 = pexp(x4);\nf5 = pexp(x5);\ndf1 = derivative(x1);\ndf2 = derivative(x2);\ndf3 = derivative(x3);\ndf4 = derivative(x4);\ndf5 = derivative(x5);\n[Ax,Ay,b,K] = convexhullConvex2D(x1,f1,df1,x2,f2,df2,x3,f3,df3,x4,f4,df4,x5,f5,df5);", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/operators/pexp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7241427828135786}} {"text": "% X: data matrix, each row is one observation, each column is one feature\n% d: reduced dimension\n% Y: dimensionanlity-reduced data\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 Y=PCA(X,d)\n\n%% eigenvalue analysis\nSx=cov(X);\n[V,D]=eig(Sx);\neigValue=diag(D);\n[eigValue,IX]=sort(eigValue,'descend');\neigVector=V(:,IX);\n\n%% normailization\nnorm_eigVector=sqrt(sum(eigVector.^2));\neigVector=eigVector./repmat(norm_eigVector,size(eigVector,1),1);\n\n%% dimensionality reduction\nY=X*eigVector(:,1:d);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39715-kernel-pca-and-pre-image-reconstruction/kPCA_v2.0/code/PCA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.724142774895943}} {"text": "function [ sparserL , sparserA, sparserW ] = gsp_graph_sparsify_old(L,epsilon)\n% The graph sparsification algorithm of D. A. Spielman and N. Srivastava, \n% \"Graph sparsification by effective resistances,\" SIAM J. Comput., \n% vol. 40, no. 6, pp. 1913-1926, 2011. \n\nN=size(L,1);\n\n% Epsilon should be between 1/sqrt(N) and 1, with a larger epsilon leading to a sparser graph\nif ( (epsilon <= 1/sqrt(N)) || (epsilon >1) )\n error('Epsilon out of required range');\nend\n\n% Compute resistance distances, and check if the original graph is\n% connected\nresistance_distances = gsp_compute_resistance_distances_old(L);\nW=diag(diag(L))-L;\nW(W<1e-10)=0;\nW=sparse(W);\noriginal_connected=gsp_check_connectivity_undirected(W);\nif (original_connected==0)\n warning('Original graph not connected before sparsification');\nend\n\n% Initialize the probability distribution that will be used to select edges in the sparsified graph\n[start_nodes,end_nodes,weights] = find(tril(W));\nweights=max(0,weights);\nRe=max(0,resistance_distances(sub2ind(size(resistance_distances),start_nodes,end_nodes)));\nPe=weights.*Re;\nPe=Pe/sum(Pe);\n \nmax_tries=10; % maximum number of tries to get a connected graph\n\nfor ii=1:max_tries\n \n % Set Q\n C0=1/30; % Rudelson, 1996 Random Vectors in the Isotropic Position (too hard to figure out actual C0)\n C= 4*C0; % Rudelson and Vershynin, 2007, Thm. 3.1\n q=round(9*C^2*N*log(N)/(epsilon^2));\n\n % Choose random edges in the new graph according the probability\n % distribution initialized above\n results=gendist(Pe',q,1);\n spin_counts=hist(results,1:length(Pe'));\n per_spin_weights=weights./(q*Pe);\n\n % Tally the new weights and form the new graph\n new_weights=spin_counts'.*per_spin_weights;\n sparserW=sparse(start_nodes,end_nodes,new_weights,N,N);\n sparserW=sparserW+sparserW';\n sparserL=diag(sum(sparserW))-sparserW;\n sparserD=diag(diag(sparserL));\n sparserW=sparserD-sparserL;\n sparserA=sign(sparserW);\n\n % Check if new graph is connected. If not, reduce epsilon and try again\n new_graph_connected=gsp_check_connectivity_undirected(sparserA);\n if new_graph_connected\n break;\n elseif ii==max_tries\n warning('Despite attempts to reduce epsilon, sparsified graph is disconnected');\n else\n epsilon=epsilon-(epsilon-1/sqrt(N))/2;\n end\nend\n\nend\n\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/gsp_graph_sparsify_old.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7241427656656383}} {"text": "function B = contiguous(A)\n% CONTIGUOUS find contiguous sequences in an input vector of integers\n% B = contiguous(A)\n% Take an input vector like i = [ 2 3 4 7 11 12 13 14 17 19 21] and\n% return B.start = [2 11], B.end = [4 14]\n% meaning that ranges 2:4 and 4:14 are contiguous in A\n\n\n% using example:\n% A = [ 2 3 4 7 11 12 13 14 17 19 21]\n% mask = [ 0 1 1 0 0 1 1 1 0 0 0 0]\n% starts = [ 1 0 0 0 1 0 0 0 0 0 0]\n% ends = [ 0 0 1 0 0 0 0 1 0 0 0]\n% i(starts) = [2 11]\n% i(ends) = [4 14]\n\n% AUTHOR: Glenn Thompson, University of Alaska Fairbanks\n% Vectorized by Celso Reyes\n\n% forcing i into a column ensures this won't crash for rows OR columns.\nmask = [false; diff(A(:))==1; false]; %true where i(N) == i(N-1)+1\nstarts = mask(1:end-1) < mask(2:end);\nendIdx = mask(1:end-1) > mask(2:end);\nB.start = A(starts);\nB.end = A(endIdx);\n\n\n% tests:\n% v0 = [];\n% v1= ([ 2 3 4 7 11 12 13 14 17 19 20])\n% v2 = [0, v1, 0];\n% contiguous([ 2 3 4 7 11 12 13 14 17 19 20])\n% expectedStarts = [2 11 19];\n% expectedEnds = [4 14 20];\n% contiguous([ 0 2 3 4 7 11 12 13 14 17 19 20 22])\n% SAME RESULTS.\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/libgismo/contiguous.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7241353310837577}} {"text": "function [rhsu] = DispersiveLDGRHS1D(u,time)\n\n% function [rhsu] = DispersiveLDGRHS1D(u,time)\n% Purpose : Evaluate RHS flux in 1D u_xxx using LDG fluxes and periodic BC's\n\nGlobals1D;\n\n% Define field differences at faces, incl BC\ndu = zeros(Nfp*Nfaces,K); du(:) = u(vmapM)-u(vmapP);\nuin = u(vmapO); du (mapI) = u(vmapI) - uin; \nuout = u(vmapI); du (mapO) = u(vmapO) - uout;\nfluxu = nx.*(1.0+nx).*du/2.0;\n\n% Compute local variable p, define differences, incl BC\np = rx.*(Dr*u) - LIFT*(Fscale.*fluxu);\ndp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapM)-p(vmapP);\npin = p(vmapO); dp(mapI) = p(vmapI) - pin; \npout = p(vmapI); dp(mapO) = p(vmapO) - pout;\nfluxp = nx.*(1.0-nx).*dp/2.0;\n\n% Compute local variable q, define differences, incl BC\nq = rx.*(Dr*p) - LIFT*(Fscale.*fluxp);\ndq = zeros(Nfp*Nfaces,K); dq(:) = q(vmapM)-q(vmapP);\nqin = q(vmapO); dq (mapI) = q(vmapI) - qin; \nqout = q(vmapI); dq (mapO) = q(vmapO) - qout;\nfluxq = nx.*(1.0-nx).*dq/2.0;\n\n% compute right hand sides of the semi-discrete PDE\nrhsu = rx.*(Dr*q) - LIFT*(Fscale.*fluxq);\nreturn\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes1D/DispersiveLDGRHS1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.938124016006303, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7240849317681113}} {"text": "function a = clement2_inverse ( n, x, y )\n\n%*****************************************************************************80\n%\n%% CLEMENT2_INVERSE returns the inverse of the CLEMENT2 matrix.\n%\n% Example:\n%\n% N = 6, X and Y arbitrary:\n%\n% 0 1/Y1 0 -X2/(Y1*Y3) 0 X2*X4/(Y1*Y3*Y5)\n% 1/X1 0 0 0 0 0\n% 0 0 0 1/Y3 0 -X4/(Y3*Y5)\n% -Y2/(X1*X3) 0 1/X3 0 0 0\n% 0 0 0 0 0 1/Y5\n% Y2*Y4/(X1*X3*X5) 0 -Y4/(X3*X5) 0 1/X5 0\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Paul Clement,\n% A class of triple-diagonal matrices for test purposes,\n% SIAM Review,\n% Volume 1, 1959, pages 50-52.\n%\n% Parameters:\n%\n% Input, integer N, the order of A. N must not be odd%\n%\n% Input, real X(N-1), Y(N-1), the first super and\n% subdiagonals of the matrix A. None of the entries\n% of X or Y may be zero.\n%\n% Output, real A(N,N), the matrix.\n%\n if ( mod ( n, 2 ) == 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CLEMENT2_INVERSE - Fatal error!\\n' );\n fprintf ( 1,' The matrix is singular for odd N.\\n' );\n error ( 'CLEMENT2_INVERSE - Fatal error!' );\n end\n\n for i = 1 : n-1\n\n if ( x(i) == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CLEMENT2_INVERSE - Fatal error!\\n' );\n fprintf ( 1, ' The matrix is singular\\n' );\n fprintf ( 1, ' X(I) = 0 for I = %d\\n', i );\n error ( 'CLEMENT2_INVERSE - Fatal error!' );\n elseif ( y(i) == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CLEMENT2_INVERSE - Fatal error!\\n' );\n fprintf ( 1, ' The matrix is singular\\n' );\n fprintf ( 1, ' Y(I) = 0 for I = %d\\n', i );\n error ( 'CLEMENT2_INVERSE - Fatal error!' );\n end\n\n end\n\n a = zeros ( n, n );\n\n for i = 1 : n\n\n if ( mod ( i, 2 ) == 1 )\n\n for j = i : 2 : n-1\n\n if ( j == i )\n prod1 = 1.0 / y(j);\n prod2 = 1.0 / x(j);\n else\n prod1 = - prod1 * x(j-1) / y(j);\n prod2 = - prod2 * y(j-1) / x(j);\n end\n\n a(i,j+1) = prod1;\n a(j+1,i) = prod2;\n\n end\n\n end\n\n end\n \n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/clement2_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639067, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7240234334677396}} {"text": "function y=savitzkyGolayFilt(x,N,DN,F,W,DIM)\n%savitzkyGolayFilt Savitzky-Golay Filtering.\n% savitzkyGolayFilt(X,N,DN,F) filters the signal X using a Savitzky-Golay \n% (polynomial) filter. The polynomial order, N, must be less than the\n% frame size, F, and F must be odd. DN specifies the differentiation\n% order (DN=0 is smoothing). For a DN higher than zero, you'll have to\n% scale the output by 1/T^DN to acquire the DNth smoothed derivative of\n% input X, where T is the sampling interval. The length of the input X\n% must be >= F. If X is a matrix, the filtering is done on the columns\n% of X.\n%\n% Note that if the polynomial order N equals F-1, no smoothing\n% will occur.\n%\n% savitzkyGolayFilt(X,N,DN,F,W) specifies a weighting vector W with\n% length F containing real, positive valued weights employed during the\n% least-squares minimization. If not specified, or if specified as\n% empty, W defaults to an identity matrix.\n%\n% savitzkyGolayFilt(X,N,DN,F,[],DIM) or savitzkyGolayFilt(X,N,DN,F,W,DIM)\n% operates along the dimension DIM.\n%\n% See also savitzkyGolay, FILTER, sgolayfilt\n\n% References:\n% [1] Sophocles J. Orfanidis, INTRODUCTION TO SIGNAL PROCESSING,\n% Prentice-Hall, 1995, Chapter 8.\n\n% Author(s): R. Losada\n% Copyright 1988-2004 The MathWorks, Inc.\n% $Revision: 1.11.4.4 $ $Date: 2009/08/11 15:47:54 $\n\nerror(nargchk(4,6,nargin,'struct'));\n\n% Check if the input arguments are valid\nif round(F) ~= F, error(generatemsgid('MustBeInteger'),'Frame length must be an integer.'), end\nif rem(F,2) ~= 1, error(generatemsgid('SignalErr'),'Frame length must be odd.'), end\nif round(N) ~= N, error(generatemsgid('MustBeInteger'),'Polynomial order must be an integer.'), end\nif N > F-1, error(generatemsgid('InvalidRange'),'The Polynomial order must be less than the frame length.'), end\nif DN > N, error(generatemsgid('InvalidRange'),'The Differentiation order must be less than or equal to the Polynomial order.'), end\n\nif nargin < 5 || isempty(W)\n % No weighting matrix, make W an identity\n W = ones(F,1);\nelse\n % Check for right length of W\n if length(W) ~= F, error(generatemsgid('InvalidDimensions'),'The weight vector must be of the same length as the frame length.'),end\n % Check to see if all elements are positive\n if min(W) <= 0, error(generatemsgid('InvalidRange'),'All the elements of the weight vector must be greater than zero.'), end\nend\n\nif nargin < 6, DIM = []; end\n\n% Compute the projection matrix B\npp = fix(-F./2):fix(F./2);\nB = savitzkyGolay(pp,N,DN,pp,W);\n\nif ~isempty(DIM) && DIM > ndims(x)\n\terror(generatemsgid('InvalidDimensions'),'Dimension specified exceeds the dimensions of X.')\nend\n\n% Reshape X into the right dimension.\nif isempty(DIM)\n\t% Work along the first non-singleton dimension\n\t[x, nshifts] = shiftdim(x);\nelse\n\t% Put DIM in the first dimension (this matches the order \n\t% that the built-in filter function uses)\n\tperm = [DIM,1:DIM-1,DIM+1:ndims(x)];\n\tx = permute(x,perm);\nend\n\nif size(x,1) < F, error(generatemsgid('InvalidDimensions'),'The length of the input must be >= frame length.'), end\n\n% Preallocate output\ny = zeros(size(x));\n\n% Compute the transient on (note, this is different than in sgolayfilt,\n% they had an optimization leaving out some transposes that is only valid\n% for DN==0)\ny(1:(F+1)/2-1,:) = fliplr(B(:,(F-1)/2+2:end)).'*flipud(x(1:F,:));\n\n% Compute the steady state output\nytemp = filter(B(:,(F-1)./2+1),1,x);\ny((F+1)/2:end-(F+1)/2+1,:) = ytemp(F:end,:);\n\n% Compute the transient off\ny(end-(F+1)/2+2:end,:) = fliplr(B(:,1:(F-1)/2)).'*flipud(x(end-(F-1):end,:));\n\n% Convert Y to the original shape of X\nif isempty(DIM)\n\ty = shiftdim(y, -nshifts);\nelse\n\ty = ipermute(y,perm);\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/30299-savitzky-golay-smoothdifferentiation-filters-and-filter-application/savitzkyGolayFilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7240234326570932}} {"text": "function elliptic_km_values_test ( )\n\n%*****************************************************************************80\n%\n%% ELLIPTIC_KM_VALUES_TEST demonstrates the use of ELLIPTIC_KM_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ELLIPTIC_KM_VALUES_TEST:\\n' );\n fprintf ( 1, ' ELLIPTIC_KM_VALUES stores values of\\n' );\n fprintf ( 1, ' the complete elliptic integral of the first\\n' );\n fprintf ( 1, ' kind, with parameter modulus M.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' M KM(M)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx ] = elliptic_km_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %24.16f\\n', x, fx );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/elliptic_km_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.8688267898240861, "lm_q1q2_score": 0.724014740219218}} {"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\nf=@(n) round(n);\n\ns = sigmoid(X * theta);\n\np = f(s);\n\n\n\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "vkosuri", "repo": "CourseraMachineLearning", "sha": "b11d4152c323a084fa3bc942e108ed456b77cbd3", "save_path": "github-repos/MATLAB/vkosuri-CourseraMachineLearning", "path": "github-repos/MATLAB/vkosuri-CourseraMachineLearning/CourseraMachineLearning-b11d4152c323a084fa3bc942e108ed456b77cbd3/home/week-3/exercises/machine-learning-ex2/ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7240147253013433}} {"text": "function [out] = smoothThreshold_storage_logistic(S,Smax,r,e)\n%smoothThreshold_storage_logistic Logisitic smoother for storage 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% Q = { P, if S = Smax\n% { 0, if S < Smax\n%\n% By transforming the equation above to Q = f(P,S,Smax,e,r):\n% Q = P * 1/ (1+exp((S-Smax+r*e*Smax)/(r*Smax)))\n%\n% Inputs:\n% S : current storage\n% Smax : maximum storage\n% r : [optional] smoothing parameter rho, default = 0.01\n% e : [optional] smoothing parameter e, default 5\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% NOTE: can be applied for temperature thresholds as well (i.e. snow\n% modules). This simply means that S becomes T, and Smax T0.\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\n% if ~exist('e','var'); e = 5.00; end\nif nargin == 2\n r = 0.01;\n e = 5.00;\nelseif nargin == 3\n e = 5.00;\nend\n\n% Calculate multiplier\nSmax = max(Smax,0); % this avoids numerical instabilities when Smax<0\nif r*Smax == 0\n out = 1 ./ (1+exp((S-Smax+r*e*Smax)/(r)));\nelse\n out = 1 ./ (1+exp((S-Smax+r*e*Smax)/(r*Smax)));\nend\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_storage_logistic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7239748898988692}} {"text": "function px = gmmEval(x, gmm)\n% Computes the probability of the data given a Guassian mixture model\n% x(ndata, ndim) - the data to be evaluated\n% gmm.mu{K}, gmm.sigma{K}, gmm.priors{K} - the mixture parameters\n\nK = length(gmm.priors);\n[ndata, ndim] = size(x);\n\npx = zeros(ndata, 1);\n\nif K ==0\n return;\nend\n\n\n\n\nfor k = 1:K\n invSigma = inv(gmm.sigma{k});\n for i = 1:ndata\n px(i) = px(i) + 1/(sqrt(2*pi)*sqrt(det(gmm.sigma{k}))) * ...\n exp(-1/2 * (x(i, :)-gmm.mu{k}) * invSigma * (x(i, :)-gmm.mu{k})') ...\n * gmm.priors(k);\n end\nend\n\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/SpatialLayout_shrink/spatiallayoutcode/GeometricContext/geomContext_src_07_02_08/src/tools/misc/gmmEval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7239748779751235}} {"text": "function cdf = erlang_cdf ( x, a, b, c )\n\n%*****************************************************************************80\n%\n%% ERLANG_CDF evaluates the Erlang CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the argument of the CDF.\n%\n% Input, real A, B, integer C, the parameters of the PDF.\n% 0.0 < B.\n% 0 < C.\n%\n% Output, real CDF, the value of the CDF.\n%\n if ( x < a )\n\n cdf = 0.0;\n\n else\n\n x2 = ( x - a ) / b;\n p2 = c;\n\n cdf = gamma_inc ( p2, x2 );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/erlang_cdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7239748718829524}} {"text": "function imgOut = ExponentialTMO(img, exp_k)\n%\n% imgOut = ExponentialTMO(img, exp_k) \n%\n%\n% Input:\n% -img: input HDR image\n% -exp_k: appearance value [1, +inf)\n%\n% Output\n% -imgOut: tone mapped image\n% \n% Copyright (C) 2010-15 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\n%is it a three color channels image?\ncheck13Color(img);\n\ncheckNegative(img);\n\nif(~exist('exp_k', 'var'))\n exp_k = 1;\nend\n\nif(exp_k <= 0)\n exp_k = 1;\nend\n\n%Luminance channel\nL = lum(img);\n\nLwa = logMean(L); %geometric mean\n\n%dynamic range reduction\nLd = 1 - exp(-exp_k * ( L / Lwa));\n\n%change luminance in img\nimgOut = ChangeLuminance(img, L, Ld);\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/Tmo/ExponentialTMO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901876, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7239005870792503}} {"text": "function Q = deconvolutionDAMAS(S, e, maxIterations)\n%deconvolutionDAMAS - deconvolves the intensity plot with the DAMAS algorithm\n%as implemented in \"A deconvolution approach for the mapping of acoustic sources\n%(DAMAS) determined from phased microphone arrays\", Brooks and Humphreys, 2005\n%\n%Q = deconvolutionDAMAS(S, e, maxIterations)\n%\n%IN\n%S - MxN matrix of delay-and-sum steered response power\n%e - MxNxP steering vector/matrix for a certain frequency\n%\n%OUT\n%Q - MxN devonvolved intensity plot\n%\n%Created by J?rgen Grythe\n%Last updated 2017-02-27\n\nif ~exist('maxIterations', 'var')\n maxIterations = 100;\nend\n\nY = real(S);\ndeps = 0.1;\n\n%M # of y-points, N # of x-points, P number of mics\n[M, N, P] = size(e);\n\n%Make the A-matrix square size NxM x NxM x P\nee = reshape(e, M*N, P);\nA = (abs(ee*ee').^2)./P^2;\n\n%Initialise final source powers Q\nQ = zeros(size(Y));\nQ0 = Y;\n\n\n%Solve the system Y = AQ for Q by Gauss-Seidel iteration where Y is the\n%original delay-and-sum plot we want to deconvolve, and Q are the true\n%source powers\nfor i=1:maxIterations;\n \n %Gauss-Seidel iteration. If the solution is negative set it to zero (to\n %ensure that we only have positive and not negative power)\n for n=1:M*N\n Q(n) = max(0, Y(n) - A(n, 1:n-1)*Q(1:n-1)' ...\n - A(n, n+1:end)*Q0(n+1:end)');\n end\n\n %Break criterion for convergence\n dX = (Q - Q0);\n maxd = max(abs(dX(:)))/mean(Q0(:));\n \n if maxd < deps\n break;\n end\n \n Q0 = Q;\nend\n\n\nif i == maxIterations\n disp(['Stopped after maximum iterations (' num2str(maxIterations) ')'])\nelse\n disp(['Converged after ' num2str(i) ' iterations'])\nend\n\n", "meta": {"author": "jorgengrythe", "repo": "beamforming", "sha": "0e0406044a102869f63c6006f952094827b81669", "save_path": "github-repos/MATLAB/jorgengrythe-beamforming", "path": "github-repos/MATLAB/jorgengrythe-beamforming/beamforming-0e0406044a102869f63c6006f952094827b81669/algorithm/deconvolutionDAMAS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881363, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.7236992495134051}} {"text": "function vec=DelaunayVar(TDB1,TDB2)\n%%DELAUNAYVAR Get the Delaunay variables that are needed for tide models\n% involving Doodson numbers using the equations in the IERS\n% conventions.\n%\n%INPUTS: T The time as measured in Julian centuries Barycentric dynamical\n% time (TDB).\n%\n%OUTPUTS: vec A vector of the Delaunay variables in the order with all\n% units in RADIANS.\n% vec(1) Mean anomaly of the moon: l\n% vec(2) Mean anomaly of the sun: l'\n% vec(3) F=L-Omega, The mean longitude of the moon minus the\n% mean longitude of the ascending node of the moon.\n% vec(4) Mean Elongation of the moon from the sun: D\n% vec(5) Mean Longitude of the Ascending Node of the Moon:\n% Omega\n%\n%This function implements Equation 5.43 in Section 5.7.2 of [1]. The units\n%in those equations are degrees (and arcseconds). However, in Equation 6.8\n%in Section 6.2, it looks like the angles should be in radians, since one\n%is using trigonometric functions. Thus, the return value here is put into\n%radians to be convenient.\n%\n%REFERENCES:\n%[1] G. Petit and B. Luzum, IERS Conventions (2010), International Earth\n% Rotation and Reference Systems Service Std. 36, 2010.\n%\n%March 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n %The time as measured in Julian centuries Barycentric dynamical time\n %(TDB). The precision of the model is low enough that it shouldn't\n %matter that the two parts are added together.\n T=(TDB1+TDB2)/36525;\n\n vec=zeros(5,1);\n\n %The conversion from arcseconds to degrees\n sec2Deg=1/3600;\n\n %Mean anomaly of the moon: l\n vec(1)=134.96340251+sec2Deg*(1717915923.2178*T+31.8792*T^2+0.051635*T^3-0.00024470*T^4);\n %Mean anomaly of the sun: l'\n vec(2)=357.52910918+sec2Deg*(129596581.0481*T-0.5532*T^2+0.000136*T^3-0.00001149*T^4);\n %L-Omega, The mean longitude of the moon minus the mean longitude of the\n %ascending node of the moon.\n vec(3)=93.27209062+sec2Deg*(1739527262.8478*T-12.7512*T^2-0.001037*T^3+0.00000417*T^4);\n %Mean Elongation of the moon from the sun: D\n vec(4)=297.85019547+sec2Deg*(1602961601.2090*T-6.3706*T^2+0.006593*T^3-0.00003169*T^4);\n %Mean Longitude of the Ascending Node of the Moon: Omega\n vec(5)=125.04455501+sec2Deg*(-6962890.5431*T+7.4722*T^2+0.007702*T^3-0.00005939*T^4);\n\n %Convert from degrees to radians.\n vec=mod(vec*(pi/180),2*pi);\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/Astronomical_Code/DelaunayVar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.7236992477551939}} {"text": "function n = order( val, base )\n%Order of magnitude of number for specified base. Default base is 10.\n%order(0.002) will return -3., order(1.3e6) will return 6.\n%Author Ivar Smith\n\nif nargin < 2\n base = 10;\nend\nn = floor(log(abs(val))./log(base));", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/28559-order-of-magnitude-of-number/order.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7236992357917575}} {"text": "function Y = fillnans(varargin)\n% FILLNANS replaces all NaNs in array using inverse-distance weighting.\n%\n% Y = FILLNANS(X) replaces all NaNs in the vector or array X by\n% inverse-distance weighted interpolation:\n% Y = sum(X/D^3)/sum(1/D^3)\n% where D is the distance (in pixels) from the NaN node to all non-NaN\n% values X. Values farther from a known non-NaN value will tend toward the\n% average of all the values.\n%\n% Y = FILLNANS(...,'power',p) uses a power of p in the weighting\n% function. The higer the value of p, the stronger the weighting.\n%\n% Y = FILLNANS(...,'radius',d) only used pixels < d pixels away in\n% for weighted averaging.\n%\n% NOTE: Use in conjunction with INVDISTGRID to grid and interpolate x,y,z\n% data.\n%\n% See also INPAINT_NANS\n%\n% Ian M. Howat, Applied Physics Lab, University of Washington\n% ihowat@apl.washington.edu Ian M. Howat\n% Version 1: 05-Jul-2007 17:28:57\n% Revision 1: 16-Jul-2007 17:47:43\n% Added increment expression to waitbar to reduce number of times its\n% called. Provided by John D'Errico.\n% Revision 2: 16-Jul-2007 18:40:34\n% Added radius option and 'option',value varargin parser.\n% Revision 3: 18-Jul-2007 10:25:23\n% Adopted several code efficiency revisions made by Urs, including\n% removing the waitbar.\n\n%parse input and set defualts:\nX = varargin{1}; %input array\nY = X; %output array\nn = 2; %weighting power\nd = 0; %distance cut-off radius (0= all pixels, no cut-off)\nif nargin > 1 && nargin < 6\n for k=2:2:length(varargin)\n if isnumeric(varargin{k}) || ~isnumeric(varargin{k+1})\n error('Input arguments must be in ''option'',value form.')\n end\n switch lower(varargin{k})\t% (Urs:less error prone)\n case 'power'\n n = varargin{k+1};\n case 'radius'\n d = varargin{k+1};\n otherwise\n error(['Unrecognized input argument: ',varargin{k}])\n end\n end\nelseif nargin >= 6\n error('Too many input arguments')\nend\n\n%(Urs:use ISNAN()/NOT() once only)\nix=isnan(X);\n[rn,cn]=find(ix); %row,col of nans\nix=~ix;\n[r,c]=find(ix); %row,col of non-nans\nind=find(ix); %index of non-nans\n\n%Break distance-finding loops into with cut-off and without cut-off\n%versions. The cutoff conditional statement adds time\n%if cut-off values near the max pixel distance are used.\n\nif d %distance cut-off loop\n d=d.^2;\t\t\t\t% (Urs:allows first step without SQRT())\n for k = 1:length(rn)\n D = (rn(k)-r).^2+(cn(k)-c).^2;\t% (Urs:no SQRT() here)\n Dd = D < d;\n if sum(Dd) ~= 0\n D=1./sqrt(D(Dd)).^n; %(Urs: Compute once only for valid s)\n Y(rn(k),cn(k)) = sum(X(ind(Dd)).*D)./ sum(D);\n end\n end\nelse %no distance cut-off loop\n for k = 1:length(rn)\n D = 1./(sqrt((rn(k)-r).^2+(cn(k)-c).^2)).^n;% (Urs:compute once only)\n Y(rn(k),cn(k)) = sum(X(ind).*D)./sum(D);\n end\nend\n\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15590-fillnans/fillnans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624259, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7236992333327945}} {"text": "function [YM,Y]=multigauss(x,mi,sigm,c)\n% [YM,Y]=multigauss(x,mu,sigm,c)\n% \n% computes multigaussian likelihood\n% \n% x : data (columnwise vectors)\n% sigm: variances vector (diagonal of the covariance matrix)\n% mu : means\n% c :the weights\nDEBUG=0;\n \n[L,T]=size(x);\n\nif DEBUG L,T,end\n\nM=size(c,1);\n\nif DEBUG M,end\n\n% repeating, changing dimensions:\nX=permute(repmat(x',[1,1,M]),[1,3,2]); % (T,L) -> (T,M,L) one per mixture\n\nSigm=permute(repmat(sigm,[1,1,T]),[3,2,1]); % (L,M) -> (T,M,L)\n\nMu=permute(repmat(mi,[1,1,T]),[3,2,1]); % (L,M) -> (T,M,L)\n\nif DEBUG size(X),size(Mu),size(Sigm),pause;end\n\n\n%Y=squeeze(exp( 0.5.*dot(X-Mu,(X-Mu)./Sigm))) % L dissapears: (L,T,M) -> (T,M)\nlY=-0.5.*dot(X-Mu,(X-Mu)./Sigm,3);\n% c,const -> (T,M) and then multiply by old Y\ncoef=(2.*pi).^(L./2).*sqrt(prod(sigm,1)); % c,const -> (T,M)\nlcoef=repmat(log(c')-log(coef),[T,1]);\n\nif DEBUG log(coef),lcoef,lY,pause;end\n\nYM=exp(lcoef+lY); % ( T,M ) one mixture per column\nY=sum(YM,2); % add mixtures \n", "meta": {"author": "yueyuzhao", "repo": "gyrophone", "sha": "aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e", "save_path": "github-repos/MATLAB/yueyuzhao-gyrophone", "path": "github-repos/MATLAB/yueyuzhao-gyrophone/gyrophone-aa816eec3d7a17d9e30ab7afa0d4b79ef0a7a82e/+GMMImpl/multigauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7236992322753348}} {"text": "function hpdi = hpdi(x, p)\n% HPDI - Estimates the Bayesian HPD intervals\n%\n% Y = HPDI(X,P) returns a Highest Posterior Density (HPD) interval\n% for each column of X. P must be a scalar. Y is a 2 row matrix\n% where ith column is HPDI for ith column of X.\n\n% References:\n% [1] Chen, M.-H., Shao, Q.-M., and Ibrahim, J. Q., (2000).\n% Monte Carlo Methods in Bayesian Computation. Springer-Verlag.\n%\n% Copyright (C) 2001 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% Licence (version 3 or later); please refer to the file \n% Licence.txt, included with the software, for details.\n\nif nargin < 2\n error('Not enough arguments')\nend\n\nm=size(x,2);\npts=linspace(0.1,99.9-p,20);\npt1=prctile(x,pts);\npt2=prctile(x,p+pts);\ncis=abs(pt2-pt1);\n[foo,hpdpi]=min(cis);\nif m==1\n hpdi=[pt1(hpdpi); pt2(hpdpi)];\nelse\n hpdpi=sub2ind(size(pt1),hpdpi,1:m);\n hpdi=[pt1(hpdpi); pt2(hpdpi)];\nend\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/diag/hpdi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652496, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7236910951925106}} {"text": "% Distribution code Version 1.0 -- 02/31/2020 by Wei Liu Copyright 2020\n%\n% The code is created based on the method described in the following paper \n% [1] \"Real-time Image Smoothing via Iterative Least Squares\", Wei Liu, Pingping Zhang, \n% Xiaolin Huang, Jie Yang, Chunhua Shen and Ian Reid, ACM Transactions on Graphics, \n% presented at SIGGRAPH 2020.\n% \n% The code and the algorithm are for non-comercial use only.\n\n\n% ---------------------- Input------------------------\n% F: input image, can be gray image or RGB color image\n% lambda: \\lambda in Eq.(1), control smoothing strength\n% gamma: the \\gamma in the Welsch's penalty in Eq. (18)\n% iter: iteration number of the ILS \n\n% ---------------------- Output------------------------\n% U: smoothed image\n\nfunction U =ILS_Welsch_GPU(F, lambda, gamma, iter)\n\nF = gpuArray(single(F)); % 'single' precision is very important to reduce the computational cost\n\nc = 2;\n\n[N, M, D] = size(F);\nsizeI2D = [N, M];\n\notfFx = psf2otf_Dx_GPU(sizeI2D); % equal to otfFx = psf2otf(fx, sizeI2D) where fx = [1, -1];\notfFy = psf2otf_Dy_GPU(sizeI2D); % equal to otfFy = psf2otf(fy, sizeI2D) where fy = [1; -1];\n\nDenormin = abs(otfFx).^2 + abs(otfFy ).^2;\nDenormin = repmat(Denormin, [1, 1, D]);\nDenormin = 1 + 0.5 * c * lambda * Denormin;\n\nU = F; % smoothed image\n\nNormin1 = fft2(U);\n\nfor k = 1: iter\n \n % Intermediate variables \\mu update, in x-axis and y-axis direction\n u_h = [diff(U,1,2), U(:,1,:) - U(:,end,:)];\n u_v = [diff(U,1,1); U(1,:,:) - U(end,:,:)];\n \n mu_h = c .* u_h - 2 .* u_h .* exp(- u_h .* u_h / (2 * gamma^2));\n mu_v = c .* u_v - 2 .* u_v .* exp(- u_v .* u_v / (2 * gamma^2));\n \n % Update the smoothed image U\n Normin2_h = [mu_h(:,end,:) - mu_h(:, 1,:), - diff(mu_h,1,2)];\n Normin2_v = [mu_v(end,:,:) - mu_v(1, :,:); - diff(mu_v,1,1)];\n \n FU = (Normin1 + 0.5 * lambda * (fft2(Normin2_h + Normin2_v))) ./ Denormin;\n U = real(ifft2(FU));\n\n Normin1 = FU; % This helps to further enlarge the smoothing strength\n \nend\n\nU = gather(U);\n", "meta": {"author": "wliusjtu", "repo": "Real-time-Image-Smoothing-via-Iterative-Least-Squares", "sha": "b6c01cb519050614433b3939c82819588e79f206", "save_path": "github-repos/MATLAB/wliusjtu-Real-time-Image-Smoothing-via-Iterative-Least-Squares", "path": "github-repos/MATLAB/wliusjtu-Real-time-Image-Smoothing-via-Iterative-Least-Squares/Real-time-Image-Smoothing-via-Iterative-Least-Squares-b6c01cb519050614433b3939c82819588e79f206/ILS_Welsch_GPU.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.723691076334255}} {"text": "function J=imshift_3D(I,u,kernel)\n% USAGE : J=imshift_3D(I,u);\n% FUNCTION : Shifts the 3D image I by u{1} along the lines and by u{2}\n% along the columns and u{3} in the third dimension. 'u' is an arbitrary \n% vector field structured as:\n% u{1} = u1(x,y,z)\n% u{2} = u2(x,y,z)\n% u{3} = u2(x,y,z). \n% If 'u' is a single vector (i.e. u1 = a, u2 = b and u3 = c) then all the \n% pixels are shifted by the same amount. Note the structure of u is alwasys\n% assumed to be a cell.\n%\n% This function uses cubic spline interpolation used in 'interp_3D.m' with\n% half point symmetric image extensions (can be changed).\n%\n% DATE : 23 November 2014 (updated 28 Jan 2015 by C Gilliam)\n% AUTHOR : Thierry Blu, mailto:thierry.blu@m4x.org\n\n[M,N,P]=size(I);\n\nif nargin == 2,\n% kernel= 'cubicspline';\n kernel='cubicOMOMS';\n% kernel = 'bilinear';\nend\n\nif length(u{1})>1 % check to see if u is a single vector or a field\n [M0,N0,P0]=size(u{1});\n if M0==M&N0==N&P0==P\n \n % Generate x, y and z:\n x = repmat((1:M)',[1,N,P]);\n y = repmat((1:N), [M,1,P]);\n z = repmat(shiftdim((1:P),-1), [M,N,1]);\n \n % Interpolation:\n J=interp_3D(double(x-u{1}),double(y-u{2}),double(z-u{3}),double(I),kernel); %single/double\n J=cast(J,class(I));\n else\n error('Input image and flow dimensions do not match!')\n end\nelse\n u=[u{:}];\n integer_shift=(norm(round(u)-u)<=1e-6);\n\n if integer_shift\n u=round(u);\n xshift=abs(u(1));\n yshift=abs(u(2));\n zshift=abs(u(3));\n switch sign(u(1))\n case -1\n I1=[I;I(end-(1:xshift)+1,:,:)];\n case 0\n I1=I;\n case 1\n I1=[I((xshift:-1:1),:,:);I];\n end\n switch sign(u(2))\n case -1\n I1=[I1 I1(:,end-(1:yshift)+1,:)];\n case 0\n case 1\n I1=[I1(:,(yshift:-1:1),:) I1];\n end\n \n switch sign(u(3))\n case -1\n I1=cat(3,I1,I1(:,:,end-(1:zshift)+1));\n case 0\n case 1\n I1=cat(3,I1(:,:,(zshift:-1:1)), I1);\n end\n\n J=I1((1:M)+max(0,-u(1)),(1:N)+max(0,-u(2)), (1:P)+max(0,-u(3)));\n else\n % Generate x, y and z:\n x = repmat((1:M)',[1,N,P]);\n y = repmat((1:N), [M,1,P]);\n z = repmat(shiftdim((1:P),-1), [M,N,1]);\n \n % Interpolation:\n J=interp_3D(x-u(1),y-u(2),z-u(3),double(I),kernel);\n J=cast(J,class(I));\n end\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_BART/3DLAP/imshift_3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7236585549577821}} {"text": "function value = tfn ( h, a )\n\n%*****************************************************************************80\n%\n%% TFN calculates the T function of Owen.\n%\n% Discussion:\n%\n% Owen's T function is useful for computation of the bivariate normal\n% distribution and the distribution of a skewed normal distribution.\n%\n% Although it was originally formulated in terms of the bivariate\n% normal function, the function can be defined more directly as\n%\n% T(H,A) = 1 / ( 2 * pi ) * \n% Integral ( 0 <= X <= A ) e^( -H^2 * (1+X^2) / 2) / (1+X^2) dX\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 26 August 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% D B Owen,\n% Tables for computing the bivariate normal distribution,\n% Annals of Mathematical Statistics,\n% Volume 27, pages 1075-1090, 1956.\n%\n% J C Young and C E Minder,\n% Algorithm AS 76,\n% An Algorithm Useful in Calculating Non-Central T and \n% Bivariate Normal Distributions,\n% Applied Statistics,\n% Volume 23, Number 3, 1974, pages 455-457.\n%\n% Parameters:\n%\n% Input, real H, A, the arguments of the T function.\n%\n% Output, real VALUE, the value of the T function.\n%\n ngauss = 10;\n\n two_pi_inverse = 0.1591549430918953;\n tv1 = 1.0E-35;\n tv2 = 15.0;\n tv3 = 15.0;\n tv4 = 1.0E-05;\n weight = [ ...\n 0.666713443086881375935688098933E-01, ...\n 0.149451349150580593145776339658E+00, ...\n 0.219086362515982043995534934228E+00, ...\n 0.269266719309996355091226921569E+00, ...\n 0.295524224714752870173892994651E+00, ...\n 0.295524224714752870173892994651E+00, ...\n 0.269266719309996355091226921569E+00, ...\n 0.219086362515982043995534934228E+00, ...\n 0.149451349150580593145776339658E+00, ...\n 0.666713443086881375935688098933E-01];\n xtab = [\n -0.973906528517171720077964012084E+00, ...\n -0.865063366688984510732096688423E+00, ...\n -0.679409568299024406234327365115E+00, ...\n -0.433395394129247190799265943166E+00, ...\n -0.148874338981631210884826001130E+00, ...\n 0.148874338981631210884826001130E+00, ...\n 0.433395394129247190799265943166E+00, ...\n 0.679409568299024406234327365115E+00, ...\n 0.865063366688984510732096688423E+00, ...\n 0.973906528517171720077964012084E+00 ];\n%\n% Test for H near zero.\n%\n if ( abs ( h ) < tv1 )\n value = atan ( a ) * two_pi_inverse;\n%\n% Test for large values of abs(H).\n%\n elseif ( tv2 < abs ( h ) )\n value = 0.0;\n%\n% Test for A near zero.\n%\n elseif ( abs ( a ) < tv1 )\n value = 0.0;\n%\n% Test whether abs(A) is so large that it must be truncated.\n% If so, the truncated value of A is H2.\n%\n else\n\n hs = - 0.5 * h * h;\n h2 = a;\n as = a * a;\n%\n% Computation of truncation point by Newton iteration.\n%\n if ( tv3 <= log ( 1.0 + as ) - hs * as )\n\n h1 = 0.5 * a;\n as = 0.25 * as;\n\n while ( 1 )\n\n rt = as + 1.0;\n h2 = h1 + ( hs * as + tv3 - log ( rt ) ) ...\n / ( 2.0 * h1 * ( 1.0 / rt - hs ) );\n as = h2 * h2;\n\n if ( abs ( h2 - h1 ) < tv4 )\n break\n end\n\n h1 = h2;\n\n end\n\n end\n%\n% Gaussian quadrature on the interval [0,H2].\n%\n rt = 0.0;\n for i = 1 : ngauss\n x = 0.5 * h2 * ( xtab(i) + 1.0 );\n rt = rt + weight(i) * exp ( hs * ( 1.0 + x * x ) ) / ( 1.0 + x * x );\n end\n\n value = rt * ( 0.5 * h2 ) * two_pi_inverse;\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/tfn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7236585522084985}} {"text": "% This example shows how to find the modes of a birefringent\n% (uniaxial) waveguide. This waveguide is the same as the one\n% considered in 'uniaxial_channel.m', except that the c-axis\n% is now rotated by an angle of -pi/4 relative to the x axis.\n\nn1 = 1.55;\nn2x = 2.156;\nn2y = 2.232;\nn2z = 2.232;\ntheta = -pi/4;\n\ne2xx = n2x^2*cos(theta)^2 + n2y^2*sin(theta)^2;\ne2yy = n2y^2*cos(theta)^2 + n2x^2*sin(theta)^2;\ne2xy = cos(theta)*sin(theta)*(n2x^2-n2y^2);\ne2yx = e2xy;\n\nRx = 0.30;\nRy = 0.20;\nside = 0.2;\n\ndx = 0.0025; % grid size (x)\ndy = dx; % grid size (y)\n\nlambda = 1.00; % wavelength\nnmodes = 2; % number of modes to compute\n\n[x,y,xc,yc,nx,ny,epsxx,edges] = ...\n waveguidemeshfull([n1,sqrt(e2xx),n1],[side,2*Ry,side],2*Ry,Rx, ...\n side,dx,dy); \n[x,y,xc,yc,nx,ny,epsxy,edges] = ...\n waveguidemeshfull([0,sqrt(e2xy),0],[side,2*Ry,side],2*Ry,Rx, ...\n side,dx,dy); \n[x,y,xc,yc,nx,ny,epsyx,edges] = ...\n waveguidemeshfull([0,sqrt(e2yx),0],[side,2*Ry,side],2*Ry,Rx, ...\n side,dx,dy); \n[x,y,xc,yc,nx,ny,epsyy,edges] = ...\n waveguidemeshfull([n1,sqrt(e2yy),n1],[side,2*Ry,side],2*Ry,Rx, ...\n side,dx,dy); \n[x,y,xc,yc,nx,ny,epszz,edges] = ...\n waveguidemeshfull([n1,n2z,n1],[side,2*Ry,side],2*Ry,Rx, ...\n side,dx,dy); \n\n% Now we stretch out the mesh at the boundaries:\n[x,y,xc,yc,dx,dy] = stretchmesh(x,y,[80,80,80,80],[4,4,4,4]);\n\n[Hx,Hy,neff] = wgmodes (lambda, n2y, nmodes, dx, dy, epsxx, epsxy, epsyx, epsyy, epszz, '0000');\n\nfprintf(1,'neff = %7.5f\\n',neff);\n\nfigure(1);\n\nfor ii = 1:nmodes,\n subplot(nmodes,2,2*(ii-1)+1);\n contourmode(x,y,Hx(:,:,ii));\n title(sprintf('Hx (mode %d)',ii));\n for v = edges, line(v{:}); end \n subplot(nmodes,2,2*(ii-1)+2);\n contourmode(x,y,Hy(:,:,ii));\n title(sprintf('Hy (mode %d)',ii));\n for v = edges, line(v{:}); end \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/12734-waveguide-mode-solver/examples/uniaxial_channel_rotated.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7236585451729164}} {"text": "%% Dimensional Splitting: Front Tracking\n% In this example, we consider the 2D scalar conservation law\n% \n% $$ u_t + (u^2/2)_x + (u^3/3)_y = 0, \\qquad u(x,y,0)=u_0(x,y)$$\n%\n% which we solve using dimensional splitting. That is, we introduce two\n% one-dimensional operators\n%\n% $$ S_x(t): \\quad v_t + (v^2/2)_x = 0, \\qquad v(x,0)=v_0(x)$$\n%\n% $$ S_y(t): \\quad w_t + (w^3/3)_y = 0, \\qquad w(y,0)=w_0(y)$$\n%\n% and construct the approximate solution from the formula\n%\n% $$u(x,t)\\approx [S_x(0.5\\Delta t)\\circ S_y(\\Delta t)\\circ S_x(0.5\\Delta t) ]^n u_0(x)$$\n%\n% As a one-dimensional solver, we will use front tracking. This algorithm\n% makes a piecewise constant approximation to the flux function\n% and then solves the 1-D hyperbolic problem *exactly*, given piecewise\n% constant initial data.\n%\n% *Disclaimer*: The front-tracking code is built using arrays and is\n% admittedly very slow, e.g., compared with the . It is only meant to illustrate the concepts.\n% For serious computing, one should use e.g., a C/C++ code built using\n% pointers.\n\n%% Initial setup \nxmin=-1.0; xmax=1.0;\nT = 2.0;\nN = 50; \nh = (xmax-xmin)/N;\nx = xmin:h:xmax; y = 0.5*(x(1:end-1)+x(2:end));\n[X,Y] = meshgrid(y,y);\n\n%%\n% The initial function u0 is equal -1 inside a circle of radius 0.4\n% centered at (-1/2,-1/2), equal 1 inside a circle of radius 0.4 centered\n% at (1/2,1/2), and zero otherwise. For later use, we define an anonymous\n% function to do the computation of u0.\ninitData = (@(x,y) 1.0*((x+0.5).^2 + (y+0.5).^2 < 0.16) ...\n - 1.0*((x-0.5).^2 + (y-0.5).^2 < 0.16));\nu0 = initData(X,Y);\ncontourf(X,Y,u0,-1:0.25:1); axis equal; colorbar, title('Initial data')\n\n%% Number of time steps\n% In the first example, we fix the grid resolution and compare the\n% approximate solutions generated with four different splitting steps (n=1,\n% 4, 16, 64). Generally, it makes sense to match the resolution of the\n% front-tracking algorithm with the grid resolution. The resolution of the\n% front-tracking method is determined by segments in the piecewise linear\n% approximation of the flux functions. Here, we simply scale these segments\n% to be inversely proportional with sqrt(N).\nfor i=1:4,\n tic;\n u=DimSplit(u0,x,x,'burgerRsol','cubRsol',0.1/sqrt(N),4^(i-1), T,...\n 'wbar','periodic',[xmin xmax],[xmin xmax]);\n t=toc; st=sprintf('%4.2f',t);\n\n subplot(2,2,i);\n contourf(y,y,u,30), axis equal image; colorbar\n title( sprintf('Grid: %dx%d Steps: %d', N, N, 4^(i-1)));\n xlabel(['Time used: ', st,' sec.']);\n p=get(gca,'position'); p([3 4])=p([3 4])+0.03;\n set(gca,'position',p,'XTickLabel',[]);\nend\n%%\n% Looking at the plots, it is amazing to observe how well the operator\n% splitting method resolves the dynamics of the problem using only one\n% splitting step. The qualitative behavior of the red and blue \"plumes\" is\n% captured almost correctly, even though the shape and position of the\n% curved shock is not correct. Increasing the number of splitting steps to\n% four (CFL number of 12.5) ensures that all qualitative features of the\n% solution are captured correctly. For 64 time steps, the effective CFL\n% number is less than one and the front-tracking method is equivalent to a\n% standard Godunov method. By considering accuracy versus runtime, the\n% optimal number of splitting steps is most likely somewhere between four\n% and sixteen.\n\n%% Increasing grid resolution\n% In the second example, we fix the CFL number to 20 and consider four\n% different grid resolutions.\nCFL=20;\nfor i=1:4,\n N= 32*(2^(i-1));\n h = (xmax-xmin)/N; delta=0.1/sqrt(N); \n x = xmin:h:xmax; \n y = 0.5*(x(1:end-1)+x(2:end));\n [X,Y] = meshgrid(y,y);\n u0=initData(X,Y);\n \n tic;\n Nstep=ceil(T/(CFL*h));\n u=DimSplit(u0,x,x,'burgerRsol','cubRsol',delta,Nstep,T,...\n 'wbar','periodic',[xmin xmax],[xmin xmax]);\n t=toc; st=sprintf('%4.2f',t);\n\n subplot(2,2,i);\n pcolor(y,y,u), axis equal image; shading flat; colorbar\n title( sprintf('Grid: %dx%d, Steps: %d', N, N, Nstep));\n xlabel(['Time used: ', st,' sec.']);\n p=get(gca,'position'); p([3 4])=p([3 4])+0.03;\n set(gca,'position',p,'XTickLabel',[]);\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/OperatorSplitting/Chapter5/Dimsplit/testDS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7235908809556599}} {"text": "% ir_example_kurtosis1\n% example of kurtosis for edge-preserving denoising\n% Copyright 2012-07-28, Jeff Fessler, University of Michigan\n\nif ~exist('xtrue')\n\tN = 2^12;\n\txtrue = ones(N,1);\n\txtrue(end/2+1:end) = 2;\n\tplot(xtrue)\n\n\tsig = 0.2;\n\trng(3)\n\tyi = xtrue + sig * randn(N,1);\n\n\tax = [1 N 0 3];\n\tplot(yi, '.-'), axis(ax)\n\n\tah = [0 3];\n\thh = linspace(0, 3, 121);\n\thp = @(y, c) bar(hh, hist(y, hh), c);\n\n\tsf = @(xh) text(.1, get(gca, 'ylim') * [0; 0.7], ... \n\t\tsprintf('\\\\sigma = %3.2f', std(xh(1:round(0.9*N/2)))));\n\n\tk1f = @(xh) mean((xh-mean(xh)).^4) / std(xh)^4 - 3;\n\tkf = @(xh) text(.1, get(gca, 'ylim') * [0; 0.4], ... \n\t\tsprintf('\\\\gamma_2 = %3.2f', k1f(xh(1:round(0.9*N/2)))));\nend\n\n% use local psf to help select beta\nif ~isvar('R1'), printm 'R1'\n\tf.l2b = 2;\n\tmask = true(N,1);\n\tR1 = Reg1(mask, 'beta', 2^f.l2b);\n%\tqpwls_psf(1, R1, 1, mask, 1, 'loop', 0); % choose beta\nend\n\nif ~isvar('init'), printm 'init'\n\tpsf = qpwls_psf(1, R1, 1, mask, 1);\n\tinit = conv2(psf, yi, 'same');\nend\n\n\tnn = N/2 + (-100:102);\n%\tnn = 1:N;\n\tax = [minmax(nn)' 0 3];\n\tclf, pl = @(i,j) subplot(420+(i-1)*2+j);\n\n\tpl(1,1)\n\tplot(nn, xtrue(nn), 'g.-'), axis(ax), xtick(N/2)\n\ttitle 'true signal'\n\n\tpl(2,1)\n\tplot(nn, yi(nn), 'r.-'), axis(ax), xtick(N/2)\n\ttitle 'data with additive white gaussian noise'\n\tpl(2,2)\n\thp(yi, 'r'), axisx(ah), title 'Histogram'\n\tsf(yi), kf(yi)\n\n\tpl(4,1)\n\tplot(nn, init(nn), 'm.-'), axis(ax), xtick(N/2)\n\tpl(4,2)\n\thp(init, 'm'), axisx(ah)\n\tsf(init), kf(init)\n\nif 0\n\tpl(1,2)\n\tii = N/2+1+[-13:13];\n\tplot(ii, xtrue(ii), 'g.-', ii, init(ii), 'm.-')\n\taxis([minmax(ii)' 0.5 2.5])\nend\n\n\nif ~isvar('xpwls1'), printm 'pwls1'\n\tf.niter1 = 20;\n\txpwls1 = pwls_pcg1(init(mask), 1, 1, yi, R1, 'niter', f.niter1);\n\tplot(xpwls1), axis(ax)\nend\n\n\tpl(3,1)\n\tplot(nn, xpwls1(nn), 'y.-'), axis(ax), xtick(N/2)\n\ttitle 'PWLS with quadratic regularization'\n\tpl(3,2)\n\thp(xpwls1, 'y'), axisx(ah)\n\tsf(xpwls1), kf(xpwls1)\n\nif ~isvar('R2'), printm 'R2' % use small delta to show kurtosis\n\tR2 = Reg1(mask, 'beta', 6*2^f.l2b, 'pot_arg', {'huber', 0.01});\n%\tqpwls_psf(1, R2, 1, mask, 1);\nend\n\n\nif 0 || ~isvar('xpwls2'), printm 'pwls2'\n\tf.niter2 = 400;\n\txpwls2 = pwls_pcg1(init(mask), 1, 1, yi(:), R2, 'niter', f.niter2);\nend\n\n\tpl(4,1)\n\tplot(nn, xpwls2(nn), 'c.-'), axis(ax), xtick(N/2)\n\ttitle 'PWLS with TV (strongly edge-preserving) regularization'\n\tpl(4,2)\n\thp(xpwls2, 'c'), axisx(ah)\n\taxis([0 3 0 300])\n\tsf(xpwls2), kf(xpwls2)\n\nif 0\n\tpl(1,2)\n\tii = N/2+1+[-13:13];\n\tplot(ii, xtrue(ii), 'g.-', ii, xpwls1(ii), 'y.-', ii, xpwls2(ii), 'c.-')\n\taxis([minmax(ii)' 0.5 2.5])\nend\n\n%\tir_savefig c ir_example_kurtosis1a\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/example/ir_example_kurtosis1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.7235908753746011}} {"text": "function y = R3R(x,batch)\n% R3R is a repeated running medians of 3.\n% \n% Usage: y = R3R(x)\n% \n% where x is the input vector with length at least 3\n% y is the return vector of the same length as x\n%\n\n% See John Wilder Tukey, \"EXPLORATORY DATA ANALYSIS\".\n% Addison-Wesley Publishing Co. 1977. Chpt 7A, 7D\n\nif min(size(x)) ~= 1, error('Input must be a vector'); end\nx = x(:); xlen = length(x); cont = 1; y = x;\nif nargin<2, batch = 0; end\nif xlen < 3, \n if ~batch, warning('Input vector must be at least 3 elements long'); end\n cont = 0; \nend\nif cont,\n % running median\n for ii = 2:xlen-1,\n y(ii) = median(x(ii-1:ii+1));\n end\n % compute the low-end point\n delta = abs( y(3)-y(2) );\n slope = sign( y(3)-y(2) );\n switch slope\n case 1\n if y(2)-y(1)<=0 | y(2)-y(1)>=2*delta, y(1) = y(2) - 2*delta; end\n case -1\n if y(1)-y(2)<=0 | y(1)-y(2)>=2*delta, y(1) = y(2) + 2*delta; end\n case 0\n y(1) = y(2);\n end\n % compute the high-end point\n delta = abs( y(xlen-1)-y(xlen-2) );\n slope = sign( y(xlen-1)-y(xlen-2) );\n switch slope\n case 1\n if y(xlen)-y(xlen-1)<=0 | y(xlen)-y(xlen-1)>=2*delta,y(xlen)=y(xlen-1)+2*delta;end\n case -1\n if y(xlen-1)-y(xlen)<=0 | y(xlen-1)-y(xlen)>=2*delta,y(xlen)=y(xlen-1)-2*delta;end\n case 0\n y(xlen) = y(xlen-1);\n end\nend\n% 3-ing to death?\nif ~isequal(y(2:xlen-1),x(2:xlen-1)) & xlen > 3, y = R3R(y); end\n\nreturn\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/274-smooth/smooth/R3R.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7235908707633978}} {"text": "% TIMEDEP This code solves the nonlinear parabolic pde\n%\n% u_t = u_xx + exp(u); u(0,t) = u(1,t) = 0; u(x,0) = 0; 0 < t < 1.\n%\n% with the backward Euler discretization. Newton's method is used\n% for the nonlinear solver. The Jacobian is tridiagonal, so we\n% use the banded differencing function.\n%\n% The value of u at the current time and the time step are passed\n% to the nonlinear residual as MATLAB global variables.\n%\n% This problem is 1-D, so we can store the time history of the\n% integration and draw a surface plot.\n%\nglobal uold dt\ndt=.1;\nnx=63; nt=1+1/dt;\ndx=1/(nx+1);\ntval=0:dt:1;\nxval=0:dx:1;\n%\n% Use tight tolerances, Newton's method, and a tridiagonal Jacobian.\n%\ntol=[1.d-6,1.d-6];\nparms=[40, 1, 0, 1, 1, 1];\nuhist=zeros(nx+2,nt);\nuold=zeros(nx,1); \nfor it=1:nt-1\n [unew,it_hist,ierr]=nsold(uold,'ftime',tol,parms);\n uhist(2:nx+1,it+1)=unew;\n uold=unew;\nend\n%\n% Plot the results.\n%\nmesh(tval,xval,uhist)\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/Chapter2/timedep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.7235428059471344}} {"text": "function [param]=db3w(input)\n% [param] = db3w(input)\n% Dead beat controller for processes of 3rd order (weak version).\n% This function computes parameters of the controller (r0, q0, q1, q2, p1, p2).\n% Output of the controller is calculated follows:\n%\n% r0 q0 + q1*z^-1 + q2*z^-2 \n% U(z^-1) = ----------------------- * W(z^-1) - ------------------------ * Y(z^-1)\n% 1 + p1*z^-1 + p2*z^-2 1 + p1*z^-1 + p2*z^-2\n%\n% where q2=0 and p2=0\n% The controller parameters are calculated for step change of W. \n%\n%% Transfer function of the controlled system is:\n%\n% b1*z^-1 + b2*z^-2 + b3*z^-3\n% Gs(z^-1) = ---------------------------------\n% 1 + a1*z^-1 + a2*z^-2 + a3*z^-3\n%\n% Input: input ... input parameters\n% input(1) ... a1\n% input(2) ... b1\n% input(3) ... a2\n% input(4) ... b2\n% input(5) ... a3\n% input(6) ... b3\n% Output: param ... controller parameters \n% param(1) ... r0\n% param(2) ... q0\n% param(3) ... q1\n% param(4) ... q2\n% param(5) ... p1\n% param(6) ... p2\n\na1=input(1);\nb1=input(2);\na2=input(3);\nb2=input(4);\na3=input(5);\nb3=input(6);\n\nr0 = 1/b1;\nq0 = -a1/b1;\nq1 = -a2/b1;\nq2 = -a3/b1;\np1 = b2/b1;\np2 = b3/b1;\n\nparam=[r0; q0; q1; q2; p1; p2];", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/8381-stcsl-standard-version/db3w.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789548, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.7235428059471343}} {"text": "function [] = main(file, k, iterations)\n %=======================================\n % Initialising Data\n %=======================================\n % k = 3;\n % iterations = 20;\n % file = 'yeast_test.txt';\n data = load(file);\n rows = size(data, 1);\n cols = size(data, 2);\n data = data(1:rows, 1:cols-1);\n clusters = randi([1 k], rows, 1);\n clustered_data = [data clusters];\n mean_matrix = zeros(k, cols-1);\n \n %=======================================\n % Calculating Mean\n %=======================================\n for i = 1:k\n index = clustered_data(:, end) == i;\n indexed_data = clustered_data(index, 1:end-1);\n mean_matrix(i, :) = mean(indexed_data);\n \n end\n \n %=======================================\n % Computing Error\n %=======================================\n error = get_error(clustered_data, mean_matrix);\n fprintf('After initialization: error = %.4f \\n', error);\n \n %=======================================\n % Starting Iterations\n %=======================================\n for p = 1:iterations\n for q = 1:rows\n %=======================================\n % Deciding which Cluster data belongs\n %=======================================\n dist = get_euclidean(data(q, :), mean_matrix);\n [minimum_row, minimum_col] = min(dist);\n clusters(q) = minimum_col;\n end\n clustered_data = [data, clusters];\n \n %=======================================\n % Calculating Mean\n %=======================================\n for i = 1:k\n index = clustered_data(:, end) == i;\n indexed_data = clustered_data(index, 1:end-1);\n mean_matrix(i, :) = mean(indexed_data);\n end\n %=======================================\n % Computing Error\n %=======================================\n error = get_error(clustered_data, mean_matrix);\n fprintf('After iteration %d: error = %.4f \\n', p, error);\n end\nend\n\nfunction [error] = get_error(data, mean_matrix)\n %=======================================\n % Computing Error\n %=======================================\n error = 0;\n for j = 1: size(data, 1)\n c = data(j, end);\n dist = get_euclidean(data(j, 1:end-1), mean_matrix(c, 1:end));\n error = error + dist;\n end\nend\n\nfunction [distance_matrix] = get_euclidean(data, mean_matrix)\n %=======================================\n % Calculating Euclidean\n %=======================================\n dist = data - mean_matrix;\n dist = dist.^2;\n dist = sum(dist, 2);\n distance_matrix = sqrt(dist);\nend", "meta": {"author": "jayshah19949596", "repo": "Machine-Learning-Models", "sha": "66d18aa24744b2ed60e768e96b587594cdb4eed5", "save_path": "github-repos/MATLAB/jayshah19949596-Machine-Learning-Models", "path": "github-repos/MATLAB/jayshah19949596-Machine-Learning-Models/Machine-Learning-Models-66d18aa24744b2ed60e768e96b587594cdb4eed5/K-Mean Clustering/Source Code/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7234967430959011}} {"text": "function u = u_hat ( x )\n\n%*****************************************************************************80\n%\n%% U_HAT evaluates the target function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 March 2011\n%\n% Author:\n%\n% Jeff Borggaard, John Burkardt, Catalin Trenchea, Clayton Webster\n%\n% Parameters:\n%\n% Input, real X(*), the evaluation points.\n%\n% Output, real U(*), the function values.\n%\n u = x .* ( 1 - x.^2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/optimal_control_1d/u_hat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.723462893488487}} {"text": "function mean = gamma_mean ( a, b, c )\n\n%*****************************************************************************80\n%\n%% GAMMA_MEAN returns the mean of the Gamma PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, C, the parameters of the PDF.\n% 0.0 < B,\n% 0.0 < C.\n%\n% Output, real MEAN, the mean of the PDF.\n%\n mean = a + b * 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/prob/gamma_mean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7234462135182969}} {"text": "function Ip=perm2PermMatrix(p)\n%%PERM2PERMMATRIX Given a permutation of the values 1:n, obtain the\n% permutation matrix that corresponds to the permutation.\n%\n%INPUTS: p A 1Xn or nX1 permutation of the values 1:n.\n%\n%OUTPUTS: Ip A permutation matrix such that Ip*(1:n).'=p.\n%\n%The creation of a permutation matrix from a permutation basically involves\n%rearranging the columns of an identity matrix.\n%\n%EXAMPLE:\n% p=[3;1;4;5;2];\n% Ip=perm2PermMatrix(p);\n% all(Ip*(1:5).'==p)\n%\n%November 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nn=length(p);\nIp=zeros(n,n);\nfor i=1:n\n Ip(i,p(i))=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/Mathematical_Functions/Combinatorics/perm2PermMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.8774768002981829, "lm_q1q2_score": 0.7234461979859202}} {"text": "function X = find_line_intersection(P1,V1,P2,V2)\n\nif(length(P1) ~= 2)\n error('This function only works in 2D');\nend \n\nA = [V1(1),-V2(1) ; V1(2) -V2(2)];\nB = P2-P1;\nif(det(A) == 0)\n X = [];\n return;\nend\n\nK = inv(A)*B;\n\nX = P1 + K(1)*V1;\n", "meta": {"author": "lmb-freiburg", "repo": "orion", "sha": "db5df75e16e3068952e65a08cfb04bb7e353ce34", "save_path": "github-repos/MATLAB/lmb-freiburg-orion", "path": "github-repos/MATLAB/lmb-freiburg-orion/orion-db5df75e16e3068952e65a08cfb04bb7e353ce34/tools/general_tools/find_line_intersection.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416414, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7233800563067638}} {"text": "function y = gam_lpdf(x,a,b)\n%GAM_LPDF Log of Gamma probability density function (lpdf).\n%\n% Y = GAM_LPDF(X,A,B) Returns the gamma lpdf with\n% shape A and inverse scale B, at the values in X.\n%\n% The size of X 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% The parameterization is as in Gelman, Carlin, Stern, Dunson, Vehtari,\n% and Rubin (2013). Bayesian Data Analysis, third edition.\n%\n% Copyright (c) 1998-2004 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% License (version 3 or later); please refer to the file \n% License.txt, included with the software, for details.\n\nif nargin < 3, \n error('Requires three input arguments.');\nend\n\n%y = b.^a/gamma(a)*x^(a-1)*exp(-b*x);\ny = a.*log(b)-gammaln(a)+(a-1).*log(x)-b.*x;\n", "meta": {"author": "gpstuff-dev", "repo": "gpstuff", "sha": "114937ec0a201306489a66cbba38283e722fb998", "save_path": "github-repos/MATLAB/gpstuff-dev-gpstuff", "path": "github-repos/MATLAB/gpstuff-dev-gpstuff/gpstuff-114937ec0a201306489a66cbba38283e722fb998/dist/gam_lpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7233800532375592}} {"text": "%% MULTIGRID OF FOR THE STOKES EQNS IN 2D\n%\n% This example is to show the convergence of multigrid methods for various\n% finite element approximation of the Stokes equation on the unit square:\n%\n% -div(mu*grad u) + grad p = f in \\Omega,\n% - div u = 0 in \\Omega,\n% u = g_D on \\Gamma.\n%\n% with the pure Dirichlet boundary condition.\n%\n% Reference\n%\n% M. Wang and L. Chen. Multigrid Methods for the Stokes equations\n% using Distributive Gauss-Seidel Relaxations based on the Least Squares\n% Commutator. Journal of Scientific Computing. 56(2): 409-431, 2013.\n\nclear variables; \nclose all;\n\n%% Setting\n[node,elem] = squaremesh([0,1,0,1],0.125);\n% [node,elem] = circlemesh(0,0,1,0.25);\n% [node,elem] = uniformrefine(node,elem);\nbdFlag = setboundary(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\nfigure;\nshowmesh(node,elem); pause(0.5);\n% pde\npde = Stokesdata1; \n% pde = StokesZulehnerdata;\noption.L0 = 0;\noption.maxIt = 4;\noption.printlevel = 1;\noption.plotflag = 0;\noption.rateflag = 0;\n\n%% MG options\noption.solver = 'asmg';\noption.smoothingstep = 2;\noption.smootherbarSp = 'SGS';\n\n%% CR-P0 element\ndisp('CR-P0')\noption.elemType = 'CRP0';\nfemStokes(mesh,pde,option);\n\n%% P2-P0 element\ndisp('P2-P0')\noption.elemType = 'P2P0';\nfemStokes(mesh,pde,option);\n\n%% P2-P1 element\ndisp('P2-P1')\noption.elemType = 'P2P1';\noption.solver = 'asmg';\nfemStokes(mesh,pde,option);\n\n%% isoP2-P0 element\ndisp('isoP2-P0')\noption.elemType = 'isoP2P0';\nfemStokes(mesh,pde,option);\n\n%% isoP2-P1 element\ndisp('isoP2-P1')\noption.elemType = 'isoP2P1';\nfemStokes(mesh,pde,option);\n\n%% P1b-P1 element\ndisp('P1b-P1')\noption.elemType = 'P1bP1';\nfemStokes(mesh,pde,option);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/solver/Stokesasmgrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7233367897375692}} {"text": "function fI = faceinterpolate3(f,node,face,quadOrder)\n%% FACEINTERPOLATE3 interpolate to face elements RT0.\n%\n% uI = faceinterpolate3(u,node,face) interpolates a given function u\n% into the lowesr order RT0. The coefficient is given by the face integral \n% int_f u*n ds. \n%\n% Example\n%\n% \n% [node,elem] = cubemesh([-1,1,-1,1,-1,1],1);\n% maxIt = 3;\n% pde = polynomialdata0;\n% err = zeros(maxIt,1); \n% N = zeros(maxIt,1);\n% for i =1:maxIt\n% [node,elem] = uniformrefine3(node,elem);\n% uI = faceinterpolate3(pde.u,node,elem);\n% err(i) = getL2error3RT0(node,elem,pde.u,uI);\n% N(i) = size(u,1);\n% end\n% figure;\n% showrate(N,err,2,'r-+','||u - u_I||');\n%\n% See also edgeinterpolate, edgeinterpolate1, edgeinterpolate2\n%\n% Created by Lin Zhong and Ming Wang at July, 2012.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n%% \nNF = size(face,1);\nv12 = node(face(:,2),:) - node(face(:,1),:);\nv13 = node(face(:,3),:) - node(face(:,1),:);\nnVec = mycross(v12,v13);\n\n%% assemble the right hand side\nif ~exist('quadOrder','var'), quadOrder = 2; end\n[lambda,weight] = quadpts(quadOrder);\nnQuad = size(lambda,1);\nbt = zeros(NF,3);\nfor p = 1:nQuad\n pxy = lambda(p,1)*node(face(:,1),:) ...\n\t\t+ lambda(p,2)*node(face(:,2),:) ...\n\t\t+ lambda(p,3)*node(face(:,3),:);\n bt = bt + weight(p)*f(pxy);\nend\nfI = dot(nVec,bt,2)/2;", "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/faceinterpolate3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7233367849496455}} {"text": "% Compute empirical p-vals under the null hypothesis that observed samples\n% come from a given surrogate distribution. P-values for Type I error in\n% rejecting the null hypothesis are obtained by finding the proportion of\n% samples in the distribution that\n% (a) are larger than the observed sample (one-sided test)\n% (b) are larger or smaller than the observed sample (two-sided test).\n%\n% This function is based on Arnaud Delorme's statcond:COMPUTE_PVALS\n% function from EEGLAB\n% \n% Inputs:\n%\n% distribution: [d1 x d2 x ... x dM x N] matrix of surrogate samples. \n% distribution(i,j,k,...,:) is a collection of N samples\n% from a surrogate distribution.\n% observed: [d1 x d2 x ... x dM] matrix of observations.\n% tail: can be 'one' or 'both' indicating a one-tailed or\n% two-tailed test\n% Outputs:\n% \n% pvals: [d1 x d2 x ... x dM] matrix of p-values specifying\n% probability of Type I error in rejecting the null \n% hypothesis\n% \n% Author: Tim Mullen and Arnaud Delorme, SCCN/INC/UCSD\n\n% Copyright: Tim Mullen and Arnaud Delorme\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 pvals = stat_surrogate_pvals(distribution,observed,tail)\nnumDims = ndims(distribution);\nif iscolumn(distribution)\n\tnumDims = 1;\nend\n\nn = size(distribution, numDims);\n% once support for matlab <= R2016b is dropped:\n% pvals = sum(distribution >= observed, numDims) / n;\npvals = sum(bsxfun(@ge, distribution, observed), numDims) / n;\n\nif any(strcmpi(tail, {'right', 'one'}))\n\t% nothing to be done\n\treturn;\nend\n\np_left = 1 - pvals + sum(bsxfun(@eq, distribution, observed), numDims) / n;\n\nif strcmpi(tail, 'both')\n\tpvals = 2 * min(pvals, p_left);\nelseif strcmpi(tail, 'left')\n\tpvals = p_left;\nelse\n\terror('invalid value for tail: \"%s\", should be left, right, one or both', tail);\nend\n\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/statistics/stat_surrogate_pvals.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.7233367755094133}} {"text": "% Chapter 15 - Local and Global Bifurcations.\n% Programs_15a - Determining the coefficients of the Lyapunov function\n% for a Lienard system.\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% V3=[V30;V21;V12;V03], V4=[V40;V31;V22;V13;V04;eta4],\n% V5=[V50;V41;V32;V23;V14;V05],V6=[V60;V51;V42;V33;V24;V15;V06;eta6]\n% Symbolic Math toolbox required.\n\n% When determining coefficients of V_{4m} set V_{2m,2m}=0.\n% When determining coefficients of V_{4m+2} set V_{2m,2m+2}+V_{2m+2,2m}=0.\n\nclear all\n\nsyms a1 a2 b2 a3 b3 a4 b4 a5 b5;\nA=[3 0 -2 0;0 0 1 0;0 -1 0 0;0 2 0 -3];\nB=[b2; 0; a2; 0];\n\nV3=A\\B\n\nA=[0 -1 0 0 0 -1;0 3 0 -3 0 -2;0 0 0 1 0 -1;4 0 -2 0 0 0;0 0 2 0 -4 0; 0 0 1 0 0 0];\nB=[a3; -2*a2*b2; 0; b3-2*a2^2;0;0];\n\nV4=A\\B\n\nA=[5 0 -2 0 0 0;0 0 3 0 -4 0;0 0 0 0 1 0;0 -1 0 0 0 0;0 4 0 -3 0 0;0 0 0 2 0 -5];\nB=[b4-10*a2^2*b2/3;0;0;a4-2*a2^3;-2*a2*b3;0];\n\nV5=A\\B\n\nA=[6 0 -2 0 0 0 0 0;0 0 4 0 -4 0 0 0;0 0 0 0 2 0 -6 0;0 0 1 0 1 0 0 0;\n 0 -1 0 0 0 0 0 -1;0 5 0 -3 0 0 0 -3;0 0 0 3 0 -5 0 -3;0 0 0 0 0 1 0 -1];\nB=[b5-6*a2*a4-4*a2^2*b2^2/3+8*a2^4;16*a2^4/3+4*a2^2*b3/3-8*a2*a4/3;0;0;\n a5-8*a2^3*b2/3;-2*a2*b4+8*a2^3*b2+2*a2*b2*b3-4*a4*b2;\n 16*a2^3*b2/3+4*a2*b2*b3/3-8*a4*b2/3;0];\n\nV6=A\\B\n\nL0=-a1\neta4=V4(6,1);\n[n,d]=numden(-3/8*a3+1/4*a2*b2);\nL1=n\na3=2*a2*b2;\neta6=V6(8,1);\n[n,d]=numden(-5/16*a5+1/8*a2*b4-5/24*a2*b2*b3+5/12*a4*b2);\nL2=n\n\n% End of Programs_15a.", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2374-dynamical-systems-with-applications-using-matlab/MATLAB files 20013a/Programs_15a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.723310042481008}} {"text": "function c=ref_rdgtii(f,g,a,M)\n%REF_RDGTII Reference Real DGT type II\n% Usage: c=ref_rdgt(f,g,a,M);\n%\n% Linear algebra version of the algorithm. Create big matrix\n% containing all the basis functions and multiply with the transpose.\n\n\nL=size(f,1);\n\nb=L/M;\nN=L/a;\n\nMhalf=ceil(M/2);\n\n\nF=zeros(L,M*N);\n\nl=(0:L-1).';\n\nfor n=0:N-1\t \n\n % Do the unmodulated coefficient.\n F(:,M*n+1)=circshift(g,n*a+floor(a/2));\n \n for m=1:Mhalf-1\n F(:,M*n+2*m)=sqrt(2)*cos(2*pi*m*(l+.5)/M).*circshift(g,n*a+floor(a/2));\n \n F(:,M*n+2*m+1)=sqrt(2)*sin(2*pi*m*(l+.5)/M).*circshift(g,n*a+floor(a/2));\n \n end;\n\n if mod(M,2)==0\n F(:,M*(n+1))=cos(pi*l).*circshift(g,n*a+floor(a/2));\n end;\n \nend;\n\n% dot-transpose will work because F is real.\nc=F.'*f;\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_rdgtii.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7232911389542485}} {"text": "function [ grid_weight, grid_point ] = sparse_grid_cfn ( dim_num, level_max, ...\n rule, point_num )\n\n%*****************************************************************************80\n%\n%% SPARSE_GRID_CFN computes a sparse grid based on a CFN 1D rule.\n%\n% Discussion:\n%\n% The 1D quadrature rule is assumed to be Closed Fully Nested.\n%\n% Closed Fully Nested rules include Clenshaw Curtis rules.\n%\n% A Smolyak construction is used to create a multidimensional sparse grid.\n%\n% The user specifies:\n% * the spatial dimension of the quadrature region,\n% * the level that defines the Smolyak grid.\n% * the quadrature rule.\n% * the number of points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 31 March 2008\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, controls the size of the final\n% sparse grid.\n%\n% Input, integer RULE, the index of the rule.\n% 1, \"CC\", Clenshaw Curtis Closed Fully Nested rule.\n% 2, \"F1\", Fejer 1 Open Fully Nested rule.\n% 3, \"F2\", Fejer 2 Open Fully Nested rule.\n% 4, \"GP\", Gauss Patterson Open Fully Nested rule.\n% 5, \"GL\", Gauss Legendre Open Weakly Nested rule.\n% 6, \"GH\", Gauss Hermite Open Weakly Nested rule.\n% 7, \"LG\", Gauss Laguerre Open Non Nested rule.\n%\n% Input, integer POINT_NUM, the number of points in the grid,\n% as determined by LEVELS_INDEX_SIZE.\n%\n% Output, real GRID_WEIGHT(POINT_NUM), the weights.\n%\n% Output, real GRID_POINT(DIM_NUM,POINT_NUM), the points.\n%\n if ( rule ~= 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPARSE_GRID_CFN - Fatal error!\\n' );\n fprintf ( 1, ' Illegal input rule index = %d\\n', rule );\n error ( 'SPARSE_GRID_CFN - Fatal error!' );\n end\n%\n% Determine the index vector, relative to the full product grid,\n% that identifies the points in the sparse grid.\n%\n [ grid_index, grid_base ] = levels_index_cfn ( dim_num, level_max, point_num );\n%\n% Compute the physical coordinates of the abscissas.\n%\n if ( 0 == level_max ) \n order_max = 1;\n else\n order_max = 2^level_max + 1;\n end\n\n grid_point = zeros ( dim_num, point_num );\n\n for point = 1 : point_num\n for dim = 1 : dim_num\n\n if ( rule == 1 )\n grid_point(dim,point) = ...\n cc_abscissa ( order_max, grid_index(dim,point) + 1 );\n end\n\n end\n end\n%\n% Gather the weights.\n%\n grid_weight = sparse_grid_weights_cfn ( dim_num, level_max, rule, ...\n point_num, grid_index );\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/sandia_sparse/sparse_grid_cfn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7232819335039478}} {"text": "function fem = genFEM3D(mesh,femtype,bcind,option)\n\n%% Usage: Form FEM global degrees of freedom on 3D tetrahedron mesh\n%\n% INPUTS:\n% mesh --- a struct data contains rich mesh information.\n% bcind --- [bc1,bc2,bc3,bc4,bc5,bc6] denotes the boundary condition of\n% bc1: x = xmin bc2: x = xmax\n% bc3: y = ymin bc4: y = ymax\n% bc5: z = zmin bc6: z = zmax\n% if bc = 1: Dirichlet boundary condition\n% bc = 2: Neumann boundary condition\n% bc = 3: Robin boundary condition\n% femtype --- the type of finite element methods\n% Conforming: P1, P2\n%\n% OUTPUTS:\n% fem --- a struct data contains the following fields:\n% fem.p: (x,y,z) coordinate of each vertex w.r.t a global DoF\n% fem.t: indices of global DoF in each element\n% fem.bc: indices of global DoF on the boundary\n% fem.mapper: a vector to extract unknowns from global DoF.\n% fem.type: type of finite element methods\n% fem.ldof: number of local DoF on each element\n% fem.ng: number of Gaussian quadrature points on each element\n\n% Last Modified: 08/07/2020 by Xu Zhang\n\n%% 0. Inputs\nif nargin == 2\n bcind = [1,1,1,1,1,1]; option.ng = 4;\nend\nif nargin == 3\n option.ng = 4;\nend\nif ~isfield(option,'ng')\n option.ng = 4;\nend\nng = option.ng;\n\n%% 1. Form fem p, t, and basis functions\nif strcmp(femtype,'P1')\n fem = genP1FEM3D(mesh); option.ngauss = 4; \nelseif strcmp(femtype,'P2')\n fem = genP2FEM3D(mesh); option.ngauss = 11;\nend\n\n%% 2. Form Gaussian Quadrature\np = mesh.p; t = mesh.t;\nX1 = p(t(:,1),:); X2 = p(t(:,2),:); X3 = p(t(:,3),:); X4 = p(t(:,4),:); \ngw = gaussWtetra(ng);\n[gx,gy,gz] = gaussPtetra(X1,X2,X3,X4,ng);\nA = tetraArea(X1,X2,X3,X4);\nfem.gw = gw; fem.gx = gx; fem.gy = gy; fem.gz = gz; fem.area = A;\n\n%% 3. Form bc mapper\n[bc,mapper] = boundaryNode3D(mesh,fem.p,bcind);\nfem.bc = bc; fem.mapper = mapper; fem.ng = option.ng; fem.bcind = bcind;\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/genFEM3D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7232819270487766}} {"text": "function gaussian_test ( )\n\n%*****************************************************************************80\n%\n%% GAUSSIAN_TEST examines the gaussian correlation.\n%\n% Discussion:\n%\n% Note that I can't use the original value EIGEN_NUM = 20. The \n% EIGS function fails to converge. In fact, it still fails at 12.\n%\n% This code is based substantially on a document by Toby Driscoll.\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% Reference:\n%\n% Toby Driscoll,\n% Mercer's theorem and the Karhunen-Loeve expansion,\n% Oxford University Mathematical Institute,\n% http://www2.maths.ox.ac.uk/chebfun/examples/stats/pdf/MercerKarhunenLoeve.pdf\n%\n rmpath ( '/usr/local/matlab/toolbox/datafeed/datafeed' )\n addpath ( '../chebfun' )\n\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GAUSSIAN_TEST:\\n' );\n fprintf ( 1, ' Demonstrate Mercer''s theorem and the KL expansion\\n' );\n fprintf ( 1, ' for the gaussian kernel.\\n' );\n%\n% Set the interval.\n%\n a = 0.0;\n b = 10.0;\n fprintf ( 1, ' Using interval [%g,%g]\\n', a, b );\n s_num = 21;\n s_vec = linspace ( a, b, s_num );\n%\n% FRED is a function from the CHEBFUN library.\n%\n% It constructs a \"chebop\" representing the Fredholm integral operator\n% with kernel K for functions in domain [A,B].\n%\n F = fred ( @gaussian_correlation, domain ( [ a, b ] ) );\n%\n% EIGS has been extended to be able to compute the eigenvalues Lambda\n% and eigenfunctions Psi of the Fredholm integral operator represented by F.\n%\n% The \"LM\" switch requests that we return the eigenvalues of largest magnitude.\n%\n% Each Psi is a CHEBFUN, that is, it takes a real number argument.\n%\n eigen_num = 20;\n [ Psi, Lambda ] = eigs ( F, eigen_num, 'lm' );\n\n eigen_found = length ( Lambda );\n fprintf ( 1, ' Requested %d eigenmodes, computed %d\\n', eigen_num, eigen_found );\n eigen_num = min ( eigen_num, eigen_found );\n%\n% Print the eigenvalues.\n%\n lambda_vec = diag ( Lambda );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I Lambda(I)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : eigen_num\n fprintf ( 1, ' %2d %10g\\n', i, lambda_vec(i) );\n end\n%\n% Plot the eigenvalues.\n%\n figure ( 1 )\n clf\n plot ( lambda_vec, 'Linewidth', 2 );\n hold on\n plot ( lambda_vec, 'b.', 'Markersize', 20 );\n title ( 'gaussian: Mercer eigenvalues' );\n xlabel ( '<--- N --->')\n grid on\n print -dpng 'gaussian_figure1.png'\n%\n% Plot selected eigenfunctions.\n%\n figure ( 2 )\n subplot ( 4, 1, 1 )\n plot ( Psi(:,1), 'Linewidth', 2 );\n title ( 'gaussian: Mercer eigenfunction PSI(1)' )\n grid on\n subplot ( 4, 1, 2 )\n plot ( Psi(:,2), 'Linewidth', 2 );\n title ( 'gaussian: Mercer eigenfunction PSI(2)' )\n grid on\n subplot ( 4, 1, 3 )\n plot ( Psi(:,5), 'Linewidth', 2 );\n title ( 'gaussian: Mercer eigenfunction PSI(5)' )\n grid on\n subplot ( 4, 1, 4 )\n plot ( Psi(:,10), 'Linewidth', 2 );\n title ( 'gaussian: Mercer eigenfunction PSI(10)' )\n grid on\n print -dpng 'gaussian_figure2.png'\n%\n% Orthonormality check.\n%\n ptp = Psi' * Psi;\n error_frobenius = r8mat_is_identity ( eigen_num, ptp );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Frobenius norm of I - Psi'' * Psi = %g\\n', error_frobenius );\n%\n% K(S,S) should be exactly 1.\n% Because we are using a truncated representation of K, our estimate of K(S,S)\n% will be smaller than 1.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Truncated estimate of K(s,s) = 1 for S in the interval.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' S K(s,s) estimate\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : 21\n s = s_vec(i);\n ptlp = Psi(s,:) * Lambda * Psi(s,:)';\n fprintf ( 1, ' %10g %14g\\n', s, ptlp );\n end\n%\n% Look at eigenvalue decay.\n%\n x = diff ( log ( ( 1:eigen_num ) ) );\n y = diff ( log ( lambda_vec ) )';\n c = y ./ x;\n figure ( 3 );\n clf\n plot ( c, 'Linewidth', 2 );\n grid on\n hold on\n plot ( c, 'b.', 'Markersize', 20 );\n xlabel ( '<-- N -->' )\n title ( 'gaussian: Eigenvalue decay rate' );\n print -dpng 'gaussian_figure3.png'\n%\n% Look at eigenvalue sum.\n%\n% The trace of K(s,s) over [a,b] should be the integral of 1 over [a,b],\n% that is, b - a.\n%\n% We compare the trace to the partial sums of the lambda's to see how much\n% of the variance of the process we have captured.\n%\n trace_K = b - a;\n lambda_cum = cumsum ( lambda_vec ) / trace_K;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Index Cumulative Eigenvalue sum\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : eigen_num\n fprintf ( 1, ' %5d %10g\\n', i, lambda_cum(i) );\n end\n%\n% We decide to use the first 10 eigenfunctions.\n%\n eigen_use = 10;\n%\n% Find 400 realizations of the process by selecting, for each realization,\n% 10 random parameters Z in the truncated KL expansion.\n%\n Z = randn ( eigen_use, 400 );\n X = Psi(:,1:eigen_use) * ( sqrt ( Lambda(1:eigen_use,1:eigen_use) ) * Z ); \n%\n% Plot 40 of the realizations;\n% Plot their mean, computed from all 400.\n%\n figure ( 4 )\n clf\n plot ( X(:,1:40) )\n mu = sum ( X, 2 ) / 400;\n hold on;\n plot ( mu, 'k', 'linewidth', 3 );\n title ( 'gaussian: 40 Random Realizations X(t,omega), and their Mean.' )\n print -dpng 'gaussian_figure4.png'\n%\n% Estimate the covariance from the data.\n%\n figure ( 5 )\n clf\n [ S, T ] = meshgrid ( s_vec, s_vec );\n C = cov ( X(s_vec,:)' );\n mesh ( S, T, C );\n hold on;\n D = gaussian_correlation ( S, T );\n plot3 ( S, T, D, 'k.', 'markersize', 10 )\n title ( 'gaussian: Covariance K(S,T) (dots), and Estimate from Realizations (mesh)' )\n print -dpng 'gaussian_figure5.png'\n%\n% Using just 10 functions in the expansion,\n% reduce the correlation length,\n% and examine the sum of the lambda's.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Use a fixed number of eigenfunctions = %d\\n', eigen_use );\n fprintf ( 1, ' but vary the correlation length RHOBAR.\\n' );\n fprintf ( 1, ' (We used RHOBAR = 1 above.)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The sum of the eigenvalues, divided by (B-A),\\n' );\n fprintf ( 1, ' discloses the relative amount of the total variation\\n' );\n fprintf ( 1, ' that is captured by the truncated expansion.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' RHOBAR VARSUM\\n' );\n fprintf ( 1, '\\n' );\n rhobar = 4.0;\n for i = 1 : 10\n K = @ ( s, t ) exp ( - ( ( s - t ) / rhobar ).^2 );\n F = fred ( K, domain ( [ a, b ] ) );\n lambda_vec = eigs ( F, eigen_use, 'lm' );\n varsum = sum ( lambda_vec(1:eigen_use) ) / ( b - a );\n fprintf ( 1, ' %10g %10g\\n', rhobar, varsum );\n rhobar = rhobar / 2.0;\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GAUSSIAN_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n rmpath ( '../chebfun' )\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/correlation_chebfun/gaussian_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7232819270032034}} {"text": "function [os,os1] = getosmatrix_bb(boxes,gts)\n%% Given two sets of bounding boxes, N1 in the first one, and N2 in\n%% the second one, compute a N1xN2 overlap score matrix where the\n%% overlap score is the ratio of the intersection to union\n%% Tomasz Malisiewicz (tomasz@cmu.edu)\n\nif ~exist('gts','var')\n gts = boxes;\nend\n\nif numel(boxes) == 0 || numel(gts) == 0\n os = zeros(size(boxes,1),size(gts,1));\n\n return;\nend\n\nx1 = boxes(:,1);\ny1 = boxes(:,2);\nx2 = boxes(:,3);\ny2 = boxes(:,4);\n\narea = (x2-x1+1) .* (y2-y1+1);\n\nxa1 = gts(:,1);\nya1 = gts(:,2);\nxa2 = gts(:,3);\nya2 = gts(:,4);\n\narea2 = (xa2-xa1+1) .* (ya2-ya1+1);\n\nos = zeros(size(boxes,1),size(gts,1));\nif size(boxes,1)*size(gts,1)==0\n return;\nend\n\nif nargout == 2\n os1 = os;\nend\n\nfor i = 1:size(boxes,1)\n \n xx1 = max(boxes(i,1),gts(:,1));\n yy1 = max(boxes(i,2),gts(:,2));\n xx2 = min(boxes(i,3),gts(:,3));\n yy2 = min(boxes(i,4),gts(:,4));\n\n w = xx2-xx1+1;\n h = yy2-yy1+1;\n \n o = w.*h;\n o( (w<0) | (h<0) ) = 0;\n\n os(i,:) = o ./ (eps + (area(i) + area2 - o));\n \n if nargout == 2\n os1(i,:) = (o ./ (eps + area2));\n %os1(i,:) = o ./ area(i);\n end\nend\n\n \n\n", "meta": {"author": "quantombone", "repo": "exemplarsvm", "sha": "54c07ec4faa96fb949991ebc512eaf7446e034f7", "save_path": "github-repos/MATLAB/quantombone-exemplarsvm", "path": "github-repos/MATLAB/quantombone-exemplarsvm/exemplarsvm-54c07ec4faa96fb949991ebc512eaf7446e034f7/util/getosmatrix_bb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7232780174659886}} {"text": "\ns = [1 1 1 1 1]';\nt = [2 3 4 5 6]';\nG = graph(s',t');\nI = full(incidence(G))\n\nn = length(s);\n\nind = (1:n)'\nA = full(sparse([s;t],[ind;ind],[ones(n,1)*-1;ones(n,1)]));\n\nA\n\nI\n\n\nA - I\n\n\ns = [1 1 1 1 1]';\nt = [6 3 4 5 2]';\nG = graph(s',t');\nI = full(incidence(G))\n\nind = (1:n)'\nA = full(sparse([s;t],[ind;ind],[ones(n,1)*-1;ones(n,1)]));\n\nA\n\nI\n\n\nA - I\n\n\ns = [1 1 1 1 1 6]';\nn = length(s);\nt = [6 3 4 5 2 1]';\nG = graph(s',t');%switches orientation of duplicates\nI = full(incidence(G))\n\nind = (1:n)'\nA = full(sparse([s;t],[ind;ind],[ones(n,1)*-1;ones(n,1)]));\n\nA\n\nI\n\n\nA - I\n\ns = [1 1 1 1 1 6]';\nn = length(s);\nt = [6 3 4 5 2 1]';\nG = digraph(s',t'); %does not switch orientation of duplicates\nI = full(incidence(G))\n\nind = (1:n)'\nA = full(sparse([s;t],[ind;ind],[ones(n,1)*-1;ones(n,1)]));\n\nA\n\nI\n\n\nA - I\n", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/test/additionalTests/testHypergraphConstruction/testGraphIncidence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7232780134832578}} {"text": "function I=gausslaguerr(f2,a,b,n)\n\n%I=gausslaguerr(f,a,b,n)\n%Aproximates integral using Gauss-Laguerre method\n\n%Laguerre polynomial\np=polelague(n);\n%Roots\nx=roots(p(n+1,:));\n\nG=feval(f2,x);\t\t%Function evaluation on the nodes\n\n%Coeficients\nfor i=1:n\n C(i)=((factorial(n).^2).*x(i))./(polyval(p(n+1,:),(x(i))).^2);\nend\n\n\nI=dot(C,G);\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/8067-gauss-laguerre/gausslaguerr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.723260440530423}} {"text": "function f = p31_f ( n, x )\n\n%*****************************************************************************80\n%\n%% P31_F evaluates the objective function for problem 31.\n%\n% Discussion:\n%\n% The minimal function value is -10.15320.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 January 2001\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Zbigniew Michalewicz,\n% Genetic Algorithms + Data Structures = Evolution Programs,\n% Third Edition,\n% Springer Verlag, 1996,\n% ISBN: 3-540-60676-9,\n% LC: QA76.618.M53.\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 m = 5;\n a = [ 4.0, 4.0, 4.0, 4.0; ...\n 1.0, 1.0, 1.0, 1.0; ...\n 8.0, 8.0, 8.0, 8.0; ...\n 6.0, 6.0, 6.0, 6.0; ...\n 3.0, 7.0, 3.0, 7.0 ]';\n\n c = [ 0.1, 0.2, 0.2, 0.4, 0.6 ]';\n\n f = 0.0;\n for j = 1 : m\n f = f - 1.0 / ( c(j) + sum ( ( x(1:n) - a(1:n,j) ).^2 ) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_opt/p31_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.7232604404033268}} {"text": "function w = wf_fft(w);\n\n% WAVEFORM = WF_FFT(WAVEFORM) calculate frequency spectrum of a waveform.\n% The results of the fast fourier transform is added as new fields\n% in the waveform:\n% FFT_FREQ is a vector of frequencies with N samples\n% FFT_AMP is a vector of spetral amplitudes\n% FFT_PHASE is a vector of phases\n% FFT_DOM is the scalar frequency of the maximum amplitude \n% peak (or dominant frequency. This could change)\n\n% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks\n% $Date$\n% $Revision$\n\n\n\n\nadmin.deprecated(mfilename,'wf_fft.compute');\n\n\n% CHECK ARGUMENTS\nif ~strcmpi(class(w),'waveform')\n error('First input must be a waveform object');\nend\n\n\n% STEP THROUGH WAVFORMS ADDING NEW FIELDS\n[N,M] = size(w);\nfor i = 1:N*M\n Fn = get(w(i),'NYQ');\n x = get(w(i),'DATA');\n NFFT=2.^(ceil(log(length(x))/log(2))); % Next highest power of 2\n FFTX=fft(x,NFFT); % Take fft, padding with zeros.\n NumUniquePts = ceil((NFFT+1)/2);\n FFTX=FFTX(1:NumUniquePts); % throw out neg frequencies\n MX=abs(FFTX); % Take magnitude of X\n MX=MX*2; % Multiply by 2 \n MX=MX/length(x); \n PX=phase(FFTX); % Take magnitude of X\n f=(0:NumUniquePts-1)*2/NFFT; \n f=f*Fn;\n w(i) = addfield(w(i),'FFT_FREQ',f');\n w(i) = addfield(w(i),'FFT_AMP',MX);\n w(i) = addfield(w(i),'FFT_PHASE',PX);\n a = find(MX == max(MX));\n w(i) = addfield(w(i),'FFT_DOM',f(a));\nend;\n\n\n\n", "meta": {"author": "geoscience-community-codes", "repo": "GISMO", "sha": "a4eafca9d2ac85079253510005ef00aa9998d030", "save_path": "github-repos/MATLAB/geoscience-community-codes-GISMO", "path": "github-repos/MATLAB/geoscience-community-codes-GISMO/GISMO-a4eafca9d2ac85079253510005ef00aa9998d030/deprecated/fft_tools/wf_fft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.7232604299173884}} {"text": "function val = straight_line_integral_2(xs,ys,zs,data3d,x1,y1,z1,x2,y2,z2)\n%\n% Deshan Yang, PhD\n%\tDepartment of radiation oncology\n%\tWashington University in Saint Louis\n% 01/16/2011, Saint Louis, MO, USA\n% \n% val = straight_line_integral_2(xs,ys,zs,data3d,x1,y1,z1,x2,y2,z2)\n%\n% Perform straight line integration on the 3D data from point 1 to point\n% 2\n%\n% Deshan Yang, PhD\n% 01/16/2011, Saint Louis, MO, USA\n%\n% This function assumes that the point positions are given in the same\n% coordinate system as the 3D data. Any coordination transformation or\n% scaling should be done priorly. \n%\n% Both data and points should be in single, or double\n%\ndim = [size(data3d) 1];\n% if numel(xs)~=length(xs) || length(xs) ~= dim(2) || ...\n% \t\tnumel(ys)~=length(ys) || length(ys) ~= dim(1) || ...\n% \t\tnumel(zs)~=length(zs) || length(zs) ~= dim(3)\n% \tfprintf('Incorrect image data: length does not match to the image dimension.\\n');\n% \treturn;\n% end\n\n% Make sure the image and the voxel coordinate be positively increasing. If not, then flip it\n[xs,ys,zs,data3d] = make_sure_positive(xs,ys,zs,data3d);\npsrc = [x1,y1,z1];\npcdet = [x2,y2,z2];\n\ncorner_points = [...\n\txs(1) ys(1) zs(1);...\n\txs(1) ys(1) zs(end);...\n\txs(1) ys(end) zs(1);...\n\txs(1) ys(end) zs(end);...\n\txs(end) ys(1) zs(1);...\n\txs(end) ys(1) zs(end);...\n\txs(end) ys(end) zs(1);...\n\txs(end) ys(end) zs(end)...\n\t];\n\ncorner_points_t = zeros(8,1);\nfor k =1:8\n\tp = corner_points(k,:);\n\t[q,corner_points_t(k)] = project_1_point_to_a_line(psrc,pcdet,p);\nend\n\nt_min = min(corner_points_t);\nt_max = max(corner_points_t);\n\ndist = norm(psrc-pcdet);\n\nN = ceil(dist*(t_max-t_min));\t% N planes\ndt = (t_max-t_min)/N;\nts = t_min:dt:t_max;\n\nxst = psrc(1)+(pcdet(1)-psrc(1))*ts;\nyst = psrc(2)+(pcdet(2)-psrc(2))*ts;\nzst = psrc(3)+(pcdet(3)-psrc(3))*ts;\n\nval = sum(interp3(xs,ys,zs,data3d,xst,yst,zst,'linear',0))*dt;\n\n% % Transform the point coordinate into the image voxel index\n% x1 = (x1 - xs(1))/dx+0.5;\n% x2 = (x2 - xs(1))/dx+0.5;\n% y1 = (y1 - ys(1))/dy+0.5;\n% y2 = (y2 - ys(1))/dy+0.5;\n% z1 = (z1 - zs(1))/dz+0.5;\n% z2 = (z2 - zs(1))/dz+0.5;\n% \n% \n% nx = ceil(min(x1,x2)):floor(max(x1,x2));\n% tx = (nx-x1)/(x2-x1);\n% \n% ny = ceil(min(y1,y2)):floor(max(y1,y2));\n% ty = (ny-y1)/(y2-y1);\n% \n% nz = ceil(min(z1,z2)):floor(max(z1,z2));\n% tz = (nz-z1)/(z2-z1);\n% \n% \n% \n% ts = sort([tx ty tz]); % It may be slow here\n% dist = sqrt((x2-x1).^2+(y2-y1).^2+(z2-z1).^2);\n% \n% nx = (x2-x1)*ts+x1;\n% ny = (y2-y1)*ts+y1;\n% nz = (z2-z1)*ts+z1;\n% \n% idxes = find(nx>=0 & nx<=dim(2) & ny>=0 & ny<=dim(1) & nz>=0 & nz<=dim(3));\n% nx = nx(idxes);\n% ny = ny(idxes);\n% nz = nz(idxes);\n% N_1 = length(nx)-1;\n% \n% xidx = max(ceil((nx(1:N_1)+nx(2:end))/2),1);\n% yidx = max(ceil((ny(1:N_1)+ny(2:end))/2),1);\n% zidx = max(ceil((nz(1:N_1)+nz(2:end))/2),1);\n% \n% if ~isempty(xidx)\n% if x2~=x1\n% lengths = diff(nx)/(x2-x1);\n% else\n% lengths = diff(ny)/(y2-y1);\n% end\n% \n% val = sum(data3d(sub2ind(dim,yidx,xidx,zidx)).*lengths)*dist;\n% \tval = val*dx*dy*dz;\t% Convert the length back to the original image coordinate length\n% else\n% val = 0;\n% end\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/30207-cone-beam-ct-simulation/straight_line_integral_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7232569371524387}} {"text": "function T = tn_vector()\n\n T.expectation = @TN_vector_expectation;\n function [exp] = TN_vector_expectation(mus, taus)\n\n sigmas = 1.0 ./ sqrt(taus);\n x = - mus ./ sigmas;\n %lambdax = norm.pdf(x)/(0.5*erfc(x/sqrt(2)));\n lambdax = pdf('Normal',x,0,1) ./ (0.5 * erfc(x/sqrt(2)));\n exp = mus + sigmas .* lambdax;\n\n for i = 1 : length(exp)\n v = exp(i);\n mu = mus(i);\n tau = taus(i);\n sigma = sigmas(i);\n\n if mu < -30 * sigma\n v = 1/(abs(mu)*tau);\n else\n % do nothing;\n end\n\n if isnan(v)\n v = 0;\n end\n\n exp(i) = v;\n end\n\n\n exp(isinf(exp)) = 0;\n\n end \n\n\n T.variance = @TN_vector_variance;\n function [var] = TN_vector_variance(mus, taus)\n\n sigmas = 1.0 ./ sqrt(taus);\n x = - mus ./ sigmas;\n %lambdax = norm.pdf(x)/(0.5*erfc(x/math.sqrt(2)));\n lambdax = pdf('Normal',x,0,1) ./ (0.5 * erfc(x/sqrt(2))); \n deltax = lambdax .* (lambdax-x);\n var = sigmas.^2 .* ( 1 - deltax );\n\n for i = 1 : length(var)\n v = var(i);\n mu = mus(i);\n tau = taus(i);\n sigma = sigmas(i);\n\n if mu < -30 * sigma\n v = (1/(abs(mu)*tau)).^2;\n else\n % do nothing;\n end\n\n if isnan(v)\n v = 0;\n end\n\n var(i) = v;\n end\n\n var(isinf(var)) = 0;\n end\nend", "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/probabilistic/tn_vector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458251637412, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7232450698266063}} {"text": "function [e,E_q] = q2e(q)\n\n% Q2E Quaternion to Euler angles conversion.\n% Q2E(Q) returns an Euler angles vector [roll;pitch;yaw] corresponding to\n% the orientation quaternion Q.\n%\n% [E,Jq] = Q2E(Q) returns also the Jacobian matrix.\n%\n% See also QUATERNION, EULERANGLES, R2Q, E2Q, Q2V.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n% Revised 2018 Joan Sola - handle full gimbal range (2pi, pi, 2pi)\n\n\n\na = q(1); % a: real part\nb = q(2);\nc = q(3);\nd = q(4);\n\nr32 = 2*c*d + 2*a*b;\nr33 = a^2 - b^2 - c^2 + d^2;\nr31 = 2*b*d - 2*a*c;\nr21 = 2*b*c + 2*a*d;\nr11 = a^2 + b^2 - c^2 - d^2;\n\nn = sqrt(r11^2+r21^2);\n\ne = [ atan2( r32,r33)\n atan2(-r31, n)\n atan2( r21,r11) ];\n \nif nargout >1 \n \n % partials of R wrt q\n dr11dq = [ 2*a, 2*b, -2*c, -2*d];\n dr21dq = [ 2*d, 2*c, 2*b, 2*a];\n dr31dq = [ -2*c, 2*d, -2*a, 2*b];\n dr32dq = [ 2*b, 2*a, 2*d, 2*c];\n dr33dq = [ 2*a, -2*b, -2*c, 2*d];\n \n % partials of n wrt R elements\n dndr11 = r11/n;\n dndr21 = r21/n;\n \n % partials of e wrt n\n de2dn = r31/(n^2 + r31^2);\n \n % partials of e wrt R elements\n de1dr32 = r33/(r33^2 + r32^2);\n de1dr33 = -r32/(r33^2 + r32^2);\n de2dr31 = -n /(n^2 + r31^2);\n de3dr11 = -r21/(r11^2 + r21^2);\n de3dr21 = r11/(r11^2 + r21^2);\n \n % chain rule: rows of Jacobian\n de1dq = de1dr33*dr33dq + de1dr32*dr32dq;\n de2dq = de2dr31*dr31dq + de2dn*(dndr11*dr11dq+dndr21*dr21dq);\n de3dq = de3dr11*dr11dq + de3dr21*dr21dq;\n \n % assemble Jacobian\n E_q = [de1dq;de2dq;de3dq];\nend\n\nreturn\n\n%% jac\n\nsyms a b c d real\nq=[a;b;c;d];\n[e,E_q] = q2e(q);\nsimplify(E_q-jacobian(e,q))\n\n%% test\nfor i = 1 : 1000\n e = [2/3;1/3;2/3] .* randn(3,1);\n eo = q2e(e2q(e));\n if any(e-eo > 1e-10) % Should never enter this IF\n e\n eo\n disp('###########')\n end\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/FrameTransforms/Rotations/q2e.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7232122297232826}} {"text": "function [ r, w ] = oned_gauss ( rule )\n\n%*****************************************************************************80\n%\n%% ONED_GAUSS sets up a Gauss quadrature rule in [-1,+1].\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 March 2011\n%\n% Author:\n%\n% Jeff Borggaard\n%\n% Parameters:\n%\n% Input, integer RULE, the number of Gauss points desired.\n%\n% Output, real R(RULE), Gauss points located between (-1,1).\n%\n% Output, real W(RULE), Gauss weights corresponding to r.\n%\n r = zeros(rule,1);\n w = zeros(rule,1);\n\n if ( rule == 1 )\n r(1) = 0;\n w(1) = 2;\n elseif ( rule == 2 )\n r(1) =-1.0 / sqrt(3.0);\n r(2) =-r(1);\n w(1) = 1.0;\n w(2) = 1.0;\n elseif ( rule == 3 )\n r(1) =-sqrt(3.0/5.0);\n r(2) = 0.0;\n r(3) =-r(1);\n w(1) = 5.0 / 9.0;\n w(2) = 8.0 / 9.0;\n w(3) = w(1);\n elseif ( rule == 4 )\n r(1) =-sqrt((3.0+2.0*sqrt(6.0/5.0))/7.0);\n r(2) =-sqrt((3.0-2.0*sqrt(6.0/5.0))/7.0);\n r(3) =-r(2);\n r(4) =-r(1);\n w(1) = 0.5 - 1.0 / ( 6.0 * sqrt(6.0/5.0) );\n w(2) = 0.5 + 1.0 / ( 6.0 * sqrt(6.0/5.0) );\n w(3) = w(2);\n w(4) = w(1);\n elseif ( rule == 5 )\n r(1) =-sqrt(5.0+4.0*sqrt(5.0/14.0)) / 3.0;\n r(2) =-sqrt(5.0-4.0*sqrt(5.0/14.0)) / 3.0;\n r(3) = 0.0;\n r(4) =-r(2);\n r(5) =-r(1);\n w(1) = 161.0/450.0-13.0/(180.*sqrt(5.0/14.0));\n w(2) = 161.0/450.0+13.0/(180.*sqrt(5.0/14.0));\n w(3) = 128.0/225.0;\n w(4) = w(2);\n w(5) = w(1);\n elseif ( rule == 6 )\n r(1) = -0.2386191861;\n r(2) = -0.6612093865;\n r(3) = -0.9324695142;\n r(4) = - r(1);\n r(5) = - r(2);\n r(6) = - r(3);\n w(1) = .4679139346;\n w(2) = .3607615730;\n w(3) = .1713244924;\n w(4) = w(1);\n w(5) = w(2);\n w(6) = w(3);\n else\n error('Quadrature rule not supported')\n keyboard\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/optimal_control_1d/oned_gauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7232122229978677}} {"text": "function rank = bal_seq_rank ( n, t )\n\n%*****************************************************************************80\n%\n%% BAL_SEQ_RANK ranks a balanced sequence.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 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 0's (and 1's) in the sequence.\n% N must be positive.\n%\n% Input, integer T(2*N), a balanced sequence.\n%\n% Output, integer RANK, the rank of the balanced sequence.\n%\n\n%\n% Check.\n%\n ierror = bal_seq_check ( n, t );\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BAL_SEQ_RANK - Fatal error!\\n' );\n fprintf ( 1, ' The input array is illegal.\\n' );\n fprintf ( 1, ' IERROR = %d\\n', ierror );\n error ( 'BAL_SEQ_RANK - Fatal error!' );\n end\n\n y = 0;\n rank = 0;\n\n for x = 1 : 2 * n - 1\n\n if ( t(x) == 0 )\n y = y + 1;\n else\n mxy = mountain ( n, x, y + 1 );\n rank = rank + mxy;\n y = y - 1;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/combo/bal_seq_rank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7231940451887532}} {"text": "function v = mono_value ( d, nx, f, x )\n\n%*****************************************************************************80\n%\n%% MONO_VALUE evaluates a monomial.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 December 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer D, the spatial dimension.\n%\n% Input, integer NX, the number of evaluation points.\n%\n% Input, integer F(D), the exponents of the monomial.\n%\n% Input, real X(D,NX), the coordinates of the evaluation points.\n%\n% Output, real V(NX), the value of the monomial at X.\n%\n v = ones ( nx, 1 );\n\n for i = 1 : d\n v(1:nx,1) = v(1:nx,1) .* x(i,1:nx)' .^ f(i);\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/lagrange_nd/mono_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633915959134572, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7231940351614227}} {"text": "function out = SY_StatAv(y,whatType,n)\n% SY_StatAv Simple mean-stationarity metric, StatAv.\n%\n% The StatAv measure divides the time series into non-overlapping subsegments,\n% calculates the mean in each of these segments and returns the standard deviation\n% of this set of means.\n%\n% Empirically mean-stationary data would display StatAv approaching to zero.\n%\n% cf. \"Heart rate control in normal and aborted-SIDS infants\", S. M. Pincus et al.\n% Am J. Physiol. Regul. Integr. Comp. Physiol. 264(3) R638 (1993)\n%\n%---INPUTS:\n%\n% y, the input time series\n%\n% whatType, the type of StatAv to perform:\n% (i) 'seg': divide the time series into n segments\n% (ii) 'len': divide the time series into segments of length n\n%\n% n, either the number of subsegments ('seg') or their length ('len')\n\n% Might be nicer to use the 'buffer' function for this...?\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(whatType)\n whatType = 'seg'; % divide into n segments by default\nend\n\nif nargin < 3 || isempty(n)\n n = 5; % use 5 segments\nend\n\nN = length(y); % Time-series length\n\n% ------------------------------------------------------------------------------\n% Compute the means in local time-series segments\n% ------------------------------------------------------------------------------\n\nswitch whatType\ncase 'seg'\n % divide time series into n segments\n M = zeros(n,1);\n p = floor(N/n);% lose the last N mod n data points\n\n for j = 1:n\n M(j) = mean(y(p*(j-1)+1:p*j));\n end\ncase 'len'\n if N > 2*n\n pn = floor(N/n);\n M = zeros(pn,1);\n for j = 1:pn\n M(j) = mean(y((j-1)*n+1:j*n));\n end\n else\n fprintf(1,'This time series (N = %u) is too short for StatAv(%s,''%u'')\\n',N,whatType,n);\n out = NaN; return\n end\notherwise\n error('Error evaluating StatAv of type ''%s'', please select either ''seg'' or ''len''',whatType)\nend\n\n% ------------------------------------------------------------------------------\n% Compute the StatAv statistic\n\ns = std(y); % should be 1 (for a z-scored time-series input)\nsdav = std(M);\nout = sdav/s;\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/SY_StatAv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7231490994488713}} {"text": "%DEMEV2\tDemonstrate Bayesian classification for the MLP.\n%\n%\tDescription\n%\tA synthetic two class two-dimensional dataset X is sampled from a\n%\tmixture of four Gaussians. Each class is associated with two of the\n%\tGaussians so that the optimal decision boundary is non-linear. A 2-\n%\tlayer network with logistic outputs is trained by minimizing the\n%\tcross-entropy error function with isotroipc Gaussian regularizer (one\n%\thyperparameter for each of the four standard weight groups), using\n%\tthe scaled conjugate gradient optimizer. The hyperparameter vectors\n%\tALPHA and BETA are re-estimated using the function EVIDENCE. A graph\n%\tis plotted of the optimal, regularised, and unregularised decision\n%\tboundaries. A further plot of the moderated versus unmoderated\n%\tcontours is generated.\n%\n%\tSee also\n%\tEVIDENCE, MLP, SCG, DEMARD, DEMMLP2\n%\n\n%\tCopyright (c) Ian T Nabney (1996-2001)\n\n\nclc;\n\ndisp('This program demonstrates the use of the evidence procedure on')\ndisp('a two-class problem. It also shows the improved generalisation')\ndisp('performance that can be achieved with moderated outputs; that is')\ndisp('predictions where an approximate integration over the true')\ndisp('posterior distribution is carried out.')\ndisp(' ')\ndisp('First we generate a synthetic dataset with two-dimensional input')\ndisp('sampled from a mixture of four Gaussians. Each class is')\ndisp('associated with two of the Gaussians so that the optimal decision')\ndisp('boundary is non-linear.')\ndisp(' ')\ndisp('Press any key to see a plot of the data.')\npause;\n\n% Generate the matrix of inputs x and targets t.\n\nrand('state', 423);\nrandn('state', 423);\n\nClassSymbol1 = 'r.';\nClassSymbol2 = 'y.';\nPointSize = 12;\ntitleSize = 10;\n\nfh1 = figure;\nset(fh1, 'Name', 'True Data Distribution');\nwhitebg(fh1, 'k');\n\n% \n% Generate the data\n% \nn=200;\n\n% Set up mixture model: 2d data with four centres\n% Class 1 is first two centres, class 2 from the other two\nmix = gmm(2, 4, 'full');\nmix.priors = [0.25 0.25 0.25 0.25];\nmix.centres = [0 -0.1; 1.5 0; 1 1; 1 -1];\nmix.covars(:,:,1) = [0.625 -0.2165; -0.2165 0.875];\nmix.covars(:,:,2) = [0.25 0; 0 0.25];\nmix.covars(:,:,3) = [0.2241 -0.1368; -0.1368 0.9759];\nmix.covars(:,:,4) = [0.2375 0.1516; 0.1516 0.4125];\n\n[data, label] = gmmsamp(mix, n);\n\n% \n% Calculate some useful axis limits\n% \nx0 = min(data(:,1));\nx1 = max(data(:,1));\ny0 = min(data(:,2));\ny1 = max(data(:,2));\ndx = x1-x0;\ndy = y1-y0;\nexpand = 5/100;\t\t\t% Add on 5 percent each way\nx0 = x0 - dx*expand;\nx1 = x1 + dx*expand;\ny0 = y0 - dy*expand;\ny1 = y1 + dy*expand;\nresolution = 100;\nstep = dx/resolution;\nxrange = [x0:step:x1];\nyrange = [y0:step:y1];\n% \t\t\t\t\t\n% Generate the grid\n% \n[X Y]=meshgrid([x0:step:x1],[y0:step:y1]);\n% \n% Calculate the class conditional densities, the unconditional densities and\n% the posterior probabilities\n% \npx_j = gmmactiv(mix, [X(:) Y(:)]);\npx = reshape(px_j*(mix.priors)',size(X));\npost = gmmpost(mix, [X(:) Y(:)]);\np1_x = reshape(post(:, 1) + post(:, 2), size(X));\np2_x = reshape(post(:, 3) + post(:, 4), size(X));\n\nplot(data((label<=2),1),data(label<=2,2),ClassSymbol1, 'MarkerSize', ...\nPointSize)\nhold on\naxis([x0 x1 y0 y1])\nplot(data((label>2),1),data(label>2,2),ClassSymbol2, 'MarkerSize', ...\n PointSize)\n\n% Convert targets to 0-1 encoding\ntarget=[label<=2];\ndisp(' ')\ndisp('Press any key to continue')\npause; clc;\n\ndisp('Next we create a two-layer MLP network with 6 hidden units and')\ndisp('one logistic output. We use a separate inverse variance')\ndisp('hyperparameter for each group of weights (inputs, input bias,')\ndisp('outputs, output bias) and the weights are optimised with the')\ndisp('scaled conjugate gradient algorithm. After each 100 iterations')\ndisp('the hyperparameters are re-estimated twice. There are eight')\ndisp('cycles of the whole algorithm.')\ndisp(' ')\ndisp('Press any key to train the network and determine the hyperparameters.')\npause;\n\n% Set up network parameters.\nnin = 2;\t\t% Number of inputs.\nnhidden = 6;\t\t% Number of hidden units.\nnout = 1;\t\t% Number of outputs.\nalpha = 0.01;\t\t% Initial prior hyperparameter.\naw1 = 0.01;\nab1 = 0.01;\naw2 = 0.01;\nab2 = 0.01;\n\n% Create and initialize network weight vector.\nprior = mlpprior(nin, nhidden, nout, aw1, ab1, aw2, ab2);\nnet = mlp(nin, nhidden, nout, 'logistic', prior);\n\n% Set up vector of options for the optimiser.\nnouter = 8;\t\t\t% Number of outer loops.\nninner = 2;\t\t\t% Number of innter loops.\noptions = foptions;\t\t% Default options vector.\noptions(1) = 1;\t\t\t% This provides display of error values.\noptions(2) = 1.0e-5;\t\t% Absolute precision for weights.\noptions(3) = 1.0e-5;\t\t% Precision for objective function.\noptions(14) = 100;\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, data, target, 'scg');\n [net, gamma] = evidence(net, data, target, ninner);\n fprintf(1, '\\nRe-estimation cycle %d:\\n', k);\n disp([' alpha = ', num2str(net.alpha')]);\n fprintf(1, ' gamma = %8.5f\\n\\n', gamma);\n disp(' ')\n disp('Press any key to continue.')\n pause;\nend\n\ndisp(' ')\ndisp('Network training and hyperparameter re-estimation are now complete.')\ndisp('Notice that the final error value is close to the number of data')\ndisp(['points (', num2str(n), ') divided by two.'])\ndisp('Also, the hyperparameter values differ, which suggests that a single')\ndisp('hyperparameter would not be so effective.')\ndisp(' ')\ndisp('First we train an MLP without Bayesian regularisation on the')\ndisp('same dataset using 400 iterations of scaled conjugate gradient')\ndisp(' ')\ndisp('Press any key to train the network by maximum likelihood.')\npause;\n% Train standard network\nnet2 = mlp(nin, nhidden, nout, 'logistic');\noptions(14) = 400;\nnet2 = netopt(net2, options, data, target, 'scg');\ny2g = mlpfwd(net2, [X(:), Y(:)]);\ny2g = reshape(y2g(:, 1), size(X));\n\ndisp(' ')\ndisp('We can now plot the function represented by the trained networks.')\ndisp('We show the decision boundaries (output = 0.5) and the optimal')\ndisp('decision boundary given by applying Bayes'' theorem to the true')\ndisp('data model.')\ndisp(' ')\ndisp('Press any key to add the boundaries to the plot.')\npause;\n\n% Evaluate predictions.\n[yg, ymodg] = mlpevfwd(net, data, target, [X(:) Y(:)]);\nyg = reshape(yg(:,1),size(X));\nymodg = reshape(ymodg(:,1),size(X));\n\n% Bayesian decision boundary\n[cB, hB] = contour(xrange,yrange,p1_x,[0.5 0.5],'b-');\n[cNb, hNb] = contour(xrange,yrange,yg,[0.5 0.5],'r-');\n[cN, hN] = contour(xrange,yrange,y2g,[0.5 0.5],'g-');\nset(hB, 'LineWidth', 2);\nset(hNb, 'LineWidth', 2);\nset(hN, 'LineWidth', 2);\nChandles = [hB(1) hNb(1) hN(1)];\nlegend(Chandles, 'Bayes', ...\n 'Reg. Network', 'Network', 3);\n\ndisp(' ')\ndisp('Note how the regularised network predictions are closer to the')\ndisp('optimal decision boundary, while the unregularised network is')\ndisp('overtrained.')\n\ndisp(' ')\ndisp('We will now compare moderated and unmoderated outputs for the');\ndisp('regularised network by showing the contour plot of the posterior')\ndisp('probability estimates.')\ndisp(' ')\ndisp('The first plot shows the regularised (moderated) predictions')\ndisp('and the second shows the standard predictions from the same network.')\ndisp('These agree at the level 0.5.')\ndisp('Press any key to continue')\npause\nlevels = 0:0.1:1;\nfh4 = figure;\nset(fh4, 'Name', 'Moderated outputs');\nhold on\nplot(data((label<=2),1),data(label<=2,2),'r.', 'MarkerSize', PointSize)\nplot(data((label>2),1),data(label>2,2),'y.', 'MarkerSize', PointSize)\n\n[cNby, hNby] = contour(xrange, yrange, ymodg, levels, 'k-');\nset(hNby, 'LineWidth', 1);\n\nfh5 = figure;\nset(fh5, 'Name', 'Unmoderated outputs');\nhold on\nplot(data((label<=2),1),data(label<=2,2),'r.', 'MarkerSize', PointSize)\nplot(data((label>2),1),data(label>2,2),'y.', 'MarkerSize', PointSize)\n\n[cNbm, hNbm] = contour(xrange, yrange, yg, levels, 'k-');\nset(hNbm, 'LineWidth', 1);\n\ndisp(' ')\ndisp('Note how the moderated contours are more widely spaced. This shows')\ndisp('that there is a larger region where the outputs are close to 0.5')\ndisp('and a smaller region where the outputs are close to 0 or 1.')\ndisp(' ')\ndisp('Press any key to exit')\npause\nclose(fh1);\nclose(fh4);\nclose(fh5);", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/netlab3.3/demev2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7231490993002425}} {"text": "function colors = RainbowColors_ss(numcolors)\n% Generates RGB Triplets based on the idealized colors below:\n% 0. red [1 0 0]\n% 1. orange [1 .5 0]\n% 2. yellow [1 1 0]\n% 2.5. green [0 1 0]\n% 3. cyan [0 1 1]\n% 4. blue [0 0 1]\n% 5. purple [.5 0 .5]\n% \n% INPUT\n% -numcolors: number of colors you want out\n% OUTPUT\n% - colors a 3 column matrix signifying Red Green and Blue values with each\n% column, number of rows = numcolors\n% \n% Brendon Watson 2015\n\ncidxs = linspace(0,1,numcolors);\nr = redfunc(cidxs);\ng = greenfunc(cidxs);\nb = bluefunc(cidxs);\n\ncolors = [r g b];\n\n1;\n\nfunction y = redfunc(x)\nfor a = 1:length(x)\n if x(a)<2/5\n y(a) = 1;\n elseif x(a)>=2/5 && x(a)<2.5/5\n y(a) = 1-5*(x(a)-2/5);\n elseif x(a)>=2.5/5 && x(a)<4/5\n y(a) = 0;\n elseif x(a)>=4/5\n y(a) = 0+.5*5*(x(a)-4/5);\n end\nend\ny = y';\n\nfunction y = greenfunc(x)\nfor a = 1:length(x)\n if x(a)<2/5\n y(a) = .5*5*(x(a));\n elseif x(a)>=2/5 && x(a)<3/5\n y(a) = 1;\n elseif x(a)>=3/5 && x(a)<4/5\n y(a) = 1-5*(x(a)-3/5);\n elseif x(a)>=4/5\n y(a) = 0;\n end\nend\ny = y';\n\nfunction y = bluefunc(x)\nfor a = 1:length(x)\n if x(a)<3/5\n y(a) = 0;\n elseif x(a)>=2.5/5 && x(a)<3/5\n y(a) = 5*(x(a)-2.5/5);\n elseif x(a)>=3/5 && x(a)<4/5\n y(a) = 1;\n elseif x(a)>=4/5\n y(a) = 1-.5*5*(x(a)-4/5);\n end\nend\ny = y';\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/detectors/detectStates/SleepScoreMaster/private/RainbowColors_ss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367526, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.7231490948022314}} {"text": "function CRB = crb_general_sto_1d(design, wavelength, doas, P, noise_var, snapshot_count)\n%CRB_GENERAL_STO_1D CRB for general 1D arrays based on the stochastic\n%(unconditional) model, in radians.\n%Inputs:\n% design - Array design.\n% wavelength - Wavelength.\n% doas - DOA vector in radians.\n% P - Source covariance matrix. If all sources are uncorrelated and\n% shares the same power, you can just pass in a scalar. If all\n% sources are uncorrelated but have different powers, you can just\n% pass in a vector.\n% noise_var - Noise power.\n% snapshot_count - (Optional) number of snapshots. Default is one.\n%Reference:\n% [1] P. Stoica and A. Nehorai, \"Performance study of conditional and\n% unconditional direction-of-arrival estimation,\" IEEE Transactions on\n% Acoustics, Speech and Signal Processing, vol. 38, no. 10,\n% pp. 1783-1795, Oct. 1990.\nif design.dim ~= 1\n error('1D array expected.');\nend\nif nargin <= 5\n snapshot_count = 1;\nend\nm = design.element_count;\nk = length(doas);\nP = unify_source_power_matrix(P, k);\n[A, D] = steering_matrix(design, wavelength, doas);\nR = A*P*A' + noise_var * eye(m);\nH = D'*(eye(m) - A/(A'*A)*A')*D;\nCRB = real(H .* ((P*A'/R*A*P).'));\nCRB = eye(k) / CRB * (noise_var / snapshot_count / 2);\nend\n\n", "meta": {"author": "morriswmz", "repo": "doa-tools", "sha": "76c1cb7f365615d719fbb050c7ea52b616a28c33", "save_path": "github-repos/MATLAB/morriswmz-doa-tools", "path": "github-repos/MATLAB/morriswmz-doa-tools/doa-tools-76c1cb7f365615d719fbb050c7ea52b616a28c33/performance/crb_general_sto_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7231040463373113}} {"text": "function particles = correction_step(particles, z)\n\n% Weight the particles according to the current map of the particle\n% and the landmark observations z.\n% z: struct array containing the landmark observations.\n% Each observation z(j) has an id z(j).id, a range z(j).range, and a bearing z(j).bearing\n% The vector observedLandmarks indicates which landmarks have been observed\n% at some point by the robot.\n\n% Number of particles\nnumParticles = length(particles);\n\n% Number of measurements in this time step\nm = size(z, 2);\n\n% TODO: Construct the sensor noise matrix Q_t (2 x 2)\nQ_t = 0.01*eye(2);\n% process each particle\nfor i = 1:numParticles\n robot = particles(i).pose;\n % process each measurement\n for j = 1:m\n % Get the id of the landmark corresponding to the j-th observation\n % particles(i).landmarks(l) is the EKF for this landmark\n l = z(j).id;\n\n % The (2x2) EKF of the landmark is given by\n % its mean particles(i).landmarks(l).mu\n % and by its covariance particles(i).landmarks(l).sigma\n\n % If the landmark is observed for the first time:\n if (particles(i).landmarks(l).observed == false)\n\n % TODO: Initialize its position based on the measurement and the current robot pose:\n\t\n particles(i).landmarks(l).mu = [robot(1)+z(j).range*cos(z(j).bearing + robot(3)); robot(2) + z(j).range*sin(z(j).bearing + robot(3))];\n\n % get the Jacobian with respect to the landmark position\n [h, H] = measurement_model(particles(i), z(j));\n\n % TODO: initialize the EKF for this landmark\n\n particles(i).landmarks(l).sigma = H\\Q_t*inv(H)';\n\n % Indicate that this landmark has been observed\n particles(i).landmarks(l).observed = true;\n\n else\n\n % get the expected measurement\n [expectedZ, H] = measurement_model(particles(i), z(j));\n\n % TODO: compute the measurement covariance\n\t\n\tQ = H*particles(i).landmarks(l).sigma*H' + Q_t;\n\n % TODO: calculate the Kalman gain\n\t\n\tK = particles(i).landmarks(l).sigma*H'/Q;\n\n % TODO: compute the error between the z and expectedZ (remember to normalize the angle)\n\t\n\tz_diff = [z(j).range;z(j).bearing] - expectedZ;\n\tz_diff(2) = normalize_angle(z_diff(2));\n\n % TODO: update the mean and covariance of the EKF for this landmark\n\n\tparticles(i).landmarks(l).mu = particles(i).landmarks(l).mu + K*z_diff;\n\tparticles(i).landmarks(l).sigma = (eye(2) - K*H)*particles(i).landmarks(l).sigma;\n\n % TODO: compute the likelihood of this observation, multiply with the former weight\n % to account for observing several features in one time step\n\tparticles(i).weight = particles(i).weight*1/sqrt(det(2*pi*Q))*exp(-1/2*z_diff'/Q*z_diff);\n end\n\n end % measurement loop\nend % particle loop\n\nend\n", "meta": {"author": "kiran-mohan", "repo": "SLAM-Algorithms-Octave", "sha": "e0254ad38cfca2170b2af68c96c183df77c76252", "save_path": "github-repos/MATLAB/kiran-mohan-SLAM-Algorithms-Octave", "path": "github-repos/MATLAB/kiran-mohan-SLAM-Algorithms-Octave/SLAM-Algorithms-Octave-e0254ad38cfca2170b2af68c96c183df77c76252/6_FastSLAM/octave/correction_step.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.723050034526525}} {"text": "function [ c, seed ] = c8vec_uniform_01 ( n, seed )\n\n%*****************************************************************************80\n%\n%% C8VEC_UNIFORM_01 returns a unit pseudorandom C8VEC.\n%\n% Discussion:\n%\n% The angles should be uniformly distributed between 0 and 2 * PI,\n% the square roots of the radius uniformly distributed between 0 and 1.\n%\n% This results in a uniform distribution of values in the unit circle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 September 2006\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 N, the number of values to compute.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, complex C(N), the pseudorandom complex vector.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n c = zeros ( n, 1 );\n\n i4_huge = 2147483647;\n\n if ( seed == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'C8VEC_UNIFORM_01 - Fatal error!\\n' );\n fprintf ( 1, ' Input SEED = 0!\\n' );\n error ( 'C8VEC_UNIFORM_01 - Fatal error!' );\n end\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 = sqrt ( seed * 4.656612875E-10 );\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 theta = 2.0 * pi * seed * 4.656612875E-10;\n\n c(j) = r * ( cos ( theta ) + sin ( theta ) * i );\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/uniform/c8vec_uniform_01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.8354835309589073, "lm_q1q2_score": 0.7228804715821493}} {"text": "function [points1, points2] = get_uniform_points_boundary(ellipse1, ellipse2, nr_points)\n% GET_UNIFORM_POINTS_BOUNDARY gives the sets of points that are\n% equidistantly chosen on the boudary of two ellipses, so that future OSPA \n% could be calculated\n%\n% Input:\n% ellipse1, 1x5, parameterization of one ellispe [m1 m2 alpha l1 l2]\n% ellipse2, 1x5, parameterization of the other ellispe [m1 m2 alpha l1 l2]\n% nr_points, nr of points that are uniformly chosen on the boundary\n% to calculate OPSA distance\n% Output:\n% points1, 2xnr_points, points that are chosen on the ellipse1\n% poitns2, 2xnr_points, points that are chosen on the ellispe2\n% Written by Shishan Yang\n\ntheta = (0:2*pi/nr_points:2*pi-2*pi/nr_points);\n\nalpha1 = ellipse1(3);\ncenter1 = ellipse1(1:2)';\nl1 = ellipse1(4:5);\ngt_rotation_mat = [cos(alpha1) -sin(alpha1); sin(alpha1) cos(alpha1)];\npoints1(1,:) = l1(1)*cos(theta);\npoints1(2,:) = l1(2)*sin(theta);\n\nalpha2 = ellipse2(3);\ncenter2 = ellipse2(1:2)';\nl2 = ellipse2(4:5);\nest_rotation_mat = [cos(alpha2) -sin(alpha2); sin(alpha2) cos(alpha2)];\npoints2(1,:) = l2(1)*cos(theta);\npoints2(2,:) = l2(2)*sin(theta);\n\n\n\npoints1 = gt_rotation_mat*points1 + repmat(center1,1,size(points1,2));\npoints2 = est_rotation_mat*points2 + repmat(center2,1,size(points2,2));\nend", "meta": {"author": "Fusion-Goettingen", "repo": "ExtendedObjectTracking", "sha": "716c66f078162f7891a40e5ef664643fd74b9101", "save_path": "github-repos/MATLAB/Fusion-Goettingen-ExtendedObjectTracking", "path": "github-repos/MATLAB/Fusion-Goettingen-ExtendedObjectTracking/ExtendedObjectTracking-716c66f078162f7891a40e5ef664643fd74b9101/Evaluation/get_uniform_points_boundary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.7228687706661728}} {"text": "function value = r8_aid ( x )\n\n%*****************************************************************************80\n%\n%% R8_AID evaluates the derivative of the Airy function Ai of an R8 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 derivative of the Airy function\n% Ai of X.\n%\n persistent aifcs\n persistent aigcs\n persistent naif\n persistent naig\n persistent x2sml\n persistent x3sml\n\n if ( isempty ( naif ) )\n aifcs = [ ...\n 0.105274612265314088088970057325134114, ...\n 0.011836136281529978442889292583980840, ...\n 0.000123281041732256643051689242469164, ...\n 0.000000622612256381399016825658693579, ...\n 0.000000001852988878441452950548140821, ...\n 0.000000000003633288725904357915995625, ...\n 0.000000000000005046217040440664768330, ...\n 0.000000000000000005223816555471480985, ...\n 0.000000000000000000004185745090748989, ...\n 0.000000000000000000000002672887324883, ...\n 0.000000000000000000000000001392128006, ...\n 0.000000000000000000000000000000602653, ...\n 0.000000000000000000000000000000000220 ]';\n aigcs = [ ...\n 0.0212338781509186668523122276848937, ...\n 0.0863159303352144067524942809461604, ...\n 0.0017975947203832313578033963225230, ...\n 0.0000142654998755506932526620687495, ...\n 0.0000000594379952836832010488787064, ...\n 0.0000000001524033664794478945214786, ...\n 0.0000000000002645876603490435305100, ...\n 0.0000000000000003315624296815020591, ...\n 0.0000000000000000003139789757594792, ...\n 0.0000000000000000000002325767379040, ...\n 0.0000000000000000000000001384384231, ...\n 0.0000000000000000000000000000676629, ...\n 0.0000000000000000000000000000000276 ]';\n eta = 0.1 * r8_mach ( 3 );\n naif = r8_inits ( aifcs, 13, eta );\n naig = r8_inits ( aigcs, 13, eta );\n x3sml = r8_mach ( 3 )^0.3334;\n x2sml = sqrt ( r8_mach ( 3 ) );\n end\n\n if ( x < - 1.0 )\n [ xn, phi ] = r8_admp ( x );\n value = xn * cos ( phi );\n elseif ( abs ( x ) <= x2sml )\n x2 = 0.0;\n x3 = 0.0;\n value = ( x2 * ( 0.125 + r8_csevl ( x3, aifcs, naif ) ) ...\n - r8_csevl ( x3, aigcs, naig ) ) - 0.25;\n elseif ( abs ( x ) <= x3sml )\n x2 = x * x;\n x3 = 0.0;\n value = ( x2 * ( 0.125 + r8_csevl ( x3, aifcs, naif ) ) ...\n - r8_csevl ( x3, aigcs, naig ) ) - 0.25;\n elseif ( x <= 1.0 )\n x2 = x * x;\n x3 = x * x * x;\n value = ( x2 * ( 0.125 + r8_csevl ( x3, aifcs, naif ) ) ...\n - r8_csevl ( x3, aigcs, naig ) ) - 0.25;\n else\n value = r8_aide ( x ) ...\n * exp ( - 2.0 * x * sqrt ( x ) / 3.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/fn/r8_aid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7228249221254087}} {"text": "function pols = kjacopols ( x, a, b, n )\n\n%*****************************************************************************80\n%\n%% KJACOPOLS evaluates Jacobi polynomials.\n%\n% Discussion:\n%\n% This routine evaluates Jacobi polynomials.\n%\n% Licensing:\n%\n% This code is distributed under the GNU GPL license.\n%\n% Modified:\n%\n% 26 June 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This 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, real X, the evaluation point.\n%\n% Input, real A, B, the parameter values.\n%\n% Input, integer N, the highest degree to be evaluated.\n%\n% Output, real POLS(N+1), the polynomial values.\n%\n pols = zeros(n+1,1);\n\n pkp1 = 1.0;\n pols(1) = pkp1;\n\n if ( n == 0 )\n return\n end\n\n pk = pkp1;\n pkp1 = ( a / 2.0 - b / 2.0 ) ...\n + ( 1.0 + a / 2.0 + b / 2.0 ) * x;\n pols(2) = pkp1;\n\n if ( n == 1 )\n return\n end\n\n for k = 2 : n\n\n pkm1 = pk;\n pk = pkp1;\n\n alpha = ( 2.0 * k + a + b - 1.0 ) ...\n * ( a * a - b * b + ( 2.0 * k + a + b - 2.0 ) ...\n * ( 2.0 * k + a + b ) * x );\n\n beta = 2.0 * ( k + a - 1.0 ) * ( k + b - 1.0 ) ...\n * ( 2.0 * k + a + b );\n\n pkp1 = ( alpha * pk - beta * pkm1 ) ...\n / ( 2.0 * k * ( k + a + b ) ...\n * ( 2.0 * k + a + b - 2.0 ) );\n\n pols(k+1) = pkp1;\n\n end\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/triangle_symq_rule/kjacopols.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7228249137764396}} {"text": "function [ t, wts ] = h_quadrature_rule ( nt )\n\n%*****************************************************************************80\n%\n%% H_QUADRATURE_RULE: quadrature for H(i,x).\n%\n% Discussion:\n%\n% H(i,x) is the physicist's Hermite polynomial of degree I.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NT, the order of the rule.\n%\n% Output, real T(NT,1), WTS(NT,1), the points and weights of the rule.\n%\n aj = zeros ( nt, 1 );\n bj = sqrt ( ( 1 : nt )' / 2.0 );\n wts = zeros ( nt, 1 );\n wts(1,1) = sqrt ( sqrt ( pi ) );\n\n [ t, wts ] = imtqlx ( nt, aj, bj, wts );\n\n wts(1:nt,1) = wts(1:nt,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/hermite_polynomial/h_quadrature_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7227940521686398}} {"text": "function v = dquat2pos(dq)\n\n% DQUAT2POS Transforms a double quaternion point position representation \n% into a vector representation.\n%\n% V = DQUAT2POS(DQ) transforms the double quaternion representation of\n% a point position (in the euclidean space) into a vector v, which\n% represents the point coordinates. DQ is either a vector of size 8 \n% or an array of size 8*N (each column represents a point position \n% dual quaternion) where N is the number of point locations. V is a\n% vector of size 3 or an array of size 3*N depending on the input \n% format.\n%\n% See also POS2DQUAT, DQUAT2VEL, DQUAT2LINE, DQUAT2LINEVEL\n\nsdq = size(dq);\nif sdq == [1 8], dq = dq'; sdq = size(dq); end\n\n% wrong format\nif sdq(1) ~= 8 \n error('DualQuaternion:dquat2pos:wrongsize',...\n '%d rows in the DQ array. It should be 8.',sdq(1));\nend\n\n% check point position dual quaternion\ntol = 1e-6;\n[maxval1,imax1] = max(abs(dq(1,:)-1));\n[maxval2,imax2] = max(max(abs(dq(2:5,:))));\nimax = union(imax1,imax2);\nif maxval1 > tol || maxval2 > tol \n warning('DualQuaternion:dquat2pos:wrongFormat',...\n 'At least one dual quaternion is not a point position dual quaternion (tol = %.1e).\\n Indices of max values: %d',...\n tol,imax);\nend\n\n% extraction of the point position coordinates\nv = dq(6:8,:);\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/39288-dual-quaternion-toolbox/Dual quaternion toolbox v2/dquat2pos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7227940361444574}} {"text": "function [gamma]=wildual(g,M,L)\n%WILDUAL Wilson dual window\n% Usage: gamma=wildual(g,M);\n% gamma=wildual(g,M,L);\n%\n% Input parameters:\n% g : Gabor window.\n% M : Number of modulations.\n% L : Length of window. (optional)\n% Output parameters:\n% gamma : Canonical dual window.\n%\n% `wildual(g,M)` returns the dual window of the Wilson or WMDCT basis with\n% window *g*, parameter *M* and length equal to the length of the window *g*.\n%\n% The window *g* may be a vector of numerical values, a text string or a\n% cell array. See the help of |wilwin| for more details.\n%\n% If the length of *g* is equal to $2\\cdot M$ then the input window is\n% assumed to be an FIR window. In this case, the dual window also has\n% length of $2\\cdot M$. Otherwise the smallest possible transform length is\n% chosen as the window length.\n%\n% `wildual(g,M,L)` does the same, but now *L* is used as the length of the\n% Wilson basis.\n%\n% The input window *g* must be real and whole-point even. If *g* is not\n% whole-point even, then reconstruction using the dual window will not be\n% perfect. For a random window *g*, the window closest to *g* that satisfies\n% these restrictions can be found by ::\n%\n% g_wpe = real(peven(g));\n%\n% All windows in the toolbox satisfies these restrictions unless\n% clearly stated otherwise.\n%\n% See also: dwilt, wilwin, wmdct, wilorth, isevenfunction\n\n% AUTHOR : Peter L. Søndergaard.\n% TESTING: TEST_DWILT\n% REFERENCE: OK\n\ncomplainif_argnonotinrange(nargin,2,3,mfilename);\n\nif nargin==2\n L=[];\nend;\n\n%% ------ step 2: Verify a, M and L\nif isempty(L)\n if isnumeric(g)\n % Use the window length\n Ls=length(g);\n else\n % Use the smallest possible length\n Ls=1;\n end;\n\n % ----- step 2b : Verify M and get L from the window length ----------\n L=dwiltlength(Ls,M);\n\nelse\n\n % ----- step 2a : Verify M and get L\n\n Luser=dwiltlength(L,M);\n if Luser~=L\n error(['%s: Incorrect transform length L=%i specified. Next valid length ' ...\n 'is L=%i. See the help of DWILTLENGTH for the requirements.'],...\n upper(mfilename),L,Luser);\n end;\n\nend;\n\n\n%% ----- step 3 : Determine the window \n\n[g,info]=wilwin(g,M,L,upper(mfilename));\n\nif L 1,\n\n dRdin = [0 0 0;\n 0 0 1;\n 0 -1 0;\n 0 0 -1;\n 0 0 0;\n 1 0 0;\n 0 1 0;\n -1 0 0;\n 0 0 0];\n\n %end;\n\n else\n if n==length(in) in=in'; end; \t%% make it a column vec. if necess.\n\n %m3 = [in,theta]\n\n dm3din = [eye(3);in'/theta];\n\n omega = in/theta;\n\n %m2 = [omega;theta]\n\n dm2dm3 = [eye(3)/theta -in/theta^2; zeros(1,3) 1];\n\n alpha = cos(theta);\n beta = sin(theta);\n gamma = 1-cos(theta);\n omegav=[[0 -omega(3) omega(2)];[omega(3) 0 -omega(1)];[-omega(2) omega(1) 0 ]];\n A = omega*omega';\n\n %m1 = [alpha;beta;gamma;omegav;A];\n\n dm1dm2 = zeros(21,4);\n dm1dm2(1,4) = -sin(theta);\n dm1dm2(2,4) = cos(theta);\n dm1dm2(3,4) = sin(theta);\n dm1dm2(4:12,1:3) = [0 0 0 0 0 1 0 -1 0;\n 0 0 -1 0 0 0 1 0 0;\n 0 1 0 -1 0 0 0 0 0]';\n\n w1 = omega(1);\n w2 = omega(2);\n w3 = omega(3);\n\n dm1dm2(13:21,1) = [2*w1;w2;w3;w2;0;0;w3;0;0];\n dm1dm2(13: 21,2) = [0;w1;0;w1;2*w2;w3;0;w3;0];\n dm1dm2(13:21,3) = [0;0;w1;0;0;w2;w1;w2;2*w3];\n\n R = eye(3)*alpha + omegav*beta + A*gamma;\n\n dRdm1 = zeros(9,21);\n\n dRdm1([1 5 9],1) = ones(3,1);\n dRdm1(:,2) = omegav(:);\n dRdm1(:,4:12) = beta*eye(9);\n dRdm1(:,3) = A(:);\n dRdm1(:,13:21) = gamma*eye(9);\n\n dRdin = dRdm1 * dm1dm2 * dm2dm3 * dm3din;\n\n\n end;\n out = R;\n dout = dRdin;\n\n %% it is prob. a rot matr.\nelseif ((m==n) & (m==3) & (norm(in' * in - eye(3)) < bigeps)...\n & (abs(det(in)-1) < bigeps))\n R = in;\n\n % project the rotation matrix to SO(3);\n [U,S,V] = svd(R);\n R = U*V';\n\n tr = (trace(R)-1)/2;\n dtrdR = [1 0 0 0 1 0 0 0 1]/2;\n theta = real(acos(tr));\n\n\n if sin(theta) >= 1e-4,\n\n dthetadtr = -1/sqrt(1-tr^2);\n\n dthetadR = dthetadtr * dtrdR;\n % var1 = [vth;theta];\n vth = 1/(2*sin(theta));\n dvthdtheta = -vth*cos(theta)/sin(theta);\n dvar1dtheta = [dvthdtheta;1];\n\n dvar1dR = dvar1dtheta * dthetadR;\n\n\n om1 = [R(3,2)-R(2,3), R(1,3)-R(3,1), R(2,1)-R(1,2)]';\n\n dom1dR = [0 0 0 0 0 1 0 -1 0;\n 0 0 -1 0 0 0 1 0 0;\n 0 1 0 -1 0 0 0 0 0];\n\n % var = [om1;vth;theta];\n dvardR = [dom1dR;dvar1dR];\n\n % var2 = [om;theta];\n om = vth*om1;\n domdvar = [vth*eye(3) om1 zeros(3,1)];\n dthetadvar = [0 0 0 0 1];\n dvar2dvar = [domdvar;dthetadvar];\n\n\n out = om*theta;\n domegadvar2 = [theta*eye(3) om];\n\n dout = domegadvar2 * dvar2dvar * dvardR;\n\n\n else\n if tr > 0; \t\t\t% case norm(om)=0;\n\n out = [0 0 0]';\n\n dout = [0 0 0 0 0 1/2 0 -1/2 0;\n 0 0 -1/2 0 0 0 1/2 0 0;\n 0 1/2 0 -1/2 0 0 0 0 0];\n else\n\n % case norm(om)=pi;\n if(0)\n\n %% fixed April 6th by Bouguet -- not working in all cases!\n out = theta * (sqrt((diag(R)+1)/2).*[1;2*(R(1,2:3)>=0)'-1]);\n %keyboard;\n\n else\n\n % Solution by Mike Burl on Feb 27, 2007\n % This is a better way to determine the signs of the\n % entries of the rotation vector using a hash table on all\n % the combinations of signs of a pairs of products (in the\n % rotation matrix)\n\n % Define hashvec and Smat\n hashvec = [0; -1; -3; -9; 9; 3; 1; 13; 5; -7; -11];\n Smat = [1,1,1; 1,0,-1; 0,1,-1; 1,-1,0; 1,1,0; 0,1,1; 1,0,1; 1,1,1; 1,1,-1;\n 1,-1,-1; 1,-1,1];\n\n M = (R+eye(3,3))/2;\n uabs = sqrt(M(1,1));\n vabs = sqrt(M(2,2));\n wabs = sqrt(M(3,3));\n\n mvec = [M(1,2), M(2,3), M(1,3)];\n syn = ((mvec > 1e-4) - (mvec < -1e-4)); % robust sign() function\n hash = syn * [9; 3; 1];\n idx = find(hash == hashvec);\n svec = Smat(idx,:)';\n\n if ( isempty(svec) )\n out = theta * (sqrt((diag(R)+1)/2).*[1;2*(R(1,2:3)>=0)'-1]);\n else\n out = theta * [uabs; vabs; wabs] .* svec;\n end\n\n end;\n\n if nargout > 1,\n fprintf(1,'WARNING!!!! Jacobian domdR undefined!!!\\n');\n dout = NaN*ones(3,9);\n end;\n end;\n end;\n\nelse\n error('Neither a rotation matrix nor a rotation vector were provided');\nend;\n\nreturn;\n\n%% test of the Jacobians:\n\n%%%% TEST OF dRdom:\nom = randn(3,1);\ndom = randn(3,1)/1000000;\n\n[R1,dR1] = rodrigues(om);\nR2 = rodrigues(om+dom);\n\nR2a = R1 + reshape(dR1 * dom,3,3);\n\ngain = norm(R2 - R1)/norm(R2 - R2a)\n\n%%% TEST OF dOmdR:\nom = randn(3,1);\nR = rodrigues(om);\ndom = randn(3,1)/10000;\ndR = rodrigues(om+dom) - R;\n\n[omc,domdR] = rodrigues(R);\n[om2] = rodrigues(R+dR);\n\nom_app = omc + domdR*dR(:);\n\ngain = norm(om2 - omc)/norm(om2 - om_app)\n\n\n%%% OTHER BUG: (FIXED NOW!!!)\n\nomu = randn(3,1); \nomu = omu/norm(omu)\nom = pi*omu; \n[R,dR]= rodrigues(om);\n[om2] = rodrigues(R);\n[om om2]\n\n%%% NORMAL OPERATION\n\nom = randn(3,1); \n[R,dR]= rodrigues(om);\n[om2] = rodrigues(R);\n[om om2]\n\nreturn\n\n% Test: norm(om) = pi\n\nu = randn(3,1);\nu = u / sqrt(sum(u.^2));\nom = pi*u;\nR = rodrigues(om);\n\nR2 = rodrigues(rodrigues(R));\n\nnorm(R - R2)", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/VP/vanishingpoint/private/rodrigues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7227679471794172}} {"text": "function [r, v] = orb2eci(mu, oev)\n\n% convert classical orbital elements to eci state vector\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% output\n\n% r = eci position vector (kilometers)\n% v = eci velocity vector (kilometers/second)\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nr = zeros(3, 1);\nv = zeros(3, 1);\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\nslr = sma * (1 - ecc * ecc);\n\nrm = slr / (1 + ecc * cos(tanom));\n \narglat = argper + tanom;\n\nsarglat = sin(arglat);\ncarglat = cos(arglat);\n \nc4 = sqrt(mu / slr);\nc5 = ecc * cos(argper) + carglat;\nc6 = ecc * sin(argper) + sarglat;\n\nsinc = sin(inc);\ncinc = cos(inc);\n\nsraan = sin(raan);\ncraan = cos(raan);\n\n% position vector\n\nr(1) = rm * (craan * carglat - sraan * cinc * sarglat);\nr(2) = rm * (sraan * carglat + cinc * sarglat * craan);\nr(3) = rm * sinc * sarglat;\n\n% velocity vector\n\nv(1) = -c4 * (craan * c6 + sraan * cinc * c5);\nv(2) = -c4 * (sraan * c6 - craan * cinc * c5);\nv(3) = c4 * c5 * sinc;\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/39178-circular-orbit-plane-change/orb2eci.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7227111871821653}} {"text": "function Stall_margin = retreating_stall_envelope(mu_act,Cts_act)\n% Datum Rotor Coefficients (mu verus Cw/s) High Speed Rotor Coefficients (mu verus Cw/s)\t\t\t\n% a:\t-7.6568\tSquared term a:\t-7.4029\tSquared term\t\n% b:\t0.2992\tLinear term b:\t1.2392\tLinear term\t\n% c:\t0.5357\tConstant c:\t0.4827\tConstant\t\n\nhighspeed = 0; %0: datum; 1: high speed\n\n% Datum Rotor Coefficients (mu verus Cw/s) \nCdat=[-7.6568 ; \n0.2992; \n0.5357];\t\n\n% High Speed Rotor Coefficients (mu verus Cw/s)\t\t\t\nChs=[-7.4029\t;\t\n1.2392\t;\n0.4827\t];\t\n\nC = highspeed*Chs+(1-highspeed)*Cdat;\na = C(1); b = C(2); c = C(3);\n\n\nCts_act=Cts_act*2; %because of the way to find Ct in the place where this data comes from (with a 1/2 in Ct calc)\n\nmu_all = a*Cts_act.^2+Cts_act*b+c;\n\nCts_all = (-b-sqrt(b^2-4*a*(c-mu_act)))/(2*a);\n\nStall_margin = (mu_all-mu_act)/abs(mu_all);\nif isreal(Cts_all)\n Ct_margin = (Cts_all-Cts_act)/abs(Cts_all);\n Stall_margin = (Stall_margin+Ct_margin)/2;\nelse\n Stall_margin = -abs(Stall_margin);\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/41725-core-conceptual-optimization-of-rotorcraft-environment/CORE_v0p7 - for upload may 2013/CORE/retreating_stall_envelope.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7227111855386453}} {"text": "function kf = polynomial_correlation(xf, yf, a, b)\n%POLYNOMIAL_CORRELATION Polynomial Kernel at all shifts, i.e. kernel correlation.\n% Evaluates a polynomial kernel with constant A and exponent B, for all\n% relative shifts between input images XF and YF, which must both be MxN.\n% They must also be periodic (ie., pre-processed with a cosine window).\n% The result is an MxN map of responses.\n%\n% Inputs and output are all in the Fourier domain.\n%\n% Joao F. Henriques, 2014\n% http://www.isr.uc.pt/~henriques/\n\t\n\t%cross-correlation term in Fourier domain\n\txyf = xf .* conj(yf);\n\txy = sum(real(ifft2(xyf)), 3); %to spatial domain\n\t\n\t%calculate polynomial response for all positions, then go back to the\n\t%Fourier domain\n\tkf = fft2((xy / numel(xf) + a) .^ b);\n\nend\n\n", "meta": {"author": "thias15", "repo": "Context-Aware-CF-Tracking", "sha": "2b1198a24aea6420d28987f68622f50a2970ffac", "save_path": "github-repos/MATLAB/thias15-Context-Aware-CF-Tracking", "path": "github-repos/MATLAB/thias15-Context-Aware-CF-Tracking/Context-Aware-CF-Tracking-2b1198a24aea6420d28987f68622f50a2970ffac/SAMF_CA/polynomial_correlation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362849986365572, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7226654981495567}} {"text": "function d = DistanceToSE3(mat)\n% *** CHAPTER 3: RIGID-BODY MOTIONS ***\n% Takes mat: A 4x4 matrix.\n% Returns the Frobenius norm to describe the distance of mat from the SE(3) \n% manifold.\n% Compute the determinant of matR, the top 3x3 submatrix of mat. If \n% det(matR) <= 0, return a large number. If det(matR) > 0, replace the top \n% 3x3 submatrix of mat with matR' * matR, and set the first three entries \n% of the fourth column of mat to zero. Then return norm(mat - I).\n% Example Inputs:\n% \n% clear; clc;\n% mat = [1.0, 0.0, 0.0, 1.2;\n% 0.0, 0.1, -0.95, 1.5;\n% 0.0, 1.0, 0.1, -0.9;\n% 0.0, 0.0, 0.1, 0.98];\n% d = DistanceToSE3(mat)\n% \n% Output:\n% d =\n% 0.1349\n\n[R, p] = TransToRp(mat);\nif det(R) > 0\n\td = norm([R' * R, [0; 0; 0]; mat(4, :)] - eye(4), 'fro');\nelse\n d = 1e+9;\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/DistanceToSE3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144267, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7226654847802989}} {"text": "function Metric_table = MFSK_DEMOD(Data_in,M,E_s,SNR_dB)\n%*** MFSK DEMOD ***\n%function Metric_table = MFSK_DEMOD(Data_in,M,E_s,SNR_dB)\n% Create a (M x n) matrix containing the metrics of the M-FSK demodulator,\n% simulating an AWGN channel\n% Data_in is random values [0 .. M-1], representing the data that must be\n% transmitted\n% M is the number of frequencies used (M-FSK)\n% E_s is the transmitted signal energy\n% SNR_dB is the signal-to-noise ratio, measured in dBs\n \n n = length(Data_in);\n \n %Calculate the mu and sigma_2 values from the SNR\n \n SNR = Convert_SNR(SNR_dB);\n N_o = E_s / SNR; % Noise Power on channel in dB (Proakis - MFSK)\n \n mu = 0;\n sigma_2 = (1/2)*N_o;\n sigma = sqrt(sigma_2);\n \n \n %******************************\n %*** Create Decision matrix ***\n %******************************\n \n Metric_table = [];\n T_Metrics =[];\n \n %Create 2 x M metric outputs for timeslot i (M equals number of frequencies in M-FSK)\n for num = 1:n\n Signal = [];\n for i = 0:M-1\n if (i == Data_in(num))\n %It is the symbol that was transmitted\n \n %Determine a value for phi\n phi = 2 * pi * rand;\n \n % Compute the COS Component:\n Signal(i+1,1) = sqrt(E_s) * cos(phi) + normrnd(mu,sigma);\n \n % Compute the SIN Component \n Signal(i+1,2) = sqrt(E_s) * sin(phi) + normrnd(mu,sigma);\n \n else\n Signal(i+1,1) = normrnd(mu,sigma);\n Signal(i+1,2) = normrnd(mu,sigma);\n end\n end\n \n \n % Compute the Envelope metrics for each symbol\n Metrics = []; % Vector containing the computed envelope metrics\n \n \n for i = 1:M\n Metrics(i) = Decision_metric(Signal(i,1),Signal(i,2));\n end\n \n \n Metric_table = [Metric_table transpose(Metrics)];\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/27116-mfsk-modulation-in-awgn-noise-with-reed-solomon-decoding/MFSK/MFSK/MFSK_DEMOD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7226620611182533}} {"text": "% Demo of use of TVDIP - total variation denoising algorithm\nclear all;\n\n% Generate test signal: piecewise smooth with noise corruption\ny = [1.5*ones(10000,1); -0.7*ones(2000,1); 1.3*ones(100,1); -0.3*ones(5000,1)];\nN = length(y);\ny = y + 0.5*randn(N,1);\n\n% Find the value of lambda greater than which the TVD solution is just the\n% mean\nlmax = tvdiplmax(y);\n\n% Perform TV denoising for lambda across a range of values up to a small\n% fraction of the maximum found above\nlratio = [1e-4 1e-3 1e-2 1e-1];\nL = length(lratio);\n[x, E, status] = tvdip(y,lmax*lratio,1,1e-3,100);\n\n% Plots - display original test signal y, and TVD results\nclose all;\nfigure;\nfor l = 1:L\n subplot(L,1,l);\n hold on;\n plot(y,'-','Color',0.8*[1 1 1]);\n plot(x(:,l),'k-');\n axis tight;\n title(sprintf('\\\\lambda=%5.2e, \\\\lambda/\\\\lambda_{max}=%5.2e',lmax*lratio(l),lratio(l)));\nend\nxlabel('n');\nlegend({'Input y_n','TVD x_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/TVDIP/tvdipdemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7226620461527102}} {"text": "function p=v_sone2phon(s)\n%V_PHON2SONE convert SONE loudness values to PHONs p=(s)\n%Inputs: s is a matrix of sone values\n%\n%Outputs: p is a matrix, the same size as s, of phon values\n%\n% The phon scale measures perceived loudness in dB; at 1 kHz it is identical to dB SPL\n% relative to 20e-6 Pa sound pressure. The sone scale is proportional to apparent loudness\n% and, by definition, equals 1 at 40 phon. The form of the loudness curve is taken from [1].\n% The hearing threshold at 1 kHz for 18 to 25 year olds with normal hearing is taken from [2].\n%\n% Refs: [1]\tJ. Lochner and J. Burger. Form of the loudness function in the presence of masking noise.\n% The Journal of the Acoustical Society of America, 33: 1705, 1961.\n% [2]\tISO/TC43. Acoustics, Normal equal-loudness-level contours.\n% Standard ISO 226:2003, Aug. 2003.\n\n\n% Copyright (C) Mike Brookes 2012-2013\n% Version: $Id: v_sone2phon.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 a b d\nif isempty(a)\n b=1/(log(10)*0.1*0.27); % 0.27 is the exponent from [1] and [2]\n d=exp(2.4/b); % 2.4 dB is teh hearing threshold from [2]\n a=exp(40/b)-d; % scale factor to make p=40 give s=1\nend\nif nargout>0\n\n p=b*log(a*s+d);\nelse\n if nargin<1 || isempty(s)\n pp=linspace(5,90,100)'; % phon values\n ss=v_phon2sone(pp);\n else\n ss=s;\n end\n semilogx(ss,v_sone2phon(ss));\n v_axisenlarge(-1);\n v_xticksi;\n ylabel('phon = dB SPL @ 1 kHz');\n xlabel('sone');\nend\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_sone2phon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7226620461527102}} {"text": "function hammersley_dataset ( )\n\n%*****************************************************************************80\n%\n%% HAMMERSLEY_DATASET generates a Hammersley dataset and writes it to a file.\n%\n% Discussion:\n%\n% This program is meant to be used interactively. It's also\n% possible to prepare a simple input file beforehand and use it\n% in batch mode.\n%\n% The program requests input values from the user:\n%\n% * NDIM, the spatial dimension,\n% * N, the number of points to generate,\n% * STEP, the index of the first subsequence element to be computed.\n% * SEED(1:NDIM), the Hammersley sequence index corresponding to STEP = 0.\n% * LEAP(1:NDIM), the successive jumps in the Hammersley sequence.\n% * BASE(1:NDIM), the bases (usually distinct primes or -N).\n%\n% The program generates the data, writes it to the file\n%\n% hammersley_NDIM_N.txt\n%\n% where \"NDIM\" and \"N\" are the numeric values specified by the user,\n% and then asks the user for more input. To indicate that no further\n% computations are desired, it is enough to input a nonsensical\n% value, such as -1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HAMMERSLEY_DATASET\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Generate a Hammersley dataset.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' This program is meant to be used interactively.\\n' );\n fprintf ( 1, ' It is also possible to prepare a simple input \\n' );\n fprintf ( 1, ' file beforehand and use it in batch mode.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The program requests input values from the user:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' * NDIM, the spatial dimension,\\n' );\n fprintf ( 1, ' * N, the number of points to generate,\\n' );\n fprintf ( 1, ' * STEP, the index of the first subsequence element.\\n' );\n fprintf ( 1, ' * SEED(1:NDIM), the sequence element\\n' );\n fprintf ( 1, ' corresponding to STEP = 0\\n' );\n fprintf ( 1, ' * LEAP(1:NDIM), the successive jumps in the sequence.\\n' );\n fprintf ( 1, ' * BASE(1:M), the bases, usually distinct primes\\n' );\n fprintf ( 1, ' or -N (to generate values like J/N).\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The program generates the data, writes it to the file\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' hammersley_NDIM_N.txt\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' where \"NDIM\" and \"N\" are the numeric values specified\\n' );\n fprintf ( 1, ' by the user, and then asks the user for more input.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' To indicate that no further computations are \\n' );\n fprintf ( 1, ' desired, it is enough to input a nonsensical value, \\n' );\n fprintf ( 1, ' such as -1.\\n' );\n\n while ( 1 )\n\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, '* Ready to generate a new dataset:\\n' );\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, ' *\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' NDIM is the spatial dimension.\\n' );\n fprintf ( 1, ' (Try \"2\" if you have no preference.\\n' );\n fprintf ( 1, ' Any value less than 1 terminates execution.\\n' );\n ndim = [];\n ndim = input ( ' Enter NDIM: ' );\n\n fprintf ( 1, ' User input NDIM = %d\\n', ndim );\n\n if ( ~halham_ndim_check ( ndim ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HAMMERSLEY_DATASET\\n' );\n fprintf ( 1, ' The input value of NDIM = %d\\n', ndim );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N is the number of points.\\n' );\n fprintf ( 1, ' (Try \"25\" if you have no preference.\\n' );\n fprintf ( 1, ' (Any value less than 1 terminates execution.)\\n' );\n n = [];\n n = input ( ' Enter N: ' );\n\n fprintf ( 1, ' User input N = %d\\n', n );\n\n if ( ~halham_n_check ( n ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HAMMERSLEY_DATASET\\n' );\n fprintf ( 1, ' The input value of N = %d\\n', n );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' STEP is the index of the first subsequence element.\\n' );\n fprintf ( 1, ' (Try \"0\" or \"1\" if you have no preference.\\n' );\n fprintf ( 1, ' (Any value less than 0 terminates execution.)\\n' );\n step = [];\n step = input ( ' Enter STEP: ' );\n\n fprintf ( 1, ' User input STEP = %d\\n', step );\n\n if ( ~halham_step_check ( step ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HAMMERSLEY_DATASET\\n' );\n fprintf ( 1, ' The input value of STEP = %d\\n', step );\n fprintf ( 1, ' is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n break\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' SEED(1:NDIM) is the starting element index\\n' );\n fprintf ( 1, ' for each coordinate.\\n' );\n fprintf ( 1, ' (Try \"[0,0,...,0]\" if you have no preference.\\n' );\n fprintf ( 1, ' (Any value less than 0 terminates execution.)\\n' );\n seed = [];\n seed(1:ndim) = input ( ' Enter SEED(1:NDIM): ' );\n\n fprintf ( 1, '\\n' );\n i4vec_transpose_print ( ndim, seed, 'SEED:' );\n\n if ( ~halham_seed_check ( ndim, seed ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HAMMERSLEY_DATASET\\n' );\n fprintf ( 1, ' The negative input value of at least one entry of\\n' );\n fprintf ( 1, ' SEED is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' LEAP(1:NDIM) is the leaping multiplier\\n' );\n fprintf ( 1, ' for each coordinate.\\n' );\n fprintf ( 1, ' (Try \"[1,1,...,1]\" if you have no preference.\\n' );\n fprintf ( 1, ' (Another choice is a prime bigger than all the bases.)\\n' );\n fprintf ( 1, ' (Any value less than 1 terminates execution.)\\n' );\n leap = [];\n leap(1:ndim) = input ( ' Enter LEAP(1:NDIM): ' );\n\n fprintf ( 1, '\\n' );\n i4vec_transpose_print ( ndim, leap, 'LEAP:' );\n\n if ( ~halham_leap_check ( ndim, leap ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HAMMERSLEY_DATASET\\n' );\n fprintf ( 1, ' The input value of at least one entry of\\n' );\n fprintf ( 1, ' LEAP is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' BASE(1:NDIM) is the base for each coordinate,\\n' );\n fprintf ( 1, ' usually distinct primes or -N for values like J/N.\\n' );\n fprintf ( 1, ' (Try \"[-N,2,3,5,7,11,13,...]\" if you have no preference.\\n' );\n fprintf ( 1, ' (Any value of 0 or 1 terminates execution.)\\n' );\n base = [];\n base(1:ndim) = input ( ' Enter BASE: ' );\n\n fprintf ( 1, '\\n' );\n i4vec_transpose_print ( ndim, base, 'BASE:' );\n\n if ( ~hammersley_base_check ( ndim, base ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HAMMERSLEY_DATASET\\n' );\n fprintf ( 1, ' The input value of at least one entry of\\n' );\n fprintf ( 1, ' BASE is interpreted as a request for termination.\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n end\n\n r = i4_to_hammersley_sequence ( ndim, n, step, seed, leap, base );\n\n file_out_name = ...\n strcat ( 'hammersley_', num2str ( ndim ), '_', num2str ( n ), '.txt' );\n\n halham_write ( ndim, n, step, seed, leap, base, r, file_out_name );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The data was written to the file \"%s\".\\n', ...\n file_out_name );\n\n end\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\n", "meta": {"author": "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_dataset/hammersley_dataset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117983401364, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.7226099643272241}} {"text": "disp(' ');\ndisp('fdct_wrapping_demo_basic.m -- Displays a curvelet')\ndisp ('both in the spatial and frequency domains.');\ndisp(' ');\ndisp(['This is achieved by setting all the coefficients in the curvelet'])\ndisp(['domain to zero except that at the required location (which'])\ndisp(['is set to one). The curvelet is obtained by taking the'])\ndisp(['adjoint curvelet transform. Notice how the curvelet is sharply '])\ndisp(['localized in both space and frequency.']); \ndisp(' ');\n\n% fdct_wrapping_demo_basic.m -- Displays a curvelet both in the spatial and frequency domains.\n\n% m = 512;\n% n = 512;\n% \n% X = zeros(m,n);\n\n%forward curvelet transform\ndisp('Take curvelet transform: fdct_wrapping');\ntic; C = fdct_wrapping(X,0); toc;\n\n%specify one curvelet\ns = 5;\nw = 1;\n[A,B] = size(C{s}{w});6\na = ceil((A+1)/2);\nb = ceil((B+1)/2);\nC{s}{w}(a,b) = 1;\n\n%adjoint curvelet transform\ndisp('Take adjoint curvelet transform: ifdct_wrapping');\ntic; Y = ifdct_wrapping(C,0); toc;\n\n%display the curvelet\nF = ifftshift(fft2(fftshift(Y)));\nsubplot(1,2,1); colormap gray; imagesc(real(Y)); axis('image'); ...\n title('a curvelet: spatial viewpoint');\nsubplot(1,2,2); colormap gray; imagesc(abs(F)); axis('image'); ...\n title('a curvelet: frequency viewpoint');\n\n%get parameters\n[SX,SY,FX,FY,NX,NY] = fdct_wrapping_param(C);\n\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/NSCT_SR/fdct_wrapping_matlab/fdct_wrapping_demo_basic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.8267117855317474, "lm_q1q2_score": 0.7226099571994087}} {"text": "function [sorted_vertices, ...\n h_fes, h_bnd, h_fill, h_vert, h_int, h_max, g_labels] = ...\n plot_feasible(A, b, c, lower_b, upper_b, varargin)\n% Plot the feasible region of a linear program\n%\n% file: \tplot_feasible.m, (c) Matthew Roughan, 2009\n% created: \tMon Jun 22 2009 \n% author: \tMatthew Roughan \n% email: \tmatthew.roughan@adelaide.edu.au\n% \n% Plot the feasible region of the 2D linear program\n% maximize f = c'*x\n% subject to A x <= b\n% on the region bounded by lower_b and upper_b. Note that the inputs\n% A is a mx2 matrix, where there are m constraints\n% b is a mx1 column vector, where there are m constraints\n% c is a 2x1 column vector\n% lower_b, upper_b are 2x1 column vectors\n%\n% If the problem includes non-negativity bounds, i.e., \n% x >= 0 \n% which is quite common, then these need to be explicitly included into\n% the constraints: A x <= b, not implicitly through the bounds, which are mainly there to\n% allow us to make a nice plot.\n%\n% The feasible region is filled with lines at a setable angle and separation, much as fill\n% would do with a solid colour, though options allow you to fill with a color, or both.\n%\n% This code is primarily (for me) useful for teaching about linear programming, and only\n% works for 2D problems (for the obvious reason that problems with more than two variables\n% are hard to plot).\n%\n% Note that if you want to cross-hatch just call this routine twice, with a change in angle\n% of 90 degrees.\n% \n% There are a bunch of optional inputs in pairs, as for the plot command\n% 'linecolor' color of feasible region boundary lines (default black)\n% 'backgroundcolor' background color of feasible region (default no background)\n% 'linewidth' width of lines (default 1)\n% 'linestyle' style of the boundary lines\n% 'filllinestyle' style of the fill lines\n% 'linesep' separation of cross-hatch lines (default 1)\n% if this is set to -1, don't put any fill lines in\n% 'lineangle' angle (in degrees) of cross-hatch lines\n% the default is to put them along lines of equal values of the\n% objective function\n% 'hold' hold_n=1 means keep previous plot\n% hold_n=0 (default) means clear previous figure\n% use this to plot multiple feasible regions on same plot, or to do\n% crosshatching.\n%\n% 'plot_vertices' if defined indicates that we should plot the vertices of the feasible region\n% the value will determine the symbol to use to plot the vertices,\n% e.g., 'rx', or 'o+'\n% 'label_vertices' if not 0, then label the vertices with their position (label_vertices=1)\n% or value (label_vertices=1) or both (label_vertices=3)\n% 'label_vertices_size' size of vertex labels, default = 12\n% 'label_vertices_color' size of vertex labels, default = 'k'\n% 'label_vertices_prec' precision of vertex labels (default = 2 decimal places)\n%\n% 'plot_intersections' if defined indicates that we should plot the intersection points of boundaries\n% the value will determine the symbol to use to plot the vertices,\n% e.g., 'rx', or 'o+'\n% Note that vertices are also intersection points, and will be double\n% plotted if used with the plot_vertices option\n% \n% 'plot_max' if not 0, then plot the location of the maximum, using the defined symbol\n%\n% 'extend_boundaries' if defined, plot each of the constraint lines past the feasible region\n% using the linewidth and color defined above. The style of the line can\n% be given as the value, e.g., ':'\n%\n% OUTPUTS:\n% sorted_vertices = a 2x(n+1) vector of the vertices of the feasible region\n% note the last one is a repeat of the first to aid in plotting the region\n% \n%\n% h_fes = handles to boundary lines of the linear program\n% h_bnd = handles to the boundary lines\n% h_fill = handles to the fill lines\n% h_vert = handles to the vertices (if plotted)\n% h_int = handles to the intersection points (if plotted)\n% h_max = a handle to the plotted maximum point \n% g_labels = handles to vertex labels if used\n% \n% version 0.1, July 22nd 2009\n%\n% TODO\n% speckled fill\n% testing for boundedness and autosizing the figure\n% plotting bounds with cross-hatch on feasible side\n% at present the code uses the optimization toolkit (through the linprog) function\n% which we use to solve the linear program, but as this is a 2D problem we should be able to\n% remove this dependence with a little work.\n% currently the intersections with upper and lower bounds for plotting are also included\n% in intersection set, and plotted\n% automate ability to put text description of the problem in the window\n%\n\n% check sizes of inputs\nsA = size(A);\nsb = size(b);\nif (sA(1) ~= sb(1))\n error('incorrect input sizes\\n');\nend\nif (sA(2) ~= 2)\n error('can only plot for 2 variables\\n');\nend\nn = sA(1); % number of constraints\nif (size(upper_b,1) ~=2 | size(upper_b,2) ~= 1)\n error('upper_b is the wrong size\\n');\nend\nif (size(lower_b,1) ~=2 | size(lower_b,2) ~= 1)\n error('lower_b is the wrong size\\n');\nend\n\n% set default output values\nh_fes = [];\nh_bnd = [];\nh_fill = [];\nh_vert = [];\nh_int = [];\nh_max = [];\n\n% parse the variable input arguments\nlinecolor = 'k'; \nbackgroundcolor = 0;\nlinewidth = 1;\nlinestyle = '-';\nfilllinestyle = '-';\nlinesep = 1;\n% default line angle is so that lines will be iso-objective\nif (abs(c(1)) < 1.0e-12)\n lineangle = 90; % degrees\nelse\n lineangle = atand(c(2)/c(1));\nend\nhold_n = 0;\nplot_vertices = 0;\nlabel_vertices = 0;\nlabel_vertices_size = 12;\nlabel_vertices_color = 'k';\nlabel_vertices_prec = 2;\nplot_intersections = 0;\nextend_boundaries = 0;\nplot_max = 0;\nif (length(varargin) > 0)\n % process variable arguments\n for k = 1:2:length(varargin)\n if (ischar(varargin{k}))\n argument = char(varargin{k}); \n value = varargin{k+1};\n switch argument\n case {'linecolor','lc'}\n\tlinecolor = value;\n case {'backgroundcolor','bgc'}\n\tbackgroundcolor = value;\n case {'linewidth','lw'}\n\tlinewidth = value;\n case {'linestyle','ls'}\n\t linestyle = value;\n case {'filllinestyle','fls'}\n\t filllinestyle = value;\n case {'linesep','ls'}\n\tlinesep = value;\n case {'lineangle','la'}\n\tlineangle = value;\n case {'hold'}\n\thold_n = value;\n case {'plot_vertices', 'pv'}\n\tplot_vertices = value;\n case {'label_vertices', 'lv'}\n\tlabel_vertices = value;\n case {'label_vertices_size', 'lvs'}\n\tlabel_vertices_size = value;\n case {'label_vertices_color', 'lvc'}\n\tlabel_vertices_color = value;\n case {'label_vertices_prec', 'lvp'}\n\tlabel_vertices_prec = value;\n case {'plot_intersections', 'pi'}\n\tplot_intersections = value;\n case {'extend_boundaries', 'eb'}\n\textend_boundaries = value;\n case {'plot_max', 'pm'}\n\t plot_max = value;\n otherwise\n\terror('incorrect input parameters');\n end\n end\n end\nend\n\n% set up the plot region\nif (hold_n==0)\n hold off\n plot(lower_b(1), lower_b(2));\nend\ndiff_x = (upper_b(1)-lower_b(1))/20; \ndiff_y = (upper_b(2)-lower_b(2))/20; \nset(gca, 'xlim', [lower_b(1)-diff_x upper_b(1)+diff_x]);\nset(gca, 'ylim', [lower_b(2)-diff_y upper_b(2)+diff_y]);\nhold on\nepsilon = 1.0e-14;\n\n% plot the boundary line lines of the linear program across the plot region\nif ~(extend_boundaries == 0)\n for i=1:n\n % find end-points of the lines along the boundaries\n constraint = A(i,:);\n k = b(i);\n if (abs(constraint(1)) < epsilon)\n % fprintf('(abs(constraint(1) < epsilon): i = %d\\n', i);\n if (lower_b(1)<=k/constraint(2) & k/constraint(2)<=upper_b(1))\n\tx = [lower_b(1) upper_b(1)];\n\ty = [1 1] * k/constraint(2);\n else \n\tx = [];\n\ty = [];\n end\n elseif (abs(constraint(2)) < epsilon)\n % fprintf('(abs(constraint(2) < epsilon): i = %d\\n', i);\n if (lower_b(2)<=k/constraint(1) & k/constraint(1)<=upper_b(2))\n\tx = [1 1] * k/constraint(1);\n\ty = [lower_b(2) upper_b(2)];\n else \n\tx = [];\n\ty = [];\n end\n else\n % compute all four intersections, and decide which is feasible\n % horizontal intercept points\n y_1 = [lower_b(2) upper_b(2)];\n x_1 = (k - constraint(2)*y_1) / constraint(1);\n i_1 = find(lower_b(1) 0)\n % find min and max via linprog to see start and end points of lines\n % add in implicit boundary constraints when do it\n c_line = [cosd(lineangle), sind(lineangle)];\n x_min = linprog(c_line, A, b, [], [], lower_b, upper_b);\n % plot(x_min(1), x_min(2), 'b*');\n \n x_max = linprog(-c_line, A, b, [], [], lower_b, upper_b);\n % plot(x_max(1), x_max(2), 'b*');\n \n distance = sqrt( sum((x_max-x_min).^2) );\n \n % draw lines clipping them at the boundaries\n for i=0:linesep:distance\n counter = ceil(i/linesep) + 1;\n \n % sigma = x_min + i*(x_max-x_min)/distance;\n sigma = x_min + i*c_line';\n % plot(sigma(1), sigma(2), '+', 'color', linecolor);\n \n % for each line, consider its intersepts with each possible \n % boundary, and check whether they are feasible\n edge_vertices = [];\n for j=1:m\n M = [Aex(j,:); c_line];\n d = [bex(j); sum(c_line.*sigma')];\n x = M \\ d;\n % test for feasibility\n if (A*x <= b)\n\tedge_vertices = [edge_vertices, x];\n end\n end\n edge_vertices = round(100*edge_vertices)'/100;\n edge_vertices = unique(edge_vertices, 'rows')';\n if (size(edge_vertices,2) >= 2)\n h_fill(counter) = plot(edge_vertices(1,:), edge_vertices(2,:), ...\n\t\t\t 'color', linecolor, 'linestyle', filllinestyle, 'linewidth', linewidth);\n end\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/24816-plotfeasible-m/plot_feasible.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8740772302445241, "lm_q1q2_score": 0.7226099551717756}} {"text": "function value = rodman_determinant ( n, alpha )\n\n%*****************************************************************************80\n%\n%% RODMAN_DETERMINANT returns the determinant of the RODMAN matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Input, real ALPHA, the parameter.\n%\n% Output, real VALUE, the determinant.\n%\n value = ( 1.0 - alpha )^( n - 1 ) * ( 1.0 + alpha * ( 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_mat/rodman_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7226099538158735}} {"text": "function prob_test1188 ( )\n\n%*****************************************************************************80\n%\n%% PROB_TEST1188 tests NORMAL_TRUNCATED_B_CDF, NORMAL_TRUNCATED_B_CDF_INV, NORMAL_TRUNCATED_B_PDF;\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 August 2013\n%\n% Author:\n%\n% John Burkardt\n%\n seed = 123456789;\n b = 150.0;\n mu = 100.0;\n s = 25.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PROB_TEST1188\\n' );\n fprintf ( 1, ' For the Upper Truncated Normal PDF:\\n' );\n fprintf ( 1, ' NORMAL_TRUNCATED_B_CDF evaluates the CDF.\\n' );\n fprintf ( 1, ' NORMAL_TRUNCATED_B_CDF_INV inverts the CDF.\\n' );\n fprintf ( 1, ' NORMAL_TRUNCATED_B_PDF evaluates the PDF.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The \"parent\" normal distribution has\\n' );\n fprintf ( 1, ' mean = %g\\n', mu );\n fprintf ( 1, ' standard deviation = %g\\n', s );\n fprintf ( 1, ' The parent distribution is truncated to\\n' );\n fprintf ( 1, ' the interval [-oo,%g]\\n', b );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X PDF CDF CDF_INV\\n' );\n fprintf ( 1, '\\n');\n\n for i = 1 : 10\n\n [ x, seed ] = normal_truncated_b_sample ( mu, s, b, seed );\n\n pdf = normal_truncated_b_pdf ( x, mu, s, b );\n\n cdf = normal_truncated_b_cdf ( x, mu, s, b );\n\n x2 = normal_truncated_b_cdf_inv ( cdf, mu, s, b );\n\n fprintf( 1, ' %14g %14g %14g %14g\\n', x, pdf, cdf, x2 );\n\n end\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/prob/prob_test1188.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7226099521241054}} {"text": "function [ num_int, pint ] = halfspace_normal_triangle_int_3d ( p, normal, t )\n\n%*****************************************************************************80\n%\n%% HALFSPACE_NORMAL_TRIANGLE_INT_3D: intersection ( normal halfspace, triangle ) in 3D.\n%\n% Discussion:\n%\n% The normal form of a halfspace in 3D may be described as the set\n% of points (X,Y,Z) on or \"above\" a plane described in normal form:\n%\n% P is a point on the plane,\n% NORMAL is the unit normal vector, pointing \"out\" of the\n% halfspace.\n%\n% The triangle is specified by listing its three vertices.\n%\n% The intersection may be described by the number of vertices of the\n% triangle that are included in the halfspace, and by the location of\n% points between vertices that separate a side of the triangle into\n% an included part and an unincluded part.\n%\n% 0 vertices, 0 separators (no intersection)\n% 1 vertex, 0 separators (point intersection)\n% 2 vertices, 0 separators (line intersection)\n% 3 vertices, 0 separators (triangle intersection)\n%\n% 1 vertex, 2 separators, (intersection is a triangle)\n% 2 vertices, 2 separators, (intersection is a quadrilateral).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 May 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real T(3,3), the vertices of the triangle.\n%\n% Input, real P(3,1), a point on the bounding plane\n% that defines the halfspace.\n%\n% Input, real NORMAL(3,1), the components of the normal vector\n% to the bounding plane that defines the halfspace. By convention, the\n% normal vector points \"outwards\" from the halfspace.\n%\n% Output, integer NUM_INT, the number of intersection points returned,\n% which will always be between 0 and 4.\n%\n% Output, real PINT(3,4), the coordinates of the NUM_INT\n% intersection points. The points will lie in sequence on the triangle.\n% Some points will be vertices, and some may be separators.\n%\n dim_num = 3;\n%\n% Compute the signed distances between the vertices and the plane.\n%\n d = - normal(1:dim_num,1)' * p(1:dim_num,1);\n%\n% Compute the signed distances between the vertices and the plane.\n%\n dist1 = d + normal(1:dim_num,1)' * t(1:dim_num,1);\n dist2 = d + normal(1:dim_num,1)' * t(1:dim_num,2);\n dist3 = d + normal(1:dim_num,1)' * t(1:dim_num,3);\n%\n% Now we can find the intersections.\n%\n [ num_int, pint ] = halfspace_triangle_int_3d ( t, dist1, dist2, dist3 );\n\n return\nend\n", "meta": {"author": "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/halfspace_normal_triangle_int_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.7226099511040693}} {"text": "function divdif_test18 ( )\n\n%*****************************************************************************80\n%\n%% DIVDIF_TEST18 tests ROOTS_TO_DIF and DIF_TO_R8POLY.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 October 2006\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DIVDIF_TEST18\\n' );\n fprintf ( 1, ' ROOTS_TO_DIF computes the divided difference\\n' );\n fprintf ( 1, ' polynomial with given roots;\\n' );\n fprintf ( 1, ' DIF_TO_R8POLY converts it to a standard form\\n' );\n fprintf ( 1, ' polynomial.\\n' );\n fprintf ( 1, '\\n' );\n\n nroots = 1;\n roots(1) = 3.0;\n r8vec_print ( nroots, roots, ' The roots:' );\n\n [ ntab, xtab, diftab ] = roots_to_dif ( nroots, roots );\n\n c = dif_to_r8poly ( ntab, xtab, diftab );\n\n r8poly_print ( ntab, c, ' The polynomial:' );\n\n nroots = 2;\n roots(1:2) = [ 3.0, 1.0 ];\n r8vec_print ( nroots, roots, ' The roots:' );\n\n [ ntab, xtab, diftab ] = roots_to_dif ( nroots, roots );\n\n c = dif_to_r8poly ( ntab, xtab, diftab );\n\n r8poly_print ( ntab, c, ' The polynomial:' );\n\n nroots = 3;\n roots(1:3) = [ 3.0, 1.0, 2.0 ];\n r8vec_print ( nroots, roots, ' The roots:' );\n\n [ ntab, xtab, diftab ] = roots_to_dif ( nroots, roots );\n\n c = dif_to_r8poly ( ntab, xtab, diftab );\n\n r8poly_print ( ntab, c, ' The polynomial:' );\n\n nroots = 4;\n roots(1:4) = [ 3.0, 1.0, 2.0, 4.0 ];\n r8vec_print ( nroots, roots, ' The roots:' );\n\n [ ntab, xtab, diftab ] = roots_to_dif ( nroots, roots );\n\n c = dif_to_r8poly ( ntab, xtab, diftab );\n\n r8poly_print ( ntab, c, ' The polynomial:' );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/divdif/divdif_test18.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.7225222351510776}} {"text": "function determ = vand2_determinant ( n, x )\n\n%*****************************************************************************80\n%\n%% VAND2_DETERMINANT returns the determinant of the VAND2 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 desired.\n%\n% Input, real X(N), the values that define A.\n%\n% Output, real DETERM, the determinant.\n%\n determ = 1.0;\n\n for i = 1 : n\n for j = 1 : i - 1\n determ = determ * ( x(i) - x(j) );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/vand2_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7225222308361862}} {"text": "function value = r4_cosh ( x )\n\n%*****************************************************************************80\n%\n%% R4_COSH evaluates the hyperbolic cosine 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 hyperbolic cosine of X.\n%\n persistent ymax\n\n if ( isempty ( ymax ) )\n ymax = 1.0 / sqrt ( r4_mach ( 3 ) );\n end\n\n y = exp ( abs ( x ) );\n\n value = 0.5 * y;\n\n if ( y < ymax )\n value = 0.5 * ( y + 1.0 / y );\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_cosh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7225222297270945}} {"text": "function [ o, x, w ] = epn_lag_02_xiu ( n )\n\n%*****************************************************************************80\n%\n%% EPN_LAG_02_XIU implements the Xiu rule for region EPN_LAG.\n%\n% Discussion:\n%\n% The rule has order\n%\n% O = N + 1.\n%\n% The rule has precision P = 2.\n%\n% EPN is the N-dimensional positive space [0,+oo)^N with exponential\n% or Laguerre weight function:\n%\n% w(x(1:n)) = exp ( - sum ( x(1:n) ) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 March 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% Output, integer O, the order.\n%\n% Output, real X(N,O), the abscissas.\n%\n% Output, real W(O), the weights.\n%\n o = n + 1;\n\n x = zeros ( n, o );\n w = zeros ( o, 1 );\n\n for j = 1 : o\n\n i = 0;\n for r = 1 : floor ( n / 2 )\n arg = 2 * r * ( j - 1 ) * pi / ( n + 1 );\n i = i + 1;\n x(i,j) = sqrt ( 2.0 ) * cos ( arg );\n i = i + 1;\n x(i,j) = sqrt ( 2.0 ) * sin ( arg );\n end\n\n if ( i < n )\n i = i + 1;\n x(i,j) = r8_mop ( j - 1 );\n end\n\n end\n\n gamma0 = - 1.0;\n delta0 = 1.0;\n c1 = - 1.0;\n\n x(1:n,1:o) = ( sqrt ( gamma0 * c1 ) * x(1:n,1:o) - delta0 ) / gamma0;\n\n expon = 0;\n volume_1d = ep1_lag_monomial_integral ( expon );\n volume = volume_1d ^ n;\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/epn_lag_02_xiu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7225222200692017}} {"text": "%\n% Calculation of the fractal dimension which is the slope on the\n% log-log graph.\n%\nderiv = diff(log10(corint))./diff(log10(r));\t\t\t% deriv= Vector of the appr. derivatives\nr2 = r(1:(end-1));\t\t\t\t\t\t\t\t\t\t\t% Forward difference approximation: deriv has one element less, and r must have the # of elements so r2\n\nswitch(dof)\n\n case 'newf'\n\n %\n % Calculation of the fractal dimension, by first calculating the\n % distances of depopulation \"rd\" and of saturation \"rs\".\n %\n rad = 0.8;\t\t\t\t% 2rmax= linear size of the hypercube encompassing a given dataset\n ras = 7;\n v = find(r2 >= rad & r2 <= ras);\t\t\t\t\t% v= Vector of the all the interevent distances that fall in the interval [rn,rs]\n lr = log10(r2(v));\n lc = log10(corint(v));\n\n [fd, Err] = polyfit(lr,lc,1);\n [ev, delta] = polyval(fd, log10(r), Err);\n\n %[fdlo,Err] = polyfit(log10(r2(v)), log10(corint(v)), 1);\n %[fd,Err] = polyfit(log10(r2(v)), log10(corint(v)), 1);\n %[deriv3, delta] = polyval(fd, log10(r2(v)), Err);\n\n Ha_Cax = gca;\n Hf_Cfig;\n hold on;\n Hl_gr2a = loglog(r2(v), corint(v), 'k.','Markersize',7);\n Hl_gr2b = plot(r,10.^ev,'k','Linewidth',1);\n xlabel('Interevent Distance R [km]');\n ylabel('Correlation Integral C(R)');\n set(Ha_Cax,'pos',[0.21 0.1 0.75 0.75]);\n\n if d == 2\n title('Correlation Integral versus the 2D Interevent Distance R');\n else\n title('Correlation Integral versus the 3D Interevent Distance R');\n end\n\n g = [];\n uicontrol('Units','normal','Position',[.0 .92 .15 .07],...\n 'String','Scaling range', 'Callback','g = ginput(2);dof = ''newc''; dofdim')\n\n\n str1 = ['Range = ' num2str(rd,3) ' - ' num2str(rs,3) ' [km]'];\n str2 = ['D = ' num2str(fd(1,1),3)];\n axes('pos',[0 0 1 1]); axis off; hold on;\n te1 = text(0.25, 0.8, str1 ,'Fontweight','bold');\n te2 = text(0.25, 0.75, str2, 'Fontweight', 'bold');\n\n\n %str3 = [' The scaling range is calculated as proposed by Nerenberg & Essex (1990): ' num2str(rd,3) ' - ' num2str(rs,4) ' [km] . If you wish to change the scaling range please click on the \"scaling range\" button'];\n %msg1 = msgbox( str3,'Fractal Dimension');\n\n\n case 'newc'\n\n rd = min(g(:,1)); rs = max(g(:,1));\n v = find(r2 >= rd & r2 <= rs);\n\n lr = log10(r2(v));\n lc = log10(corint(v));\n\n [fd, Err] = polyfit(lr,lc,1);\n [ev, delta] = polyval(fd, log10(r), Err);\n\n delete(Hl_gr2a);\n delete(Hl_gr2b);\n Hl_gr2a = loglog(r2(v), corint(v), 'k.','Markersize',7);\n Hl_gr2b = plot(r,10.^ev,'k','Linewidth',1);\n\n delete(te1);\n delete(te2);\n str1 = ['Range = ' num2str(rd,3) ' - ' num2str(rs,3) ' [km]'];\n str2 = ['D = ' num2str(fd(1,1),3)];\n axes('pos',[0 0 1 1]); axis off; hold on;\n te1 = text(0.25, 0.8, str1 ,'Fontweight','bold');\n te2 = text(0.25, 0.75, str2, 'Fontweight', 'bold');\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/zmap_deprecated/orphaned/src/fractal/dofdN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7225103441929321}} {"text": "function [H,S,D]=sobi(X,n,p),\n% program by A. Belouchrani and A. Cichocki\n%\n% Second\n% Order\n% Blind\n% Identification\n% SOBI\n%**************************************************\n% blind identification by joint diagonalization *\n% of correlation matrices. *\n% \t\t\t *\n% ------------------------------------------------*\n% THIS CODE ASSUMES TEMPORALLY CORRELATED SIGNALS *\n% in estimating the cumulants *\n% ------------------------------------------------*\n%\n% [H,S]=SOBI(X,m,p) produces a matrix H of dimension [m by n] and a matrix S\n% of dimension [n by N] wich are respectively an estimate of the mixture matrix and \n% an estimate of the source signals of the linear model from where the \n% observation matrix X of dimension [m by N] derive.\n% Note: > m: sensor number.\n% > n: source number by default m=n.\n% > N: sample number.\n%\t> p: number of correlation matrices to be diagonalized by default p=4.\n%\n% REFERENCES:\n% A. Belouchrani, K. Abed-Meraim, J.-F. Cardoso, and E. Moulines, ``Second-order\n% blind separation of temporally correlated sources,'' in Proc. Int. Conf. on\n% Digital Sig. Proc., (Cyprus), pp. 346--351, 1993.\n%\n% A. Belouchrani and K. Abed-Meraim, ``Separation aveugle au second ordre de\n% sources correlees,'' in Proc. Gretsi, (Juan-les-pins), \n% pp. 309--312, 1993.\n%\n% A. Belouchrani, and A. Cichocki, \n% Robust whitening procedure in blind source separation context, \n% Electronics Letters, Vol. 36, No. 24, 2000, pp. 2050-2053.\n% \n% A. Cichocki and S. Amari, \n% Adaptive Blind Signal and Image Processing, Wiley, 2002.\n\n\n[m,N]=size(X);\nif nargin==1,\n n=m; % source detection (hum...)\n\n p=4; % number of correlation matrices to be diagonalized \n end;\nif nargin==2,\n p=4 ; % number of correlation matrices to be diagonalized\nend; \npm=p*m; % for convenience\nX=X-kron(mean(X')',ones(1,N)); % zero mean\n%%%% whitening\n% Rx=(X*X')/T;\n% if mepsil ;\n encore=encore | oui ;\n if oui , %%%update of the M and V matrices \n colp=M(:,p:m:pm);colq=M(:,q:m:pm);\n M(:,p:m:pm)=c*colp+sr*colq;M(:,q:m:pm)=c*colq-sc*colp;\n rowp=M(p,:);rowq=M(q,:);\n M(p,:)=c*rowp+sc*rowq;M(q,:)=c*rowq-sr*rowp;\n temp=V(:,p);\n V(:,p)=c*V(:,p)+sr*V(:,q);V(:,q)=c*V(:,q)-sc*temp;\n end%% if\n end%% q loop\n end%% p loop\nend%% while\n%%%estimation of the mixing matrix and source signals\nHf=pinv(Q)*V; %estimated mixing matrix\nSf=V'*X; %estimated sources\n\nH = Hf(:,1:n);\nS = Sf(1:n,:);\n\n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/NMFLABSP_ver1.2/sobi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7224539001294742}} {"text": "function [X,nuclearnorm] = prox_nuclear(B,lambda)\n\n% The proximal operator of the nuclear norm of a matrix\n% \n% min_X lambda*||X||_*+0.5*||X-B||_F^2\n%\n% version 1.0 - 18/06/2016\n%\n% Written by Canyi Lu (canyilu@gmail.com)\n% \n\n[U,S,V] = svd(B,'econ');\nS = diag(S);\nsvp = length(find(S>lambda));\nif svp>=1\n S = S(1:svp)-lambda;\n X = U(:,1:svp)*diag(S)*V(:,1:svp)';\n nuclearnorm = sum(S);\nelse\n X = zeros(size(B));\n nuclearnorm = 0;\nend", "meta": {"author": "canyilu", "repo": "LibADMM-toolbox", "sha": "fa9bc9458b8fbe22ac264c6008b26e7e41e70742", "save_path": "github-repos/MATLAB/canyilu-LibADMM-toolbox", "path": "github-repos/MATLAB/canyilu-LibADMM-toolbox/LibADMM-toolbox-fa9bc9458b8fbe22ac264c6008b26e7e41e70742/proximal_operators/prox_nuclear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.7224538811871204}} {"text": "clear all; close all; clear classes; clc;\n\n%% Ag in Table I on p.4374 of Johnson and Christy, 1972 Phys. Rev. B\neV = [0.64 0.77 0.89 1.02 1.14 1.26 1.39 1.51 1.64 1.76 1.88 2.01 2.13 2.26 2.38 2.50 2.63 2.75 2.88 3.00 3.12 3.25 3.37 3.50 3.62 3.74 3.87 3.99 4.12 4.24 4.36 4.49 4.61 4.74 4.86 4.98 5.11 5.23 5.36 5.48 5.60 5.73 5.85 5.98 6.10 6.22 6.35 6.47 6.60];\nn = [0.24 0.15 0.13 0.09 0.04 0.04 0.04 0.04 0.03 0.04 0.05 0.06 0.05 0.06 0.05 0.05 0.05 0.04 0.04 0.05 0.05 0.05 0.07 0.10 0.14 0.17 0.81 1.13 1.34 1.39 1.41 1.41 1.38 1.35 1.33 1.31 1.30 1.28 1.28 1.26 1.25 1.22 1.20 1.18 1.15 1.14 1.12 1.10 1.07];\nk = [14.08 11.85 10.10 8.828 7.795 6.992 6.312 5.727 5.242 4.838 4.483 4.152 3.858 3.586 3.324 3.093 2.869 2.657 2.462 2.275 2.070 1.864 1.657 1.419 1.142 0.829 0.392 0.616 0.964 1.161 1.264 1.331 1.372 1.387 1.393 1.389 1.378 1.367 1.357 1.344 1.342 1.336 1.325 1.312 1.296 1.277 1.255 1.232 1.212];\n\n%% Convert the photon energies to the wavelengths.\nwvlen = PhysC.h * PhysC.c0 * 1e9 ./ eV;\n\n%% Make the row vectors into column vectors to be used in interp1q().\neV = eV.';\nn = n.';\nk = k.';\nwvlen = wvlen.';\n\n%% Calculate the permittivity from n and k following the exp(+i w t) time dependence.\neps = (n - 1i*k).^2;\n\n%% Plot real(eps) and imag(eps). Compare with Fig.3 on p.4375 of Johnson.\n\nnk_wvlen = 1;\neps_eV = 2;\neps_wvlen = 3;\neps_omega = 4;\nq_omega = 5;\nplotstyle = eps_eV;\nswitch plotstyle\n case nk_wvlen % plot n and k\n loglog(wvlen, n, 'o-', wvlen, k, 'o-')\n %plot(wvlen, n, wvlen, k)\n legend('n', 'k', 'Location', 'SouthEast');\n xlabel 'wavelength (nm)'\n %axis([1e2 1e4 1e-2 1e2])\n case eps_eV % plot real(eps) and -imag(eps)\n plot(eV, real(eps), 'o-', eV, -imag(eps), 'o-')\n legend('\\epsilon_1', '\\epsilon_2', 'Location', 'SouthEast');\n xlabel 'Photon Energy (eV)'\n% axis([0.5 6.5 -7 7]);\n case eps_wvlen\n plot(wvlen, real(eps), 'o-', wvlen, -imag(eps), 'o-')\n legend('\\epsilon_1', '\\epsilon_2', 'Location', 'SouthEast');\n xlabel 'wavelength (nm)'\n %axis([1e2 1e4 1e-2 1e2])\n case eps_omega\n plot(2*pi./wvlen, real(eps), 'o-', 2*pi./wvlen, -imag(eps), 'o-')\n legend('\\epsilon_1', '\\epsilon_2', 'Location', 'SouthEast');\n xlabel '\\omega (c/nm)'\n case q_omega\n omega = 2*pi./wvlen;\n deps1 = real(eps(2:end)) - real(eps(1:end-1));\n domega = omega(2:end) - omega(1:end-1);\n eps1_inter = (real(eps(2:end)) + real(eps(1:end-1)))/2;\n omega_inter = (omega(2:end) + omega(1:end-1))/2;\n numer = eps1_inter + omega_inter .* (deps1./domega);\n denom = -(imag(eps(2:end)) + imag(eps(1:end-1))); % extra factor 2\n plot(2*pi./omega_inter, numer./denom, 'o-');\n xlabel 'wavelength (nm)'\n ylabel 'electric Q';\nend\ntitle(mfilename)\n\n%% Save data.\nsave(mfilename, 'eV', 'n', 'k');\n", "meta": {"author": "wsshin", "repo": "maxwellfdfd", "sha": "f7d583813781694c8a6f0533a91f56c2a78a9ee5", "save_path": "github-repos/MATLAB/wsshin-maxwellfdfd", "path": "github-repos/MATLAB/wsshin-maxwellfdfd/maxwellfdfd-f7d583813781694c8a6f0533a91f56c2a78a9ee5/dielconst/Johnson/Ag.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7224429922946607}} {"text": "function p = predictOneVsAll(all_theta, X)\n%PREDICT Predict the label for a trained one-vs-all classifier. The labels \n%are in the range 1..K, where K = size(all_theta, 1). \n% p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions\n% for each example in the matrix X. Note that X contains the examples in\n% rows. all_theta is a matrix where the i-th row is a trained logistic\n% regression theta vector for the i-th class. You should set p to a vector\n% of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2\n% for 4 examples) \n\nm = size(X, 1);\nnum_labels = size(all_theta, 1);\n\n% You need to return the following variables correctly \np = zeros(size(X, 1), 1);\n\n% Add ones to the X data matrix\nX = [ones(m, 1) X];\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Complete the following code to make predictions using\n% your learned logistic regression parameters (one-vs-all).\n% You should set p to a vector of predictions (from 1 to\n% num_labels).\n%\n% Hint: This code can be done all vectorized using the max function.\n% In particular, the max function can also return the index of the \n% max element, for more information see 'help max'. If your examples \n% are in rows, then, you can use max(A, [], 2) to obtain the max \n% for each row.\n% \n\nall_predictions = all_theta * X';\n[M, I] = max(all_predictions);\np = I(:);\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "zlotus", "repo": "Coursera_Machine_Learning_Exercises", "sha": "3000f402e8e495b7c49e80c0ce4a58d42bf6b430", "save_path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises", "path": "github-repos/MATLAB/zlotus-Coursera_Machine_Learning_Exercises/Coursera_Machine_Learning_Exercises-3000f402e8e495b7c49e80c0ce4a58d42bf6b430/ex3/predictOneVsAll.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.722428515568736}} {"text": "function order = gl_level_to_order ( dim_num, level )\n\n%*****************************************************************************80\n%\n%% GL_LEVEL_TO_ORDER converts a GL level to a GL order.\n%\n% Discussion:\n%\n% Gauss-Legendre rules cannot be nested, but in order to facilitate\n% comparison with Clenshaw Curtis grids, we need to be able to\n% convert a \"level\" into an order. Except for the\n% first case of LEVEL = 0, the relationship is\n%\n% ORDER = 2**LEVEL + 1\n%\n% Level Order\n%\n% 0 1\n% 1 3 = 2 + 1\n% 2 5 = 4 + 1\n% 3 9 = 8 + 1\n% 4 17 = 16 + 1\n% 5 33 = 32 + 1\n%\n% In this routine, we assume that a vector of levels is given,!\n% and the corresponding orders are desired.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 November 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL(DIM_NUM), the level.\n%\n% Output, integer ORDER(DIM_NUM), the order (number of points) of the\n% corresponding rule.\n%\n for dim = 1 : dim_num\n\n if ( level(dim) < 0 )\n order(dim) = -1;\n elseif ( level(dim) == 0 )\n order(dim) = 1;\n else\n order(dim) = ( 2^level(dim) ) + 1;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/gl_display/gl_level_to_order.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7224285013538495}} {"text": "function r = taylorinit(v,k)\n%TAYLORINIT Initialization of taylor variable\n%\n% x = taylorinit(v,k)\n%\n%The dependent variable x is identified and initialized with v, and Taylor\n%coefficients up to k>0 are calculated. For example,\n%\n% u = taylorinit(-3,5)\n%\n%initializes \"u\" to be a Taylor variable with value -3 and Taylor coefficients\n%up to order k=5, i.e. [-3,1,0,0,0,0]. The default for k is 4. After initialization,\n%the order of Taylor coefficients can be obtained by\n%\n% k = taylororder\n%\n%In our example, the result will be k=5. The evaluation\n%\n% f = inline('x*sin(x)-exp(x^2)')\n% y = f(u)\n%\n%computes the Taylor coefficients of f up to order 5. Note the first component of y\n%is f(u), followed by f'(u), f''(u)/2!, f'''(u)/3!, etc. For example,\n%\n% t0 = y{0}\n%\n%is the 0-th Taylor coefficients, namely f(u), and \n%\n% sum( y{0:k} .* e.^(0:k) )\n%\n%is approximately equal to f(u+e) up to O(e^(k+1)). The subsequent statement\n%\n% v = taylor( intval('3.14159_') )\n%\n%initializes v to be the constant with interval value infsup(3.14158,3.14160).\n%\n%Taylor expansions are implemented for univariate functions. However, it is \n%sometimes useful to evaluate a function at an array of points. The statement\n%\n% w = taylorinit((-3:1)',5)\n%\n%initializes w to be a vector of dependent variables with values -3,-2,-1,0,1. All \n%operations with u are executed pointwise, so y=f(w) is executed as w.*sin(w)-exp(w.^2).\n%In this case\n%\n% y(3)\n%\n%is the Taylor expansion of f at -1 up to order 5.\n%\n%For other examples, see demotaylor.\n%\n\n% written 05/21/09 S.M. Rump\n% modified 09/15/10 S.M. Rump\n% modified 08/26/12 S.M. Rump global variables removed\n%\n\n setappdata(0,'INTLAB_TAYLOR_END',0);\n\n if nargin==0\n setappdata(0,'INTLAB_TAYLOR_ORDER',0);\n return\n end\n \n if ~isa(v,'double') & ~isa(v,'intval')\n error('invalid initialization of dependent Taylor variables')\n end\n if nargin==1\n setappdata(0,'INTLAB_TAYLOR_ORDER',4);\n else\n setappdata(0,'INTLAB_TAYLOR_ORDER',k);\n end\n dummy.init = v;\n r = taylor( dummy , 'taylorinit' );\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/taylor/taylorinit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.7224284982521839}} {"text": "function [C, dC] = gplvm_grad(x, X, sigma)\n%GPLVM_GRAD Gradient of the Gaussian Process Latent Variable model\n%\n% [C, dC] = gplvm_grad(x, no_dims, sigma)\n%\n% Computes the gradient of the Gaussian Process Latent Variable model.\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n\n % Decode solution\n [n, d] = size(X);\n no_dims = numel(x) ./ n;\n Y = reshape(x, [n no_dims]);\n\n % Compute kernel matrix (in latent space)\n sum_Y = sum(Y .^ 2, 2);\n K = exp(bsxfun(@minus, bsxfun(@minus, 2 * (Y * Y'), sum_Y'), sum_Y) / (2 * sigma ^ 2));\n \n % Compute gradient with respect to kernel\n% invK = inv(K);\n% dLdK = invK * X * X' * invK - d * invK;\n tmp = (K \\ X) * X';\n dLdK = (tmp - d * eye(n)) / K;\n\n % Compute gradient with respect to coordinates\n dC = zeros(n, no_dims);\n dLdK = K .* dLdK;\n for i=1:n\n dC(i,:) = sum(bsxfun(@times, dLdK(:,i), bsxfun(@minus, Y(i,:), Y)), 1);\n end\n dC = (-1 / sigma ^ 2) * dC(:);\n \n % Compute log-likelihood\n C = -((d * n) / 2) * log(2 * pi) - (d / 2) * log(det(K) + realmin) - .5 * trace(tmp);\n", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/gplvm_grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7222890036951671}} {"text": "function [OP,MM] = CurvedPoissonIPDG2D()\n\n% function [OP,MM] = CurvedPoissonIPDG2D()\n% Purpose: Set up a discrete Poisson matrix and mass matrix\n% using Interior Penalty Discontinuous Galerkin (IPDG).\n \nGlobals2D;\n\nNGauss = gauss.NGauss;\n\n% build DG derivative matrices\nMM = zeros(K*Np*Np, 3); OP = zeros(K*Np*Np*(1+Nfaces), 3); \n\n% global node numbering\nentries = (1:Np*Np)'; entriesMM = (1:Np*Np)'; \nfor k1=1:K \n if(~mod(k1,200)) k1, end;\n\n % Location of k1'th diagonal block entries in OP matrix\n rows1 = ((k1-1)*Np+1:k1*Np)'*ones(1,Np); cols1 = rows1';\n\n % Extract local mass matrix and cubature weights\n locmm = cub.mm(:,:,k1);\n cw = spdiags(cub.W (:,k1), 0, cub.Ncub, cub.Ncub);\n\n % Evaluate derivatives of Lagrange basis functions at cubature nodes\n [cDx, cDy] = PhysDmatrices2D(x(:,k1), y(:,k1), cub.V);\n\n % Evaluate local stiffness matrix\n OP11 = cDx'*cw*cDx + cDy'*cw*cDy;\n \n % Build element-to-element parts of stiffness matrix for element k1\n for f1=1:Nfaces\n\n % Find neighbor\n k2 = EToE(k1,f1); f2 = EToF(k1,f1);\n\n idsM = (f1-1)*NGauss+1:f1*NGauss;\n \n % Extract Lagrange basis function -> Gauss node interpolation matrix\n gVM = gauss.finterp(:,:,f1);\n gVP = gauss.finterp(:,:,f2); gVP = gVP(NGauss:-1:1,:);\n\n % Evaluate spatial derivatives of Lagrange basis function at Gauss nodes\n [gDxM, gDyM] = PhysDmatrices2D(x(:,k1), y(:,k1),gVM);\n [gDxP, gDyP] = PhysDmatrices2D(x(:,k2), y(:,k2),gVP);\n\n % Evaluate normals at Gauss nodes on face\n gnx = spdiags(gauss.nx(idsM, k1), 0, NGauss, NGauss);\n gny = spdiags(gauss.ny(idsM, k1), 0, NGauss, NGauss);\n gw = spdiags(gauss.W(idsM, k1), 0, NGauss, NGauss);\n\n % Compute normal derivatives of Lagrange basis functions at Gauss nodes\n gDnM = gnx*gDxM + gny*gDyM;\n gDnP = gnx*gDxP + gny*gDyP;\n\n % Locate global numbers of Lagrange nodes in neighboring element \n cols2 = ones(Np,1)*((k2-1)*Np+1:k2*Np); \n\n % Find minimum height of two elements sharing this face\n hinv = max(Fscale( 1 + (f1-1)*Nfp, k1), Fscale( 1 + (f2-1)*Nfp, k2)); \n\n % Set penalty scaling\n gtau = 20*(N+1)*(N+1)*hinv; \n\n % Determine type of face\n switch(BCType(k1,f1))\n case {Dirichlet}\n % Dirichlet boundary face variational terms\n\tOP11 = OP11 + ( gVM'*gw*gtau*gVM - gVM'*gw*gDnM - gDnM'*gw*gVM);\n\n case {Neuman}\n % Do nothing\n otherwise\n\t% Interior face variational terms for stiffness matrix\n\tOP11 = OP11 + 0.5*( gVM'*gw*gtau*gVM - gVM'*gw*gDnM - gDnM'*gw*gVM );\n\n\tOP12 = - 0.5*( gVM'*gw*gtau*gVP + gVM'*gw*gDnP - gDnM'*gw*gVP );\n\n % Store self-neighbor interaction term in global stiffness matrix\n OP(entries(:), :) = [rows1(:), cols2(:), OP12(:)];\n\tentries = entries + Np*Np;\n end \n end \n\n % Store k1'th self-self interaction term in global stiffness matrix\n OP(entries(:), :) = [rows1(:), cols1(:), OP11(:)];\n MM(entriesMM(:), :) = [rows1(:), cols1(:), locmm(:)];\n entries = entries + Np*Np; entriesMM = entriesMM + Np*Np;\nend \n\n% Convert OP and MM from coordinate storage format to Matlab's intrinsic sparse matrix format\nOP = OP(1:max(entries)-Np*Np,:); \nOP = myspconvert(OP, Np*K, Np*K, 1e-15); MM = myspconvert(MM, Np*K, Np*K, 1e-15);\nreturn\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes2D/CurvedPoissonIPDG2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676518712608, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.7222889894988771}} {"text": "function b_n = beamWeightsHypercardioid2Spherical(N)\n%BEAMWEIGHTSHYPERCARDIOID2SPHERICAL Generate spherical beamweights for hypercardioids\n%\n% The hypercardioid is the pattern that maximizes the directivity-factor\n% for a certain SH order N. The hypercardioid is also the plane-wave\n% decomposition beamformer in the SHD, also called 'regular' because the\n% beamweights are just the SH values on the beam-direction. \n% Since the pattern is axisymmetric only the N+1 coefficients of m=0 are \n% returned.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% BEAMWEIGHTSHYPERCARDIOID2SPHERICAL.M - 11/7/2013\n% Archontis Politis, archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nc_n = 4*pi/(N+1)^2 * getSH(N,[0 0],'real');\nb_n = zeros(N+1,1);\nfor n=0:N\n b_n(n+1) = c_n((n+1)^2 -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/beamWeightsHypercardioid2Spherical.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7222628376086289}} {"text": "function lambda = bab_eigenvalues ( n, alpha, beta )\n\n%*****************************************************************************80\n%\n%% BAB_EIGENVALUES returns the eigenvalues of the BAB matrix.\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 N, the order of the matrix.\n%\n% Input, real ALPHA, BETA, the parameters.\n%\n% Output, real LAMBDA(N,1), the eigenvalues.\n%\n lambda = zeros ( n, 1 );\n\n for i = 1 : n\n angle = i * pi / ( n + 1 );\n lambda(i,1) = alpha + 2.0 * beta * cos ( angle );\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/bab_eigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7222485960954963}} {"text": "function [x, infos] = rank2nmf(V, in_options)\n% Rank-two NMF computes a rank-two NMF of X\n%\n% If X >= 0 and rank(X) = 1, take W as any non-zero column of X and compute\n% H accordingly \n% \n% If X >= 0 and rank(X) = 2, this is Algorithm 4.1 in Chapter 4, \n% with alpha1 = alpha2 = 0. This is an exact algorithm. \n% \n% Otherwise, the input matrix has is replaced by max(0,X2) where X2 is its \n% best rank-two approximation; cf. Chapter 6. \n%\n% Inputs:\n% matrix V\n% options options\n% Output:\n% w solution of w\n% infos information\n%\n% References:\n% Nicolas Gillis,\n% \"Nonnegative Matrix Factorization,\"\n% SIAM, 2020.\n%\n%\n% This file is part of NMFLibrary.\n%\n% This file has been ported from \n% Rank2NMF.m at https://gitlab.com/ngillis/nmfbook/-/tree/master/algorithms\n% by Nicolas Gillis (nicolas.gillis@umons.ac.be)\n%\n% Change log: \n%\n% June 13, 2022 (Mitsuhiko Horie and Hiroyuki Kasai): Ported initial version \n%\n\n\n % set dimensions and samples\n [m, n] = size(V);\n \n % set local options\n local_options = []; \n local_options.delta = 1e-6;\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 if options.verbose > 0\n fprintf('# Rank2-NMF: started ...\\n'); \n end \n\n if min(V(:)) < 0 \n if options.verbose > 0 \n fprintf(' * Rank2-NMF: The input matrix is not nonnegative: V <-- max(V,0).\\n'); \n end\n V = max(0,V); \n end \n [u, s, v] = svds(V, 3);\n\n % Case 0. rank(V) = 0\n if s(1, 1) <= eps\n if options.verbose > 0 \n fprintf(' * Rank2-NMF: The input matrix is (close to) zero.');\n end\n [m,n] = size(V); \n W = zeros(m,1); \n H = zeros(1,n); \n return;\n end\n\n % Case 1. rank(V) = 1\n if s(2, 2) < 1e-9 * s(1, 1)\n if options.verbose > 0 \n fprintf(' * Rank2-NMF: The input matrix has rank one, an optimal solution is returned.\\n');\n end\n sumV = sum(V); \n [~,j] = max(sumV); \n W = V(:,j); \n H = sumV/sum(W); \n return; \n end\n\n % Case 2. rank(V) >= 2 \n if s(3, 3) > 1e-9 * s(2, 2)\n if options.verbose > 0 \n\t fprintf(' * Rank2-NMF: The input matrix does not have rank two.\\n'); \n fprintf(' * Rank2-NMF: V <-- rank(V2,0) where V2 is the rank-2 truncated SVD of V.\\n'); \n fprintf(' * Rank2-NMF: The solution computed might not be optimal.\\n'); \n end\n [u, s, v] = svds(V, 2);\n Vj = max(u*s*v', 0); \n else\n if options.verbose > 0 \n fprintf(' * Rank2-NMF: The input matrix has rank two, an optimal solution is returned.\\n');\n end\n Vj = V; \n end\n\n % remove zero columns\n sumVj = sum(Vj); \n J = find(sumVj > 0); \n Vj = Vj(:, J);\n \n % normalize columns\n [m, n] = size(Vj); \n for i = 1 : n\n Vj(:, i) = Vj(:, i) / sum(Vj(:, i));\n end\n \n % compute extreme points of conv(Vj) hence a feasible solution W\n % given that rank(V) = 2. \n W = zeros(m, 2); \n [~, j1] = max(sum(Vj.^2)); \n W(:, 1) = Vj(:, j1); \n [~, j2] = max(sum( (Vj-repmat(Vj(:, j1), 1, n)).^2)); \n W(:, 2) = Vj(:, j2); \n \n W = full(W); \n WtW = W' * W;\n WtV = W' * V;\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_nmflibrary(V, W, WtW, WtV); \n else\n H = options.init; \n end \n\n \n %% perform main routine\n options.alg_name = 'Rank2-NMF';\n options.V = V;\n options.W = W;\n options.main_routine_mode = true;\n options.eps0 = 0; \n options.eps = 1;\n\n [H, WtW, WtV, infos] = nnls_solver(V, W, options); \n\n x.W = W;\n x.H = H;\n \nend", "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/rank2/rank2nmf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658466, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7221606807673241}} {"text": "function sqi = ksqi(signal)\n%kSQI Kurtosis SQI\n% \n% Returns the kurtosis of a signal\n% \n% Reference:\n% Li, Q., Mark, R. G., Clifford, G. D., & Li. (2008). Robust heart rate \n% estimation from multiple asynchronous noisy sources using signal quality \n% indices and a Kalman filter. Physiol. Meas., 29(1), 15–32. \n% http://doi.org/10.1088/0967-3334/29/1/002\n% \n% Input:\n% signal: single channel (F)ECG [1xN double]\n% \n% Output:\n% sqi: resulting kSQI for segment\n% \n% Fetal Extraction Toolbox, version 1.0, February 2014\n% Released under the GNU General Public License\n%\n% Copyright (C) 2014 Fernando Andreotti\n% Dresden University of Technology, Institute of Biomedical Engineering\n% fernando.andreotti@mailbox.tu-dresden.de\n%\n% Last updated : 09-03-2014\n%\n%\n% This program 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 of the License, or (at your\n% option) any later version.\n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n% Public License for more details.\n\nsqi=kurtosis(signal);\n\nend\n\n", "meta": {"author": "fernandoandreotti", "repo": "cinc-challenge2017", "sha": "78cfc8e6194857cee0cd731f41ba5b2dd589aed2", "save_path": "github-repos/MATLAB/fernandoandreotti-cinc-challenge2017", "path": "github-repos/MATLAB/fernandoandreotti-cinc-challenge2017/cinc-challenge2017-78cfc8e6194857cee0cd731f41ba5b2dd589aed2/featurebased-approach/subfunctions/lib/fernando/sqi_metrics/ksqi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7221606680004357}} {"text": "function res = qdist(a,b)\n%QDIST Implements q(a,b) metrical distance\n% name qdist is used to avoid ambiguities with variable q\n%\n% res = qdist(a,b) max( abs(inf(a)-inf(b)) , abs(sup(a)-sup(b)) )\n%\n% for real intervals max( abs(inf(a)-inf(b)) , abs(sup(a)-sup(b)) )\n% for complex intervals qdist(real(a),real(b)) + qdist(imag(a),imag(b))\n%\n\n% written 10/16/98 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%\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 ~isa(a,'intval')\n a = intval(a);\n end\n if ~isa(b,'intval')\n b = intval(b);\n end\n\n if ~a.complex & ~b.complex\n res = max( abs(a.inf-b.inf) , abs(a.sup-b.sup) ) ;\n else\n res = qdist(real(a),real(b)) + qdist(imag(a),imag(b)) ;\n end\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/intval/@intval/qdist.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7221507213893255}} {"text": "function [nll,g,H,T] = LogisticLoss(w,X,y)\n% w(feature,1)\n% X(instance,feature)\n% y(instance,1)\n\n[n,p] = size(X);\n\nXw = X*w;\nyXw = y.*Xw;\n\nnll = sum(mylogsumexp([zeros(n,1) -yXw]));\n\nif nargout > 1\n if nargout > 2\n sig = 1./(1+exp(-yXw));\n g = -X.'*(y.*(1-sig));\n else\n g = -X.'*(y./(1+exp(yXw)));\n end\nend\n\nif nargout > 2\n H = X.'*diag(sparse(sig.*(1-sig)))*X;\nend\n\nif nargout > 3\n T = zeros(p,p,p);\n for j1 = 1:p\n for j2 = 1:p\n for j3 = 1:p\n T(j1,j2,j3) = sum(y(:).^3.*X(:,j1).*X(:,j2).*X(:,j3).*sig.*(1-sig).*(1-2*sig));\n end\n end\n end\nend", "meta": {"author": "huashiyiqike", "repo": "LSTM-MATLAB", "sha": "2c3f7af2917d610a3dc920aa7e561238f360c1ef", "save_path": "github-repos/MATLAB/huashiyiqike-LSTM-MATLAB", "path": "github-repos/MATLAB/huashiyiqike-LSTM-MATLAB/LSTM-MATLAB-2c3f7af2917d610a3dc920aa7e561238f360c1ef/dependence/matlabserver_r1/minFunc/logistic/LogisticLoss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012701768145, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7221039082391066}} {"text": "function[C] = localCorrections(x,y,a,G,rq,tol,gradOpt)\n% C = localCorrections(x,y,a,G,rq,rMax,tol)\n% Local correction matrix for the EBD.\n% inputs :\n% - x and y : arrays of size N1x2 and N2x2 (clouds of points) inside the\n% unit disk.\n% - a : the cutoff parameter of the EBD method\n% - G : the kernel\n% - rq : the radial quadrature that has been computed for G\n% - rMax : such that initially, the data was X = rMax*x, Y = rMax*y (before\n% rescaling).\n% - tol : required tolerance.\n% output : the sparse correction matrix C.\n\nN1 = size(x,1);\nN2 = size(y,1);\n[I,rxyTemp] = rangesearch(y,x,a*1.05);\njdx = cell2mat(I')';\nrxy = cell2mat(rxyTemp')';\nidx = zeros(size(jdx));\nsp_ind = 1;\nfor x_ind=1:length(I)\n idx(sp_ind:(sp_ind+length(I{x_ind})-1)) = x_ind;\n sp_ind = sp_ind + length(I{x_ind});\nend\n% Save memory\nclear I;\nNCI = length(rxy);\n\nif NCI ~= 0\n \n if gradOpt\n exact_Interactions = G.evalDer(rxy); % Exact local interactions\n C1 = sum(abs(rq.alpha0.*Cp(rq.rho)).*rq.rho.^3); % Bound for the second derivative.\n Ninterp = fix(sqrt(C1)*a/sqrt(8*tol))+10; % Guarantees interpolation error < tol.\n xinterp = linspace(0,a*1.1,Ninterp);\n yinterp = rq.evalDer(xinterp);\n radial_quadratureNear0 = interp1(xinterp,yinterp,rxy); % we remove the radial\n else\n exact_Interactions = G.eval(rxy); % Exact local interactions\n C1 = sum(abs(rq.alpha0.*Cp(rq.rho)).*rq.rho.^2); % Bound for the second derivative.\n Ninterp = fix(sqrt(C1)*a/sqrt(8*tol))+10; % Guarantees interpolation error < tol.\n xinterp = linspace(0,a*1.1,Ninterp);\n yinterp = rq.eval(xinterp);\n radial_quadratureNear0 = interp1(xinterp,yinterp,rxy); % we remove the radial\n end\n \n \n % quadrature contribution (using interpolation to avoid evaluating at\n % all points).\n \n C_val = exact_Interactions - radial_quadratureNear0;\n C = sparse(idx,jdx,C_val,N1,N2);\n \n if gradOpt\n Tx = sparse(idx,jdx,y(jdx,1) - x(idx,1),N1,N2);\n Ty = sparse(idx,jdx,y(jdx,2) - x(idx,2),N1,N2);\n idx = idx(rxy> 1e-12);\n jdx = jdx(rxy> 1e-12);\n rxy = rxy(rxy> 1e-12);\n R = sparse(idx,jdx,1./rxy,N1,N2);\n Cx = C.*R.*Tx;\n Cy = C.*R.*Ty;\n C = {Cx,Cy};\n end\nelse\n % No close interactions\n if gradOpt\n C = {sparse(N1,N2),sparse(N1,N2)};\n else\n C = sparse(N1,N2); % all zeros\n end\nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openEbd/LocalCorrections/localCorrections.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7220800976444923}} {"text": "function [ p2, dp2, p1 ] = jacobi_ss_recur ( x, n, alpha, beta, b, c )\n\n%*****************************************************************************80\n%\n%% JACOBI_SS_RECUR finds the value and derivative of a Jacobi polynomial.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 October 2005\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, BETA, the exponents of (1-X) and\n% (1+X) in the quadrature rule.\n%\n% Input, real B(N), 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 + ( alpha - beta ) / ( alpha + beta + 2.0 );\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 - b(i) ) * p1 - c(i) * p0;\n dp2 = ( x - b(i) ) * 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/jacobi_ss_recur.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7220530390326056}} {"text": "% SIMPDEMO\n% This program solves the simple two dimensional problem in Chapter 2,\n% and makes figure 2.1.\n%\ntol=[1.d-6,1.d-6];\n%\n% Create the mesh for the contour plot of \\| f \\|.\n%\nvl=.1:.5:2; vr=2:4:40; v=[vl,vr];\nv=.5:4:40;\nv=[.25,.5:2:40];\nxr=-5:.2:5; n=length(xr); z=zeros(n,n);\nfor i=1:n\nfor j=1:n\n w=[xr(i),xr(j)]';\n z(i,j)=norm(simple(w));\nend\nend\n%\n% Newton's method\n%\nparams=[40, 1, 0,0];\n%\n% x0 is a good initial iterate.\n%\nx0=[2,.5]';\n[sn, errsn, ierrn, x_hist]=nsold(x0, 'simple', tol, params);\n%\n% x1 is a poor initial iterate. The iteration from x1 will stagnate\n% at a point where $F'$ is singular.\n%\nx1=[3,5]';\n[sn2, errsn2, ierrn2, x_hist2]=nsold(x1, 'simple', tol, params);\n%\n% Draw a contour plot of $\\| f \\|$.\n%\nfigure(1)\ncontour(xr,xr,z,v)\nhold\n%\n% Use the x_hist array to plot the iterations on the coutour plot.\n%\nplot(x_hist(1,:),x_hist(2,:),'-*', x_hist2(1,:),x_hist2(2,:),'-o');\nlegend('Convergence','Stagnation');\nxlabel('x_1');\nylabel('x_2');\naxis([0 5 -5 5])\nhold\n%\n% Default \n%\nparams=[40, 1000, .5, 0];\n[sc, errsd, ierrd]=nsold(x0, 'simple', tol, params);\ninewt=length(errsn(:,1)); cnewt=0:inewt-1;\nidefault=length(errsd(:,1)); cdefault=0:idefault-1;\nfigure(2)\nsemilogy(cnewt,errsn(:,1),'-',cdefault,errsd(:,1),'--')\nlegend('Newton','default')\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/Chapter2/simpdemo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7220489551913005}} {"text": "function area = voronoi_areas_direct ( d_num, d_xyz, face_num, face_d, v_xyz )\n\n%*****************************************************************************80\n%\n%% VORONOI_AREAS_DIRECT computes the area of each polygon in a Voronoi diagram.\n%\n% Discussion:\n%\n% This algorithm works directly from the Delaunay triangulation and the\n% Voronoi vertex locations, without having to determine the explicit\n% description of each Voronoi polygon as a list of Voronoi vertices.\n% This means this routine should be significantly faster than\n% VORONOI_AREAS, at least for larger problems.\n%\n%\n% The Delaunay triangle has vertices D1, D2, D3, and a Voronoi vertex\n% V which we imagine is inside the triangle, although in fact it need\n% not be.\n%\n% Include now the Delaunay vertex averages, D12, D23, and D31, and\n% the Delaunay triangle can be divided into 3 pieces, contributing to\n% the Voronoi polygons associated with D1, D2 and D3 as follows:\n%\n% D1 gets D1:V:D31 + D1:D12:V\n% D2 gets D2:V:D12 + D2:D23:V\n% D3 gets D3:V:D23 + D3:D31:V\n%\n% The advantage of computing things this way is that it can be done\n% directly from the Delaunay triangle information. If we must first\n% determine the explicit list of Voronoi vertices that form a particular\n% Voronoi polygon, then compute the area, it is cumbersome and expensive\n% to determine this connectivity information.\n%\n% Presumably, if things have been done correctly, the cases where\n% the Voronoi vertex is outside of the Delaunay triangle will correspond\n% to situations where some of the areas come out negative, and \n% sum to the correct final result.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 11 May 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer D_NUM, the number of data points and Voronoi polygons.\n%\n% Input, real D_XYZ(3,D_NUM), the coodinates of the data points.\n%\n% Input, integer FACE_NUM, the number of faces, and Voronoi vertices.\n%\n% Input, integer FACE_D(3,FACE_NUM), the data points that form\n% each triangle.\n%\n% Input, real V_XYZ(3,FACE_NUM), the coordinates of the Voronoi vertices.\n%\n% Output, real AREA(D_NUM), the area of each Voronoi polygon.\n%\n area = zeros ( d_num, 1 );\n\n r = 1.0;\n%\n% Consider each triangle.\n%\n for face = 1 : face_num\n%\n% Define some things.\n%\n p1 = face_d(1,face);\n p2 = face_d(2,face);\n p3 = face_d(3,face);\n\n d1 = d_xyz ( 1:3, p1 );\n d2 = d_xyz ( 1:3, p2 );\n d3 = d_xyz ( 1:3, p3 );\n\n d12 = 0.5 * ( d1 + d2 );\n d23 = 0.5 * ( d2 + d3 );\n d31 = 0.5 * ( d3 + d1 );\n v = v_xyz(1:3,face);\n%\n% Force all points to lie on the sphere.\n%\n d12 = d12 / norm ( d12 );\n d23 = d23 / norm ( d23 );\n d31 = d31 / norm ( d31 );\n v = v / norm ( v );\n%\n% Compute orientation and area of the 6 subtriangles.\n%\n o1a = stri_vertices_to_orientation ( d1, v, d31 );\n a1a = stri_vertices_to_area ( r, d1, v, d31 );\n o1b = stri_vertices_to_orientation ( d1, d12, v );\n a1b = stri_vertices_to_area ( r, d1, d12, v );\n\n o2a = stri_vertices_to_orientation ( d2, v, d12 );\n a2a = stri_vertices_to_area ( r, d2, v, d12 );\n o2b = stri_vertices_to_orientation ( d2, d23, v );\n a2b = stri_vertices_to_area ( r, d2, d23, v );\n\n o3a = stri_vertices_to_orientation ( d3, v, d23 );\n a3a = stri_vertices_to_area ( r, d3, v, d23 );\n o3b = stri_vertices_to_orientation ( d3, d31, v );\n a3b = stri_vertices_to_area ( r, d3, d31, v );\n%\n% Contribute to the Voronoi areas.\n%\n area(p1) = area(p1) + o1a * a1a + o1b * a1b;\n area(p2) = area(p2) + o2a * a2a + o2b * a2b;\n area(p3) = area(p3) + o3a * a3a + o3b * a3b;\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_voronoi/voronoi_areas_direct.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7219411155476955}} {"text": "function out = ggrnd(n,p,g)\n% GG - random numbers from generalized Gaussian distribution (requires\n% Statistics toolbox)\n% R = GGRND(N,P,G) returns a vector of N random numbers having a \n% generalized gaussian distribution with shape parameter P, and scale \n% parameter G, i.e. p(x) \\propto exp(-G*|x|^P).\n%\n% If P=2 it GGRND returns normally distributed random numbers\n%\n% Reference: Johnson, M. E., Computer generation of the exponential power\n% distributions\", Journal of Statistical Computation and Simulation, 9,\n% pp. 239--240, 1979\n%\n% See also: RANDN, GAMRND\n\n% Author: G. Gomez-Herrero, german.gomezherrero@ieee.org\n% $Revision: 1.0 $Date: 21/06/2007\n\nif nargin < 3, g=1; end\nif abs(p-2)<1e-3,\n x = randn(1,n);\nelse\n y = gamrnd(1/p,1,1,n);\n x = abs(g.*y).^(1/p);\n pos = find(rand(1,n)<0.5);\n x(pos) = -x(pos);\nend\n% normalize variance and return\nout = x'./sqrt(var(x));\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/SIFT-private/utils/ggrnd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.7219103134074853}} {"text": "function r = toep_cholesky_upper ( n, g )\n\n%*****************************************************************************80\n%\n%% TOEP_CHOLESKY_UPPER: upper Cholesky factor of a compressed Toeplitz matrix.\n%\n% Discussion:\n%\n% The Toeplitz matrix A is supplied in a compressed form G.\n%\n% The Toeplitz matrix must be positive semi-definite.\n%\n% After factorization, A = R' * R.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2012\n%\n% Author:\n%\n% Michael Stewart\n%\n% Reference:\n%\n% Michael Stewart,\n% Cholesky factorization of semi-definite Toeplitz matrices.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real G(2,N), the compressed Toeplitz matrix.\n% G(1,1:N) contains the first row.\n% G(2,2:N) contains the first column.\n%\n% Output, real R(N,N), the upper Cholesky factor.\n%\n r = zeros ( n, n );\n r(1,1:n) = g(1,1:n);\n g(1,2:n) = g(1,1:n-1);\n g(1,1) = 0.0;\n for i = 2 : n\n rho = - g(2,i) / g(1,i);\n g(:,i:n) = ( [ 1 rho; rho 1 ] * g(:,i:n) ) / sqrt ( ( 1 - rho ) * ( 1 + rho ) );\n r(i,i:n) = g(1,i:n);\n g(1,i+1:n) = g(1,i:n-1);\n g(1,i) = 0.0;\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/toeplitz_cholesky/toep_cholesky_upper.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7216728087984843}} {"text": "% ASTROTIK by Francesco Santilli\n% Compute spherical coordinates of a given position.\n%\n% Usage: [r,alpha,delta] = spherical(X)\n%\n% where: X = position [L]\n% r = radius [L]\n% alpha = right ascension [rad]\n% delta = declination [rad]\n\nfunction [r,alpha,delta] = spherical(X)\n\n if ~(nargin == 1)\n error('Wrong number of input arguments.')\n end\n \n D = check(X,1);\n \n if ~(D==3)\n error('Wrong size of an input argument.')\n end\n\n xx1 = X(1)^2;\n xx2 = X(2)^2;\n xx3 = X(3)^2;\n r = sqrt(xx1 + xx2 + xx3);\n xy = sqrt(xx1 + xx2);\n alpha = atan2(X(2),X(1));\n delta = atan(X(3)/xy);\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/tools/spherical.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7216728087984843}} {"text": "function out_m = updownsample( in_m,out_x_sz,out_y_sz,is_fourier_flag,is_real_flag )\n%\n% updownsample - up-sample or down-sample an input series using fourier domain\n% input series needs to be continuous of a high degree\n%\n% format: out_m = updownsample( in_m,out_x_sz,out_y_sz,is_fourier_flag,is_real_flag )\n%\n% input: in_m - input matrix for up/down sampling. can be in\n% space domain OR in fourier domain, in such\n% case, needs to be in matlab format !!!\n% (matlab-format = the save as given from fft/fft2)\n% out_x_sz,out_y_sz - desired number of pixels in the output image\n% is_fourier_flag - 1: the input is given in the fourier domain\n% 0: the input is given in the space domain\n% (we need to use fft2 to convert to fourier domain)\n% is_real_flag - 0: the input is a complex matrix -> don't use\n% abs() at the output, perform complex\n% up/down sampling\n% 1: the input is real BUT has negative values ->\n% use real() at the output\n% 2: the input is real and positive -> using\n% abs() at the output \n%\n% output: out_m - up/down sampled image \n%\n% NOTE: it is important to specify if the image is REAL or COMPLEX, since\n% if the image is REAL -> we have to use ABS() on the inverse fourier\n% transform (because of roundoff errors of the transform).\n%\n% NOTE: since a desired amount of pixels is needed at the output, there is\n% no attempt to use matrices which are in size of power of 2. this\n% optimization can not be used in this case\n%\n% NOTE: input series needs to be CONTINUOUS OF A HIGH DEGREE, since the\n% upsampling is done in the frequency domain, which samples the output\n% grid with SINE-like (harmonic) functions\n%\n% \n% Example: type \"updownsample\" for an example. it will load the matlab's\n% child image to a temporary variable, as upsample it\n%\n% out = updownsample( A,300,300,0,1 );\n% figure;\n% colormap gray;\n% subplot( 1,2,1 );\n% imagesc( A );\n% subplot( 1,2,2 );\n% imagesc( out );\n%\n\n\n% \n% Theory: the upsampling is done by zero-padding in the input domain BETWEEN the samples,\n% then at the fourier domain, taking the single spectrum (out of the repetition of spectrums)\n% i.e. low pass with Fcutoff=PI/upsample_factor, zeroing the rest of the spectrum\n% and then doing ifft to the distribution.\n% since we have a zero padding operation in time, we need to multiply by the fourier gain.\n%\n% +-----------+ +-------+ +---------+ +--------+ +--------+\n% y[n,m] --> | up-sample | --> | FFT | --> | LPF | --> | * Gain | --> | IFFT | --> interpolated \n% | factor M | +-------+ | Fc=PI/M | +--------+ +--------+\n% +-----------+ +---------+\n%\n% this operation is the same as the following one (which has less operations):\n%\n% +-------+ +--------+ +--------------+ +--------+\n% y[n,m] --> | FFT | --> | * Gain | --> | Zero Padding | --> | IFFT | --> interpolated \n% +-------+ +--------+ +--------------+ +--------+\n%\n% NOTE THAT, the zero-padding must be such that the D.C. ferquency remains the D.C. frequency\n% and that the zero padding is applied to both positive and negative frequencies. \n% The zero padding actually condences the frequency -> which yields a longer series in the \n% image domain, but without any additional information, thus the operation must be an interpolation.\n\n\n% Copyright (c) 2003, Ohad Gal\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% check input parameters\n% ==============================================\nif (nargin==0)\n hFig = figure( 'visible','off' );\n hImage = image;\n Child = get( hImage,'cdata' );\n close( hFig );\n\tout = updownsample( Child,300,300,0,1 );\n\tfigure;\n\tcolormap gray;\n\tsubplot( 1,2,1 );\n\timagesc( Child );\n\tsubplot( 1,2,2 );\n\timagesc( out );\n return\nelseif (nargin<5)\n error( 'UpDownSample - insufficient input parameters' );\nend\n\n\n% ==============================================\n% get input image size, and calculate the gain\n% ==============================================\n[in_y_sz,in_x_sz] = size( in_m );\ngain_x = out_x_sz/in_x_sz;\ngain_y = out_y_sz/in_y_sz;\n\n% ==============================================\n% check if up/down sampling is needed at all\n% ==============================================\nif (gain_x == 1) & (gain_y==1)\n\n % same gain -> do not change sampling rate\n % ==========================================\n if is_fourier_flag\n switch is_real_flag\n case 0, out_m = ifft2( in_m );\n case 1, out_m = real( ifft2( in_m ) );\n case 2, out_m = abs( ifft2( in_m ) );\n end\n else\n out_m = in_m;\n end\n \nelse\n\n % upsample or downsample as needed\n % ==================================\n \n % convert to fourier domain, if input is given in the space domain\n if ~is_fourier_flag\n in_m = fft2(in_m);\n end\n \n % build grid vectors for the up/down sampling\n % ============================================\n % if the input is even & output is odd-> use floor for all\n % if the output is even & input is odd -> use ceil for all\n % other cases - don't care\n % for downsampling -> the opposite\n if (~mod( in_x_sz,2 ) & (out_x_sz>in_x_sz)) | (mod( in_x_sz,2 ) & (out_x_szin_y_sz)) | (mod( in_y_sz,2 ) & (out_y_sz\n% Copyright © 2015 University of Oxford\n% Version: 0.1.0\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, 1);\nnargoutchk(0, 1);\n\nif (size(im, 3) > 1)\n error('IM must be a grayscale image')\nend\n\n% grid for image coordinates\n[grow, gcol] = ndgrid(1:size(im, 1), 1:size(im, 2));\n\n% centre of mass\nc = single(im(:));\nc = sum([c .* grow(:), c .* gcol(:)]) / sum(c);\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/imcmass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7216718566360484}} {"text": "function b = r8blt_to_r8ge ( n, ml, a )\n\n%*****************************************************************************80\n%\n%% R8BLT_TO_R8GE copies a R8BLT matrix to a R8GE matrix.\n%\n% Discussion:\n%\n% The R8BLT storage format is used 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% 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% 28 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, integer ML, the lower bandwidth.\n%\n% Input, real A(ML+1,N), the R8BLT matrix.\n%\n% Output, real B(N,N), the R8GE matrix.\n%\n for i = 1 : n\n for j = 1 : n\n if ( j <= i & i <= j + ml )\n b(i,j) = a(i-j+1,j);\n else\n b(i,j) = 0.0;\n end\n end\n end\n \n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r8blt_to_r8ge.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7216718529569501}} {"text": "function t = transmission_exponential(d, beta, varargin)\n%TRANSMISSION_EXPONENTIAL Compute transmission map using given depth map based\n%on the Lambert-Beer law\n% Inputs:\n% -|d|: H-by-W matrix with values of depth for processed image in meters.\n% -|beta|: positive constant that parameterizes the density of haze.\n% Larger values indicate thicker haze.\n%\n% Outputs:\n% -|t|: H-by-W matrix with medium transmission values ranging in [0, 1].\n\nt = exp(-beta * d);\n\nend\n\n", "meta": {"author": "sakaridis", "repo": "fog_simulation-SFSU_synthetic", "sha": "8048e2ea208bd797ef2298e6b50f0d4e3a1b77a3", "save_path": "github-repos/MATLAB/sakaridis-fog_simulation-SFSU_synthetic", "path": "github-repos/MATLAB/sakaridis-fog_simulation-SFSU_synthetic/fog_simulation-SFSU_synthetic-8048e2ea208bd797ef2298e6b50f0d4e3a1b77a3/source/Fog_simulation/transmission_exponential.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.7216526759378686}} {"text": "function bessel_j1_values_test ( )\n\n%*****************************************************************************80\n%\n%% BESSEL_J1_VALUES_TEST demonstrates the use of BESSEL_J1_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BESSEL_J1_VALUES_TEST:\\n' );\n fprintf ( 1, ' BESSEL_J1_VALUES stores values of \\n' );\n fprintf ( 1, ' the Bessel J1 function.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X J1(X)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, x, fx ] = bessel_j1_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, ' %12f %24.16f\\n', x, fx );\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/bessel_j1_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7216416133561768}} {"text": "% KERNEL = binomialFilter(size)\n%\n% Returns a vector of binomial coefficients of order (size-1) .\n\n% Eero Simoncelli, 2/97.\n\nfunction [kernel] = binomialFilter(sz)\n\nif (sz < 2)\n error('size argument must be larger than 1');\nend\n\nkernel = [0.5 0.5]';\n\nfor n=1:sz-2\n kernel = conv([0.5 0.5]', kernel);\nend\n \n", "meta": {"author": "jbhuang0604", "repo": "SelfExSR", "sha": "8f6dd8c1d20cb7e8792a7177b4f6fd677633f598", "save_path": "github-repos/MATLAB/jbhuang0604-SelfExSR", "path": "github-repos/MATLAB/jbhuang0604-SelfExSR/SelfExSR-8f6dd8c1d20cb7e8792a7177b4f6fd677633f598/quant_eval/ifcvec_release/matlabPyrTools/binomialFilter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.7215647022194562}} {"text": "function [rho, stationary]=inverse_ar_roots(phi)\n% Computes the inverted roots of the characteristic equation of an AR(P)\n%\n% USAGE:\n% [RHO, STATIONARY] = inverse_ar_roots(PARAMETERS)\n% \n% INPUTS:\n% PARAMETERS - A column vector containing the AR parameters in the order\n% y(t) = mu + phi(1) y(t-1) + phi(2)y(t-2) + ... + phi(P) y(t-P) + e(t)\n%\n% OUTPUTS:\n% RHO - A max(P) by 1 vector containing the inverted roots of the characteristic equation\n% corresponding to the AR model input \n% STATIONARY - Logical indicating whether the AR process is stationary\n% \n% COMMENTS:\n% Process is stationary if min(abs(rho)) > 1\n% \n% See also ARMAROOTS, ACF\n \n% Copyright: Kevin Sheppard\n% kevin.sheppard@economics.ox.ac.uk\n% Revision: 3 Date: 1/1/2007\n\n%Make sure phi is a row vector;\n\np=length(phi);\n%Make sure phi is a row vector\nif size(phi,1)>=size(phi,2) && min(size(phi))==1\n phi=phi';\nelse\n error('Phi should be a column vector.')\nend\nrho=roots([-fliplr(phi) 1]);\nstationary=min(abs(rho))>1;", "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/timeseries/inverse_ar_roots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7215646988961499}} {"text": "function tet_mesh_test005 ( )\n\n%*****************************************************************************80\n%\n%% TET_MESH_TEST005 tests TETRAHEDRON_BARYCENTRIC.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 August 2009\n%\n% Author:\n%\n% John Burkardt\n%\n test1_num = 3;\n test2_num = 5;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST005\\n' );\n fprintf ( 1, ' TETRAHEDRON_BARYCENTRIC computes the barycentric\\n' );\n fprintf ( 1, ' coordinates of a point.\\n' );\n%\n% Choose a random tetrahedron.\n%\n for test1 = 1 : test1_num\n\n [ tet_xyz, seed ] = r8mat_uniform_01 ( 3, 4, seed );\n\n r8mat_transpose_print ( 3, 4, tet_xyz, ' Random tetrahedron:' );\n%\n% Choose barycentric coordinates C1 at random.\n%\n% Define a point P.\n%\n% Have TETRAHEDRON_BARYCENTRIC compute C2, the barycentric coordinates of P.\n%\n for test2 = 1 : test2_num\n\n [ c1, seed ] = r8vec_uniform_01 ( 4, seed );\n c1_sum = sum ( c1(1:4) );\n c1(1:4) = c1(1:4) / c1_sum;\n\n p(1:3) = tet_xyz(1:3,1:4) * c1(1:4)';\n\n c2 = tetrahedron_barycentric ( tet_xyz, p );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' C1 = %14.6f %14.6f %14.6f %14.6f\\n', c1 );\n fprintf ( 1, ' C2 = %14.6f %14.6f %14.6f %14.6f\\n', c2 );\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/tet_mesh/tet_mesh_test005.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7215646968583906}} {"text": "% RES = RCONV2(MTX1, MTX2, CTR)\n%\n% Convolution of two matrices, with boundaries handled via reflection\n% about the edge pixels. Result will be of size of LARGER matrix.\n% \n% The origin of the smaller matrix is assumed to be its center.\n% For even dimensions, the origin is determined by the CTR (optional) \n% argument:\n% CTR origin\n% 0 DIM/2 (default)\n% 1 (DIM/2)+1 \n\n% Eero Simoncelli, 6/96.\n\nfunction c = rconv2(a,b,ctr)\n\nif (exist('ctr') ~= 1)\n ctr = 0;\nend\n\nif (( size(a,1) >= size(b,1) ) & ( size(a,2) >= size(b,2) ))\n large = a; small = b;\nelseif (( size(a,1) <= size(b,1) ) & ( size(a,2) <= size(b,2) ))\n large = b; small = a;\nelse\n error('one arg must be larger than the other in both dimensions!');\nend\n\nly = size(large,1);\nlx = size(large,2);\nsy = size(small,1);\nsx = size(small,2);\n\n%% These values are one less than the index of the small mtx that falls on \n%% the border pixel of the large matrix when computing the first \n%% convolution response sample:\nsy2 = floor((sy+ctr-1)/2);\nsx2 = floor((sx+ctr-1)/2);\n\n% pad with reflected copies\nclarge = [ \n large(sy-sy2:-1:2,sx-sx2:-1:2), large(sy-sy2:-1:2,:), ...\n\tlarge(sy-sy2:-1:2,lx-1:-1:lx-sx2); ...\n large(:,sx-sx2:-1:2), large, large(:,lx-1:-1:lx-sx2); ...\n large(ly-1:-1:ly-sy2,sx-sx2:-1:2), ...\n large(ly-1:-1:ly-sy2,:), ...\n large(ly-1:-1:ly-sy2,lx-1:-1:lx-sx2) ];\n\nc = conv2(clarge,small,'valid');\n\n", "meta": {"author": "jbhuang0604", "repo": "SelfExSR", "sha": "8f6dd8c1d20cb7e8792a7177b4f6fd677633f598", "save_path": "github-repos/MATLAB/jbhuang0604-SelfExSR", "path": "github-repos/MATLAB/jbhuang0604-SelfExSR/SelfExSR-8f6dd8c1d20cb7e8792a7177b4f6fd677633f598/quant_eval/ifcvec_release/matlabPyrTools/rconv2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7215646968583905}} {"text": "function [u,v,un,vn]=CalculateVelocityFromVortex2D(s,xc,yc,x,y)\n\n%--------------------------------------------------------------------------\n%CalculateVelocityFromVortex2D\n%Version 1.00\n%Created by Stepen\n%Created 8 January 2011\n%--------------------------------------------------------------------------\n%CalculateVelocityFromVortex2D calculates the flow velocity influenced by\n%several given vortex flow at several given locations in 2D domain.\n%CalculateVelocityFromVortex2D assumes that the vortexs that influence the\n%flow are point vortexes.\n%--------------------------------------------------------------------------\n%Syntax:\n%[u,v,un,vn]=CalculateVelocityFromvortex2D(s,xc,yc,x,y)\n%Input argument:\n%- s (m x 1 num) specifies the strength of all point vortexes.\n%- xc (m x 1 num) specifies the x axis location of all point vortexes.\n%- yc (m x 1 num) specifies the y axis location of all point vortexes.\n%- x (p x q num) specifies the x axis location of the corresponding\n% velocity vector.\n%- y (p x q num) specifies the y axis location of the corresponding\n% velocity vector.\n%Output argument:\n%- u (m x n) specifies the horizontal velocity component at the\n% corresponding location.\n%- u (m x n) specifies the vertical velocity component at the corresponding\n% location.\n%- un (m x n num) specifies the normalized horizontal velocity component of\n% the corresponding location. un output was generated for plotting\n% purpose. Use this output instead of u for velocity quiver plotting.\n%- vn (m x n num) specifies the normalized vertical velocity component of\n% the corresponding location. vn output was generated for plotting\n% purpose. Use this output instead of v for velocity quiver plotting.\n%--------------------------------------------------------------------------\n\n%CodeStart-----------------------------------------------------------------\n%Checking input point vortexes\n s_size=size(s);\n xc_size=size(xc);\n yc_size=size(yc);\n if (s_size(2)~=1)||(xc_size(2)~=1)||(yc_size(2)~=1)\n error('Input point vortexs must be a i x 1 array!')\n end\n if (numel(s)~=numel(xc))||(numel(s)~=numel(yc))\n error('Input s, xc, and yc do not have the same size!')\n end\n vortexcount=numel(s);\n%Checking input location\n x_size=size(x);\n y_size=size(y);\n if (x_size(1)~=y_size(1))||(x_size(2)~=y_size(2))\n error('Input x and y do not have the same size!')\n end\n rowcount=x_size(1);\n colcount=x_size(2);\n%Preallocating array for speed\n u=zeros(rowcount,colcount);\n v=zeros(rowcount,colcount);\n un=zeros(rowcount,colcount);\n vn=zeros(rowcount,colcount);\n%Calculating influenced velocity\n for i=1:1:rowcount\n for j=1:1:colcount\n for k=1:1:vortexcount\n if (x(i,j)==xc(k))&&(y(i,j)==yc(k))\n u(i,j)=u(i,j);\n v(i,j)=v(i,j);\n else\n r=norm([(x(i,j)-xc(k)),(y(i,j)-yc(k))]);\n vtheta=-s(k)/(2*pi()*r);\n u(i,j)=u(i,j)+(vtheta*((y(i,j)-yc(k))/r));\n v(i,j)=v(i,j)+(vtheta*((xc(k)-x(i,j))/r));\n end\n end\n end\n end\n%Calculating normalized vector\n for i=1:1:rowcount\n for j=1:1:colcount\n V=norm([u(i,j),v(i,j)]);\n un(i,j)=u(i,j)/V;\n vn(i,j)=v(i,j)/V;\n end\n end\n%CodeEnd-------------------------------------------------------------------\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/32474-2d-potential-flow-simulator/CalculateVelocityFromVortex2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7215646961061774}} {"text": "function neg_log_p = neglogsigmoid(log_odds)\n% neg_log_p = NEGLOGSIGMOID(log_odds)\n% This is mathematically equivalent to -log(sigmoid(log_odds)), \n% but numerically better, when log_odds is large negative \n\nassert(nargin==1)\n\nneg_log_p = -log_odds;\ne = exp(-log_odds);\nf=find(eseuil,\n encore = 1 ;\n pair = [p;q] ;\n G = [ c -conj(s) ; s c ] ;\n V(:,pair) = V(:,pair)*G ;\n M(pair,:) = G' * M(pair,:) ;\n M(:,[Ip Iq]) \t= [ c*M(:,Ip)+s*M(:,Iq) -conj(s)*M(:,Ip)+c*M(:,Iq) ] ;\n end\n end\n end\nend\n\n%% Estimation of the mixing matrix and signal separation\nA\t= IW*V;\nS\t= V'*Y ;\n\nreturn ;\n\n", "meta": {"author": "danmcduff", "repo": "iphys-toolbox", "sha": "65deeb46aea80c04009fe304a6612e4ef1497f08", "save_path": "github-repos/MATLAB/danmcduff-iphys-toolbox", "path": "github-repos/MATLAB/danmcduff-iphys-toolbox/iphys-toolbox-65deeb46aea80c04009fe304a6612e4ef1497f08/tools/ica/jade.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.7214953697023914}} {"text": "function [nll,g,H,T] = LogisticLoss(w,X,y)\n% w(feature,1)\n% X(instance,feature)\n% y(instance,1)\n\n[n,p] = size(X);\n\nXw = X*w;\nyXw = y.*Xw;\n\nnll = sum(mylogsumexp([zeros(n,1) -yXw]));\n\nif nargout > 1\n if nargout > 2\n sig = 1./(1+exp(-yXw));\n g = -X.'*(y.*(1-sig));\n else\n %g = -X.'*(y./(1+exp(yXw)));\n g = -(X.'*(y./(1+exp(yXw))));\n end\nend\n\nif nargout > 2\n H = X.'*diag(sparse(sig.*(1-sig)))*X;\nend\n\nif nargout > 3\n T = zeros(p,p,p);\n for j1 = 1:p\n for j2 = 1:p\n for j3 = 1:p\n T(j1,j2,j3) = sum(y(:).^3.*X(:,j1).*X(:,j2).*X(:,j3).*sig.*(1-sig).*(1-2*sig));\n end\n end\n end\nend", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/minFunc_2012/logisticExample/LogisticLoss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763572, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.7214926343361311}} {"text": "function Qd = calculateQd(tau,alpha,h)\n%calculates Qd for noise simulation algorithm from paper DISCRETE SIMULATION OF POWER LAW NOISE\n%equation: Qd = h / (2*(2pi)^alpha * tau^(alpha-1))\n\nQd = h / (2*(2*pi)^alpha * tau^(alpha-1)); %calculate Qd", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/31319-stability-analyzer-53230a/Stability Analyzer 2.0/calculateQd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947086083139, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7214881217527446}} {"text": "function [data,data2,Isymbols,Qsymbols]=serial_to_parallel(N)\n%Bob Gess, June 2008 for EE 473\n%Extracted and modified from original code (QPSK_TX_IQ_RX) written by JC and posted on\n%Mathworks 12-23-2005.\n\n%This module generates the data and splits it into the I channel and Q\n%channel\n%N=1e3;\t\t % Number of data bits(bit rate)\nfs=40*2e3;\t\t % Sampling frequency\nFn=fs/2; % Nyquist frequency\nTs=1/fs;\t % Sampling time = 1/fs\nT=1/N;\t\t % Bit time\nrandn('state',0); % Keeps PRBS from changing on reruns\ntd=[0:Ts:(N*T)-Ts]';% Time vector(data)(transpose)\n%===================================================================\n% Input data\n%===================================================================\ndata=sign(randn(N,1))';%transpose\ndata1=ones(T/Ts,1)*data;\ndata2=data1(:);\n%length(data2)\n\n%display input data bits in command window\ndata_2=data2';\ndata_2=data_2 >0;\nx=0;\ntransmitted_data_bits=data_2(1:(fs+x)/N:end);\n\n%Serial to parallel (alternating)\ntiq = [0:Ts*2:(N*T)-Ts]';% Time vector for I and Q symbols(transpose)\n\nbs1=data(1:2:length(data));%odd\nsymbols=ones(T/Ts,1)*bs1;\nIsymbols=symbols(:);%I_waveform\n%LI=length(Isymbols)\n\nbs2=data(2:2:length(data));%even\nsymbols1=ones(T/Ts,1)*bs2;\nQsymbols=symbols1(:);%Q_waveform\n%LQ=length(Qsymbols)\n\n%=====================================================================\n%Plots\n%======================================================================\nfigure(1)\nsubplot(3,1,1)\nplot(td,data2)\naxis([0 20/N -2 2]);\ngrid on\nxlabel(' Time')\nylabel('Amplitude')\ntitle('Input Data')\n\nsubplot(3,1,2)\nplot(tiq,Isymbols)\naxis([0 20/N -2 2]);\ngrid on\nxlabel(' Time')\nylabel('Amplitude')\ntitle('I Channel(one bit/symbol(phase)) Data')\n\nsubplot(3,1,3)\nplot(tiq,Qsymbols)\naxis([0 20/N -2 2]);\ngrid on\nxlabel(' Time')\nylabel('Amplitude')\ntitle('Q Channel(one bit/symbol(phase)) Data')\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/20344-direct-sequence-spread-spectrum/serial_to_parallel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7214518798441436}} {"text": "function a = rutis2_inverse ( )\n\n%*****************************************************************************80\n%\n%% RUTIS2_INVERSE returns the inverse of the RUTIS2 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% 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 28.0, -22.0, -1.0, -1.0; ...\n -22.0, 28.0, -1.0, -1.0; ...\n -1.0, -1.0, 17.0, -8.0; ...\n -1.0, -1.0, -8.0, 17.0 ];\n\n a(1:4,1:4) = a(1:4,1:4) / 50.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/rutis2_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7213084566060127}} {"text": "%HOMTRANS Apply a homogeneous transformation\n%\n% P2 = HOMTRANS(T, P) applies the homogeneous transformation T to the points \n% stored columnwise in P.\n%\n% - If T is in SE(2) (3x3) and\n% - P is 2xN (2D points) they are considered Euclidean (R^2)\n% - P is 3xN (2D points) they are considered projective (P^2)\n% - If T is in SE(3) (4x4) and\n% - P is 3xN (3D points) they are considered Euclidean (R^3)\n% - P is 4xN (3D points) they are considered projective (P^3)\n%\n% P2 and P have the same number of rows, ie. if Euclidean points are given\n% then Euclidean points are returned, if projective points are given then\n% projective points are returned.\n%\n% TP = HOMTRANS(T, T1) applies homogeneous transformation T to the \n% homogeneous transformation T1, that is TP=T*T1. If T1 is a 3-dimensional \n% transformation then T is applied to each plane as defined by the first two \n% dimensions, ie. if T is NxN and T1 is NxNxM then the result is NxNxM.\n%\n% Notes::\n% - If T is a homogeneous transformation defining the pose of {B} with respect to {A},\n% then the points are defined with respect to frame {B} and are transformed to be\n% with respect to frame {A}.\n%\n% See also E2H, H2E, RTBPose.mtimes.\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 pt = homtrans(T, p)\n\n if numrows(p) == numrows(T)\n if ndims(p) == 3\n % homtrans(T1, T2)\n pt = [];\n for i=1:size(p,3)\n pt = cat(3, pt, T*p(:,:,i));\n end\n else\n % points are in projective coordinates\n pt = T * p;\n end\n elseif (numrows(T)-numrows(p)) == 1\n % points are in Euclidean coordinates, promote to homogeneous\n pt = h2e( T * e2h(p) );\n else\n error('SMTB:homtrans:badarg', 'matrices and point data do not conform')\n end\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/homtrans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.7213084487075709}} {"text": "function p4 = angle_half_2d ( p1, p2, p3 )\n\n%*****************************************************************************80\n%\n%% ANGLE_HALF_2D finds half an angle in 2D.\n%\n% Discussion:\n%\n% The original angle is defined by the sequence of points P1, P2 and P3.\n%\n% The point P4 is calculated so that:\n%\n% (P1,P2,P4) = (P1,P2,P3) / 2\n%\n% P1\n% /\n% / P4\n% / .\n% / .\n% P2--------->P3\n%\n% Thanks to Cesar Fraga Bobis for pointing out a typographical error in\n% a previous version of this routine.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real P1(2,1), P2(2,1), P3(2,1), points defining the angle.\n%\n% Input, real P4(2,1), a point defining the half angle.\n% The vector P4 - P2 will have unit norm.\n%\n p4(1:2,1) = 0.5 * ( ...\n ( p1(1:2,1) - p2(1:2,1) ) / sqrt ( sum ( ( p1(1:2,1) - p2(1:2,1) ).^2 ) ) ...\n + ( p3(1:2,1) - p2(1:2,1) ) / sqrt ( sum ( ( p3(1:2,1) - p2(1:2,1) ).^2 ) ) );\n\n p4(1:2,1) = p2(1:2,1) + p4(1:2,1) / sqrt ( sum ( ( p4(1:2,1) ).^2 ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/geometry/angle_half_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7213084381885594}} {"text": "function f = dtlz2a(x)\n\nalpha = 1;\n\n%% g function\nsum = 0;\nfor i = 3:8\nsum = sum + (x(:,i)-0.5)^2;\nend\ng = sum;\n\n%% cost functions\nf(:,1) = (1+g)*cos(((x(:,1)^alpha)*pi)/2)*cos(((x(:,2)^alpha)*pi)/2);\nf(:,2) = (1+g)*cos(((x(:,1)^alpha)*pi)/2)*sin(((x(:,2)^alpha)*pi)/2);\nf(:,3) = (1+g)*sin(((x(:,1)^alpha)*pi)/2);\nend\n", "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/dtlz2a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.959154281754899, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.7212960747244196}} {"text": "%% 2D Advection-Diffusion D2Q4\n% by Manuel Diaz\nclc; clear; %close all;\n\n%% Domain Grid\nL = 100; % Length\nH = 100; % Height\nn = 100; % Nodes in x\nm = 100; % Nodes in y\ndx = L/n; dy = H/m; dt = 1;\nx = 1:dx:L; y = 1:dy:H;\n\n%% Initial Condition\nf1 = zeros(m,n);\nf2 = zeros(m,n);\nf3 = zeros(m,n);\nf4 = zeros(m,n);\nfeq1 = zeros(m,n);\nfeq2 = zeros(m,n);\nfeq3 = zeros(m,n);\nfeq4 = zeros(m,n);\nrho = zeros(m,n); % initial value of the dependent variable rho = T(x,t)\n\n%% Constants\nu = 0.1;\nv = -0.2; % <- interesting result if we change to -v!\nck = dx/dt;\ncsq = (dx^2)/(dt^2);\nalpha = 0.25;\nomega = 1/(2*alpha/(dt*csq)+0.5);\nw = [1/4,1/4,1/4,1/4];\ncx = [ 1, -1, 0, 0];\ncy = [ 0, 0, 1, -1]; \nlink = [ 1, 2, 3, 4];\ntEnd = 400; % time steps\n\n%% Movie Parameters\ntPlot = 10; frames= tEnd/tPlot; count = 0;\nfigure(1)\ncolordef white %black\n\n%% Boundary Conditions\ntwall = 1; \n\n%% Main Loop\nfor cycle = 2:tEnd;\n % Collision process \n rho = f1 + f2 + f3 + f4;\n \n feq1 = 0.25 * rho *(1+2*u/ck);\n feq2 = 0.25 * rho *(1-2*u/ck);\n feq3 = 0.25 * rho *(1+2*v/ck);\n feq4 = 0.25 * rho *(1-2*v/ck);\n \n f1 = w(1) * rho;\n f2 = w(2) * rho;\n f3 = w(3) * rho;\n f4 = w(4) * rho;\n \n f1 = omega * feq1 + (1-omega) * f1;\n f2 = omega * feq2 + (1-omega) * f2;\n f3 = omega * feq3 + (1-omega) * f3;\n f4 = omega * feq4 + (1-omega) * f4;\n \n % Streaming process\n f1 = stream2d( f1 , [cy(1),cx(1)]);\n f2 = stream2d( f2 , [cy(2),cx(2)]);\n f3 = stream2d( f3 , [cy(3),cx(3)]);\n f4 = stream2d( f4 , [cy(4),cx(4)]);\n \n % Boundary conditions\n f1(:,1) = twall*w(1) + twall*w(2) - f2(:,1); %Dirichlet BC\n f3(:,1) = twall*w(3) + twall*w(4) - f4(:,1); %Dirichlet BC\n \n f1(m,:) = 0; %Dirichlet BC\n f2(m,:) = 0; %Dirichlet BC\n f3(m,:) = 0; %Dirichlet BC\n f4(m,:) = 0; %Dirichlet BC\n \n f1(:,n) = 0; %Dirichlet BC\n f2(:,n) = 0; %Dirichlet BC\n f3(:,n) = 0; %Dirichlet BC\n f4(:,n) = 0; %Dirichlet BC\n \n f1(1,:) = f1(2,:); %Neumann BC\n f2(1,:) = f2(2,:); %Neumann BC\n f3(1,:) = f3(2,:); %Neumann BC\n f4(1,:) = f4(2,:); %Neumann BC \n \n % Visualization\n if mod(cycle,tPlot) == 1\n count = count + 1;\n contourf(rho)\n colormap hot\n colorbar('location','southoutside')\n axis tight\n M(count) = getframe;\n end\n \n % Animated gif file\n if mod(cycle,tPlot) == 1\n F = getframe;\n if count == 1\n [im,map] = rgb2ind(F.cdata,256,'nodither');\n im(1,1,1,tEnd/tPlot) = 0;\n end\n im(:,:,1,count) = rgb2ind(F.cdata,map,'nodither');\n end\nend\n\n%% Make Movie\nmovie(M,1,10); % movie(M,n,fps)\n\n%% Export to Gif\nimwrite(im,map,'advec_diff_d2q4.gif','DelayTime',0,'LoopCount',3)", "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/LBM/advec_diff_d2q4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480248488136, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7212904205136536}} {"text": "%rate = mimo_iso_conv(nn,P,error,tx,rx,K) computes the converse bound on\n%the maximal channel coding rate over a quasi-static MIMO Rician fading\n%channel with isotropic inputs. \n%\n%The function takes the following inputs:\n%\n%nn: blocklength, scalar/vector;\n%P: total input power (linear scale), scalar;\n%error: block error probability, scalar;\n%tx: number of transmit antennas, scalar;\n%rx: number of receive antennas, scalar;\n%K: rician K factor, scalar; the default value is 0.\n\nfunction rate_c = mimo_iso_conv(nn,P,error,tx,rx,K)\nif (nargin < 6) || isempty(K)\n\tK = 0;\nend\nloop_h=round(1000/error);\n\nP=P/tx;\n\nrate_c=[];\n\nmin_tx_rx = min(tx,rx);\n\neig_vec=zeros( min_tx_rx, loop_h);\n\nfor ij = 1:loop_h\n h = (randn(tx,rx)+1i*randn(tx,rx))*sqrt(0.5/(K+1)) + sqrt(K/(K+1));\n %eigenvalues of H^{H}*Q*H, where Q is a scaled identity matrix P*I\n eig_vec(:,ij)= P* abs(svd( h)).^2;\nend\n\n%nn=[60:10:200 220:20:500 550:50:1000];\n\nfor n=nn\n %information density under P\n S_n = sum( n*log(1 + eig_vec)) + n*min_tx_rx - sum(ncx2rnd(2*n, 2*n ./ eig_vec).* eig_vec./ (1 + eig_vec))/2;\n \n S_n_sort=sort(S_n);\n\n tau = (error + 1/loop_h ): 1/loop_h : 2*error;\n \n gamma_n_array = S_n_sort(round(tau*loop_h));\n \n %lower-bounding beta_{error} using the standard inequality \n y_a = gamma_n_array/n - log(tau-error)/n;\n %optimizing over gamma\n y_min=min(y_a);\n \n rate =y_min./log(2);\n rate_c=[rate_c,rate];\nend\n\n\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/quasi-static/MIMO_ISO/mimo_iso_conv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938533, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7212904198716104}} {"text": "function s = rectangular_plate_analytical_solution (a, b, h, E, nu, q0)\n%\n% INPUT\n% a: length of the rectangular section\n% b: height of the rectangular section\n% h: thickness of the plate\n% E: Young modulus\n% nu: Poisson ratio\n% q0: distributed load\n%\n% OUTPUT\n% displ: maximum displacement\n\nx=a/2;\ny=b/2;\n%pi = %pi;\nD=E*h^3/(12*(1-nu^2));\nks = 16*q0*a^4*b^4/(pi^6*D);\nkm = 16*q0*a^4*b^4/(pi^4);\n\ns=0;\nmx=0;\nmy=0;\nn = 1;\nnMax = 1001;\nwhile n<=nMax\n m = 1;\n while m<=nMax\n den = (n^2*a^2 + m^2*b^2)^2;\n sinA = sin(m*pi*x/a);\n sinB = sin(n*pi*y/b);\n knm = sinA*sinB/(m*n*den);\n s = s + ks*knm;\n mx = mx + km*knm*((m/a)^2 + nu*(n/b)^2);\n my = my + km*knm*(nu*(m/a)^2 + (n/b)^2);\n m = m+2;\n end;\n n = n+2;\nend\n\nx=0;\ny=0;\nkmxy = -(1-nu)*16*q0*a^3*b^3/(pi^4);\nmxy = 0;\nn=1;\nwhile n<=nMax\n m = 1;\n while m<=nMax\n den = (n^2*a^2 + m^2*b^2)^2;\n cosA = cos(m*pi*x/a);\n cosB = cos(n*pi*y/b);\n mxy = mxy + kmxy*cosA*cosB/den;\n m = m+2;\n end;\n n = n+2;\nend\n\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/examples/elasticity/data_files/rectangular_plate_analytical_solution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.948154531885212, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.7212143532283309}} {"text": "function value = p24_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P24_F evaluates the integrand for problem 24.\n%\n% Dimension:\n%\n% DIM_NUM is arbitrary.\n%\n% Region:\n%\n% 0 <= X(1:DIM_NUM) <= 1\n%\n% Integral Parameters:\n%\n% C(1:DIM_NUM) defaults to 0.0.\n%\n% A typical, more difficult problem, has\n% C(I) = I**(1/3)\n% \n% Call P24_R8VEC to get or set C.\n%\n% Integrand:\n%\n% F(X) = product ( ( abs ( 4 * X(1:DIM_NUM) - 2 ) + C(1:DIM_NUM) ) \n% / ( 1 + C(1:DIM_NUM) ) \n% )\n%\n% Exact Integral:\n%\n% 1\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% Stephen Joe, Frances Kuo,\n% Remark on Algorithm 659:\n% Implementing Sobol's Quasirandom Seqence Generator,\n% ACM Transactions on Mathematical Software,\n% Volume 29, Number 1, March 2003, pages 49-57.\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 c = [];\n c = p24_r8vec ( 'G', 'C', dim_num, c );\n\n value(1:point_num) = 0.0;\n\n for point = 1 : point_num\n\n value(point) = prod ...\n ( ...\n ( abs ( 4.0 * x(1:dim_num,point) - 2.0 ) + c(1:dim_num)' ) ...\n ./ ( 1.0 + c(1:dim_num)' ) ...\n );\n end\n\n p24_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/p24_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7211798705225253}} {"text": "%% RATE OF CONVERGENCE OF PRIMAL-DUAL WEAK-GALERKIN for DIV-CURL SYSTEM\n%\n% This example is to show the rate of convergence on an L-shaped domain with a singular solution.\n%\n% See also DivCurl3PDWG\n%\n% Reference: A New Numerical Method for Div-Curl Systems with Low Regularity Assumptions\n% S. Cao, C. Wang, J. Wang, https://arxiv.org/abs/2101.03466\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nclear; close all;\n%%\nmaxIt = 4;\nN = zeros(maxIt,1);\nh = zeros(maxIt,1);\nerrL2UTotal = zeros(maxIt,1);\nerrqlambdaTotal = zeros(maxIt,1);\nerrSTotal = zeros(maxIt,1);\nerrL2QuTotal = zeros(maxIt,1); % \\|Q_h u - u \\|\n\n\n%% Generate an initial mesh \n[node,elem] = cubemesh([-1,1,-1,1,-1,1],1/2);\n% [node,elem] = delmesh(node,elem,'(x < 0 & y > 0) | (z<0.5)');\n\n% [node,elem] = delmesh(node,elem,'(x < 0 & y < 0) | (z<0) | (z>0.5)'); %\n% for gradient\n\n[node,elem] = delmesh(node,elem,'(x > 0 & y < 0) | (z<0) | (z>0.5)');\n% for curl\nbdFlag = setboundary3(node,elem,'Dirichlet');\n\n%% data\npde = DataDivCurlSingular4;\noption.inverseh = true;\n\n%% Finite Element Method \nfor k = 1:maxIt\n % solve the equation\n [soln,eqn,info] = DivCurl3PDWG(node,elem,bdFlag,pde,option);\n N(k) = size(elem,1);\n% h(k) = (36./N(k)).^(1/3);\n h(k) = 1/2^k;\n \n errL2UTotal(k) = eqn.errorU;\n errqlambdaTotal(k) = eqn.errorqlambda;\n errSTotal(k) = eqn.errorS;\n \n [errL2QuTotal(k), ~] = getL2error3vec(node,elem,soln.u,pde);\n% [errL2QuTotal(k), ~] = getL2error3(node,elem,pde.exactu, soln.u);\n \n \n fprintf('PDWG method with h: %3g \\n', h(k));\n fprintf('Number of Dof: %d \\n', sum(eqn.freeDof));\n fprintf('L2 error in u: %6g \\n', errL2UTotal(k));\n fprintf('L2 error in Qu-u_h: %6g \\n', errL2QuTotal(k));\n fprintf('L2 error in (q,lambda): %6g \\n', errqlambdaTotal(k));\n fprintf('L2 error in s: %6g \\n\\n\\n', errSTotal(k));\n \n % refine mesh\n if k < maxIt; [node,elem,bdFlag] = uniformrefine3(node,elem,bdFlag); end \nend\n\n%%\nvisualizationPDwgDivCurl;", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/PDWG/femratePDwgDivCurlLshape.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.721179617283567}} {"text": "function [ y, m, d, f ] = jed_to_ymdf_julian3 ( jed )\n\n%*****************************************************************************80\n%\n%% JED_TO_YMDF_JULIAN3 converts a JED to a Julian YMDF date.\n%\n% Discussion:\n%\n% The theory behind this routine is very clean. The Julian\n% calendar has cycles of 1 and 4 years, and we can analyze a date\n% by determining where it lies within these cycles.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 July 2012\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, real JED, the Julian Ephemeris Date.\n%\n% Output, integer Y, M, D, real F,\n% the YMDF date.\n%\n cycle_length = 1461;\n year_length = 365;\n\n jed_epoch = epoch_to_jed_julian ( );\n\n j = floor ( jed - jed_epoch );\n f1 = ( jed - jed_epoch ) - j;\n\n if ( f1 < 0.0 )\n f1 = f1 + 1.0;\n j = j - 1;\n end\n\n d0 = j;\n n4 = 0;\n\n while ( d0 <= 0 )\n d0 = d0 + cycle_length;\n n4 = n4 - 1;\n end\n\n n4 = n4 + floor ( d0 / cycle_length );\n d1 = i4_modp ( d0, cycle_length );\n n1 = floor ( d1 / year_length );\n d2 = i4_modp ( d1, year_length );\n\n if ( n1 == 4 )\n j1 = 366;\n y1 = 4 * n4 + n1;\n else\n j1 = d2 + 1;\n y1 = 4 * n4 + n1 + 1;\n end\n%\n% Any year before 1 AD must be moved one year further back, since\n% this calendar does not include a year 0.\n%\n y1 = y_astronomical_to_common ( y1 );\n\n [ y, m, d, f ] = yjf_to_ymdf_julian ( y1, j1, f1 );\n\n return\nend\n", "meta": {"author": "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/jed_to_ymdf_julian3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7210053420775694}} {"text": "function [ud,UD_up,UD_dist] = distort(up,dist)\n\n% DISTORT Distort projected point with radial distortion.\n% DISTORT(UP,DIST) computes the position in the image plane of the\n% distorted pixel corresponding to the projected pixel UP. DIST is the\n% vector of distortion parameters. Distortion is calculated with the\n% radial distortion model:\n%\n% UD = UP * (1 + k2*r^2 + k4*r^4 + k6*r^6 + ...)\n%\n% where r^2 = UP(1)^2 + UP(2)^2\n% and DIST = [k4 k4 k6 ...]\n%\n% [ud,UD_up,UD_dist] = DISTORT(...) returns Jacobians wrt UP and DIST.\n%\n% See also PINHOLE.\n%\n\n% FIXME: RMAX works not so nice\n% DISTORT(...,RMAX) accepts the maximum image radius to limit the effect\n% of distortion to the image plane. The image radius is one half of the\n% image diagonal. In case norm(UP) > RMAX then UD = RMAX/norm(UP)*UP. The\n% Jacobians are trivially computed just for argument consistency: UDup =\n% eye(2) and UDdist = zeros(2,length(dist)).\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nr2 = sum(up.^2);\n\nn = length(dist);\n\nif n == 0 % No distortion\n ud = up;\n\n if size(up,2) == 1\n UD_up = eye(2);\n UD_dist = zeros(2,0);\n else\n error('??? Jacobians not available for multiple points.')\n end\n \n \nelse % Distortion\n\n if size(up,2) == 1 % One only pixel\n\n nn = 1:n; % orders vector\n r2n = r2.^nn; % powers vector\n ratio = 1 + r2n*dist; % distortion ratio\n \n ud = ratio*up;\n\n if nargout > 1 % jacobians\n\n dnn = 2:2:2*n;\n dr2n = r2.^(0:n-1);\n dratio = (dnn.*dr2n)*dist;\n\n UD_up = ratio*eye(2) + dratio*(up*up');\n\n UD_dist = kron(up,r2n);\n end\n \n else % vectorized operation for multiple pixels.\n\n ratio = ones(size(r2));\n for i=1:n\n ratio = ratio + dist(i)*r2.^i;\n end\n\n ud = up.*[ratio;ratio];\n\n if nargout > 1 % jacobians\n\n error('??? Jacobians not available for multiple points.')\n\n end\n end\nend\n\n\n\nreturn\n\n%% Build jacobians up to order 3\n% For higher orders:\n% 1/ add k8,k10,k(2n)... to syms line below for an order n.\n% 2/ add k8,k10,k(2n)... to vector dist below for an order n.\n% 3/ Execute this cell (Apple+return keys)\n% 4/ Copy the results in UDup and UDdist above, caring for the matrices'\n% opening and closing brackets (do not forget them).\n\nsyms u1 u2 k2 k4 k6 k8 real\nup = [u1;u2];\ndist = [k2;k4;k6;k8];\nud = distort(up,dist);\n\nUDup = simple(jacobian(ud,up))\nUDdist = simple(jacobian(ud,dist))\n\n%% test\n\n[ud, UD_up, UD_dist] = distort(up,dist);\n\nsimplify(UD_up - jacobian(ud,up))\nsimplify(UD_dist - jacobian(ud,dist))\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/distort.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7210053401301474}} {"text": "function invT = TransInv(T)\n% *** CHAPTER 3: RIGID-BODY MOTIONS ***\n% Takes a transformation matrix T.\n% Returns its inverse. \n% Uses the structure of transformation matrices to avoid taking a matrix\n% inverse, for efficiency.\n% Example Input:\n% \n% clear; clc;\n% T = [[1, 0, 0, 0]; [0, 0, -1, 0]; [0, 1, 0, 3]; [0, 0, 0, 1]];\n% invT = TransInv(T)\n% \n% Ouput:\n% invT =\n% 1 0 0 0\n% 0 0 1 -3\n% 0 -1 0 0\n% 0 0 0 1\n\n[R, p] = TransToRp(T);\ninvT = [R', -R' * p; 0, 0, 0, 1];\nend", "meta": {"author": "ShuoYangRobotics", "repo": "QuadrupedSim", "sha": "8427715395b63bddb77329e66f7484e529998445", "save_path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim", "path": "github-repos/MATLAB/ShuoYangRobotics-QuadrupedSim/QuadrupedSim-8427715395b63bddb77329e66f7484e529998445/mr/TransInv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7210053376809971}} {"text": "function Pb=parbound(P,Ps)\n\n% function Pb=parbound(P,Ps)\n% ------------------------------------------------------------------------\n% Maps the values in the vector P to Pb according to upper and lower limits\n% set in the input structure Ps. \n%\n% Ps.ub -> Upper bound\n% Ps.lb -> Lower bound\n% Ps.c -> Centre of the output interval (i.e. initial parameter)\n% Ps.f -> Scale factor such that at for the input range\n% [-f*(ub-lb),f*(ub-lb)] the width of the output range is Ps.t*(ub-lb)\n% Ps.t -> Factor (0-1) of the output range width in relation to the intput\n% range width \n%\n% \n% %% EXAMPLE\n% Ps.f=2; \n% Ps.t=0.9;\n% Ps.ub=10;\n% Ps.lb=0;\n% Ps.c=7;\n% \n% w=Ps.ub-Ps.lb;\n% P=linspace(Ps.c-Ps.f*w,Ps.c+Ps.f*w,500);\n% Pb=parbound(P,Ps);\n% hf1=cFigure; hold on; grid on;\n% xlabel('P','FontSize'); ylabel('Pb','FontSize'); \n% hf=plot(P,Pb,'b-','LineWidth',5);\n% hf=plot(P,(Ps.ub-(0.5*(1-Ps.t)*w))*ones(size(P)),'g-','LineWidth',5);\n% hf=plot(P,(Ps.lb+(0.5*(1-Ps.t)*w))*ones(size(P)),'g-','LineWidth',5);\n% hf=plot(P,Ps.ub*ones(size(P)),'r-','LineWidth',5);\n% hf=plot(P,Ps.lb*ones(size(P)),'r-','LineWidth',5);\n% axis equal; axis tight; ylim([Ps.lb Ps.ub]);\n% \n%\n%\n% Kevin Mattheus Moerman\n% kevinmoerman@hotmail.com\n% 06/02/2012\n%------------------------------------------------------------------------\n\nw=abs(Ps.ub-Ps.lb); %Interval width\nb=Ps.f*w; %Point at which the output interval width equals t*w\na=tan(Ps.t*0.5*pi);\nx=(P-Ps.c)./(b./a);\nPb=(w.*(0.5+(atan(x)./pi)))+Ps.lb;\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/parbound.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.8031737869342624, "lm_q1q2_score": 0.7210053360680605}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Inverse Short-Time Fourier Transform %\n% with MATLAB Implementation %\n% %\n% Author: M.Sc. Eng. Hristo Zhivomirov 12/26/13 %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [x, t] = istft(stft, h, nfft, fs)\n\n% function: [x, t] = istft(stft, h, nfft, fs)\n% stft - STFT matrix (only unique points, time across columns, freq across rows)\n% h - hop size\n% nfft - number of FFT points\n% fs - sampling frequency, Hz\n% x - signal in the time domain\n% t - time vector, s\n\n% estimate the length of the signal\ncoln = size(stft, 2);\nxlen = nfft + (coln-1)*h;\nx = zeros(1, xlen);\n\n% form a periodic hamming window\nwin = hamming(nfft, 'periodic');\n\n% perform IFFT and weighted-OLA\nif rem(nfft, 2) % odd nfft excludes Nyquist point\n for b = 0:h:(h*(coln-1))\n % extract FFT points\n X = stft(:, 1 + b/h);\n X = [X; conj(X(end:-1:2))];\n \n % IFFT\n xprim = real(ifft(X));\n \n % weighted-OLA\n x((b+1):(b+nfft)) = x((b+1):(b+nfft)) + (xprim.*win)';\n end\nelse % even nfft includes Nyquist point\n for b = 0:h:(h*(coln-1))\n % extract FFT points\n X = stft(:, 1+b/h);\n X = [X; conj(X(end-1:-1:2))];\n \n % IFFT\n xprim = real(ifft(X));\n \n % weighted-OLA\n x((b+1):(b+nfft)) = x((b+1):(b+nfft)) + (xprim.*win)';\n end\nend\n\nW0 = sum(win.^2); % find W0\nx = x.*h/W0; % scale the weighted-OLA\n\n% calculate the time vector\nactxlen = length(x); % find actual length of the signal\nt = (0:actxlen-1)/fs; % generate time vector\n\nend", "meta": {"author": "dynamicslab", "repo": "databook_matlab", "sha": "d390d39d18489a4804ee87a143ae8db8a1f3010b", "save_path": "github-repos/MATLAB/dynamicslab-databook_matlab", "path": "github-repos/MATLAB/dynamicslab-databook_matlab/databook_matlab-d390d39d18489a4804ee87a143ae8db8a1f3010b/UTILS/istft/istft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7210053292223386}} {"text": "% FIT_CUBIC_BEZIER Fit a cubic bezier spline (G1 continuous) to an ordered list\n% of input points in any dimension, according to \"An algorithm for automatically\n% fitting digitized curves\" [Schneider 1990].\n% \n% Inputs:\n% d #d by dim list of points along a curve to be fit with a cubic bezier\n% spline (should probably be roughly uniformly spaced). If d(0)==d(end),\n% then will treat as a closed curve.\n% error maximum squared distance allowed\n% Output:\n% cubics #cubics list of 4 by dim lists of cubic control points\n%\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_gptoolbox/mex/fit_cubic_bezier.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.720997481719791}} {"text": "function R = euler2rotMat(phi, theta, psi)\n R(1,1,:) = cos(psi).*cos(theta);\n R(1,2,:) = -sin(psi).*cos(phi) + cos(psi).*sin(theta).*sin(phi);\n R(1,3,:) = sin(psi).*sin(phi) + cos(psi).*sin(theta).*cos(phi);\n \n R(2,1,:) = sin(psi).*cos(theta);\n R(2,2,:) = cos(psi).*cos(phi) + sin(psi).*sin(theta).*sin(phi);\n R(2,3,:) = -cos(psi).*sin(phi) + sin(psi).*sin(theta).*cos(phi);\n \n R(3,1,:) = -sin(theta);\n R(3,2,:) = cos(theta).*sin(phi);\n R(3,3,:) = cos(theta).*cos(phi);\nend\n\n", "meta": {"author": "xioTechnologies", "repo": "Gait-Tracking-With-x-IMU", "sha": "040966bd249bb842531e495eb78e1133820c4947", "save_path": "github-repos/MATLAB/xioTechnologies-Gait-Tracking-With-x-IMU", "path": "github-repos/MATLAB/xioTechnologies-Gait-Tracking-With-x-IMU/Gait-Tracking-With-x-IMU-040966bd249bb842531e495eb78e1133820c4947/Gait Tracking With x-IMU/Quaternions/euler2rotMat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985936, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7209212030652468}} {"text": "function zi = lagrange_interp_nd_value ( m, n_1d, a, b, nd, zd, ni, xi )\n\n%*****************************************************************************80\n%\n%% LAGRANGE_INTERP_ND_VALUE evaluates an ND Lagrange interpolant.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 September 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N_1D(M), the order of the 1D rule to be used\n% in each dimension.\n%\n% Input, real A(M), B(M), the lower and upper interval endpoints in \n% each dimension.\n%\n% Input, integer ND, the number of points in the product grid.\n%\n% Input, real ZD(ND), the function evaluated at the points XD.\n%\n% Input, integer NI, the number of points at which the interpolant\n% is to be evaluated.\n%\n% Input, real XI(M,NI), the points at which the interpolant is to be\n% evaluated.\n%\n% Output, real ZI(NI), the interpolant evaluated at the points XI.\n%\n zi = zeros(ni,1);\n\n for j = 1 : ni\n\n w = ones ( nd, 1 );\n\n for i = 1 : m\n n = n_1d(i);\n x_1d(1:n) = cc_compute_points ( n );\n x_1d(1:n) = 0.5 * ( ( 1.0 - x_1d(1:n) ) * a(i) ...\n + ( 1.0 + x_1d(1:n) ) * b(i) );\n value = lagrange_basis_1d ( n, x_1d, 1, xi(i,j) );\n w = r8vec_direct_product2 ( i, n, value, m, nd, w );\n end\n\n zi(j) = zd' * 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/lagrange_interp_nd/lagrange_interp_nd_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7208790079185029}} {"text": "function s = DotXBLAS(x,y)\n%DOTXBLAS Dot product 'as if' computed in 2-fold precision\n%\n% res = DotXBLAS(x,y)\n%\n%On return, res approximates x'*y with accuracy as if computed \n% in 2-fold precision.\n%\n%Implements algorithm BLAS_ddot_x from\n% X. Li, J. Demmel, D. Bailey, G. Henry, Y. Hida, J. Iskandar, \n% W. Kahan, S. Kang, {S.}, A. Kapur, M. Martin, B. Thompson, {B.},\n% T. Tung, {T.}, D. Yoo: Design, Implementation and Testing of \n% Extended and Mixed Precision BLAS, ACM Trans. Math. Software, \n% 2(28), p. 152-205, 2002.\n%Requires 37n flops.\n%\n%Reference implementation! Slow due to interpretation!\n%\n\n% written 03/03/07 S.M. Rump\n% modified 05/09/09 S.M. Rump rounding to nearest, complex input\n%\n\n if ( ~isreal(x) ) | ( ~isreal(y) )\n error('DotXBLAS for real input only')\n end\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 s = 0;\n t = 0;\n for i=1:length(x)\n [h,r] = TwoProduct(x(i),y(i));\n [s1,s2] = TwoSum(s,h);\n [t1,t2] = TwoSum(t,r);\n s2 = s2 + t1;\n [t1,s2] = FastTwoSum(s1,s2);\n t2 = t2 + s2;\n [s,t] = FastTwoSum(t1,t2);\n end\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/DotXBLAS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7208790042619895}} {"text": "function [phi, lam, h, phiC] = cart2geod(X, Y, Z)\n\n% SYNTAX:\n% [phi, lam, h, phiC] = cart2geod(X, Y, Z);\n% [phi, lam, h, phiC] = cart2geod(xyz);\n%\n% INPUT:\n% X = X axis cartesian coordinate\n% Y = Y axis cartesian coordinate\n% Z = Z axis cartesian coordinate\n%\n% OUTPUT:\n% phi = latitude\n% lam = longitude\n% h = ellipsoidal height\n% phiC = geocentric latitude\n%\n% DESCRIPTION:\n% Conversion from cartesian coordinates to geodetic 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:\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%global a_GPS e_GPS\n\nif nargin == 1\n Z = X(:, 3);\n Y = X(:, 2);\n X = X(:, 1);\nend\n\na = GPS_SS.ELL_A;\ne = GPS_SS.ELL_E;\n\n%radius computation\nr = sqrt(X.^2 + Y.^2 + Z.^2);\n\n%longitude\nlam = atan2(Y,X);\n\n%geocentric latitude\nphiC = atan(Z./sqrt(X.^2 + Y.^2));\n\n%coordinate transformation\npsi = atan(tan(phiC)/sqrt(1-e^2));\n\nphi = atan((r.*sin(phiC) + e^2*a/sqrt(1-e^2) * (sin(psi)).^3) ./ ...\n \t\t\t(r.*cos(phiC) - e^2*a * (cos(psi)).^3));\n\nN = a ./ sqrt(1 - e^2 * sin(phi).^2);\n\n%height\nh = r .* cos(phiC)./cos(phi) - 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/geo/cart2geod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7208789969781297}} {"text": "function S = oblateSurfaceArea(elli, varargin)\n%OBLATESURFACEAREA Approximated surface area of an oblate ellipsoid\n%\n% S = oblateSurfaceArea(R1,R2)\n%\n% Example\n% oblateSurfaceArea\n%\n% See also\n% geom3d, ellipsoidSurfaceArea, prolateSurfaceArea\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2015-07-03, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2015 INRA - Cepia Software Platform.\n\n%% Parse input argument\n\nif size(elli, 2) == 7\n R1 = elli(:, 4);\n R2 = elli(:, 5);\n \nelseif size(elli, 2) == 1 && ~isempty(varargin)\n R1 = elli(:, 1);\n R2 = varargin{1};\nend\n\nassert(R1 < R2, 'First radius must be smaller than second radius'); \n\n% surface theorique d'un ellipsoide oblate \n% cf http://fr.wikipedia.org/wiki/Ellipso%C3%AFde_de_r%C3%A9volution\ne = sqrt(R2.^2 - R1.^2) ./ R2;\nS = 2 * pi * R2.^2 + pi * R1.^2 * log((1 + e) ./ (1 - e)) ./ e;\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom3d/oblateSurfaceArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7208581332792242}} {"text": "function [T, Y]=FOChuaM(parameters, orders, TSim, Y0)\n%\n% Numerical Solution of the Fractional-Order Chua's System\n% with piecewise linear nonlinearity defined by a memristor.\n%\n% D^q1 x(t) = alpha(y(t) - x(t) + epsilon x(t) - W(w)x(t)) \n% D^q2 y(t) = x(t) - y(t) + z(t)\n% D^q3 z(t) = -beta y(t) - gamma z(t)\n% D^q4 w(t) = x(t)\n% where W(x) is defined as W_w(a, b, w);\n%\n% function [T, Y] = FOChuaM(parameters, orders, TSim, Y0)\n%\n% Input: parameters - model parameters [alpha, beta, gamma, epsilon, a, b]\n% orders - derivatives orders [q1, q2, q3, q4]\n% TSim - simulation time (0 - TSim) in sec\n% Y0 - initial conditions [Y0(1), Y0(2), Y0(3), Y0(4)]\n%\n% Output: T - simulation time (0 : Tstep : TSim)\n% Y - solution of the system (x=Y(1), y=Y(2), z=Y(3), w=Y(4))\n%\n% Author: (c) Ivo Petras (ivo.petras@tuke.sk), 2010.\n%\n\n% time step:\nh=0.005; \n% number of calculated mesh points:\nn=round(TSim/h);\n%orders of derivatives, respectively:\nq1=orders(1); q2=orders(2); q3=orders(3); q4=orders(4);\n% constants of Chua's system:\nalpha=parameters(1); beta=parameters(2); gamma=parameters(3);\nepsilon=parameters(4); a=parameters(5); b=parameters(6);\n% binomial coefficients calculation:\ncp1=1; cp2=1; cp3=1; cp4=1;\nfor j=1:n\n c1(j)=(1-(1+q1)/j)*cp1;\n c2(j)=(1-(1+q2)/j)*cp2;\n c3(j)=(1-(1+q3)/j)*cp3;\n c4(j)=(1-(1+q4)/j)*cp4;\n cp1=c1(j); cp2=c2(j); \n cp3=c3(j); cp4=c4(j);\nend\n% initial conditions setting:\nx(1)=Y0(1); y(1)=Y0(2); z(1)=Y0(3); w(1)=Y0(4);\n% calculation of phase portraits /numerical solution/:\nfor i=2:n\n x(i)=(alpha*(y(i-1)-x(i-1)+epsilon*x(i-1)-W_w(a,b,w(i-1))*x(i-1)))*h^q1 - memo(x, c1, i);\n y(i)=(x(i)-y(i-1)+z(i-1))*h^q2 - memo(y, c2, i);\n z(i)=(-beta*y(i)-gamma*z(i-1))*h^q3 - memo(z, c3, i);\n w(i)=(x(i))*h^q4 - memo(w, c4, i);\nend\nfor j=1:n\n Y(j,1)=x(j);\n Y(j,2)=y(j);\n Y(j,3)=z(j);\n Y(j,4)=w(j);\nend\nT=h:h:TSim;\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/27336-fractional-order-chaotic-systems/FOChuaM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989810230102, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7208581310842606}} {"text": "function [param]=pp2chp(input)\n% [param]=pp2chp(input)\n% LQ controller for 2nd order processes.\n% This function computes parameters of the controller (r0, r1, q0, q1, p0, p1).\n% The dynamic behavoiour of the closed-loop is defined by LQ criterion\n% Output of the controller is calculated follows:\n%\n% r0 + r1*z^-1 q0 + q1*z^-1 \n% U(z^-1) = -------------- * W(z^-1) - -------------- * Y(z^-1)\n% p0 + p1*z^-1 p0 + p1*z^-1\n%\n% Transfer function of the controlled system is:\n%\n% b1*z^-1 + b2*z^-2\n% Gs(z^-1) = -----------------------\n% 1 + a1*z^-1 + a2*z^-2\n%\n% Input: \n% input(1:4) ... [a1 b1 a2 b2]\n% input(5) ... type of reference signal (1-step, 2-ramp, 3-sin)\n% input(6) ... frequency [Hz] (used if reference signal is sin wave)\n% input(7) ... sample time (used if reference signal is sin wave)\n% input(8) ... penalisation of u (constant fi in LQ criterion)\n% Output: param ... controller parameters [r0; r1; q0; q1; p0; p1];\n\na1 = input(1);\nb1 = input(2);\na2 = input(3);\nb2 = input(4);\nrs_type = input(5);\nrs_freq = input(6);\nT0 = input(7);\nfi = input(8);\n\n% LQ: AP+BQ = D where D determined by spectral factorization\n% A(z^-1)*fi*A(z) + B(Z^-1)*B(z) = D(z^-1)*delta*D(z)\n% M(z^-1)*M(z) = D(z^-1)*delta*D(z)\nm0 = fi*(1+a1^2+a2^2) + b1^2 + b2^2;\nm1 = fi*a1*(1+a2) + b1*b2;\nm2 = fi*a2;\n\nla = m0/2 - m2 + sqrt( (m0/2+m2)^2 - m1^2 );\ndelta = (la + sqrt(la^2-4*m2^2)) / 2;\nd2 = m2 / delta;\nd1 = m1 / (delta+m2);\nd0 = 1;\nd3 = 0;\n\n% FBFW controller: Y=BR/(AP+BQ)*W\n% conditions: 1) AP+BQ=D\n% 2) BR+FS=D where W=H/F and S is any polynomial\n% 1st condition:\n% A = 1 + a1*z^-1 + a2*z^-2 B = b1*z^-1 + b2*z^-2\n% P = p0 + p1*z^-1 Q = q0 + q1*z^-1\n% system of linear equations:\n% [ 1 0 0 0] [p0] [d0]\n% [a1 1 b1 0] [p1] [d1]\n% [a2 a1 b2 b1] * [q0] = [d2]\n% [ 0 a2 0 b2] [q1] [d3]\np0 = d0;\np1 = (d0*b2^2*a1-d0*b2*b1*a2-b2^2*d1+b1*b2*d2-b1^2*d3)/(-b2^2+a1*b1*b2-a2*b1^2);\nq0 = -(d0*a1^2*b2-d0*a1*b1*a2-d0*a2*b2-d1*a1*b2+d1*b1*a2+b2*d2-b1*d3)/(-b2^2+a1*b1*b2-a2*b1^2);\nq1 = -(d0*a2*a1*b2-d0*a2^2*b1-a2*b2*d1+b1*a2*d2+d3*b2-d3*b1*a1)/(-b2^2+a1*b1*b2-a2*b1^2);\n\n% 2nd condition:\nswitch (rs_type)\ncase 1, %step:\n % B = b1*z^-1 + b2*z^-2 F = 1 - z^-1\n % R = r0 S = s0 + s1*z^-1 + s2*z^-2\n % [ 0 1 0 0] [r0] [d0]\n % [b1 -1 1 0] [s0] [d1]\n % [b2 0 -1 1] * [s1] = [d2]\n % [ 0 0 0 -1] [s2] [d3]\n r0 = (d0+d1+d2+d3)/(b1+b2);\n r1 = 0;\ncase 2, %ramp\n % B = b1*z^-1 + b2*z^-2 F = 1 - 2*z^-1 + z^-2\n % R = r0 + r1*z^-1 S = s0 + s1*z^-1\n % [ 0 0 1 0] [r0] [d0]\n % [b1 0 -2 1] [r1] [d1]\n % [b2 b1 1 -2] * [s0] = [d2]\n % [ 0 b2 0 1] [s1] [d3]\n r0 = (2*d0*b1+3*d0*b2+d1*b1+2*d1*b2+b2*d2-b1*d3)/(b1+b2)^2;\n r1 = -(d0*b1+2*d0*b2+d1*b2-b1*d2-2*b1*d3-d3*b2)/(b1+b2)^2;\ncase 3, %sin(om*t/T0)\n om = 2*pi*rs_freq*T0;\n % B = b1*z^-1 + b2*z^-2 F = 1 - 2*cos(om)*z^-1 + z^-2\n % R = r0 + r1*z^-1 S = s0 + s1*z^-1\n % [ 0 0 1 0] [r0] [d0]\n % [b1 0 -2*cos(om) 1] [r1] [d1]\n % [b2 b1 1 -2*cos(om)] * [s0] = [d2]\n % [ 0 b2 0 1] [s1] [d3]\n r0 = (2*d0*b1*cos(om)+2*d0*b2*cos(2*om)+d0*b2+d1*b1+2*d1*b2*cos(om)+b2*d2-b1*d3)/(b1^2+2*b1*b2*cos(om)+b2^2);\n r1 = (-d0*b1-2*d0*b2*cos(om)-b2*d1+b1*d2+2*d3*b1*cos(om)+d3*b2)/(b1^2+2*b1*b2*cos(om)+b2^2);\nend;\n\nparam=[r0; r1; q0; q1; p0; p1];\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/8381-stcsl-standard-version/pp2lq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7208393594042647}} {"text": "function D = gsp_distanz(X, Y, P)\n%GSP_DISTANZ calculates the distances between all vectors in X and Y\n% Usage: D = gsp_distanz(X, Y);\n%\n% Input parameters:\n% X : matrix with col vectors\n% Y : matrix with col vectors (default == X)\n% P : distance matrix (default Identity)\n% Output parameters:\n% D : distance matrix, not squared\n%\n% This code computes the following\n%\n% .. D = ( (X-Y)^T P (X-Y) )^(0.5)\n%\n% .. math:: D = \\sqrt{(X-Y)^T P (X-Y)}\n%\n% for all vectors in X an Y!\n% \n% This code is not optimized for memory, but for speed because it uses no\n% loops.\n%\n\n% Testing: test_gsp_distanz\n\n\n\n\n% Handle Input parameters\nif nargin<1, error('Not enought inputs parameters!'); end\nif nargin<2, Y=X; end\n\n% Get the size\n[rx, cx] = size(X);\n[ry, cy] = size(Y);\n\n% Verify the size\nif rx~=ry, error('The sizes of x and y do not fit!'), end\n\nif nargin < 3 \n xx = sum(X.*X,1); % ||x||^2\n yy = sum(Y.*Y,1); % ||y||^2 \n xy = X'*Y; % \n % \\|x-y\\|^2 = ||x||^2 +||y||^2 - 2 \n D = abs(repmat(xx',[1 cy]) + repmat(yy,[cx 1]) - 2*xy);\nelse\n \n [rp,rp2] = size(P);\n if rx~=rp, error('The sizes of x and P do not fit!'), end\n if rp2~=rp, error('P must be square!'), end\n \n xx = sum(X .* (P* X),1 ); % x^T P x\n yy = sum(Y .* (P* Y),1 ); % y^T P y \n xy = X'*(P*Y); % x^T P y\n yx = Y'*(P*X); % x^T P y\n\n D = abs(repmat(xx',[1 cy]) + repmat(yy,[cx 1]) - xy-yx);\nend\n\nif sum(D(:)<0)\n warning('gsp_distanz: P is not semipositive or x is not real!')\nend\n \n% Take the square root\nD = sqrt(D);\n\nif nargin < 2 % if Y == X\n % The diagonal has to be zero!\n D(1:cx+1:end) = 0;\nend\n\n\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/utils/gsp_distanz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7208393562834013}} {"text": "function [alt, lat] = geodet1 (rmag, dec)\n\n% geodetic latitude and altitude\n\n% series solution\n\n% input\n\n% rmag = geocentric radius (kilometers)\n% dec = geocentric declination (radians)\n% (+north, -south; -pi/2 <= dec <= +pi/2)\n\n% output\n\n% alt = geodetic altitude (kilometers)\n% lat = geodetic latitude (radians)\n% (+north, -south; -pi/2 <= lat <= +pi/2)\n\n% global constants\n\n% req = equatorial radius (kilometers)\n% flat = flattening factor (non-dimensional)\n\n% reference: NASA TN D-7522\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal req flat\n\nn = req / rmag;\no = flat * flat;\n \na = 2 * dec;\np = sin(a);\nq = cos(a);\n \na = 4 * dec;\nr = sin(a);\ns = cos(a);\n \n% geodetic latitude (radians)\n\nlat = dec + flat * n * p + o * n * r * (n - 0.25);\n \n% geodetic altitude (kilometers)\n\nalt = rmag + req * (flat * 0.5 * (1.0 - q) + o * (0.25 * n - 0.0625) * (1.0 - s) - 1.0);\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/geodet1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377284730286, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.7208324295622569}} {"text": "% GAMMA_LOGPDF - The log pdf of a Gamma distribution.\n%\n% Computes the logarithm of the Gamma probability density function\n% G(ALPHA|A,B), where ALPHA is the random variable, A is the shape and B is\n% the inverse scale (note the difference to MATLAB's built-in functions).\n%\n% The function is called as\n%\n% L = GAMMA_LOGPDF(ALPHA, A, B)\n% L = GAMMA_LOGPDF(ALPHA, A, B, LOG_ALPHA)\n%\n% where LOG_ALPHA is LOG(ALPHA). Letting the user to evaluate this logarithm\n% allows greater flexibility (e.g., for variational Bayesian cost function\n% one can give the expectation of the logarithm). However, A and B are\n% assumed to be fixed parameters in order to keep the function simple.\n\n% Last modified 2010-06-07\n% Copyright (c) Jaakko Luttinen\n\nfunction [lp, dlp] = gamma_logpdf(alpha, a, b, log_alpha)\n\nif nargin < 4\n log_alpha = log(alpha);\n% $$$ if nargin == 4\n% $$$ error(['Check the order of your input variables - the function has been ' ...\n% $$$ 'changed!'])\n% $$$ end\n% $$$ else\n% $$$ error('Improper number of inputs')\nend\n\nlp = (a-1).*log_alpha - b.*alpha - gammaln(a) + a.*log(b);\n\nif nargout >= 2\n inv_alpha = 1./alpha;\n dlp = (a-1).*inv_alpha - b;\nend\n\n%lp(alpha<=0) = -inf;\n%dlp(alpha<=0) = nan;", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/distributions/gamma_logpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.7799929053683039, "lm_q1q2_score": 0.7208240696559939}} {"text": "function quadrule_test28 ( )\n\n%*****************************************************************************80\n%\n%% TEST28 tests LEGENDRE_SET_X0_01 and SUM_SUB.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 19 October 2009\n%\n% Author:\n%\n% John Burkardt\n%\n order_max = 8;\n\n nfunc = func_set ( 'COUNT', 'DUMMY' );\n\n a = 0.0;\n b = 1.0;\n\n nsub = 1;\n\n xlo = 0.0;\n xhi = 1.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST28\\n' );\n fprintf ( 1, ' LEGENDRE_SET_X0_01 sets up Gauss-Legendre quadrature\\n' );\n fprintf ( 1, ' for integrating F(X) over [0,1];\\n' );\n fprintf ( 1, ' SUM_SUB carries it out.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The integration interval is [%f, %f]\\n', a, b );\n fprintf ( 1, ' Number of subintervals is %d\\n', nsub );\n fprintf ( 1, ' Quadrature order will vary.\\n' );\n fprintf ( 1, ' Integrand will vary.\\n' );\n fprintf ( 1, '\\n' );\n\n for ilo = 1 : 5 : nfunc\n\n ihi = min ( ilo + 4, nfunc );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ' );\n for i = ilo : ihi\n fprintf ( '%14s', fname(i) );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, '\\n' );\n\n for norder = 1 : order_max\n\n fprintf ( 1, ' %2d', norder );\n\n for i = ilo : ihi\n\n func_set ( 'SET', i );\n\n [ xtab, weight ] = legendre_set_x0_01 ( norder );\n\n result(i) = sum_sub ( @func, a, b, nsub, norder, xlo, xhi, ...\n xtab, weight );\n\n fprintf ( 1, ' %12f', result(i) );\n\n end\n\n fprintf ( 1, '\\n' );\n\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/quadrule/quadrule_test28.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.720703044142763}} {"text": "% VL_PEGASOS PEGASOS linear SVM solver\n% W = VL_PEGASOS(X, Y, LAMBDA) learns a linear SVM W given training\n% vectors X, their labels Y, and the regularization parameter LAMBDA\n% using the PEGASOS [1] solver. The algorithm finds a minimizer W of\n% the objective function\n%\n% LAMBDA/2 |W|^2 + 1/N SUM_i LOSS(W, X(:,i), Y(i))\n%\n% where LOSS(W,X,Y) = MAX(0, 1 - Y W'X) is the hinge loss and N is\n% the number of training vectors in X.\n%\n% ALGORITHM. PEGASOS is an implementation of stochastic subgradient\n% descent. At each iteration a data point is selected at random, the\n% subgradient of the cost function relative to that data point is\n% computed, and a step is taken in that direction. The step size is\n% inversely proportional to the iteration number. See [1] for\n% details.\n%\n% NumIterations:: [10 / LAMBDA]\n% Sets the maximum number of iterations.\n%\n% BiasMultiplier:: [0]\n% Appends to the data X the specified scalar value B. This\n% approximates the training of a linear SVM with bias. The bias\n% can be recovered from the optimal weight vector W as W(end) *\n% B. It is often useful to precondition the computation of the\n% gradient with respect to this element by a small value,\n% e.g. 0.1/B (see PRECONDITIONER).\n%\n% StartingModel:: [null vector]\n% Specify the initial value for the weight vector W.\n%\n% StartingIteration:: [1]\n% Specify the iteration number to start from. The only effect\n% is to change the step size, as this is inversely proportional\n% to the iteration number.\n%\n% Permutation:: [empty]\n% Specify a permutation PERM to be used to sample the data (this\n% disables random sampling). Specifically, at the T-th iteration\n% the algorithm takes a step w.r.t. the PERM[T']-th data point,\n% where T' is T modulo the number of data samples\n% (i.e. MOD(T'-1,NUMSAMPLES)+1). PERM needs not to be\n% bijective. This allows specifying certain data points more or\n% less frequently, implicitly increasing their relative weight in\n% the error term. A common application is to balance an unbalanced\n% dataset.\n%\n% Preconditioner:: [empty]\n% Specify a diagonal preconditioner PREC. The elements of this\n% vector are multiplied to the function subgradient before adding\n% the latter to the current model estimate. The dimension of the\n% vector PREC is the same of the model, plus one if the SVM has\n% bias (see BIASMULTIPLIER).\n%\n% Verbose::\n% Be verbose.\n%\n% Example::\n% The options StartingModel and StartingIteration can be used\n% to continue training. I.e., the command\n%\n% vl_twister('state',0) ;\n% w = vl_pegasos(x,y,lambda,'NumIterations',1000) ;\n%\n% produces the same result as the sequence\n%\n% vl_twister('state',0) ;\n% w = vl_pegasos(x,y,lambda,'NumIterations',500) ;\n% w = vl_pegasos(x,y,lambda,'NumIterations',500, ...\n% 'StartingIteration', 501, ...\n% 'StartingModel', w) ;\n%\n% REFERENCES::\n% [1] S. Shalev-Shwartz, Y. Singer, N. Srebro, and\n% A. Cotter. Pegasos: Primal Estimated sub-GrAdient SOlver for\n% SVM. MBP, 2010.\n%\n% See also: VL_HOMKERMAP(), VL_HELP().\n\n% AUTHORIGHTS\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/misc/vl_pegasos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7207030393084409}} {"text": "function monogrid_poisson_1d_test01_multi ( ) \n\n%*****************************************************************************80\n%\n%% MONOGRID_POISSON_1D_TEST01_MULTI tests MULTIGRID_POISSON_1D on test case 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 December 2011\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONOGRID_POISSON_1D_TEST01_MULTI\\n' );\n fprintf ( 1, ' MULTIGRID_POISSON_1D solves a 1D Poisson BVP\\n' );\n fprintf ( 1, ' using the multigrid method.\\n' );\n\n a = 0.0;\n b = 1.0;\n ua = 0.0;\n ub = 0.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' -u\"(x) = 1, for %g < x < %g\\n', a, b );\n fprintf ( 1, ' u(%g) = %g, u(%g) = %g.\\n', a, ua, b, ub );\n fprintf ( 1, ' Solution is u(x) = ( -x^2 + x ) / 2\\n' );\n\n for k = 5 : 5\n\n n = 2^k;\n x = ( linspace ( a, b, n + 1 ) )';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Mesh index K = %d\\n', k );\n fprintf ( 1, ' Number of intervals N=2^K = %d\\n', n );\n fprintf ( 1, ' Number of nodes = 2^K+1 = %d\\n', n + 1 );\n\n [ u, it_num ] = multigrid_poisson_1d ( n, a, b, ua, ub, @force1, @exact1 );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I X(I) U(I) U Exact(X(I))\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n + 1\n fprintf ( 1, ' %4d %10f %14g %14g\\n', i, x(i), u(i), exact1 ( x(i) ) );\n end\n\n fprintf ( 1, '\\n' );\n\n difmax = 0.0;\n for i = 1 : n + 1\n difmax = max ( difmax, abs ( u(i) - exact1 ( x(i) ) ) );\n end\n fprintf ( 1, ' Maximum error = %g\\n', difmax );\n fprintf ( 1, ' Number of iterations = %d\\n', it_num );\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/multigrid_poisson_1d/multigrid_poisson_1d_test01_multi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7207030281144187}} {"text": "function [eigvec, eigval] = PTKVectorisedEigenvalues(M, eigenvalues_only)\n % PTKVectorisedEigenvalues. Computes eigenvalues and eigenvectors for many symmetric matrices\n %\n % PTKVectorisedEigenvalues is similar to Matlab's eigs() function, but can be\n % used to compute the eigenvalues and eigenvectors for multiple matrices,\n % which for a large number of points is significantly quicker than using a\n % for loop. Each input matrix must be symmetric and is represented by a\n % single row of the input matrix as described below.\n %\n % The mex function PTKFastEigenvalues is equivalent to function but runs\n % faster. PTKVectorisedEigenvalues is slower than PTKFastEigenvalues but still\n % significantly faster than running eigs() in a for loop when a large\n % number of matrices is involved.\n %\n %\n % Syntax:\n % [eigvectors, eigvalues] = PTKFastEigenvalues(M [, eigenvalues_only])\n %\n % Input:\n % M is a 6xn matrix. Each column of M represents one 3x3 symmetric matrix as follows\n %\n % [V(1) V(2) V(3); V(2) V(4) V(5); V(3) V(5) V(6)]\n % \n % where V is a 6x1 column of M\n % \n % eigenvalues_only is an optional parameter which defaults to\n % false. Set to true to only calculate eigenvalues and not\n % eigenvectors, which reduces the execution time.\n % \n % Outputs:\n % eigenvalues is a 3xn matrix. Each column contains the 3\n % eigenvalues of the matrix V described above\n %\n % eigenvectors is a 3x3xn matrix, where each 3x1 row represents\n % an eigenvector (3 for each of the n matrices V described\n % above).\n % \n % \n % \n % Licence\n % -------\n % Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit\n % Author: Tom Doel, 2012. www.tomdoel.com\n % Distributed under the GNU GPL v3 licence. Please see website for details.\n %\n\n compute_eigenvectors = true;\n if exist('eigenvalues_only', 'var')\n if (eigenvalues_only)\n compute_eigenvectors = false;\n end\n end\n\n numvoxels = size(M, 2);\n eigval = zeros(3, numvoxels, 'double');\n\n m = (M(1,:) + M(4,:) + M(6,:))/3;\n\n q = (( M(1,:) - m) .* (M(4,:) - m) .* (M(6,:) - m) + ...\n 2 * M(2,:) .* M(5,:) .* M(3,:) - ...\n M(3,:).^2 .* (M(4,:) - m) - ...\n M(5,:).^2 .* (M(1,:) - m) - M(2,:).^2 .* (M(6,:) - m) )/2;\n\n p = ( ( M(1,:) - m ).^2 + 2 * M(2,:).^2 + 2 * M(3,:).^2 + ...\n ( M(4,:) - m ).^2 + 2 * M(5,:).^2 + ( M(6,:) - m ).^2 )/6;\n \n \n p = max(0.01, p);\n \n phi = 1/3*acos(min(1, q./p.^(3/2)));\n phi(phi<0) = phi(phi<0)+pi/3;\n \n eigval(1,:) = m + 2*sqrt(p).*cos(phi);\n eigval(2,:) = m - sqrt(p).*(cos(phi) + sqrt(3).*sin(phi));\n eigval(3,:) = m - sqrt(p).*(cos(phi) - sqrt(3).*sin(phi));\n \n [~, i] = sort(abs(eigval));\n i = i + size(eigval,1)*ones(size(eigval,1), 1)*(0:size(eigval, 2) - 1);\n eigval = eigval(i);\n\n % Only compute the eigenvectors if requested\n if (compute_eigenvectors)\n \n eigvec = zeros(3,3, numvoxels, 'double');\n for l = 1 : 2\n Ai = M(1,:) - eigval(l,:);\n Bi = M(4,:) - eigval(l,:);\n Ci = M(6,:) - eigval(l,:);\n \n eix = ( M(2,:) .* M(5,:) - Bi .* M(3,:) ) .* ( M(3,:) .* M(5,:) - Ci .* M(2,:) );\n eiy = ( M(3,:) .* M(5,:) - Ci .* M(2,:) ) .* ( M(3,:) .* M(2,:) - Ai .* M(5,:) );\n eiz = ( M(2,:) .* M(5,:) - Bi .* M(3,:) ) .* ( M(3,:) .* M(2,:) - Ai .* M(5,:) );\n \n vec = sqrt(eix.^2+eiy.^2+eiz.^2);\n vec = max(0.01, vec);\n eigvec(:,l,:) = [eix; eiy; eiz] ./ vec([1;1;1], :);\n end\n \n eigvec(:,3,:) = cross(eigvec(:,1,:), eigvec(:,2,:));\n else\n eigvec = [];\n end \nend\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/Library/PTKVectorisedEigenvalues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.720667530327103}} {"text": "%% Simplicial Complex in 3D\n%\n% We describe general idea of the data structure generated for three\n% dimensional triangular grids, suppose $N,NE,NF,NT$ represents the number\n% of vertices, edges, faces and elements resprectively. \n\n%% Construct Data Structure\n% elem is $NT\\times 4$ matrix with $NT$ be the number of the tetrahedrons.\n% elem(i,:) contain the global index of the vertex of the i-th tetrahedron.\n% we sort the vertices of elem such\n% that:elem(i,1)> sig_e = bay_errorbar({X,Y,'function',gam,sig2}, Xt)\n% >> sig_e = bay_errorbar(model, Xt)\n% \n% The computation takes into account the estimated noise variance\n% and the uncertainty of the model parameters, estimated by\n% Bayesian inference. sig_e is the estimated standard deviation of\n% the error bars of the points Xt. A plot is obtained by replacing\n% Xt by the string 'figure'.\n% \n%\n% Full syntax\n% \n% 1. Using the functional interface:\n% \n% >> sig_e = bay_errorbar({X,Y,'function',gam,sig2,kernel,preprocess}, Xt)\n% >> sig_e = bay_errorbar({X,Y,'function',gam,sig2,kernel,preprocess}, Xt, type)\n% >> sig_e = bay_errorbar({X,Y,'function',gam,sig2,kernel,preprocess}, Xt, type, nb)\n% >> sig_e = bay_errorbar({X,Y,'function',gam,sig2,kernel,preprocess}, 'figure')\n% >> sig_e = bay_errorbar({X,Y,'function',gam,sig2,kernel,preprocess}, 'figure', type)\n% >> sig_e = bay_errorbar({X,Y,'function',gam,sig2,kernel,preprocess}, 'figure', type, nb)\n% \n% Outputs \n% sig_e : Nt x 1 vector with the [$ \\sigma^2$] errorbands of the test data\n% Inputs \n% X : N x d matrix with the inputs of the training data\n% Y : N x 1 vector with the inputs of the training data\n% type : 'function estimation' ('f')\n% gam : Regularization parameter\n% sig2 : Kernel parameter\n% kernel(*) : Kernel type (by default 'RBF_kernel')\n% preprocess(*) : 'preprocess'(*) or 'original'\n% Xt : Nt x d matrix with the inputs of the test data\n% type(*) : 'svd'(*), 'eig', 'eigs' or 'eign'\n% nb(*) : Number of eigenvalues/eigenvectors used in the eigenvalue decomposition approximation\n%\n% 2. Using the object oriented interface:\n% \n% >> [sig_e, bay, model] = bay_errorbar(model, Xt)\n% >> [sig_e, bay, model] = bay_errorbar(model, Xt, type)\n% >> [sig_e, bay, model] = bay_errorbar(model, Xt, type, nb)\n% >> [sig_e, bay, model] = bay_errorbar(model, 'figure')\n% >> [sig_e, bay, model] = bay_errorbar(model, 'figure', type)\n% >> [sig_e, bay, model] = bay_errorbar(model, 'figure', type, nb)\n% \n% Outputs \n% sig_e : Nt x 1 vector with the [$ \\sigma^2$] errorbands of the test data\n% model(*) : Object oriented representation of the LS-SVM model\n% bay(*) : Object oriented representation of the results of the Bayesian inference\n% Inputs \n% model : Object oriented representation of the LS-SVM model\n% Xt : Nt x d matrix with the inputs of the test data\n% type(*) : 'svd'(*), 'eig', 'eigs' or 'eign'\n% nb(*) : Number of eigenvalues/eigenvectors used in the eigenvalue decomposition approximation\n% \n% See also:\n% bay_lssvm, bay_optimize, bay_modoutClass, plotlssvm\n\n% Copyright (c) 2002, KULeuven-ESAT-SCD, License & help @ http://www.esat.kuleuven.ac.be/sista/lssvmlab\n\nif iscell(model), model = initlssvm(model{:}); end\n\n\nif model.type(1)~='f',\n error(['confidence bounds only for function estimation. For' ...\n\t ' classification, use ''bay_modoutClass(...)'' instead;']);\nend\n\neval('type;','type=''svd'';');\neval('nb;','nb=model.nb_data;');\nif ~(strcmpi(type,'svd') | strcmpi(type,'eig') | strcmpi(type,'eigs') | strcmpi(type,'eign')),\n error('Eigenvalue decomposition via ''svd'', ''eig'', ''eigs'' or ''eign''...');\nend\n\nif strcmpi(type,'eign')\n warning('The resulting errorbars are most probably not very usefull...'); \nend\n\nif ~isstr(Xt),\n\n eval('[sig_e, bay] = bay_confb(model,Xt,type,nb,bay);',...\n '[sig_e, bay] = bay_confb(model,Xt,type,nb);');\n \nelse\n\n grid = 50;\n [X,Y] = postlssvm(model,model.xtrain,model.ytrain);\n eval('[sig_e, bay] = bay_confb(model,X,type,nb,bay);',...\n '[sig_e, bay] = bay_confb(model,X,type,nb);');\n\n % plot the curve including confidence bound\n sige = sqrt(sig_e);\n Yt = simlssvm(model,X);\n \n figure;\n hold on;\n title(['LS-SVM_{\\gamma=' num2str(model.gam(1)) ', \\sigma^2=' num2str(model.kernel_pars(1)) ...\n\t '}^{' model.kernel_type(1:3) '} and its 95% (2\\sigma) error bands']);\n\n if model.x_dim==1,\n xlabel('X');\n ylabel('Y');\n [~,si] = sort(X);\n plot(X(si),Yt(si),'k'); hold on; \n plot(X(si),Yt(si)+2.*sige(si),'-.r'); \n plot(X(si),Yt(si)-2.*sige(si),':r');\n plot(X(si),Y(si),'k*'); hold off;\n else\n xlabel('time');\n ylabel('Y');\n plot(Yt,'k'); hold on; \n plot(Yt+2.*sige,'-.r'); \n plot(Yt-2.*sige,':r');\n plot(Y,'k*'); hold off;\n end\n \nend\n\n\n\nfunction [sig_e, bay] = bay_confb(model,X,type,nb,bay)\n% see formula's thesis TvG blz 126\n\n\nnD = size(X,1);\n%tol = .0001;\n\n%\n% calculate the eigenvalues\n%\neval('bay;','[c1,c2,c3,bay] = bay_lssvm(model,1,type,nb);');\nomega = kernel_matrix(model.xtrain(model.selector,1:model.x_dim), ...\n\t\t model.kernel_type, model.kernel_pars);\noo = ones(1,model.nb_data)*omega;\n\n% kernel values of X\ntheta = kernel_matrix(model.xtrain(model.selector, 1:model.x_dim), ...\n\t\t model.kernel_type, model.kernel_pars, X);\nfor i=1:nD,\n kxx(i,1) = feval(model.kernel_type, X(i,:),X(i,:), model.kernel_pars);\nend\n\n\n\nZc = eye(model.nb_data) - ones(model.nb_data)./model.nb_data;\n\n\nHd = (Zc*bay.Rscores);\nHd = Hd*diag(1./bay.mu - (bay.mu+ bay.zeta*bay.eigvals).^-1)*Hd';\n\n\n% forall x\nfor i=1:nD,\n term1(i,1) = bay.zeta^-1 + kxx(i)/bay.mu - theta(:,i)'*Hd*theta(:,i);\n term2(i,1) = 2/model.nb_data*sum(theta(:,i)'*Hd*omega) - 2/bay.mu/model.nb_data* sum(theta(:,i));\nend\n\n\n% once\nterm3 = 1/(bay.zeta*model.nb_data) ...\n\t+ 1/(bay.mu*model.nb_data^2)* sum(oo) ...\n\t-1/(model.nb_data^2)* oo*Hd*oo';\n\nsig_e = term1+term2+term3;\n\n\n", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v3.0/Algorithms/extract_resp_sig/feat_based_extraction/LSSVMlabv1_8_R2009b_R2011a/bay_errorbar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7206434029909357}} {"text": "function [u, flag, normres, Q] = gmres(varargin)\n%GMRES Iterative solution of chebfun operator equations.\n% U = GMRES(A, F) attempts to solve the operator equation A(U) = F, where F\n% and U are CHEBFUNs and A is a function handle defining a linear operator\n% on CHEBFUN.\n%\n% U = GMRES(A, F, RESTART) chooses a restart parameter. Use Inf or [] for no\n% restarts. The default is Inf.\n%\n% U = GMRES(A, F, RESTART, TOL) tries to find a solution for which the\n% residual norm is less than TOL relative to the norm of F. The default\n% value is 1e-10.\n%\n% U = GMRES(A, F, RESTART, TOL, MAXIT) stops after MAXIT total iterations.\n% This defaults to 36.\n%\n% U = GMRES(A, F, RESTART, TOL, MAXIT, M1INV, M2INV) applies the left and\n% right preconditioners M1INV and M2INV, defined as functions. They should\n% approximate the inverse of A. Note that this usage of preconditioners\n% differs from that in the built-in GMRES.\n%\n% [U, FLAG] = GMRES(A,F,...) also returns a convergence FLAG:\n% 0 GMRES converged to the desired tolerance TOL within MAXIT iterations.\n% 1 GMRES iterated MAXIT times but did not converge.\n%\n% [U, FLAG, NORMRES] = GMRES(A, F, ...) also returns a vector of the relative\n% residual norms for all iterations. Note the output ordering is not the same\n% as for built-in GMRES. This calling sequence will also print out updates on\n% the progress of the iteration.\n%\n% Example:\n% % To solve a simple Volterra integral equation:\n% f = chebfun('exp(-4*x.^2)', [-1 1]);\n% A = @(u) cumsum(u) + 20*u;\n% u = gmres(A, f, Inf, 1e-14);\n%\n% See also GMRES, CHEBOP/MLDIVIDE.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Parse inputs and supply defaults:\ndefaults = {[], [], Inf, 1e-10, 36, [], []};\nidx = nargin+1:length(defaults);\nargs = [varargin, defaults(idx)];\n[L, f, m, tol, maxiter, M1inv, M2inv] = deal( args{:} );\nshowtrace = (nargout > 2);\n\nif ( m == 0 )\n % No restarts:\n m = Inf;\nend\n% Avoid warning about Inf in for loop:\nm = min(m, maxiter + 1);\n\n% Initialise:\nu = chebfun(0, domain(f));\nnormb = norm(f);\nr = f;\nif ( ~isempty(M1inv) )\n r = M1inv(r);\nend\nnormres(1) = norm(r)/normb;\n\nj = 1; % total iterations\nwhile ( (normres(j) > tol) && (j < maxiter) ) % outer iterations\n \n H = [];\n QTb = norm(r);\n Q = r/QTb ; % Krylov basis\n \n for n = 1:m % inner iterations\n \n % Next Krylov vector, with preconditioners.\n q = Q(:,n);\n if ( ~isempty(M2inv) )\n q = M2inv(q);\n end\n v = L(q);\n \n if ( ~isempty(M1inv) )\n v = M1inv(v);\n end\n \n % Modified Gram-Schmidt iteration.\n for k = 1:n\n H(k,n) = Q(:,k)' * v ; %#ok\n v = v - H(k,n)*Q(:,k);\n end\n H(n+1,n) = norm(v); %#ok\n \n % Use QR factorization to find the residual norm.\n % TODO: This could be made more efficient (worthwhile?).\n QTb(n+1,1) = 0; % by orthogonality\n j = j + 1;\n [P, R] = qr(H);\n normres(j) = abs( P(1,n+1)*QTb(1) ) / normb; %#ok\n \n % Done?\n if ( normres(j) < tol )\n showtrace = false;\n flag = 0;\n break\n end\n \n % Trace iteration--for debugging, not an official option.\n if ( showtrace && (rem(j - 1, 5) == 0) )\n fprintf('Iteration %2i: relative residual norm = %.3e\\n', ...\n j - 1, normres(j));\n end\n \n % Give up?\n if ( j == maxiter + 1 )\n warning('CHEBFUN:CHEBFUN:gmres:maxiter', ...\n 'Maximum number of iterations reached.')\n showtrace = false;\n break\n end\n \n % New basis vector:\n Q(:,n+1) = v / H(n+1,n); \n \n % Reorthogonalize (for research only--not an official option).\n if ( rem(n, Inf) == 0 )\n [Q, ignored] = qr(Q, 0);\n end\n \n end % end inner iterations\n \n y = R(1:n,1:n)\\(P(:,1:n)'*QTb); % least squares soln\n u0 = Q(:,1:n)*y; % new part of solution\n if ( ~isempty(M2inv) )\n u0 = M2inv(u0);\n end\n u = u + u0; % solution\n v = L(u0);\n if ( ~isempty(M1inv) )\n v = M1inv(v);\n end\n r = r - v; % new residual\n if ( showtrace )\n fprintf(' (restart)\\n')\n end\n \nend % end outer iterations\n\nif ( j >= maxiter )\n flag = 1;\nend\nif ( nargout < 2 )\n fprintf('\\n Final relative residual: %.3e\\n\\n', normres(end))\nend\n\nend % end main function\n\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun/gmres.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7206434011059336}} {"text": "function [ o, c, f ] = lp_coefficients ( n )\n\n%*****************************************************************************80\n%\n%% LP_COEFFICIENTS: coefficients of Legendre polynomials P(n,x).\n%\n% Discussion:\n%\n% The Legendre polynomial with index N will have O = 1 + (N/2) terms.\n% The monomials of orders N, N-2, N-2, ... will have nonzero coefficients.\n%\n% First terms:\n%\n% 1\n% 0 1\n% -1/2 0 3/2\n% 0 -3/2 0 5/2\n% 3/8 0 -30/8 0 35/8\n% 0 15/8 0 -70/8 0 63/8\n% -5/16 0 105/16 0 -315/16 0 231/16\n% 0 -35/16 0 315/16 0 -693/16 0 429/16\n%\n% 1.00000\n% 0.00000 1.00000\n% -0.50000 0.00000 1.50000\n% 0.00000 -1.50000 0.00000 2.5000\n% 0.37500 0.00000 -3.75000 0.00000 4.37500\n% 0.00000 1.87500 0.00000 -8.75000 0.00000 7.87500\n% -0.31250 0.00000 6.56250 0.00000 -19.6875 0.00000 14.4375\n% 0.00000 -2.1875 0.00000 19.6875 0.00000 -43.3215 0.00000 26.8125\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz 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 N, the degree of the polynomial.\n%\n% Output, integer O, the number of coefficients.\n%\n% Output, real C(1:O,1), the coefficients of the Legendre polynomial\n% of degree N.\n%\n% Output, integer F(1:O,1), the exponents.\n%\n\n%\n% Compute the table.\n%\n ctable(1:n+1,1:n+1) = 0.0;\n\n ctable(1,1) = 1.0;\n\n if ( 1 <= n)\n\n ctable(2,2) = 1.0;\n \n for i = 2 : n\n ctable(i+1,1:i-1) = ( - i + 1 ) * ctable(i-1,1:i-1) / i;\n ctable(i+1,2:i+1) = ctable(i+1,2:i+1) + ( i + i - 1 ) * ctable(i ,1:i ) / i;\n end\n \n end\n%\n% Extract the nonzero data from the alternating columns of the last row.\n%\n o = floor ( ( n + 2 ) / 2 );\n\n c = zeros ( o, 1 );\n f = zeros ( o, 1 ); \n\n k = o;\n for j = n + 1 : -2 : 1\n c(k) = ctable(n+1,j);\n f(k) = j - 1;\n k = k - 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/lagrange_nd/lp_coefficients.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642804, "lm_q2_score": 0.8080672204860317, "lm_q1q2_score": 0.7206432796564413}} {"text": "function c = assemble_mass ( node_num, node_x, element_num, element_node, ...\n quad_num )\n\n%*****************************************************************************80\n%\n%% ASSEMBLE_MASS assembles the finite element mass matrix.\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 NODE_NUM, the number of nodes.\n%\n% Input, real NODE_X(NODE_NUM), the coordinates of nodes.\n%\n% Input, integer ELEMENT_NUM, the number of elements.\n%\n% Input, integer ELEMENT_NODE(2,ELEMENT_NUM);\n% ELEMENT_NODE(I,J) is the global index of local node I in element J.\n%\n% Input, integer QUAD_NUM, the number of quadrature points used in assembly.\n%\n% Output, sparse real C(NODE_NUM,NODE_NUM), the finite element mass matrix.\n%\n% Local parameters:\n%\n% Local, real BI, DBIDX, the value of some basis function\n% and its first derivative at a quadrature point.\n%\n% Local, real BJ, DBJDX, the value of another basis\n% function and its first derivative at a quadrature point.\n%\n\n%\n% Initialize the arrays.\n%\n c = [];\n c = sparse ( node_num, node_num );\n%\n% Get the quadrature weights and nodes.\n%\n [ reference_w, reference_q ] = quadrature_set ( quad_num );\n%\n% Consider each ELEMENT.\n%\n for element = 1 : element_num\n\n element_x(1:2,1) = node_x(element_node(1:2,element));\n\n element_q(1:quad_num,1) = reference_to_physical ( element, element_node, ...\n node_x, quad_num, reference_q );\n\n element_area = element_x(2) - element_x(1);\n\n element_w(1:quad_num,1) = ( element_area / 2.0 ) * reference_w(1:quad_num);\n%\n% Consider the QUAD-th quadrature point in the element.\n%\n for quad = 1 : quad_num\n%\n% Consider the TEST-th test function.\n%\n% We generate an integral for every node associated with an unknown.\n%\n for i = 1 : 2\n\n test = element_node(i,element);\n\n [ bi, dbidx ] = basis_function ( test, element, node_x, 1, element_q(quad) );\n%\n% Consider the BASIS-th basis function, which is used to form the\n% value of the solution function.\n%\n for j = 1 : 2\n\n basis = element_node(j,element);\n\n [ bj, dbjdx ] = basis_function ( basis, element, node_x, 1, element_q(quad) );\n\n c(test,basis) = c(test,basis) + element_w(quad) * bi * bj;\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/fem1d_heat_explicit/assemble_mass.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7206302697782964}} {"text": "function [A1nmb] = moran(initsize, popsize) \n% MORAN generates a trajectory of a Moran type process \n% which gives the number of genes of allelic type A1 in a population \n% of haploid individuals that can exist in either type A1 or type A2.\n% The population size is popsize and the initial number of type A1 \n% individuals os initsize.\n%\n% [A1nmb] = galtonwatson(initsize, popsize) \n% \n% Inputs: initsize - initial number of A1 genes\n% popsize - the total population size (preserved)\n% \n% Outputs: A1nmb - the successive number of type A1 genes in the population\n\n% Authors: R.Gaigalas, I.Kaj\n% v1.2 04-Oct-02\n\nif (nargin==0)\n initsize=10;\n popsize=30;\nend\n\nA1nmb=zeros(1,popsize);\nA1nmb(1)=initsize;\n\nlambda = inline('(x-1).*(1-(x-1)./N)', 'x', 'N');\nmu = inline('(x-1).*(1-(x-1)./N)', 'x', 'N');\n\nx=initsize;\ni=1;\nwhile (x>1 & xrand)\n x=x+1;\n A1nmb(i)=x;\n else\n x=x-1;\n A1nmb(i)=x;\n end;\n i=i+1;\nend;\nnmbsteps=length(A1nmb);\nrate = lambda(A1nmb(1:nmbsteps-1),popsize) ...\n +mu(A1nmb(1:nmbsteps-1),popsize); \n\njumptimes=cumsum(-log(rand(1,nmbsteps-1))./rate);\njumptimes=[0 jumptimes];\n \nstairs(jumptimes,A1nmb);\naxis([0 jumptimes(nmbsteps) 0 popsize+1]);\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2493-simulation-of-stochastic-processes/stproc/moran.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.7206302670383973}} {"text": "function out = proj_spectahedron_box(X,r,l,u,eq_flag)\n%PROJ_SPECTAHEDRON_BOX computes the orthogonal projection onto the spectahedron {X : Tr(X) = r, X psd, l<=eig(X)<=u} or\n% onto the full spectahedron {X : Tr(X)<= r, X psd, l<=eig(X)<=u}\n%\n% Usage: \n% out = PROJ_SPECTAHEDRON_BOX(X,[r],[l],[u],[eq_flag])\n% ===========================================\n% Input:\n% X - matrix to be projected\n% r - positive scalar [default: 1]\n% l - lower bound (scalar) [default: 0]\n% u - upper bound (scalar) [default: inf]\n% eq_flag - a flag that determines whether the projection is onto the spectahedron ('eq') or \n% the full spectahedron ('ineq') [defualt: 'eq']\n% ===========================================\n% Assumptions:\n% X symmetric\n% r > 0 \n% ===========================================\n% Output:\n% out - projection matrix\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\n%reading the user X and setting defalut values when required.\nif (nargin < 1)\n error ('usage: spectahedron_box(X,[r],[l],[u],[eq_flag])') ;\nend\n\nif (( nargin < 5) || (isempty(eq_flag)) )\n %eq_flag is not given, setting to default value: true\n eq_flag = 'eq' ;\nend\n\nif ((nargin < 4) || (isempty(u)))\n %u is not given, setting to default value: inf\n u=inf ;\nend\n\nif ((nargin < 3) || (isempty(l)))\n %l is not given, setting to default value: 0\n l=0 ;\nend\n\nif ((nargin < 2) || (isempty(r)))\n %r is not given, setting to default value: 1\n r = 1 ;\nend\n\nif ( r <= 0 ) \n error('Set is infeasible') ;\nend\n\neps = 1e-10 ; % defalut value for eps : 1e-10\nif ((size(X,1) ~= size(X,2)) || (norm( X - X') > eps))\n error('usage: spectahedron_box(X,[r],[eq_flag]) - X should be a symmetric matrix') ;\nend\n\nX = 0.5 * (X + X');\n\n[V,D] = eig(X) ;\n\nif (strcmp(eq_flag,'eq') == 1)\n %call proj_simplex with eq\n out = V * diag(proj_hyperplane_box(diag(D),ones(length(X),1),r,l,u)) * V' ; \n out=(out+out')/2;\nelse\n if (strcmp(eq_flag,'ineq') == 1)\n %call proj_simplex with ineq\n out = V * diag((proj_halfspace_box(diag(D),ones(length(X),1),r,l,u))) * V' ;\n out=(out+out')/2;\n else\n error('usage: spectahedron(X,[r],[eq_flag]) - eq_flag should be either eq or ineq') ;\n end\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/proj_spectahedron_box.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7206302547447921}} {"text": "function op = proj_nuclear( q, sz )\n\n%PROJ_NUCLEAR Projection onto the set of matrices with nuclear norm less than or equal to q.\n% OP = PROJ_NUCLEAR( q ) returns a function that implements the\n% indicator for matrices with nuclear norm less than q.\n% Q is optional; if omitted, Q=1 is assumed. But if Q is supplied, \n% it must be a positive real scalar.\n% This function is like proj_psdUTrace.m but does not assume\n% that inputs are square Hermitian positive semidefinite matrices.\n%\n% OP = PROJ_NUCLEAR( ..., SZ )\n% where SZ = [n1,n2], will assume the input has been vectorized\n% and thus will reshape it into a matrix of size n1 x n2. TFOCS\n% can handle matrix variables so this form of PROJ_NUCLEAR is not\n% always necessary, but it can be easier to find bugs if using\n% only vector variables.\n%\n% This version uses a dense svd decomposition; future versions\n% of TFOCS will take advantage of low-rank and/or sparse structure.\n% Dual function: prox_spectral.m\n% See also prox_spectral, proj_psdUTrace.m, proj_simplex.m, prox_nuclear.m\n\n% June 26, 2012\n\nif nargin == 0,\n\tq = 1;\nelseif ~isnumeric( q ) || ~isreal( q ) || numel( q ) ~= 1 || q <= 0,\n\terror( 'Argument must be positive.' );\nend\nif nargin < 2, sz = []; end\nq = proj_simplex( q );\nop = @(varargin)proj_nuclear_q( q, sz, varargin{:} );\n\nfunction [ v, X ] = proj_nuclear_q( eproj, sz, X, t )\n\nVECTORIZE = false;\n% Input must be a matrix\n\n% In proj_psdUTrace.m, we allow vector inputs because\n% we can reshape them (since we have square matrices).\n% For nuclear norm, inputs can be rectangular matrices,\n% so we do not know how to correctly reshape a vector in\n% this case.\n\n% if size(X,1) ~= size(X,2)\n% n = sqrt(length(X));\n% X = reshape(X, n, n );\n% VECTORIZE = true;\n% end\n\n% Update, Jan 2014, allowing vector variables, as long\n% as the 'sz' variable has been given\nif ~isempty(sz)\n if size(X,2) > 1\n error('proj_nuclear: when using an explicit size value \"sz\", variable should be a vector');\n end\n X = reshape(X, sz(1), sz(2) );\n VECTORIZE = true;\nelseif size(X,2) == 1\n warning('proj_nuclear: appears variable is a vector not a matrix. Are you sure you want the SVD of a vector?');\nend\n\nv = 0;\nif nargin > 3 && t > 0,\n [U,D,V] = svd(X,'econ');\n [dum,D] = eproj(diag(D),t);\n tt = D > 0;\n X = U(:,tt)*diag(D(tt))*V(:,tt)';\n if VECTORIZE, X = X(:); end\nelseif any(svd(X)<0),\n v = Inf;\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/proj_nuclear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7206127948232812}} {"text": "function [ c, seed ] = i4mat_uniform_ab ( m, n, a, b, seed )\n\n%*****************************************************************************80\n%\n%% I4MAT_UNIFORM_AB returns a scaled pseudorandom I4MAT.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2006\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% Pierre L'Ecuyer,\n% Random Number Generation,\n% in Handbook of Simulation,\n% edited by Jerry Banks,\n% Wiley Interscience, page 95, 1998.\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 row and column dimensions of the matrix.\n%\n% Input, integer A, B, the minimum and maximum acceptable values.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, integer C(M,N), the randomly chosen integer vector.\n%\n% Output, integer SEED, the updated seed.\n%\n if ( seed == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4MAT_UNIFORM_AB - Fatal error!\\n' );\n fprintf ( 1, ' Input SEED = 0!\\n' );\n error ( 'I4MAT_UNIFORM_AB - Fatal error!' );\n end\n\n seed = floor ( seed );\n a = round ( a );\n b = round ( b );\n\n for j = 1 : n\n\n for i = 1 : m\n\n seed = mod ( seed, 2147483647 );\n\n if ( seed < 0 ) \n seed = seed + 2147483647;\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 + 2147483647;\n end\n\n r = seed * 4.656612875E-10;\n%\n% Scale R to lie between A-0.5 and B+0.5.\n%\n r = ( 1.0 - r ) * ( min ( a, b ) - 0.5 ) ...\n + r * ( max ( a, b ) + 0.5 );\n%\n% Use rounding to convert R to an integer between A and B.\n%\n value = round ( r );\n\n value = max ( value, min ( a, b ) );\n value = min ( value, max ( a, b ) );\n\n c(i,j) = value;\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/i4lib/i4mat_uniform_ab.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.7204774395564104}} {"text": "function ulimit = SlopeLimitLin(ul,xl,vm1,v0,vp1);\n\n% function ulimit = SlopeLimitLin(ul,xl,vm1,v0,vp1);\n% Purpose: Apply slopelimited on linear function ul(Np,1) on x(Np,1)\n% (vm1,v0,vp1) are cell averages left, center, and right\n\nGlobals1D;\n\n% Compute various geometric measures\nulimit = ul; h = xl(Np,:)-xl(1,:); \nx0 = ones(Np,1)*(xl(1,:) + h/2);\n\nhN = ones(Np,1)*h;\n\n% Limit function\nux = (2./hN).*(Dr*ul);\n\nulimit = ones(Np,1)*v0+(xl-x0).*(ones(Np,1)*minmod([ux(1,:);(vp1-v0)./h;(v0-vm1)./h]));\n%ulimit = ones(Np,1)*v0+(xl-x0).*(ones(Np,1)*minmodB([ux(1,:);(vp1-v0)./h;(v0-vm1)./h],1e-2,h));\nreturn\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/CFD1D/SlopeLimitLin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308165850443, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7204625162614887}} {"text": "function y=rdct(x,n)\n%RDCT Discrete cosine transform of real data Y=(X,N)\n% Data is truncated/padded to length N.\n%\n% This routine is equivalent to multiplying by the matrix\n%\n% rdct(eye(n)) = diag([sqrt(2) 2*ones(1,n-1)]) * cos((0:n-1)'*(0.5:n)*pi/n)\n%\n% The rows and columns of the matrix are orthogonal but not unit modulus.\n% Various versions of the DCT are obtained by pre-multiplying the above\n% matrix by diag([b/a ones(1,n-1)/a]) and post-multiplying the\n% inverse transform matrix by its inverse. A common choice is a=n and/or b=sqrt(2).\n% Choose a=sqrt(2n) and b=1 to make the matrix orthogonal.\n% If b~=1 then the columns are no longer orthogonal.\n%\n% see IRDCT for the inverse transform\n\n\n\n\n% Copyright (C) Mike Brookes 1998\n%\n% Last modified Tue Apr 13 15:56:48 1999\n%\n% VOICEBOX is a MATLAB toolbox for speech processing. Home page is at\n% 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% ftp://prep.ai.mit.edu/pub/gnu/COPYING-2.0 or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfl=size(x,1)==1;\nif fl x=x(:); end\n[m,k]=size(x);\nif nargin<2 n=m;\nelseif n>m x=[x; zeros(n-m,k)];\nelseif n>']); % number of grid\nmaxloop=40; % number of maximum iteration \ntol=10^(-3); % tolerence level for value function iteration\n\ntic; % start the clock\n\n% ******Low and upper bound of state variable k ******\n% Steady state value kstar, f'(kstar)=1/beta-1+delta\n\nkstar=(((1/(alpha*beta))-((1-delta)/alpha)))^(1/(alpha-1));\nlowk=0.8*kstar;\nupk=1.2*kstar;\n\nk=linspace(lowk,upk,nk)'; % build up grid\n[K,Kprime]=meshgrid(k);\n\nv=zeros(size(k))*ones(size(z)); vn=v;\ng=v; gn=g;\t\nloop=0; dv=1; dk=1;\n\nif method==1\n%--------------------------------------\n% No Interpolation Method, Method=1\n%---------------------------------------\n\tC=cobb(K)+(1-delta)*K-Kprime;\n\tU=util(C);\n \n\tkpos=100*ones(size(k));% initial value of loop and distance of value\n\n\twhile dv>tol & loop<=maxloop & dk\n loop=loop+1; \n [vn,kposn]=max(U+beta*v*ones(1,nk)); %new value vector\n vn=vn'; kposn=kposn';\n dv=max(abs((vn-v)./(v+eps)));\n dk=~all(kpos==kposn); % whether or not position exactly the same\n v=vn; kpos=kposn;\n\tend\n\tg=k(kpos); % policy function of next period capital\n \nelseif method==2;\n%--------------------------------------\n% Interpolation Method, Method=2\n%---------------------------------------\n \twhile dv>tol & dk>tol & loop<=maxloop\n\tloop=loop+1; \n\tpp = spline(k,v);\n\tvf=inline('-(util(-y+cobb(k)+(1-delta)*k)+beta*ppval(pp,y))','y','k','delta','beta','pp');\n\t\tfor ik=1:nk \n [gn(ik),vn(ik)]=fminbnd(vf,lowk,upk,[],k(ik),delta,beta,pp) ;\n vn(ik)=-vn(ik);\n\t\tend;\n\tdk=max(abs((gn-g)./(g+eps)));\n dv=max(abs((vn-v)./(v+eps)));\n\tv=vn; g=gn;\n end; \nend\n%------------------------------------------------------------\n% use calculated k g to get consumption policy and plot , save\n%--------------------------------------------------------------\n%Polc=cobb(k)*z+(1-delta)*k*ones(size(z))-g; % policy function of consumption\nPolc=cobb(k)+(1-delta)*k-g; % policy function of consumption\n\nvgc_plot(k,kstar,v,Polc,g, method);\n\n%--------------so other output for observation of convergence--------------\nt=toc % read clock\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/3289-neoclassic-growth-model-in-dynamic-economic-theory/neogrowth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7203656509021586}} {"text": "function c = mycross(a,b,dim)\n%% MYCROSS cross product\n%\n% c = mycross(a,b) computes the cross product of vectors a and b. It is\n% used to replace the built-in cross function which is two times slower.\n%\n% c = mycross(a,b,dim) the input a, b could be matrix of vectors. The input\n% dim specifies the dimension. By default, dim = 2. Namely each row of a\n% and b is a vector in R3.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('dim','var'), dim = 2; end\n\n% Check dimensions\nif (size(a,dim)~=3) || (size(b,dim)~=3),\n error(message('MATLAB:cross:InvalidDimAorBForCrossProd'))\nend\n\nc = zeros(size(a,1),3);\nc(:,1) = a(:,2).*b(:,3) - a(:,3).*b(:,2);\nc(:,2) = a(:,3).*b(:,1) - a(:,1).*b(:,3);\nc(:,3) = a(:,1).*b(:,2) - a(:,2).*b(:,1);", "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/mycross.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7203656491267648}} {"text": "function [sbc, fpe, logdp, np] = ARFIT_arord(R, m, mcor, ne, pmin, pmax)\n%ARORD\tEvaluates criteria for selecting the order of an AR model.\n%\n% [SBC,FPE]=ARORD(R,m,mcor,ne,pmin,pmax) returns approximate values\n% of the order selection criteria SBC and FPE for models of order\n% pmin:pmax. The input matrix R is the upper triangular factor in the\n% QR factorization of the AR model; m is the dimension of the state\n% vectors; the flag mcor indicates whether or not an intercept vector\n% is being fitted; and ne is the number of block equations of size m\n% used in the estimation. The returned values of the order selection\n% criteria are approximate in that in evaluating a selection\n% criterion for an AR model of order p < pmax, pmax-p initial values\n% of the given time series are ignored.\n%\n% ARORD is called by ARFIT. \n%\t\n% See also ARFIT, ARQR.\n\n% For testing purposes, ARORD also returns the vectors logdp and np,\n% containing the logarithms of the determinants of the (scaled)\n% covariance matrix estimates and the number of parameter vectors at\n% each order pmin:pmax.\n\n% Modified 17-Dec-99\n% Author: Tapio Schneider\n% tapio@gps.caltech.edu\n \n imax \t = pmax-pmin+1; % maximum index of output vectors\n \n % initialize output vectors\n sbc = zeros(1, imax); % Schwarz's Bayesian Criterion\n fpe = zeros(1, imax); % log of Akaike's Final Prediction Error\n logdp = zeros(1, imax); % determinant of (scaled) covariance matrix\n np = zeros(1, imax); % number of parameter vectors of length m\n np(imax)= m*pmax+mcor;\n\n % Get lower right triangle R22 of R: \n %\n % | R11 R12 |\n % R=| |\n % | 0 R22 |\n %\n R22 = R(np(imax)+1 : np(imax)+m, np(imax)+1 : np(imax)+m);\n\n % From R22, get inverse of residual cross-product matrix for model\n % of order pmax\n invR22 = inv(R22);\n Mp = invR22*invR22';\n \n % For order selection, get determinant of residual cross-product matrix\n % logdp = log det(residual cross-product matrix)\n logdp(imax) = 2.*log(abs(prod(diag(R22))));\n\n % Compute approximate order selection criteria for models of \n % order pmin:pmax\n i = imax;\n for p = pmax:-1:pmin\n np(i) = m*p + mcor;\t% number of parameter vectors of length m\n if p < pmax\n % Downdate determinant of residual cross-product matrix\n % Rp: Part of R to be added to Cholesky factor of covariance matrix\n Rp = R(np(i)+1:np(i)+m, np(imax)+1:np(imax)+m);\n\n % Get Mp, the downdated inverse of the residual cross-product\n % matrix, using the Woodbury formula\n L = chol(eye(m) + Rp*Mp*Rp')';\n N = L \\ Rp*Mp;\n Mp = Mp - N'*N;\n\n % Get downdated logarithm of determinant\n logdp(i) = logdp(i+1) + 2.* log(abs(prod(diag(L))));\n end\n\n % Schwarz's Bayesian Criterion\n sbc(i) = logdp(i)/m - log(ne) * (ne-np(i))/ne;\n\n % logarithm of Akaike's Final Prediction Error\n fpe(i) = logdp(i)/m - log(ne*(ne-np(i))/(ne+np(i)));\n\n % Modified Schwarz criterion (MSC):\n % msc(i) = logdp(i)/m - (log(ne) - 2.5) * (1 - 2.5*np(i)/(ne-np(i)));\n\n i = i-1; % go to next lower order\nend\n\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/ARFIT/ARFIT_arord.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7203656399085296}} {"text": "function y = apm_quadprog(H,f,A,b,Aeq,beq,lb,ub,x0)\n%apm_quadprog Quadratic programming. \n% y = apm_quadprog(H,f,A,b,Aeq,beq,LB,UB,X0) writes a quadratic\n% programming model in APMonitor Modeling Language and attempts \n% to solve the quadratic programming problem:\n%\n% min 0.5*x'*H*x + f'*x subject to: A*x <= b, Aeq*x = beq \n% x \n%\n% lb and ub are a set of lower and upper bounds on the design variables,\n% x, so that the solution is in the range lb <= x <= ub. Use empty \n% matrices for any of the arguments. Set lb(i) = -1e20 if x(i) has no\n% lower limit and set ub(i) = 1e20 if x(i) has no upper limit. x0 is\n% the initial guess and starting point to x. This is similar to the\n% Matlab quadprog solver but uses different solvers such as IPOPT, \n% APOPT, and BPOPT to solve the QP. Additional nonlinear constraints\n% can be added to the qp.apm model for nonlinear programming solution\n% with support for possible mixed-integer variables.\n%\n% The solution is returned in the structure y with y.names (variable\n% names), y.values (variable values), y.nvar (number of variables), \n% and y.x (a structure containing each variable and value).\n% \n% Example usage is below:\n%\n% clear all; close all; clc\n% disp('APM MATLAB available for download at http://apmonitor.com')\n% addpath('apm')\n% \n% %% example Quadratic program\n% H = [1 -1; -1 2]; \n% f = [-2; -6];\n% A = [1 1; -1 2; 2 1];\n% b = [2; 2; 3];\n% Aeq = [];\n% beq = [];\n% lb = zeros(2,1);\n% ub = [];\n% x0 = [];\n% \n% %% generate APMonitor QP model\n% y1 = apm_quadprog(H,f,A,b,Aeq,beq,lb,ub,x0);\n% \n% %% compare solution to quadprog (MATLAB)\n% y2 = quadprog(H,f,A,b,Aeq,beq,lb,ub,x0)\n% \n% disp('Validate Results with MATLAB linprog')\n% for i = 1:nx,\n% disp(['x[' int2str(i) ']: ' num2str(y1.values(i)) ' = ' num2str(y2(i))])\n% end\n\n\n% filename to write\nfilename = ['qp.apm'];\n\n% extract H and f in sparse form\nif ~isempty(H),\n [mH,nH] = size(H);\n if (mH~=nH),\n error('H must be a square matrix');\n end\n if isempty(f),\n f = zeros(mH,1);\n mf = mH;\n else\n if size(f,1)==1,\n f = f';\n end\n [mf,nf] = size(f);\n end\n if (mH~=mf),\n error('Rows of H and f must agree');\n end\n \n % convert to sparse form\n [hi,hj,hv] = find(sparse(H));\n h = [hi,hj,hv]';\n [fi,fj,fv] = find(sparse(f));\n f = [fi,fj,fv]';\n if(size(f,2)==0),\n f = [1,1,0]';\n end\n fr = [f(1,:); f(3,:)];\nend\n\n% extract A and b in sparse form\nif ~isempty(A),\n [mA,nA] = size(A);\n if isempty(b),\n b = zeros(mA,1);\n mB = mA;\n else\n if size(b,1)==1,\n b = b';\n end\n [mB,nB] = size(b);\n end\n if (mA~=mB),\n error('Rows of A and b must agree');\n end\n \n % convert to sparse form\n [ai,aj,av] = find(sparse(A));\n if (mA==1),\n a = [ai;aj;av];\n else\n a = [ai,aj,av]';\n end\n [bi,bj,bv] = find(sparse(b));\n b = [bi,bj,bv]';\n if(size(b,2)==0),\n b = [1,1,0]';\n end\n br = [b(1,:); b(3,:)];\nend\n\n% extract Aeq and beq in sparse form\nif ~isempty(Aeq),\n [mAeq,nAeq] = size(Aeq);\n if isempty(beq),\n beq = zeros(mAeq,1);\n mBeq = mAeq;\n else\n if size(beq,1)==1,\n beq = beq';\n end\n [mBeq,nBeq] = size(beq);\n end\n if (mAeq~=mBeq),\n error('Rows of Aeq and beq must agree');\n end\n \n % convert to sparse form\n [aeqi,aeqj,aeqv] = find(sparse(Aeq));\n if (mAeq==1),\n aeq = [aeqi;aeqj;aeqv];\n else\n aeq = [aeqi,aeqj,aeqv]';\n end\n [beqi,beqj,beqv] = find(sparse(beq));\n beq = [beqi,beqj,beqv]';\n if(size(beq,2)==0),\n beq = [1,1,0]';\n end\n beqr = [beq(1,:); beq(3,:)];\nend\n\ndisp('Creating Quadratic Programming Model qp.apm');\nfid = fopen(filename,'w');\nfprintf( fid,'\\n');\nfprintf( fid,'Objects \\n');\nif ~isempty(H),\n fprintf( fid,[' h = qobj\\n']);\nend\nif ~isempty(A),\n fprintf( fid,[' a = axb\\n']);\nend\nif ~isempty(Aeq),\n fprintf( fid,[' aeq = axb\\n']);\nend\nfprintf( fid,'End Objects \\n');\nfprintf( fid,'\\n');\nfprintf( fid,'Connections\\n');\nsz = -1;\nif ~isempty(H),\n fprintf( fid,[' x[1:%d] = h.x[1:%d]\\n'],nH,nH);\n sz = nH;\nend\nif ~isempty(A),\n fprintf( fid,[' x[1:%d] = a.x[1:%d]\\n'],nA,nA);\n if (sz>=0),\n if (nA~=sz),\n error('Variables in Ax < b model must be consistent');\n end\n end\nend\nif ~isempty(Aeq),\n fprintf( fid,[' x[1:%d] = aeq.x[1:%d]\\n'],nAeq,nAeq);\n if (sz>=0),\n if (nAeq~=sz),\n error('Variables in Ax = b model must be consistent');\n end\n end\nend\nfprintf( fid,'End Connections\\n');\nfprintf( fid,'\\n');\nfprintf( fid,'Model \\n');\nfprintf( fid,' Variables \\n');\nif (isempty(x0)&&isempty(lb)&&isempty(ub)),\n % default initial conditions\n fprintf( fid,' x[1:%d] = 0\\n',nH);\nelse\n % create default values\n if (isempty(x0)),\n x0 = zeros(nH,1);\n end\n if (isempty(lb)),\n lb = -1e10 * ones(nH,1);\n end\n if (isempty(ub)),\n ub = 1e10 * ones(nH,1);\n end\n % generate initial conditions and bounds\n for i = 1:nH,\n fprintf( fid,' x[%i] > %d = %d < %d\\n',i,lb(i),x0(i),ub(i));\n end\nend\nfprintf( fid,' End Variables \\n');\nfprintf( fid,'\\n');\nfprintf( fid,' Equations \\n');\nfprintf( fid,' ! add any additional equations here \\n');\nfprintf( fid,' End Equations \\n');\nfprintf( fid,'End Model \\n');\nfprintf( fid,'\\n');\n\nif ~isempty(H),\n fprintf( fid,'\\n');\n fprintf( fid,['File h.txt\\n']);\n fprintf( fid,[' sparse, minimize ! dense or sparse, minimize or maximize\\n']);\n fprintf( fid,' %d ! n=number of variables \\n',mH);\n fprintf( fid,'End File\\n');\n fprintf( fid,'\\n');\n fprintf( fid,['File h.a.txt \\n']);\n fprintf( fid,' %d %d %f\\n', h );\n fprintf( fid,'End File \\n');\n fprintf( fid,'\\n');\n fprintf( fid,['File h.b.txt \\n']);\n fprintf( fid,' %d %f\\n', fr );\n fprintf( fid,'End File \\n');\nend\n\nif ~isempty(A),\n fprintf( fid,'\\n');\n fprintf( fid,['File a.txt\\n']);\n fprintf( fid,[' sparse, Ax0) == count)\n alpha = zeros(q, 1);\n alpha(ref) = afcls_hat;\n break;\n end\n % Multiply negative elements by their counterpart in the s vector.\n % Find largest abs(a_ij, s_ij) and remove entry from alpha.\n idx = find(afcls_hat<0);\n afcls_hat(idx) = afcls_hat(idx) ./ s(idx);\n [val, maxIdx] = max(abs(afcls_hat(idx)));\n maxIdx = idx(maxIdx);\n alpha(maxIdx) = 0;\n keep = setdiff(1:size(U, 2), maxIdx);\n U = U(:, keep);\n count = count - 1;\n ref = ref(keep);\n end\n X(:, n1) = alpha;\nend\n\nreturn;\n", "meta": {"author": "zhouyuanzxcv", "repo": "Hyperspectral", "sha": "f32dcca86677f8d37596376f57e9c733058f8cff", "save_path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral", "path": "github-repos/MATLAB/zhouyuanzxcv-Hyperspectral/Hyperspectral-f32dcca86677f8d37596376f57e9c733058f8cff/GMM_SantaBarbara/competing_methods/BCM/hyperFcls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7203151948311082}} {"text": "% DEMO -- Chebyshev Polynomial Multivariate Interpolation\n% UPDATED -- October 28, 2013\n% Written by Matthew Kelly, Cornell University\n%\n% This script demonstrates how to approximate a multivariable function with\n% a chebyshev polynomial interpolant. Here we use it to approximate the\n% position and velocity of a simple harmonic oscillator.\n%\n\n%What order chebyshev polynomial to use?\norder = 25;\n\n%set up the time span for the system integration using ode45\ntspan = [0,1];\nnTime = 1001;\n\n%Initial conditions for the simple harmonic oscillator\nz0 = [0.25;0]; %[Position, Velocity]\n\n%Physical parameters for the simple harmonic osciallator\nP.m = 0.1;\nP.c = 0.4;\nP.k = 100;\n\n%Function handle for the simple harmonic oscillator\nuserFunc = @(t,z)simpleHarmonicOscillator(z,P);\n\n%Use ode45 to get the solution\nOptions = odeset(...\n 'RelTol',1e-10,... %ode45 complains if reltol is much smaller\n 'AbsTol',1e-10);\nsol = ode45(userFunc,tspan,z0,Options);\n\n%Get the \"exact\" solution at each point in tspan\ntime = linspace(tspan(1),tspan(2),nTime);\nz = deval(sol,time);\npos = z(1,:);\nvel = z(2,:);\n\n%Plot ode45 stuff\nfigure(404); clf\nsubplot(2,1,1); hold on\n plot(time,pos,'r-','LineWidth',2)\n title('Position')\n xlabel('Time')\n ylabel('Position')\nsubplot(2,1,2); hold on\n plot(time,vel,'r-','LineWidth',2)\n title('Velocity')\n xlabel('Time')\n ylabel('Velocity')\n\n%% Chebyshev Stuff\n\nIO.input = time;\nIO.output = z;\n\n%Check the grid points\n[f,d,x] = chebyshevFit(IO, order);\nsubplot(2,1,1);\n plot(x,f(1,:),'ko','MarkerSize',7,'LineWidth',1)\nsubplot(2,1,2); \n plot(x,f(2,:),'ko','MarkerSize',7,'LineWidth',1)\n\n%Check the interpolation\ntic\ny = chebyshevInterpolate(f,time,d);\ntoc\nposCheck = y(1,:);\nvelCheck = y(2,:);\n\n%Plots for the chebyshev interpolant\nsubplot(2,1,1);\n plot(time,posCheck,'k:','LineWidth',1)\n legend('ode45','chebPts','cheb-pos')\nsubplot(2,1,2); \n plot(time,velCheck,'k:','LineWidth',1)\nlegend('ode45','chebPts','cheb-vel')\n\n\n\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/chebyshevPolynomials/DEMO_5_Multivariate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7202970181451784}} {"text": "classdef linear_svm\n% This file defines l2-regularized SVM problem\n%\n% Inputs:\n% x_train train data matrix of x of size dxn.\n% y_train train data vector of y of size 1xn.\n% x_test test data matrix of x of size dxn.\n% y_test test data vector of y of size 1xn.\n% lambda l2-regularized parameter. \n% Output:\n% Problem problem instance. \n%\n%\n% The problem of interest is defined as\n%\n% min f(w) = 1/n * sum_i^n f_i(w), \n% where \n% f_i(w) = 1/2 * (max(0.0, 1 - y_i .* (w'*x_i) )^2 + lambda/2 * w^2.\n%\n% \"w\" is the model parameter of size d vector.\n%\n%\n% This file is part of GDLibrary and SGDLibrary.\n%\n% Created by H.Kasai on Feb. 17, 2016\n% Modified by H.Kasai on Mar. 23, 2018\n\n properties\n name; \n dim;\n samples;\n lambda;\n classes; \n hessain_w_independent;\n d;\n n_train;\n n_test;\n x_train;\n y_train;\n x_test;\n y_test;\n x_norm; \n x;\n end \n \n methods\n function obj = linear_svm(x_train, y_train, x_test, y_test, varargin)\n \n obj.x_train = x_train;\n obj.y_train = y_train;\n obj.x_test = x_test;\n obj.y_test = y_test; \n \n if nargin < 5\n obj.lambda = 0.1;\n else\n obj.lambda = varargin{1};\n end \n \n obj.d = size(x_train, 1);\n obj.n_train = length(y_train);\n obj.n_test = length(y_test); \n\n obj.name = 'linear_svm';\n obj.dim = obj.d;\n obj.samples = obj.n_train;\n obj.classes = 2; \n obj.hessain_w_independent = false; \n obj.x_norm = sum(obj.x_train.^2,1);\n obj.x = obj.x_train; \n end\n \n\n function f = cost(obj, w) \n\n f_sum = 0.5 * sum(max(0.0, 1 - obj.y_train' .*(w'*obj.x_train)').^2);\n f = f_sum/obj.n_train + obj.lambda/2 * w(:)'*w(:);\n\n end\n\n function g = grad(obj, w, indices)\n\n alpha = w' * obj.x_train(:,indices);\n flag = obj.y_train(indices) .* alpha;\n flag(flag<1.0) = 1;\n flag(flag>1.0) = 0;\n\n coeff = flag' .* (1 - obj.y_train(indices)' .* alpha') .* obj.y_train(indices)';\n coeff = coeff';\n coeff = repmat(coeff,[obj.d 1]);\n g = obj.lambda * w - sum(coeff .* obj.x_train(:,indices),2)/length(indices); \n\n end\n\n function g = full_grad(obj, w)\n\n g = obj.grad(w, 1:obj.n_train);\n\n end\n\n function h = hess(obj, w, indices)\n\n alpha = w' * obj.x_train(:,indices);\n flag = obj.y_train(indices) .* alpha;\n flag_indices = flag<1.0;\n\n x_part_new = obj.x_train(:,indices);\n x_part_new = x_part_new(:,flag_indices);\n\n h = obj.lambda * eye(obj.d) + x_part_new * x_part_new'/length(indices); \n end\n\n function hv = hess_vec(obj, w, v, indices)\n\n alpha = w' * obj.x_train(:,indices);\n flag = obj.y_train(indices) .* alpha;\n flag_indices = flag<1.0;\n\n x_part_new = obj.x_train(:,indices);\n x_part_new = x_part_new(:,flag_indices);\n\n hv = obj.lambda * v + (x_part_new * (x_part_new'*v) )/length(indices); \n end\n\n function p = prediction(obj, w)\n\n p = w' * obj.x_test;\n\n class1_idx = p>0;\n class2_idx = p<=0; \n p(class1_idx) = 1;\n p(class2_idx) = -1; \n\n end\n\n function a = accuracy(obj, y_pred)\n\n a = sum(y_pred == obj.y_test) / obj.n_test; \n\n end\n\n function w_opt = calc_solution(obj, maxiter, method)\n \n if nargin < 3\n method = 'lbfgs';\n end \n\n options.max_iter = maxiter;\n options.verbose = true;\n options.tol_optgap = 1.0e-24; \n options.tol_gnorm = 1.0e-16;\n options.step_alg = 'backtracking'; \n \n if strcmp(method, 'sd')\n [w_opt,~] = sd(obj, options);\n elseif strcmp(method, 'cg')\n [w_opt,~] = ncg(obj, options);\n elseif strcmp(method, 'newton')\n options.sub_mode = 'INEXACT'; \n options.step_alg = 'non-backtracking'; \n [w_opt,~] = newton(obj, options);\n else \n options.step_alg = 'backtracking'; \n options.mem_size = 5;\n [w_opt,~] = lbfgs(obj, options); \n end\n end\n end\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/problem/linear_svm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133548753619, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.7202496238760544}} {"text": "function dist = imDistance(varargin)\n%IMDISTANCE Distance map computed from a set of points\n%\n% DIST = imDistance(DIM, POINTS);\n% Create a distance map of the point given by POINTS, in the image with\n% size given by DIM = [NY NX].\n% POINTS is a N-by-2 array of double containing point coordinates\n%\n% DIST = imDistance(LX, LY, POINTS)\n% Specify the position of vertices along each axis. See meshgrid for\n% details.\n%\n% DIST = imDistance(..., N)\n% Use N point randomly and independently created inside the image bounds.\n%\n% DIST = imDistance(..., EDGE)\n% Also specify edge condition. EDGE can be one of:\n% - 'free': regions touching image borders are removed\n% - 'periodic': copy the set of points to simulate periodic set\n% - 'remove': image edges will be set to distance 0, and neighbor pixels\n% set accordingly.\n%\n% TODO: manage different types of distance (now is only euclidian).\n%\n% Example\n% % basic example with integer coordinates\n% img = imDistance([100 100], [10 10;90 90;90 10;10 90;50 50]);\n% imshow(img, [0 max(img(:))]);\n%\n% % specify floating coordinates, with periodic edge conditions\n% lx = 1:100;\n% ly = 1:100;\n% pts = [10.2 10.3;90.4 90.5; 10.8 90.8;50.1 50.0]\n% img = imDistance(lx, ly, pts, 'periodic');\n% figure; imshow(img, [0 max(img(:))]);\n%\n\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 16/06/2004.\n%\n\n% HISTORY\n% 28/06/2004 use faster algorithm\n% 22/05/2006 allocate d1 and d2 only once (should be faster)\n% 29/05/2009 add possibility to specify grid with meshgrid-like syntax\n\n\n%% Extract input arguments\n\n% default parameters values\npoints = []; % points array\nN = 20; % default number of germs\nedgecond = 'free'; % edge condition\nlx = 1:100;\nly = 1:100;\n\n% extraction of image dimensions\nif ~isempty(varargin)\n var = varargin{1};\n if size(var, 1) > 1 && size(var, 2) > 2\n % case of a 2x3 matrix with starting position, increment, end\n % position for each coordinate\n lx = var(1,1):var(1,2):var(1,3);\n ly = var(2,1):var(2,2):var(2,3);\n varargin(1) = [];\n \n elseif size(var, 1) == 1 && size(var, 2) == 2\n % first argument contains the size of the output image\n lx = 1:var(2);\n ly = 1:var(1);\n varargin(1) = [];\n \n elseif length(varargin) > 1\n % first and second arguments contain vector for each coordinate\n % respectively\n lx = varargin{1};\n ly = varargin{2};\n varargin(1:2) = [];\n \n else\n error('wrong input arguments in imDistance');\n end\nend\n\n% extraction of points, or number of points\nif ~isempty(varargin)\n var = varargin{1};\n\n if length(var)>1 % use an array of germs\n points = var;\n else % get number of germs\n N = var;\n end\n \n varargin(1) = [];\nend\n\n% extraction of edge condition\nif ~isempty(varargin)\n edgecond = varargin{1};\nend\n\n\n%% Initialisations\n\n% create array of points, if does not exist\nif isempty(points)\n % generation of germs array\n points = zeros(N, 2);\n for i = 1:N\n points(i,1) = rand * lx(end) + lx(1);\n points(i,2) = rand * ly(end) + ly(1);\n end \nend\n\n% number of points\nN = size(points, 1);\n\n% size of output image\nNx = length(lx);\nNy = length(ly);\n\n\n% create periodic conditions if needed\nif strcmp(edgecond, 'periodic')\n % compute size of the box\n wx = lx(end) + lx(2) - 2*lx(1);\n wy = ly(end) + ly(2) - 2*ly(1);\n \n points = repmat(points, [9 1]);\n for i = [1 2 3]\n points((i-1)*N+1:i*N, 1) = points((i-1)*N+1:i*N, 1) - wx;\n end\n\n for i = [7 8 9]\n points((i-1)*N+1:i*N, 1) = points((i-1)*N+1:i*N, 1) + wx;\n end\n\n for i = [1 4 7]\n points((i-1)*N+1:i*N, 2) = points((i-1)*N+1:i*N, 2) - wy;\n end\n\n for i = [3 6 9]\n points((i-1)*N+1:i*N, 2) = points((i-1)*N+1:i*N, 2) + wy;\n end \n \n % re-compute number of points\n N = size(points, 1);\nend\n\n\n%% Generation of distance function\n\n% allocate memory\ndist = Nx * Ny * ones([Ny Nx]);\n\n% pixels coordinates\n[x, y] = meshgrid(lx, ly);\n\n% update distance for each point\nfor p = 1:N\n dist = min(dist, hypot(x - points(p,1), y - points(p,2)));\nend\n\n%old algorithm, slower\n%dist = zeros(dim);\n%for i=1:dim(1)\n %disp (int2str(x));\n %for j=1:dim(2)\n %mat = points - ones(N,1)*[i j];\n %dist(i, j) = min(sqrt(diag(mat*mat')));\n % end\n %end\n\n\n%% Optional processing for borders\n\n% distance from borders of image\nif strcmp(edgecond, 'remove')\n d1 = min(repmat((1:Ny)'-1, [1 Nx]), repmat((Ny:-1:1)'-1, [1 Nx]));\n dist = min(dist, d1);\n d1 = min(repmat((1:Nx)-1, [Ny 1]), repmat((Nx:-1:1)-1, [Ny 1]));\n dist = min(dist, d1);\nend\n\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/imFilters/imDistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7202042250658688}} {"text": "function [lambda_vec, error_train, error_val] = ...\n validationCurve(X, y, Xval, yval)\n%VALIDATIONCURVE Generate the train and validation errors needed to\n%plot a validation curve that we can use to select lambda\n% [lambda_vec, error_train, error_val] = ...\n% VALIDATIONCURVE(X, y, Xval, yval) returns the train\n% and validation errors (in error_train, error_val)\n% for different values of lambda. You are given the training set (X,\n% y) and validation set (Xval, yval).\n%\n\n% Selected values of lambda (you should not change this)\nlambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';\n\n% You need to return these variables correctly.\nerror_train = zeros(length(lambda_vec), 1);\nerror_val = zeros(length(lambda_vec), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return training errors in\n% error_train and the validation errors in error_val. The\n% vector lambda_vec contains the different lambda parameters\n% to use for each calculation of the errors, i.e,\n% error_train(i), and error_val(i) should give\n% you the errors obtained after training with\n% lambda = lambda_vec(i)\n%\n% Note: You can loop over lambda_vec with the following:\n%\n% for i = 1:length(lambda_vec)\n% lambda = lambda_vec(i);\n% % Compute train / val errors when training linear\n% % regression with regularization parameter lambda\n% % You should store the result in error_train(i)\n% % and error_val(i)\n% ....\n%\n% end\n%\n%\n\n\nfor i = 1:length(lambda_vec)\n lambda = lambda_vec(i);\n\n % Compute train / val errors when training linear\n theta = trainLinearReg(X, y, lambda);\n\n error_train(i) = linearRegCostFunction(X, y, theta, 0);\n error_val(i) = linearRegCostFunction(Xval, yval, theta, 0);\nend\n\n\n% =========================================================================\n\nend\n", "meta": {"author": "benoitvallon", "repo": "coursera-machine-learning", "sha": "74ec09a5072eb5f3fec942fee45076e4f05b35af", "save_path": "github-repos/MATLAB/benoitvallon-coursera-machine-learning", "path": "github-repos/MATLAB/benoitvallon-coursera-machine-learning/coursera-machine-learning-74ec09a5072eb5f3fec942fee45076e4f05b35af/machine-learning-ex5/ex5/validationCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.7202042234770931}} {"text": "% Draw various graphs obtained from the same point set.\n%\n% output = drawSampleGraphs(input)\n%\n% Example\n% drawSampleGraphs\n%\n% See also\n%\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% INRAE - BIA Research Unit - BIBS Platform (Nantes)\n% Created: 2020-06-04, using Matlab 9.8.0.1323502 (R2020a)\n% Copyright 2020 INRAE.\n\n%% Read input points\n\n% read a set of 16 points within a [10 28]^2 bounding box\npts = load('sedgewick_points.txt');\n\n% display the sample points\nfigure; axis equal; axis([10 28 10 28]); hold on;\ndrawPoint(pts, 'bo');\ntitle('Sample points');\n\n\n%% Delaunay Graph\n\n% compute the graph\n[nodes, edges] = delaunayGraph(pts);\n\n% display the sample points\nfigure; axis equal; axis([10 28 10 28]); hold on;\ndrawPoint(pts, 'bo');\n\n% display the graph\ndrawGraphEdges(nodes, edges);\ntitle('Delaunay Graph');\n\n\n%% Minimal Spanning Tree\n\n% compute the graph\nedges = euclideanMST(pts);\n\n% display the sample points\nfigure; axis equal; axis([10 28 10 28]); hold on;\ndrawPoint(pts, 'bo');\n\n% display the graph\ndrawGraphEdges(pts, edges);\ntitle('Minimal Spanning Tree');\n\n\n%% Relative Neighborhood Graph\n\n% compute the graph\nedges = relativeNeighborhoodGraph(pts);\n\n% display the sample points\nfigure; axis equal; axis([10 28 10 28]); hold on;\ndrawPoint(pts, 'bo');\n\n% display the graph\ndrawGraphEdges(pts, edges);\ntitle('Relative Neighborhood Graph');\n\n\n%% Gabriel Graph\n\n% compute the graph\nedges = gabrielGraph(pts);\n\n% display the sample points\nfigure; axis equal; axis([10 28 10 28]); hold on;\ndrawPoint(pts, 'bo');\n\n% display the graph\ndrawGraphEdges(pts, edges);\ntitle('Gabriel Graph');\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/demos/graphs/drawSampleGraphs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8221891283434877, "lm_q1q2_score": 0.7200625432775906}} {"text": "function [fx,dF_dX,dF_dTheta] = f_doubleWell(Xt,Theta,ut,inF)\n% damped double Well Lyapunov evolution function\n% function [f,J] = f_doubleWell(t,x,theta)\n%\n% This function computes the evolution function that comes from a .\n% IN:\n% - t: time index (not used here)\n% - x: the current state of the system\n% - theta: a 2x1 vector parameter (containing the position of the two\n% wells.\n% OUT:\n% - f: the current value of the evolution function\n% - J: the jacobbian of the system\n\ndeltat = inF.deltat;\n\na = Theta(1);\nb = Theta(2);\nk = Theta(3);\nx1 = Xt(1);\nx2 = Xt(2);\n\n\nf = [ x2 ; -2*(x1-a)*(x1-b)^2-2*(x1-a)^2*(x1-b)-k.*x2 ];\nJ = [ 0 1\n -2*(x1-b)^2-8*(x1-a)*(x1-b)-2*(x1-a)^2 -k ];\n\n\nfx = deltat.*f + Xt;\ndF_dX = deltat.*J' + eye(2);\ndF_dTheta = deltat.*[ 0 2*(x1-b)^2+4*(x1-a)*(x1-b)\n 0 4*(x1-a)*(x1-b)+2*(x1-a)^2\n 0 -x2 ];\n\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/demos/_models/f_doubleWell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966762263736, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7200293795937429}} {"text": "function Speciation\n% Speciation \n% using MATLAB \n%\n% $Ekkehard Holzbecher $Date: 2006/05/03 $\n%--------------------------------------------------------------------------\ntoll = 1.e-15; % tolerance\nnmax = 50; % max. no. of iterations \nSe = [-1 -1 1]; % reaction matrix\nlogc = [1.e-10; 1.e-10; 0]; % initial guess (log)\nlogK = [-0.93]; % equilibrium constants (log)\nlogu = [-0.301; 0]; % total concentrations (log)\n \nln10 = 2.3026;\nn=size(Se,1); m=size(Se,2);\nS1 = Se(:,1:m-n); \nS2 = Se(:,m-n+1:m); \nS1star = -S2\\S1; \nU = [eye(m-n),S1star'];\n\nc=exp(ln10*logc);\nu(1:m-n,1) = exp(ln10*logu); \nerr = toll+1; nit = 0;\nwhile (nit < nmax & err > toll),\n nit = nit+1;\n F = [U*c-u; Se*log10(c)-logK];\n DF = [U; Se*diag((1/ln10)./c)]; \n dc = -DF\\F; \n cn = max(c+dc,0.005*abs(c));\n err = max(abs(cn-c));\n c = cn;\n logc = log10(c);\nend\ndisplay (['Species concentrations obtained after ' num2str(nit) ' iterations:']);\nc\nexp(ln10*logK)-c(3)/c(1)/c(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/15646-environmental-modeling/Speciation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.720015760963087}} {"text": "function Ri = get_Ri(r_i, theta_i, sigma_r, sigma_theta)\n% computes the covariance of the point p_i = r_i*[cos(theta_i); sin(theta_i)\n% in cartesian coordinates\n\n\n% first we compute the matrix square root of R, which consists of the\n% Jacobian * sqrt(R_in_polar_coords)\nRi = [cos(theta_i) -r_i*sin(theta_i)\n sin(theta_i) r_i*cos(theta_i) ] * diag([sigma_r sigma_theta]); \n\n% and then we get the entire Ri \nRi = Ri * Ri';", "meta": {"author": "rpng", "repo": "ocekf-slam", "sha": "01b5eeeee429e7767888665d4566ab3549fa93e0", "save_path": "github-repos/MATLAB/rpng-ocekf-slam", "path": "github-repos/MATLAB/rpng-ocekf-slam/ocekf-slam-01b5eeeee429e7767888665d4566ab3549fa93e0/get_Ri.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7199640061394587}} {"text": "function [Xco Tau MT] = HC_explicit_nh (Tin,TC,DE,HC,SE,DI,TS,TT,TBC,BC)\n%\n% DESCRIPTION:\n%\n% Explicit numerical method for one dimensional unsteady state \n% heat transfer by conduction for non-homogenous material\n%\n% Basic PDE equation :\n%\n% dT d^2 T \n% ------ = TD ------ for 0 < x < DI and tau > 0 \n% dtau dx^2\n%\n% Principle of method :\n% ^\n% time |\n% | m-1 m m+1\n% | | | |\n% | ---+------x------+----- p+1\n% | dtau | | |\n% | ---o------o------o----- p \n% | dtau | | |\n% | ---+------+------+----- p-1\n% | | dx | dx |\n% |\n% +--------------------------------> \n% x \n% Space description:\n% DI\n% |<------------------------------>|\n% + + + + + . . . + + \n% 1 2 3 4 5 n-1 n\n% |<->|\n% SE\n%\n% Difference equation :\n%\n% T(m,p+1) - T(m,p) TD\n% ------------------- = ------- (T(m-1,p) - 2.T(m,p) + T(m+1,p))\n% TS SE.SE\n% \n% TD.TS\n% M = -------- <= 0,5\n% SE.SE \n%\n% T(m,p+1) = M.T(m-1,p) + (1 - 2.M)T(m,p) + M.T(m+1,p)\n% \n% T(m,p+1) = M(m-1).T(m-1,p) + (1 - (M(m-1)+M(m)))T(m,p) + M(m).T(m+1,p)\n% for m <2;n-1>\n%\n% First-type boundary condition:\n% - temperatures T(1,p) and T(n,p) are given\n% - temperatures T(m,p) for m = 2, n-1 :\n% T(m,p+1) = M (T(m-1,p) + T(m+1,p)) + T(m,p).(1 - 2.M)\n%\n% Second-type boundary condition:\n% - heat flux iQ(1,p) and iQ(n,p) are given\n% - temperature T(1,p) :\n% SE\n% T(1,p) = T(2,p-1) - iQ(1,p) ---- \n% TC\n% - temperature T(n,p) :\n% SE\n% T(end,p) = T(n-1,p-1) - iQ(n,p) ---- \n% TC \n% - temperatures T(m,p) for m = 2, n-1 :\n% T(m,p+1) = M (T(m-1,p) + T(m+1,p)) + T(m,p).(1 - 2.M)\n%\n%\n% INPUTS:\n%\n% Tin - initialization temperatures [ K ] \n% TC - thermal conductivity [ W.m^-1.K^-1 ]\n% DE - density [ kg.m^-3 ]\n% HC - specific heat capacity [ kg.m^-3 ]\n% SE - size of element [ m ]\n% DI - distance [ m ]\n% TS - time step [ s ]\n% TT - total time of simulation [ s ]\n% TBC - type of boundary condition \n% (1 = first-type, 2 = second-type) [ - ]\n% BC - boundary condition \n% - first-type : BC(1) = T(1), BC(2) = T(n) [ K ]\n% - second-type: BC(1) = iQ(1), BC(2) = iQ(n) [ W.m^-2 ]\n% \n% OUTPUTS:\n%\n% Xco - vector of X coordinate [ m ]\n% Tau - vector of time [ s ]\n% MT - matrix of temperatures [ K ]\n% \n% AUXILIARY VARIABLE:\n%\n% r - time step number [ - ]\n% n - space point number [ - ] \n% TD - thermal diffusivity [ m^2.m^-1 ]\n% M - modul (Fourier number) [ - ]\n%\n% Copyright (C) 2013, Technical University of Kosice\n% Author : Zecova Monika, Terpak Jan\n% Revision: 27.08.2013\n%\n r = round(TT/TS) + 1; \n n = round(DI/SE) + 1; \n \n Xco = 0.0:SE:DI; \n Tau = 0.0:TS:TT; \n MT = zeros(r,n);\n MT(1,:) = Tin;\n \n for j=2:r\n [T] = explicit_nh (Tin,TC,DE,HC,SE,TS,TBC,BC);\n Tin = T; \n MT(j,:) = Tin; \n end\n \nend\nfunction [T] = explicit_nh (Tin,TC,DE,HC,SE,TS,TBC,BC)\n\n n = length(Tin);\n TD = zeros(1,n-1);\n for i=1:n-1\n TD(i)= TC(i)/(DE(i)*HC(i));\n end\n M = TD*TS/(SE*SE);\n \n T = Tin;\n \n if (M <= 0.5)\n \n if TBC == 1\n T(1) = BC(1);\n T(end) = BC(2);\n end\n \n if TBC == 2\n T(1) = T(2) - BC(1)*SE/TC(1);\n T(end) = T(end-1) - BC(2)*SE/TC(end);\n end \n \n for m=2:length(Tin)-1\n T(m) = M(m-1)*Tin(m-1) + (1 - (M(m-1)+M(m)))*Tin(m) + M(m)*Tin(m+1);\n end \n else\n disp(['error: unstable solution, M must be <= 0,5; M = ' num2str(M)]);\n end\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43146-heat-conduction-toolbox/HeatConductionToolbox/HC_explicit_nh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7199290945840019}} {"text": "function isInside = bst_intriangle(A, B, C, P)\n% BST_INTRIANGLE: Test if the orthogonal projection of points P on a triangle (A,B,C) are inside the triangle.\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2013\n\n% Compute vectors \nv0 = repmat(C - A, size(P,1), 1);\nv1 = repmat(B - A, size(P,1), 1);\nv2 = bst_bsxfun(@minus, P, A);\n\n% Compute dot products\ndot00 = sum(v0.^2, 2);\ndot01 = sum(v0.*v1, 2);\ndot02 = sum(v0.*v2, 2);\ndot11 = sum(v1.^2, 2);\ndot12 = sum(v1.*v2, 2);\n\n% Compute barycentric coordinates\ninvDenom = 1 ./ (dot00 .* dot11 - dot01 .* dot01);\nu = (dot11 .* dot02 - dot01 .* dot12) .* invDenom;\nv = (dot00 .* dot12 - dot01 .* dot02) .* invDenom;\n\n% Check if point is in triangle\nisInside = (u >= 0) & (v >= 0) & (u + v < 1);\n\n\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/math/bst_intriangle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213880824789, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.7199193129034661}} {"text": "function value = r8_si ( x )\n\n%*****************************************************************************80\n%\n%% R8_SI computes an approximation to the value of the sine integral.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2009\n%\n% Author:\n%\n% Original FORTRAN77 version by Wayne Fullerton.\n% MATLAB version by John Burkardt.\n%\n% Parameters:\n%\n% Input, real X, the argument of the sine integral.\n%\n% Output, real VALUE, the value of the sine integral.\n%\n nsics = 12;\n sics = [ ...\n -0.1315646598184841929, -0.2776578526973601892, ...\n 0.0354414054866659180, -0.0025631631447933978, ...\n 0.0001162365390497009, -0.0000035904327241606, ...\n 0.0000000802342123706, -0.0000000013562997693, ...\n 0.0000000000179440722, -0.0000000000001908387, ...\n 0.0000000000000016670, -0.0000000000000000122 ];\n\n eta = 0.1 * eps;\n nsi = inits ( sics, nsics, 0.1 * eps );\n\n i = find ( abs ( x ) < sqrt ( eps ) );\n value(i) = x(i);\n\n j = find ( abs ( x ) <= 4.0 );\n value(j) = csevl ( ( x(j).^2 - 8.0 ) * 0.125, sics, nsi );\n value(j) = x(j) .* ( 0.75 + value(j) );\n\n k = find ( 4.0 < abs ( x ) );\n [ f, g ] = r89sifg ( abs ( x(k) ) );\n value(k) = 0.5 * pi - f .* cos ( abs ( x(k) ) ) - g .* sin ( x(k) );\n l = find ( x(k) < 0.0 );\n value(l) = - value(l);\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_int/r8_si.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.7199193042985047}} {"text": "function result = square_unit_sum ( func, norder, xtab, ytab, weight )\n\n%*****************************************************************************80\n%\n%% SQUARE_UNIT_SUM carries out a quadrature rule over the unit square.\n%\n% Integration region:\n%\n% Points (X,Y) such that\n%\n% -1 <= X <= 1, and\n% -1 <= Y <= 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the function to be\n% integrated. The user must declare the name an EXTERNAL\n% parameter in the calling program, pass the name of the\n% function in FUNC, and write a function of the form\n% function value = func ( x, y )\n% which evaluates the function at the point (X,Y).\n%\n% Input, integer NORDER, the order of the rule.\n%\n% Input, real XTAB(NORDER), YTAB(NORDER), the abscissas of\n% the rule.\n%\n% Input, real WEIGHT(NORDER), the weights of the rule.\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n quad = 0.0E+00;\n for i = 1 : norder\n quad = quad + weight(i) * feval ( func, xtab(i), ytab(i) ) / 4.0E+00;\n end\n\n volume = 1.0E+00;\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/square_unit_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7199193022129505}} {"text": "% NMFLAB for Signal Processing written by A. Cichocki and R. Zdunek \n% in cooperation with other members of Laboratory for Advanced Brain Signal\n% Processing, BSI, RIKEN, Saitama, JAPAN\n\nfunction [x,grad_x,k] = nmf_proj_grad(b,A,x,tol,no_iter,beta_dec,loss_fun,beta)\n\n% Projected Gradient Algorithm based on the Armijo rule\n%\n% [x, grad_x, k]=nmf_proj_grad(b,A,x,tol,no_iter,beta_dec,loss_fun,beta) finds\n% such x that solves the equation Ax = b.\n%\n% INPUTS:\n% b - data matrix of dimension [m by T]\n% A - fixed matrix of dimension [m by r]\n% x - initial guess\n% tol - tolerance\n% no_iter - maximum number of iterations\n% beta_dec - multiplier of learning rate in descent gradient direction\n% loss_fun - index for the loss function (1--4)\n% beta - parameter \"alpha\" in the Amari alpha-divergence\n% \n% OUTPUTS:\n% x - estimated matrix of dimension [r by T]\n% grad_x - gradient of x\n% k - number of performed iterations \n%\n% #########################################################################\n\nif beta == 0\n loss_fun = 2;\nend\n \nsigma = 0.01; alpha = 1; kinc = 1;\n\nfor k=1:no_iter \n \n switch loss_fun \n \n case 1 % Frobenius\n \n res = b - A*x; \n grad_x = -A'*res;\n F = .5*norm(res,'fro')^2;\n lower_bound = 0;\n \n case 2 % KL\n \n bx = A*x; \n grad_x = A'*(1 - b./(bx + eps));\n F = sum(sum(b.*log(b./(bx + eps)) + bx - b));\n lower_bound = 0.1;\n \n case 3 % Dual KL\n \n bx = A*x; \n grad_x = A'*log(bx./b);\n F = sum(sum(bx.*log(bx./b) + b - bx));\n lower_bound = 1E-4;\n \n case 4 % Amari alpha divergence\n \n bx = A*x; \n grad_x = (1/beta)*A'*(1 - (b./bx).^beta);\n F = sum(sum(b.*((b./bx).^(beta - 1) - 1)/(beta^2 - beta) + (bx - b)/beta));\n lower_bound = 1E-2;\n \n end % switch \n \n \n tol_grad = norm(grad_x(grad_x < lower_bound | x > lower_bound));\n if tol_grad < tol,\n break\n end\n\n% alpha = 1;\n s = 0;\n \n% search step size \nwhile (alpha > 1E-15) & (alpha < 1E8)\n \n s = s + 1; \n \n xn = max(x - alpha*grad_x,lower_bound); \n delta = xn-x; \n \n switch loss_fun \n\n case 1 % Frobenius\n \n Fn = .5*norm(b - A*xn,'fro')^2;\n \n case 2 % KL\n \n bx = A*xn; \n Fn = sum(sum(b.*log(b./(bx + eps)) + bx - b));\n \n case 3 % Dual KL\n \n bx = A*xn; \n Fn = sum(sum(bx.*log(bx./b) + b - bx));\n \n case 4 % Amari alpha divergence\n \n bx = A*xn; \n Fn = sum(sum(b.*((b./bx).^(beta - 1) - 1)/(beta^2 - beta) + (bx - b)/beta));\n \n end % switch \n \n cond_alpha = ((Fn - F) <= sigma*grad_x(:)'*delta(:));\n \n if cond_alpha | (xn == x)\n % Increase\n if ~kinc & (s > 1), x = xn; break; end\n alpha = alpha/beta_dec;\n kinc = 1; xp = xn;\n else\n % Decrease\n if kinc & (s > 1), x = xp; alpha = alpha*beta_dec; break; end\n alpha = alpha*beta_dec;\n kinc = 0;\n end\n \n \nend % while\n \nend % for k\n% \n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/NMFLABSP_ver1.2/nmf_proj_grad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7199192978316462}} {"text": "function [E1 E2] = cao_deneme(x,tao,mmax)\n%x : time series\n%tao : time delay\n%mmax : maximum embedding dimension\n%reference:Cao, L. (1997), ``Practical method for determining the minimum\n%embedding dimension of a scalar time series'', Physcai D, 110, pp. 43-50. \n%author:\"Merve Kizilkaya\"\nN=length(x);\nfor m=1:mmax\n M=N-m*tao;\n Y=psr_deneme(x,m,tao,M);\n for n=1:M\n y0=ones(M,1)*Y(n,:);\n distance=max(abs(Y-y0),[],2);\n [neardis nearpos]=sort(distance);\n \n newpoint=[Y(n,:) x(n+m*tao)];\n newneig=[Y(nearpos(2),:) x(nearpos(2)+m*tao)];\n R1=max(abs(newpoint-newneig),[],2);\n \n a(n)=R1/neardis(2);\n d(n)=abs(x(n+m*tao)-x(nearpos(2)+m*tao));\n end\n E(m)=sum(a)/M;\n Ey(m)=sum(d)/M;\nend\nfigure\nE1=E(2:end)./E(1:end-1);\nE2=Ey(2:end)./Ey(1:end-1);\nplot(1:length(E1),E1,'k')\nhold on\nplot(1:length(E2),E2)\ngrid on\ntitle('embedding dimension with cao method')\nlegend('E1','E2',4);\n\nfunction Y=psr_deneme(x,m,tao,npoint)\n%Phase space reconstruction\n%x : time series \n%m : embedding dimension\n%tao : time delay\n%npoint : total number of reconstructed vectors\n%Y : M x m matrix\n% author:\"Merve Kizilkaya\"\nN=length(x);\nif nargin == 4\n M=npoint;\nelse\n M=N-(m-1)*tao;\nend\n\nY=zeros(M,m); \n\nfor i=1:m\n Y(:,i)=x((1:M)+(i-1)*tao)';\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/36935-minimum-embedding-dimension/cao_deneme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7199192935554398}} {"text": "function [Ax,Ay,b,K] = convexhullConvex(varargin)\n% Two lower bounds from tangents\n% y > f(xL) + (x-xL)*df(xL)\n% y > f(xU) + (x-xL)*df(xU)\n% Upper bound from connecting extreme points\n% y < f(xU)(x-xL)/(xU-xL) + f(xL)(xU-x)/(xU-xL)\n% can be written as\n% Ax*x + Ay*y <= b\n\nif rem(nargin,3)\n error('The convex hull generator assumes n triplets (x,f,df).')\nend\nm = nargin/3;\nx = [varargin{(1:m)}]';\nf = [varargin{(1:m)+m}]';\ndf = [varargin{(1:m)+2*m}]';\n\nif df(1) == df(end)\n % This is a linear function\n % return y = f(1) + df*(x-x(1))\n Ax = df(1);\n Ay = -1;\n b = df(1)*x(1)-f(1);\n K.f = 1;\n K.l = 0;\n return\nend\n\nif all(diff(x)>=0) | all(diff(x(~isinf(x))))>=0 % Support [0 inf inf]\n Ay = [-ones(m,1);1];\n b = [-f + x.*df; -f(end)*x(1)/(x(end)-x(1)) + f(1)*x(end)/(x(end)-x(1))];\n Ax = [df;-f(end)/(x(end)-x(1)) + f(1)/(x(end)-x(1))];\n \n % Don't use ill-conditioned cuts\n if df(1)<-1000\n Ax(1)=[];\n Ay(1) = [];\n b(1) = [];\n end\n if df(end-1)>1000\n Ax(end-1)=[];\n Ay(end-1) = [];\n b(end-1) = [];\n end \nelse\n Ax = [];\n Ay = [];\n b = [];\nend\nj = find(any(isnan([Ax Ay b]),2));\nif ~isempty(j)\n b(j)=[];\n Ax(j,:)=[];\n Ay(j,:)=[];\nend\nK.f = 0;\nK.l = length(b);\nif 0\n sdpvar x y;plot(Ax*x+Ay*y <= b);\nend\n\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/modules/global/convexhullConvex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.7199142446241449}} {"text": "% Combined wire sizing and spacing\n% Section 5.5, L. Vandenberghe, S. Boyd, and A. El Gamal\n% \"Optimizing dominant time constant in RC circuits\"\n% Original by Lieven Vandenberghe\n% Adapted for CVX by Joelle Skaf - 11/27/05\n% Modified by Michael Grant - 3/8/06\n%\n% The problem is to determine the optimal sizes of interconnect wires and\n% the optimal distances between them. We will consider an example with 3\n% wires, each consisting of 5 segments (see paper, fig.21). The variables\n% are the widths wij , and the distances s1 and s2 between the wires.\n% The difference with the models used in other scripts is that we include a\n% parasitic capacitance between the wires.\n% The objective is to minimize the total width s1+s2.\n% The problem can be formulated with the following SDP:\n% mimimize s1 + s2\n% s.t. Tmax*G(w11,..,w35)-C(w11,..,w35,t11,..,t23) >=0\n% 1/t1j <= s1 - w1j - 0.5*w2j , j = 1,..,5\n% 1/t2j <= s2 - w3j - 0.5*w2j , j = 1,..,5\n% 0 <= tij <= 1 , i = 1,2 , j = 1,..,5\n% t1 >=0, t2 >= 0, s1 >=smin, s2>=smin\n% 0 <= wij <= wmax\n% the 2nd and 3rd constraints are nonlinear convex constraints that can be\n% cast as 3 x 3-LMIs (Please refer to the paper for more details).\n\n%\n% Circuit parameters\n%\n\nn = 6; % number of nodes per wire\nN = 3*n; % total number of nodes\nm = n-1; % number of segments per wire\nalpha = 1; % conductance per segment is is alpha*size\nbeta = 0.5; % capacitance per segment is twice beta*size\ngamma = 2; % coupling capacitance is twice gamma*distance\nG0 = 100; % source conductance\nC0 = [10,20,30]; % loads of first, second, third wires\nwmin = 0.1; % minimum width\nwmax = 2.0; % maximum width\nsmin = 1.0; % minimum distance between wires\nsmax = 50; % upper bound on s1 and s2 (meant to be inactive)\n\n%\n% Construct the capacitance and conductance matrices\n% C(x) = C0 + w11 * C1 + w21 * C2 + ...\n% G(x) = G0 + w11 * G1 + w21 * G2 + ...\n% and we assemble the coefficient matrices together as follows:\n% CC = [ C0(:) C1(:) C2(:) ... ]\n% GG = [ G0(:) G1(:) G2(:) ... ]\n%\n\nCC = zeros(N,N,5*m+1);\nGG = zeros(N,N,3*m+1);\nfor w = 0 : 2,\n % Constant terms\n CC(w*n+n,w*n+n,1) = C0(w+1);\n GG(w*n+1,w*n+1,1) = G0;\n for i = 1 : m,\n % capacitances to ground\n CC(w*n+[i,i+1],w*n+[i,i+1],w*m+i+1) = beta*[1,0;0,1];\n if w < 2,\n % coupling capacitors\n CC(w*n+[i, n+i ],w*n+[i, n+i ],(w+3)*m+i+1) = gamma*[1,-1;-1,1];\n CC(w*n+[i+1,n+i+1],w*n+[i+1,n+i+1],(w+3)*m+i+1) = gamma*[1,-1;-1,1];\n end\n % segment conductances\n GG(w*n+[i,i+1],w*n+[i,i+1],w*m+i+1) = alpha*[1,-1;-1,1];\n end\nend\n% Reshape for Matlab use\nCC = reshape(CC,N*N,5*m+1);\nGG = reshape(GG,N*N,3*m+1);\n\n%\n% Compute points the tradeoff curve and the two desired points\n%\n\nnpts = 50;\ndelays = linspace( 85, 200, npts );\nxdelays = [ 130, 90 ];\nxnpts = length(xdelays);\nareas = zeros(1,npts);\nxareas = zeros(1,xnpts);\nfor j = 1 : npts + xnpts,\n\n if j > npts,\n xj = j - npts;\n delay = xdelays(xj);\n disp( sprintf( 'Particular solution %d of %d (Tmax = %g)', xj, xnpts, delay ) );\n else,\n delay = delays(j);\n disp( sprintf( 'Point %d of %d on the tradeoff curve (Tmax = %g)', j, npts, delay ) );\n end\n\n %\n % Construct and solve the convex model\n %\n\n cvx_begin sdp quiet\n variables w(m,3) t(m,2) s(1,2)\n variable G(N,N) symmetric\n variable C(N,N) symmetric\n minimize( sum(s) )\n subject to\n G == reshape( GG * [ 1 ; w(:) ], N, N );\n C == reshape( CC * [ 1 ; w(:) ; t(:) ], N, N );\n delay * G - C >= 0;\n wmin <= w(:) <= wmax;\n t( : ) <= 1 / smin;\n s( : ) <= smax;\n inv_pos( t(:,1) ) <= s(1) - w(:,1) - 0.5 * w(:,2);\n inv_pos( t(:,2) ) <= s(2) - w(:,3) - 0.5 * w(:,2);\n cvx_end\n ss = cvx_optval;\n\n if j <= npts,\n areas(j) = ss;\n else,\n xareas(xj) = ss;\n\n %\n % Draw the wires\n %\n\n figure(4*xj-2);\n m2 = 2 * m;\n x1 = reshape( [ 1 : m ; 1 : m ], 1, m2 );\n x2 = x1( 1, end : -1 : 1 );\n y = [ ss*ones(m2,1), s(2) + 0.5*w(x1,2), zeros(m2,1) ; ...\n ss-w(x2,1), s(2) - 0.5*w(x2,2), w(x2,3) ; ...\n ss, s(2) + 0.5*w(1,2), 0 ];\n x1 = reshape( [ 0 : m - 1 ; 1 : m ], m2, 1 );\n x2 = x1( end : -1 : 1, 1 );\n x = [ x1 ; x2 ; 0 ];\n hold off;\n fill( x, y, 0.9 * ones(size(y)) );\n hold on\n plot( x, y, '-' );\n axis( [-0.1, m+0.1,-0.1, ss+0.1]);\n colormap(gray);\n caxis([-1,1])\n title(sprintf('Solution (%d), Tmax = %g',xj,delay));\n\n %\n % Build the state space models and plot step responses\n %\n\n A = -inv(C)*G;\n T = linspace(0,2*delay,1000);\n B = -A * kron( eye(3), ones(n,1) );\n for inp = 1 : 3,\n figure(4*xj-2+inp);\n Y1 = simple_step(A,B(:,inp),T(2),length(T));\n hold off;\n plot(T,Y1([n,2*n,3*n],:),'-');\n hold on;\n text(T(1000),Y1( n,1000),'v1');\n text(T(1000),Y1(2*n,1000),'v2');\n text(T(1000),Y1(3*n,1000),'v3');\n axis([0 2*delay -0.1 1.1]);\n % show dominant time constant\n plot(delay*[1;1], [-0.1;1.1], '--');\n title(sprintf('Solution (%d), Tmax = %g, step applied to wire %d',xj,delay,inp));\n end\n\n end\n\nend\n\n%\n% Plot the tradeoff curve\n%\n\nfigure(1);\nind = isfinite(areas);\nplot(areas(ind), delays(ind));\nxlabel('total width s_1 + s_2');\nylabel('dominant time constant');\ntitle('Width-delay tradeoff curve')\nhold on;\nfor k = 1 : xnpts,\n text( xareas(k), xdelays(k), sprintf( '(%d)', k ) );\nend\n\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/circuit_design/wire_sizing_spacing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642906, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7199142373763036}} {"text": "function K = covMaternard(d, hyp, x, z, i)\n\n% Matern covariance function with nu = d/2 and with Automatic Relevance\n% Determination (ARD) distance measure. For d=1 the function is also known as\n% the exponential covariance function or the Ornstein-Uhlenbeck covariance \n% in 1d. The covariance function is:\n%\n% k(x^p,x^q) = sf^2 * f( sqrt(d)*r ) * exp(-sqrt(d)*r)\n%\n% with f(t)=1 for d=1, f(t)=1+t for d=3 and f(t)=1+t+t²/3 for d=5.\n% Here r is the distance sqrt((x^p-x^q)'*inv(P)*(x^p-x^q)), where the P matrix\n% is diagonal with ARD parameters ell_1^2,...,ell_D^2, where D is the dimension\n% of the input space and sf2 is the signal variance. The hyperparameters are:\n%\n% hyp = [ log(ell_1)\n% log(ell_2)\n% ..\n% log(ell_D)\n% log(sf) ]\n%\n% Copyright (c) by Hannes Nickisch, 2013-10-13.\n%\n% See also COVFUNCTIONS.M.\n\nif nargin<3, K = '(D+1)'; return; end % report number of parameters\nif nargin<4, z = []; end % make sure, z exists\nxeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode\n\n[n,D] = size(x);\nell = exp(hyp(1:D));\nsf2 = exp(2*hyp(D+1));\nif all(d~=[1,3,5]), error('only 1, 3 and 5 allowed for d'), end % degree\n\nswitch d\n case 1, f = @(t) 1; df = @(t) 1./t; % df(t) = (f(t)-f'(t))/t\n case 3, f = @(t) 1 + t; df = @(t) 1;\n case 5, f = @(t) 1 + t.*(1+t/3); df = @(t) (1+t)/3;\nend\n m = @(t,f) f(t).*exp(-t); dm = @(t,f) df(t).*exp(-t);\n\n% precompute distances\nif dg % vector kxx\n K = zeros(size(x,1),1);\nelse\n if xeqz % symmetric matrix Kxx\n K = sq_dist(diag(sqrt(d)./ell)*x');\n else % cross covariances Kxz\n K = sq_dist(diag(sqrt(d)./ell)*x',diag(sqrt(d)./ell)*z');\n end\nend\n\nif nargin<5 % covariances\n K = sf2*m(sqrt(K),f);\nelse % derivatives\n if i<=D % length scale parameter\n if dg\n Ki = zeros(size(x,1),1);\n else\n if xeqz\n Ki = sq_dist(sqrt(d)/ell(i)*x(:,i)');\n else\n Ki = sq_dist(sqrt(d)/ell(i)*x(:,i)',sqrt(d)/ell(i)*z(:,i)');\n end\n end\n K = sf2*dm(sqrt(K),f).*Ki;\n K(Ki<1e-12) = 0; % fix limit case for d=1\n elseif i==D+1 % magnitude parameter\n K = 2*sf2*m(sqrt(K),f);\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/covMaternard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192066862062, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7199011457682861}} {"text": "function [Texp,Lexp]=lyapunov(n,rhs_ext_fcn,fcn_integrator,tstart,stept,tend,ystart,ioutp);\n%\n% Lyapunov exponent calcullation for ODE-system.\n%\n% The alogrithm employed in this m-file for determining Lyapunov\n% exponents was proposed in\n%\n% A. Wolf, J. B. Swift, H. L. Swinney, and J. A. Vastano,\n% \"Determining Lyapunov Exponents from a Time Series,\" Physica D,\n% Vol. 16, pp. 285-317, 1985.\n%\n% For integrating ODE system can be used any MATLAB ODE-suite methods. \n% This function is a part of MATDS program - toolbox for dynamical system investigation\n% See: http://www.math.rsu.ru/mexmat/kvm/matds/\n%\n% Input parameters:\n% n - number of equation\n% rhs_ext_fcn - handle of function with right hand side of extended ODE-system.\n% This function must include RHS of ODE-system coupled with \n% variational equation (n items of linearized systems, see Example). \n% fcn_integrator - handle of ODE integrator function, for example: @ode45 \n% tstart - start values of independent value (time t)\n% stept - step on t-variable for Gram-Schmidt renormalization procedure.\n% tend - finish value of time\n% ystart - start point of trajectory of ODE system.\n% ioutp - step of print to MATLAB main window. ioutp==0 - no print, \n% if ioutp>0 then each ioutp-th point will be print.\n%\n% Output parameters:\n% Texp - time values\n% Lexp - Lyapunov exponents to each time value.\n%\n% Users have to write their own ODE functions for their specified\n% systems and use handle of this function as rhs_ext_fcn - parameter. \n%\n% Example. Lorenz system:\n% dx/dt = sigma*(y - x) = f1\n% dy/dt = r*x - y - x*z = f2\n% dz/dt = x*y - b*z = f3\n%\n% The Jacobian of system: \n% | -sigma sigma 0 |\n% J = | r-z -1 -x |\n% | y x -b |\n%\n% Then, the variational equation has a form:\n% \n% F = J*Y\n% where Y is a square matrix with the same dimension as J.\n% Corresponding m-file:\n% function f=lorenz_ext(t,X)\n% SIGMA = 10; R = 28; BETA = 8/3;\n% x=X(1); y=X(2); z=X(3);\n%\n% Y= [X(4), X(7), X(10);\n% X(5), X(8), X(11);\n% X(6), X(9), X(12)];\n% f=zeros(9,1);\n% f(1)=SIGMA*(y-x); f(2)=-x*z+R*x-y; f(3)=x*y-BETA*z;\n%\n% Jac=[-SIGMA,SIGMA,0; R-z,-1,-x; y, x,-BETA];\n% \n% f(4:12)=Jac*Y;\n%\n% Run Lyapunov exponent calculation:\n% \n% [T,Res]=lyapunov(3,@lorenz_ext,@ode45,0,0.5,200,[0 1 0],10); \n% \n% See files: lorenz_ext, run_lyap. \n% \n% --------------------------------------------------------------------\n% Copyright (C) 2004, Govorukhin V.N.\n% This file is intended for use with MATLAB and was produced for MATDS-program\n% http://www.math.rsu.ru/mexmat/kvm/matds/\n% lyapunov.m is free software. lyapunov.m is distributed in the hope that it \n% will be useful, but WITHOUT ANY WARRANTY. \n%\n\n\n\n%\n% n=number of nonlinear odes\n% n2=n*(n+1)=total number of odes\n%\n\nn1=n; n2=n1*(n1+1);\n\n% Number of steps\n\nnit = round((tend-tstart)/stept);\n\n% Memory allocation \n\ny=zeros(n2,1); cum=zeros(n1,1); y0=y;\ngsc=cum; znorm=cum;\n\n% Initial values\n\ny(1:n)=ystart(:);\n\nfor i=1:n1 y((n1+1)*i)=1.0; end;\n\nt=tstart;\n\n% Main loop\n\nfor ITERLYAP=1:nit\n\n% Solutuion of extended ODE system \n\n [T,Y] = feval(fcn_integrator,rhs_ext_fcn,[t t+stept],y); \n \n t=t+stept;\n y=Y(size(Y,1),:);\n\n for i=1:n1 \n for j=1:n1 y0(n1*i+j)=y(n1*j+i); end;\n end;\n\n%\n% construct new orthonormal basis by gram-schmidt\n%\n\n znorm(1)=0.0;\n for j=1:n1 znorm(1)=znorm(1)+y0(n1*j+1)^2; end;\n\n znorm(1)=sqrt(znorm(1));\n\n for j=1:n1 y0(n1*j+1)=y0(n1*j+1)/znorm(1); end;\n\n for j=2:n1\n for k=1:(j-1)\n gsc(k)=0.0;\n for l=1:n1 gsc(k)=gsc(k)+y0(n1*l+j)*y0(n1*l+k); end;\n end;\n \n for k=1:n1\n for l=1:(j-1)\n y0(n1*k+j)=y0(n1*k+j)-gsc(l)*y0(n1*k+l);\n end;\n end;\n\n znorm(j)=0.0;\n for k=1:n1 znorm(j)=znorm(j)+y0(n1*k+j)^2; end;\n znorm(j)=sqrt(znorm(j));\n\n for k=1:n1 y0(n1*k+j)=y0(n1*k+j)/znorm(j); end;\n end;\n\n%\n% update running vector magnitudes\n%\n\n for k=1:n1 cum(k)=cum(k)+log(znorm(k)); end;\n\n%\n% normalize exponent\n%\n\n for k=1:n1 \n lp(k)=cum(k)/(t-tstart); \n end;\n\n% Output modification\n\n if ITERLYAP==1\n Lexp=lp;\n Texp=t;\n else\n Lexp=[Lexp; lp];\n Texp=[Texp; t];\n end;\n\n if (mod(ITERLYAP,ioutp)==0)\n fprintf('t=%6.4f',t);\n for k=1:n1 fprintf(' %10.6f',lp(k)); end;\n fprintf('\\n');\n end;\n\n for i=1:n1 \n for j=1:n1\n y(n1*j+i)=y0(n1*i+j);\n end;\n end;\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/4628-calculation-lyapunov-exponents-for-ode/lyapunov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7199008836151766}} {"text": "function [yData,betas,P,errors] = tsne_d(D, parameters)\n%TSNE_D Performs symmetric t-SNE on the pairwise Euclidean distance matrix D\n%\n% [yData,betas,P,errors] = tsne_d(D, parameters)\n%\n% The function performs symmetric t-SNE on the NxN pairwise \n% distance matrix D to construct an embedding with no_dims dimensions \n% (default = 2). An initial solution obtained from an other dimensionality \n% reduction technique may be specified in initial_solution. \n% The perplexity of the Gaussian kernel that is employed can be specified \n% through perplexity. \n%\n%\n% Input variables:\n%\n% D -> NxN distance matrix \n% parameters -> structure containing non-default parameters\n%\n%\n% Output variables:\n%\n% yData -> Nx2 (or Nx3) array of embedded values\n% betas -> list of individual area parameters\n% P -> sparse transition matrix\n% errors -> D_{KL}(P || Q) as a function of iteration\n%\n%\n% (C) Laurens van der Maaten, 2010\n% University of California, San Diego\n%\n% Modified by Gordon J. Berman, 2014\n% Princeton University\n\n\n no_dims = parameters.num_tsne_dim;\n perplexity = parameters.perplexity;\n sigmaTolerance = parameters.sigmaTolerance;\n relTol = parameters.relTol;\n \n\n if numel(no_dims) > 1\n initial_solution = true;\n yData = no_dims;\n no_dims = size(ydata, 2);\n else\n initial_solution = false;\n end\n \n \n D = D / max(D(:)); \n [P,betas] = d2p_sparse(D .^ 2, perplexity, sigmaTolerance); \n P(isnan(P)) = 0;\n \n clear D\n \n % Run t-SNE\n if initial_solution\n [yData,errors] = tsne_p_sparse(P, parameters, yData, relTol);\n else\n [yData,errors] = tsne_p_sparse(P, parameters, no_dims, relTol);\n end\n ", "meta": {"author": "gordonberman", "repo": "MotionMapper", "sha": "1b7e84931beae780ffd765b850a4a7f7378acace", "save_path": "github-repos/MATLAB/gordonberman-MotionMapper", "path": "github-repos/MATLAB/gordonberman-MotionMapper/MotionMapper-1b7e84931beae780ffd765b850a4a7f7378acace/t_sne/tsne_d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7198456246414586}} {"text": "function edge_length = tetrahedron_edge_length_3d ( tetra )\n\n%*****************************************************************************80\n%\n%% TETRAHEDRON_EDGE_LENGTH_3D returns edge lengths of a tetrahedron in 3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 May 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real TETRA(3,4), the tetrahedron vertices.\n%\n% Output, real EDGE_LENGTH(6,1), the length of the edges.\n%\n dim_num = 3;\n edge_length = zeros ( 6, 1 );\n\n k = 0;\n for j1 = 1 : 3\n for j2 = j1+1 : 4\n k = k + 1;\n edge_length(k) = r8vec_length ( dim_num, ...\n tetra(1:dim_num,j2) - tetra(1:dim_num,j1) );\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/tet_mesh/tetrahedron_edge_length_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.719845619961079}} {"text": "% Copyright (c) Technische Universität München, 2012\n% All rights reserved.\n%\n% Author: Clemens Hage\n% Contact: hage@tum.de\n% Date: 2012-11-12\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% This script runs a quick numerical demo on Robust PCA (batch mode with\n% incomplete observation)\n\n% Dimension of the data set\nm = 400;\n\n% Number of samples\nn = 400;\n\n% Dimension of the underlying subspace\nk = 40; % i.e. relative rank of 0.1\n\n% Relative density of outliers\nrho = 0.1; % i.e. 10% of the matrix entries are corrupted\n\n% Max. magnitude of the outliers\namplitude = 5;\n\n% Create test data\n[X,L_0]=testdata(m,n,k,rho,amplitude,0);\n\nsupport=0.5; % 50% of the entries are observed\n\n% Create support set\n\n% number of observed entries\nnentries = ceil(support * m * n);\n\n% random positions\nindices = randperm(m*n,nentries);\n\n% convert to indices\n[i,j]=ind2sub([m n],indices);\n\n% create sparse matrix\nOmega = sparse(i,j,true(nentries,1),m,n,nentries);\n\n% run Robust PCA\nL=robustpca_batch(X,k,'atansquare','L_0',L_0,'Omega',Omega);\n\n% Compute relative subspace reconstruction error\nerr = norm(Omega.*L-Omega.*L_0,'fro') / norm(Omega.*L_0,'fro');\ndisplay(['Relative subspace reconstruction error (robust method): ' num2str(err)])\n\n% % Compare to common PCA approach\nX_sampled = Omega.*X;\n[U,~,~]=svds(X_sampled,k);\n\nL_PCA = U * (U' * X_sampled);\n\nerr_PCA = norm(Omega.*L_PCA-Omega.*L_0,'fro') / norm(Omega.*L_0,'fro');\ndisplay(['Relative subspace reconstruction error (common PCA): ' num2str(err_PCA)])\n\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/st/pROST/robustpca_demo_incomplete.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7198456157385524}} {"text": "% DemoTV_UP.m\n%\n% This is a short script that performs TV minimization recovery \n% from partial Fourier measurements \n% \n% min Lambda ||x||_TV +1/2||b - A x||_2\n%\n% Here A*A is assumed to be an orthogonal projector\n%\n% Parameters to set : 1) n : the size of the image to reconstruct (default: 128)\n% 2) Dyna : the dynamic range of the original image (in dB) (default : 40)\n% 3) Lambda : value of the Lagrange multiplier (default: 0.05)\n%\n% Created entities : I : original image\n% Xnesta : image recovered with Nesta\n% NA_nesta = number of calls of A or A* for the method\n%\n% Written by: Jerome Bobin, Caltech\n% Email: bobin@acm.caltech.edu\n% Created: May 2009\n%\n% NESTA Version 1.1\n% See also NESTA_UP and Core_Nesterov_UP\nclear; clc;\nn = 128; %--- The data are n*n images\nDyna = 40; %--- Dynamic range in dB\nLambda = 0.05; \nSetup_Nesta % -- add the solvers to the path\n%% Setting up the experiment\n\nN = n*n;\nI=MakeRDSquares(n,7,Dyna);\nx = reshape(I,n*n,1);\nL = floor(55*(n/256)); %--- so as to get a compression ratio ~10\n[M,Mh,mi,mhi] = LineMask(L,n);\nOMEGA = mhi;\nOMEGA = [OMEGA];\nK = length(OMEGA);\nA = @(z) A_fhp(z,OMEGA);\nAt = @(z) At_fhp(z,OMEGA,n);\nb0 = A(x);\nsigma = 0.1;\nnoise = sigma*randn(size(b0));\nb = b0+noise;\n\nfprintf('##############################################\\n\\n');\nfprintf('NESTA: Total Variation minimization experiment\\n\\n');\nfprintf('##############################################\\n\\n');\nfprintf('Image size = %g x %g / Dynamic range : %g / Noise level : %g\\n\\n',n,n,Dyna,sigma);\n\n%% Setting up the experiment for NESTA\n\nfprintf(' NESTA starts\\n\\n');\nU = @(z) z;\nUt = @(z) z;\nmu = 0.2; %--- can be chosen to be small\nopts = [];\nopts.maxintiter = 5;\nopts.TOlVar = 1e-4;\nopts.verbose = 25;\nopts.maxiter = 5000;\nopts.U = U;\nopts.Ut = Ut;\nopts.stoptest = 1; \nopts.typemin = 'tv';\ncounter();\nAc = @(z) counter(A,z);\nAtc = @(z) counter(At,z);\ntic;\n[x_nesta,niter,resid,err] = NESTA_UP(Ac,Atc,b,Lambda,1,mu,opts);\nt.NESTA = toc;\nNA_nesta = counter();\ntvnesta = calctv(n,n,reshape(x_nesta,n,n));\nXnesta = reshape(x_nesta,n,n);\n\n\n% -- Print results\n\nfprintf('\\nNESTA: TV: %g -- ||b-Ax|| = %g -- # calls : %g\\n\\n',tvnesta,norm(b - A(Xnesta(:))),NA_nesta);\nfprintf('relative l2 error compared to original signal: %.2e\\n',norm(Xnesta-I,'fro')/norm(I,'fro') );\n%% Plot results\nfigure(1); clf;\n\nsubplot(1,2,1);\nimage( I ); title('Original image');\nmap = colormap(hsv);\nmap(1,:) = [1,1,1];\ncolormap(map);\n% colorbar('westoutside');\naxis square; axis off\n\nsubplot(1,2,2);\nimage(Xnesta); title(sprintf(...\n 'Reconstruction via NESTA\\n%.1f sec',t.NESTA));\naxis square; axis off", "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/DemoTV_UP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7198456155096254}} {"text": "function hermite_rule ( n, a, b, scale, filename )\n\n%*****************************************************************************80\n%\n%% HERMITE_RULE generates a Gauss-Hermite rule.\n%\n% Discussion:\n%\n% This program computes a Gauss-Hermite quadrature rule \n% and writes it to a file.\n%\n% The integral to be approximated has the form\n%\n% C * integral ( -oo < x < +oo ) f(x) rho(x) dx\n%\n% where the weight rho(x) is:\n%\n% rho(x) = exp ( - b * ( x - a )^2 ) * sqrt ( b / pi ) dx\n%\n% and A and B are parameters.\n%\n% The user specifies:\n% * N, the number of points in the rule;\n% * A, the center point;\n% * B, the scale factor in the exponential;\n% * SCALE, is 1 if the weights are to be normalized;\n% * FILENAME, the root name of the output files.\n%\n% If SCALE = 0, then the factor C in front of the integrand is 1.\n% If SCALE is nonzero, then the factor C is sqrt ( B ) / sqrt ( PI ).\n% which means that the function f(x)=1 will integrate to 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 February 2014\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HERMITE_RULE\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Compute a Gauss-Hermite rule for approximating\\n' );\n fprintf ( 1, ' integral ( -oo < x < +oo ) f(x) rho(x) dx\\n' );\n fprintf ( 1, ' where the weight rho(x) is:\\n' );\n fprintf ( 1, ' exp ( - b * ( x - a )^2 ) * sqrt ( b / pi ) dx\\n' );\n fprintf ( 1, ' using N points.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The user specifies N, A, B, SCALE, FILENAME.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N is the number of points;\\n' );\n fprintf ( 1, ' A is the center point (typically 0).\\n' );\n fprintf ( 1, ' B is the exponential scale factor (typically 1).\\n' );\n fprintf ( 1, ' SCALE is 1 if the weights are to be normalized.\\n');\n fprintf ( 1, ' FILENAME is used to generate 3 files:\\n' );\n fprintf ( 1, ' filename_w.txt - the weight file\\n' );\n fprintf ( 1, ' filename_x.txt - the abscissa file.\\n' );\n fprintf ( 1, ' filename_r.txt - the region file.\\n' );\n%\n% Initialize the parameters.\n%\n alpha = 0.0;\n beta = 0.0;\n%\n% Get N.\n%\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N is the number of points in the rule, such as 5.\\n' );\n n = input ( ' Enter N: ' );\n elseif ( ischar ( n ) )\n n = str2num ( n );\n end\n%\n% Get A.\n%\n if ( nargin < 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A is the center point, typically 0.\\n' );\n fprintf ( 1, '\\n' );\n a = input ( ' Enter A: ' );\n elseif ( ischar ( a ) )\n a = str2num ( a );\n end\n%\n% Get B.\n%\n if ( nargin < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' B is the scale factor, typically 0.5 or 1.0.\\n' );\n fprintf ( 1, '\\n' );\n b = input ( ' Enter B: ' );\n elseif ( ischar ( b ) )\n b = str2num ( b );\n end\n%\n% Get SCALE.\n%\n if ( nargin < 4 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' SCALE is 1 to normalize the weights, 0 otherwise.\\n' );\n fprintf ( 1, '\\n' );\n b = input ( ' Enter SCALE (0/1): ' );\n elseif ( ischar ( scale ) )\n scale = str2num ( scale );\n end\n%\n% Get FILENAME.\n%\n if ( nargin < 5 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' FILENAME is the ''root name'' of the quadrature files).\\n' );\n filename = input ( ' Enter FILENAME as a quoted string:' );\n end\n%\n% Input summary.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Input summary:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N = %d\\n', n );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n fprintf ( 1, ' SCALE = %d\\n', scale );\n fprintf ( 1, ' FILENAME = \"%s\".\\n', filename );\n%\n% Construct the rule.\n%\n kind = 6;\n [ x, w ] = cgqf ( n, kind, alpha, beta, a, b );\n%\n% Normalize the rule.\n% This way, the weights add up to 1.\n%\n if ( scale == 1.0 )\n w(1:n) = w(1:n) * sqrt ( b ) / sqrt ( pi );\n end\n%\n% Set the R values to suggest an infinite interval.\n%\n r = zeros ( 2, 1 );\n r(1) = - r8_huge ( );\n r(2) = r8_huge ( );\n%\n% Write the rule.\n%\n rule_write ( n, filename, x, w, r );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HERMITE_RULE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction [ t, wts ] = cdgqf ( nt, kind, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CDGQF computes a Gauss quadrature formula with default A, B and simple knots.\n%\n% Discussion:\n%\n% This routine computes all the knots and weights of a Gauss quadrature\n% formula with a classical weight function with default values for A and B,\n% and only simple knots.\n%\n% There are no moments checks and no printing is done.\n%\n% Use routine EIQFS to evaluate a quadrature computed by CGQFS.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n parchk ( kind, 2 * nt, alpha, beta );\n%\n% Get the Jacobi matrix and zero-th moment.\n%\n [ aj, bj, zemu ] = class_matrix ( kind, nt, alpha, beta );\n%\n% Compute the knots and weights.\n%\n [ t, wts ] = sgqf ( nt, aj, bj, zemu );\n\n return\nend\nfunction [ t, wts ] = cgqf ( nt, kind, alpha, beta, a, b )\n\n%*****************************************************************************80\n%\n%% CGQF computes knots and weights of a Gauss quadrature formula.\n%\n% Discussion:\n%\n% The user may specify the interval (A,B).\n%\n% Only simple knots are produced.\n%\n% The user may request that the routine print the knots and weights,\n% and perform a moment check.\n%\n% Use routine EIQFS to evaluate this quadrature formula.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, real A, B, the interval endpoints.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Compute the Gauss quadrature formula for default values of A and B.\n%\n [ t, wts ] = cdgqf ( nt, kind, alpha, beta );\n%\n% All knots have multiplicity = 1.\n%\n mlt = zeros(nt,1);\n mlt(1:nt) = 1;\n%\n% NDX(I) = I.\n%\n ndx = ( 1 : nt );\n%\n% Scale the quadrature rule.\n%\n [ t, wts ] = scqf ( nt, t, mlt, wts, nt, ndx, kind, alpha, beta, a, b );\n\n return\nend\nfunction [ aj, bj, zemu ] = class_matrix ( kind, m, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CLASS_MATRIX computes the Jacobi matrix for a quadrature rule.\n%\n% Discussion:\n%\n% This routine computes the diagonal AJ and subdiagonal BJ\n% elements of the order M tridiagonal symmetric Jacobi matrix\n% associated with the polynomials orthogonal with respect to\n% the weight function specified by KIND.\n%\n% For weight functions 1-7, M elements are defined in BJ even\n% though only M-1 are needed. For weight function 8, BJ(M) is\n% set to zero.\n%\n% The zero-th moment of the weight function is returned in ZEMU.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, integer M, the order of the Jacobi matrix.\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Output, real AJ(M), BJ(M), the diagonal and subdiagonal\n% of the Jacobi matrix.\n%\n% Output, real ZEMU, the zero-th moment.\n%\n temp = eps;\n\n parchk ( kind, 2 * m - 1, alpha, beta );\n\n temp2 = 0.5;\n\n if ( 500.0 * temp < abs ( ( gamma ( temp2 ) )^2 - pi ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CLASS - Fatal error!\\n' );\n fprintf ( 1, ' Gamma function does not match machine parameters.\\n' );\n error ( 'CLASS - Fatal error!' );\n end\n\n bj = zeros(m,1);\n aj = zeros(m,1);\n\n if ( kind == 1 )\n\n ab = 0.0;\n\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod ( i, 2 );\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 2 )\n\n zemu = pi;\n\n aj(1:m) = 0.0;\n\n bj(1) = sqrt ( 0.5 );\n bj(2:m) = 0.5;\n\n elseif ( kind == 3 )\n\n ab = alpha * 2.0;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 )^2 ...\n / gamma ( ab + 2.0 );\n\n aj(1:m) = 0.0;\n bj(1) = 1.0 / ( 2.0 * alpha + 3.0 );\n for i = 2 : m\n bj(i) = i * ( i + ab ) / ( 4.0 * ( i + alpha )^2 - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 4 )\n\n ab = alpha + beta;\n abi = 2.0 + ab;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 ) ...\n * gamma ( beta + 1.0 ) / gamma ( abi );\n aj(1) = ( beta - alpha ) / abi;\n bj(1) = 4.0 * ( 1.0 + alpha ) * ( 1.0 + beta ) ...\n / ( ( abi + 1.0 ) * abi * abi );\n a2b2 = beta * beta - alpha * alpha;\n\n for i = 2 : m\n abi = 2.0 * i + ab;\n aj(i) = a2b2 / ( ( abi - 2.0 ) * abi );\n abi = abi^2;\n bj(i) = 4.0 * i * ( i + alpha ) * ( i + beta ) * ( i + ab ) ...\n / ( ( abi - 1.0 ) * abi );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 5 )\n\n zemu = gamma ( alpha + 1.0 );\n\n for i = 1 : m\n aj(i) = 2.0 * i - 1.0 + alpha;\n bj(i) = i * ( i + alpha );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 6 )\n\n zemu = gamma ( ( alpha + 1.0 ) / 2.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n bj(i) = ( i + alpha * mod ( i, 2 ) ) / 2.0;\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 7 )\n\n ab = alpha;\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod(i,2);\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 8 )\n\n ab = alpha + beta;\n zemu = gamma ( alpha + 1.0 ) * gamma ( - ( ab + 1.0 ) ) ...\n / gamma ( - beta );\n apone = alpha + 1.0;\n aba = ab * apone;\n aj(1) = - apone / ( ab + 2.0 );\n bj(1) = - aj(1) * ( beta + 1.0 ) / ( ab + 2.0 ) / ( ab + 3.0 );\n for i = 2 : m\n abti = ab + 2.0 * i;\n aj(i) = aba + 2.0 * ( ab + i ) * ( i - 1 );\n aj(i) = - aj(i) / abti / ( abti - 2.0 );\n end\n\n for i = 2 : m - 1\n abti = ab + 2.0 * i;\n bj(i) = i * ( alpha + i ) / ( abti - 1.0 ) * ( beta + i ) ...\n / ( abti^2 ) * ( ab + i ) / ( abti + 1.0 );\n end\n\n bj(m) = 0.0;\n bj(1:m) = sqrt ( bj(1:m) );\n\n end\n\n return\nend\nfunction [ d, z ] = imtqlx ( n, d, e, z )\n\n%*****************************************************************************80\n%\n%% IMTQLX diagonalizes a symmetric tridiagonal matrix.\n%\n% Discussion:\n%\n% This routine is a slightly modified version of the EISPACK routine to\n% perform the implicit QL algorithm on a symmetric tridiagonal matrix.\n%\n% The authors thank the authors of EISPACK for permission to use this\n% routine.\n%\n% It has been modified to produce the product Q' * Z, where Z is an input\n% vector and Q is the orthogonal matrix diagonalizing the input matrix.\n% The changes consist (essentialy) of applying the orthogonal transformations\n% directly to Z as they are generated.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Roger Martin, James Wilkinson,\n% The Implicit QL Algorithm,\n% Numerische Mathematik,\n% Volume 12, Number 5, December 1968, pages 377-383.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real D(N), the diagonal entries of the matrix.\n%\n% Input, real E(N), the subdiagonal entries of the\n% matrix, in entries E(1) through E(N-1). \n%\n% Input, real Z(N), a vector to be operated on.\n%\n% Output, real D(N), the diagonal entries of the diagonalized matrix.\n%\n% Output, real Z(N), the value of Q' * Z, where Q is the matrix that \n% diagonalizes the input symmetric tridiagonal matrix.\n%\n itn = 30;\n\n prec = eps;\n\n if ( n == 1 )\n return\n end\n\n e(n) = 0.0;\n\n for l = 1 : n\n\n j = 0;\n\n while ( 1 )\n\n for m = l : n\n\n if ( m == n )\n break\n end\n\n if ( abs ( e(m) ) <= prec * ( abs ( d(m) ) + abs ( d(m+1) ) ) )\n break\n end\n\n end\n\n p = d(l);\n\n if ( m == l )\n break\n end\n\n if ( j == itn )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'IMTQLX - Fatal error!\\n' );\n fprintf ( 1, ' Iteration limit exceeded.\\n' );\n error ( 'IMTQLX - Fatal error!' );\n end\n\n j = j + 1;\n g = ( d(l+1) - p ) / ( 2.0 * e(l) );\n r = sqrt ( g * g + 1.0 );\n g = d(m) - p + e(l) / ( g + r8_sign ( g ) * abs ( r ) );\n s = 1.0;\n c = 1.0;\n p = 0.0;\n mml = m - l;\n\n for ii = 1 : mml\n\n i = m - ii;\n f = s * e(i);\n b = c * e(i);\n\n if ( abs ( f ) >= abs ( g ) )\n c = g / f;\n r = sqrt ( c * c + 1.0 );\n e(i+1) = f * r;\n s = 1.0 / r;\n c = c * s;\n else\n s = f / g;\n r = sqrt ( s * s + 1.0 );\n e(i+1) = g * r;\n c = 1.0 / r;\n s = s * c;\n end\n\n g = d(i+1) - p;\n r = ( d(i) - g ) * s + 2.0 * c * b;\n p = s * r;\n d(i+1) = g + p;\n g = c * r - b;\n f = z(i+1);\n z(i+1) = s * z(i) + c * f;\n z(i) = c * z(i) - s * f;\n\n end\n\n d(l) = d(l) - p;\n e(l) = g;\n e(m) = 0.0;\n\n end\n\n end\n\n for ii = 2 : n\n\n i = ii - 1;\n k = i;\n p = d(i);\n\n for j = ii : n\n if ( d(j) < p )\n k = j;\n p = d(j);\n end\n end\n\n if ( k ~= i )\n d(k) = d(i);\n d(i) = p;\n p = z(i);\n z(i) = z(k);\n z(k) = p;\n end\n\n end\n\n return\nend\nfunction parchk ( kind, m, alpha, beta )\n\n%*****************************************************************************80\n%\n%% PARCHK checks parameters ALPHA and BETA for classical weight functions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, integer M, the order of the highest moment to\n% be calculated. This value is only needed when KIND = 8.\n%\n% Input, real ALPHA, BETA, the parameters, if required\n% by the value of KIND.\n%\n if ( kind <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND <= 0.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check ALPHA for Gegenbauer, Jacobi, Laguerre, Hermite, Exponential.\n%\n if ( 3 <= kind && alpha <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' 3 <= KIND and ALPHA <= -1.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check BETA for Jacobi.\n%\n if ( kind == 4 && beta <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND == 4 and BETA <= -1.0.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check ALPHA and BETA for rational.\n%\n if ( kind == 8 )\n tmp = alpha + beta + m + 1.0;\n if ( 0.0 <= tmp || tmp <= beta )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND == 8 but condition on ALPHA and BETA fails.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n end\n\n return\nend\nfunction value = r8_huge ( )\n\n%*****************************************************************************80\n%\n%% R8_HUGE returns a \"huge\" real number.\n%\n% Discussion:\n%\n% The value returned by this function is NOT required to be the\n% maximum representable R8. This value varies from machine to machine,\n% from compiler to compiler, and may cause problems when being printed.\n% We simply want a \"very large\" but non-infinite number.\n%\n% MATLAB provides a built-in symbolic constant \"inf\" that can be used\n% if a huge number is really what you want!\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real VALUE, a huge number.\n%\n value = 1.0E+30;\n\n return\nend\nfunction value = r8_sign ( x )\n\n%*****************************************************************************80\n%\n%% R8_SIGN returns the sign of an R8.\n%\n% Discussion:\n%\n% The value is +1 if the number is positive or zero, and it is -1 otherwise.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the number whose sign is desired.\n%\n% Output, real VALUE, the sign of X.\n%\n if ( 0 <= x )\n value = +1.0;\n else\n value = -1.0;\n end\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 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, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n% For smaller data files, and less precision, try:\n%\n% fprintf ( output_unit, ' %14.6f', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %24.16f', 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 rule_write ( order, filename, x, w, r )\n\n%*****************************************************************************80\n%\n%% RULE_WRITE writes a quadrature rule to a file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the rule.\n%\n% Input, string FILENAME, specifies the output files.\n% write files 'filename_w.txt', 'filename_x.txt', 'filename_r.txt' defining \n% weights, abscissas, and region.\n%\n% Input, real X(ORDER), the abscissas.\n%\n% Input, real W(ORDER), the weights.\n%\n% Input, real R(2), the region.\n%\n filename_x = strcat ( filename, '_x.txt' );\n filename_w = strcat ( filename, '_w.txt' );\n filename_r = strcat ( filename, '_r.txt' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1,' Creating quadrature files.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"Root\" file name is \"%s\".\\n', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Weight file will be \"%s\".\\n', filename_w );\n fprintf ( 1, ' Abscissa file will be \"%s\".\\n', filename_x );\n fprintf ( 1, ' Region file will be \"%s\".\\n', filename_r );\n\n r8mat_write ( filename_w, 1, order, w' );\n r8mat_write ( filename_x, 1, order, x' );\n r8mat_write ( filename_r, 1, 2, r' );\n\n return\nend\nfunction [ t, wts ] = scqf ( nt, t, mlt, wts, nwts, ndx, kind, alpha, ...\n beta, a, b )\n\n%*****************************************************************************80\n%\n%% SCQF scales a quadrature formula to a nonstandard interval.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real T(NT), the original knots.\n%\n% Input, integer MLT(NT), the multiplicity of the knots.\n%\n% Input, real WTS(NWTS), the weights.\n%\n% Input, integer NWTS, the number of weights.\n%\n% Input, integer NDX(NT), used to index the array WTS.\n% For more details see the comments in CAWIQ.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, real A, B, the interval endpoints.\n%\n% Output, real T(NT), the scaled knots.\n%\n% Output, real WTS(NWTS), the scaled weights.\n%\n temp = eps;\n\n parchk ( kind, 1, alpha, beta )\n\n if ( kind == 1 )\n\n al = 0.0;\n be = 0.0;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 2 )\n\n al = -0.5;\n be = -0.5;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 3 )\n\n al = alpha;\n be = alpha;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 4 )\n\n al = alpha;\n be = beta;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 5 )\n\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = 1.0 / b;\n al = alpha;\n be = 0.0;\n\n elseif ( kind == 6 )\n\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = 1.0 / sqrt ( b );\n al = alpha;\n be = 0.0;\n\n elseif ( kind == 7 )\n\n al = alpha;\n be = 0.0;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 8 )\n\n if ( a + b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' A + B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = a + b;\n al = alpha;\n be = beta;\n\n elseif ( kind == 9 )\n\n al = 0.5;\n be = 0.5;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n end\n\n p = slp^( al + be + 1.0 );\n\n for k = 1 : nt\n\n t(k) = shft + slp * t(k);\n l = abs ( ndx(k) );\n\n if ( l ~= 0 )\n tmp = p;\n for i = l : l + mlt(k) - 1\n wts(i) = wts(i) * tmp;\n tmp = tmp * slp;\n end\n end\n\n end\n\n return\nend\nfunction [ t, wts ] = sgqf ( nt, aj, bj, zemu )\n\n%*****************************************************************************80\n%\n%% SGQF computes knots and weights of a Gauss Quadrature formula.\n%\n% Discussion:\n%\n% This routine computes all the knots and weights of a Gauss quadrature\n% formula with simple knots from the Jacobi matrix and the zero-th\n% moment of the weight function, using the Golub-Welsch technique.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real AJ(NT), the diagonal of the Jacobi matrix.\n%\n% Input, real BJ(NT), the subdiagonal of the Jacobi\n% matrix, in entries 1 through NT-1. On output, BJ has been overwritten.\n%\n% Input, real ZEMU, the zero-th moment of the weight function.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Exit if the zero-th moment is not positive.\n%\n if ( zemu <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGQF - Fatal error!\\n' );\n fprintf ( 1, ' ZEMU <= 0.\\n' );\n error ( 'SGQF - Fatal error!' );\n end\n%\n% Set up vectors for IMTQLX.\n%\n wts = zeros ( nt, 1 );\n\n wts(1) = sqrt ( zemu );\n wts(2:nt) = 0.0;\n%\n% Diagonalize the Jacobi matrix.\n%\n [ t, wts ] = imtqlx ( nt, aj, bj, wts );\n\n wts(1:nt) = wts(1:nt).^2;\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/hermite_rule/hermite_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7198009786842167}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% % Simple Low Rank Tensor Completion (SiLRTC) \n% Time: 03/11/2012\n% Reference: \"Tensor Completion for Estimating Missing Values \n% in Visual Data\", PAMI, 2012.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [X, errList] = SiLRTC(T, Omega, alpha, gamma, maxIter, epsilon, X)\n%%%%%%%%%%%%%%%%%%%%%%%%%%\n% min(X, M1, M2, M3,... Mn): (\\gamma1||X_(1)-M1||^2 + \\gamma2||X_(2)-T2||^2 + \\gamma3||X_(3)-T3||^2 + ...)/2 + \n% \\alpha1||M1||_* + \\alpha2||M2||_* + \\alpha3||M3||_* + ....\n% s.t. X_\\Omega = T_\\Omega\n%%%%%%%%%%%%%%%%%%%%%%%%%%\nif nargin < 7\n X = T;\n X(logical(1-Omega)) = mean(T(Omega));\nend\n\nerrList = zeros(maxIter, 1);\nnormT = norm(T(:));\n%L = errList;\ndim = size(T);\nM = cell(ndims(T), 1);\ngammasum = sum(gamma);\ntau = alpha./ gamma;\n\n%normT = norm(T(:));\nfor k = 1:maxIter\n if mod(k, 20) == 0\n fprintf('SiLRTC: iterations = %d difference=%f\\n', k, errList(k-1));\n end\n Xsum = 0;\n for i = 1:ndims(T)\n M{i} = Fold(Pro2TraceNorm(Unfold(X, dim, i), tau(i)), dim, i);\n Xsum = Xsum + gamma(i) * M{i};\n end\n Xlast = X;\n X = Xsum / gammasum;\n X(Omega) = T(Omega);\n errList(k) = norm(X(:)-Xlast(:)) / normT;\n if (errList(k) < epsilon)\n errList = errList(1:k);\n break;\n end\n %L(k) = norm(X(:)-T(:)) / normT;\nend\nfprintf('SiLRTC ends: total iterations = %d difference=%f\\n\\n', k, errList(k));", "meta": {"author": "andrewssobral", "repo": "mctc4bmi", "sha": "fbcbcd25654b818646387c3d6a64304fb60e12dd", "save_path": "github-repos/MATLAB/andrewssobral-mctc4bmi", "path": "github-repos/MATLAB/andrewssobral-mctc4bmi/mctc4bmi-fbcbcd25654b818646387c3d6a64304fb60e12dd/algs_tc/LRTC/SiLRTC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7197925341610419}} {"text": "function [ xstar, seed ] = rk2_ti_step ( x, t, h, q, fi, gi, seed )\n\n%*****************************************************************************80\n%\n%% RK2_TI_STEP takes one step of a stochastic Runge Kutta scheme.\n%\n% Discussion:\n%\n% The Runge-Kutta scheme is second-order, and suitable for time-invariant\n% systems.\n%\n% d/dx X(t,xsi) = F ( X(t,xsi) ) + G ( X(t,xsi) ) * w(t,xsi)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 June 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Jeremy Kasdin,\n% Runge-Kutta algorithm for the numerical integration of\n% stochastic differential equations,\n% Journal of Guidance, Control, and Dynamics,\n% Volume 18, Number 1, January-February 1995, pages 114-120.\n%\n% Jeremy Kasdin,\n% Discrete Simulation of Colored Noise and Stochastic Processes\n% and 1/f^a Power Law Noise Generation,\n% Proceedings of the IEEE,\n% Volume 83, Number 5, 1995, pages 802-827.\n%\n% Parameters:\n%\n% Input, real X, the value at the current time.\n%\n% Input, real T, the current time.\n%\n% Input, real H, the time step.\n%\n% Input, real Q, the spectral density of the input white noise.\n%\n% Input, external real FI, the name of the deterministic\n% right hand side function.\n%\n% Input, external real GI, the name of the stochastic\n% right hand side function.\n%\n% Input/output, integer SEED, a seed for the random\n% number generator.\n%\n% Output, real XSTAR, the value at time T+H.\n%\n a21 = 1.0;\n a31 = 0.5;\n a32 = 0.5;\n\n q1 = 2.0;\n q2 = 2.0;\n\n t1 = t;\n x1 = x;\n [ n1, seed ] = r8_normal_01 ( seed );\n w1 = n1 * sqrt ( q1 * q / h );\n k1 = h * fi ( x1 ) + h * gi ( x1 ) * w1;\n\n t2 = t1 + a21 * h;\n x2 = x1 + a21 * k1;\n [ n2, seed ] = r8_normal_01 ( seed );\n w2 = n2 * sqrt ( q2 * q / h );\n k2 = h * fi ( x2 ) + h * gi ( x2 ) * w2;\n\n xstar = x1 + a31 * k1 + a32 * k2;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/stochastic_rk/rk2_ti_step.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7197925262721521}} {"text": "%\n% This code creates the plot of the D-value versus the b-value.\n% The code is called from view_Dv.\n%\n%\n[bvg5, ord] = sort(bvg(:,5));\nbvg1 = bvg(ord,1);\nbx = [bvg5(3):0.05: bvg5(end-1)]';\nDy = 2*bx;\nclear ord;\n\nfigure_w_normalized_uicontrolunits('Numbertitle','off','Name','D versus b');\nplot(bvg(:,5),bvg(:,1),'o');\nhold on;\nplot(bx, Dy, 'k-');\nxlabel('b-value');\nylabel('D-value');\ntitle('D-value versus b-value');\n\nreg = [ones(size(bvg,1),1), bvg(:,5)];\n[sl, cint, res, resint, stat] = regress(bvg(:,1), reg, 0.25);\n\nsl\nstat\n\nrsl = [sl(2,1) sl(1,1)];\ncoef1 = [cint(2,1), cint(1,1)];\ncoef2 = [cint(2,2), cint(1,2)];\ndeltar = sl(2,1) - cint(2,1);\n[line] = polyval(rsl,bx);\n[line1] = polyval(coef1, bx);\n[line2] = polyval(coef2, bx);\n\nhold on;\nplot(bx, line, 'r');\nplot(bx, line1, 'g');\nplot(bx, line2, 'g');\n\nstr2 = ['Correlation factor (D=xb): x = ' sprintf('%.2f',sl(2,1)) ' +/- ' sprintf('%.2f', deltar)];\naxes('pos',[0 0 1 1]); axis off; hold on;\nte1 = text(0.15, 0.85, str2,'Fontweight','bold');\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/bvdfig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505273888291, "lm_q2_score": 0.7956581024858785, "lm_q1q2_score": 0.7197925220350451}} {"text": "function x = blend_ij_w_1d1 ( x, r, s, m1, m2 )\n\n%*****************************************************************************80\n%\n%% BLEND_IJ_W_1D1 extends weighted indexed scalar data along edges into a table.\n%\n% Diagram:\n%\n% Instead of assuming that the data in the table is equally spaced,\n% the arrays R and S are supplied, which should behave as\n% \"coordinates\" for the data.\n%\n% S(1) S(2) S(3) S(4) S(5) S(6) S(M2)\n%\n% R(1) ( X11, X12, X13, X14, X15, X16, X1M2 )\n% R(2) ( X21, ..., ..., ..., ..., ..., X2M2 )\n% R(3) ( X31, ..., ..., ..., ..., ..., X3M2 )\n% R(4) ( X41, ..., ..., ..., ..., ..., X4M2 )\n% R(M1) ( XM11, XM12, XM13, XM14, XM15, XM16, XM1M2 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 October 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% William Gordon,\n% Blending-Function Methods of Bivariate and Multivariate Interpolation\n% and Approximation,\n% SIAM Journal on Numerical Analysis,\n% Volume 8, Number 1, March 1971, pages 158-177.\n%\n% William Gordon and Charles Hall,\n% Transfinite Element Methods: Blending-Function Interpolation over\n% Arbitrary Curved Element Domains,\n% Numerische Mathematik,\n% Volume 21, Number 1, 1973, pages 109-129.\n%\n% William Gordon and Charles Hall,\n% Construction of Curvilinear Coordinate Systems and Application to\n% Mesh Generation,\n% International Journal of Numerical Methods in Engineering,\n% Volume 7, 1973, pages 461-477.\n%\n% Joe Thompson, Bharat Soni, Nigel Weatherill,\n% Handbook of Grid Generation,\n% CRC Press, 1999.\n%\n% Parameters:\n%\n% Input, real X(M1,M2).\n% On input, data is contained in the \"edge entries\" X(1,J), X(I,1),\n% X(M1,J) and X(I,M2), for I = 1 to M1, and J = 1 to M2.\n%\n% Input, real R(M1), S(M2), are \"coordinates\" for the rows and\n% columns of the array. The values in R, and the values in S, should\n% be strictly increasing or decreasing.\n%\n% Input, integer M1, M2, the number of rows and columns in X.\n%\n% Output, real X(M1,M2), all entries in X have been assigned a value.\n%\n\n%\n% Interpolate values in the interior.\n%\n for i = 2 : m1 - 1\n\n rr = ( r(i) - r(1) ) / ( r(m1) - r(1) );\n\n for j = 2 : m2 - 1\n\n ss = ( s(j) - s(1) ) / ( s(m2) - s(1) );\n\n x(i,j) = blend_112 ( rr, ss, x(1,1), x(1,m2), x(m1,1), x(m1,m2), ...\n x(i,1), x(i,m2), x(1,j), x(m1,j) );\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/blend/blend_ij_w_1d1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8267118026095992, "lm_q1q2_score": 0.7197330426641727}} {"text": "function value = square_volume ( a, b )\n\n%*****************************************************************************80\n%\n%% SQUARE_VOLUME: volume of a square in 2D.\n%\n% Discussion:\n%\n% The integration region is defined as:\n% A(1) <= X <= B(1)\n% A(2) <= Y <= B(2)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A(2), B(2), the lower and upper limits.\n%\n% Output, real VALUE, the volume.\n%\n value = ( b(1) - a(1) ) * ( b(2) - a(2) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/square_felippa_rule/square_volume.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.7197330376077044}} {"text": "function c = l1pp_cholesky ( n, h )\n\n%*****************************************************************************80\n%\n%% L1PP_CHOLESKY computes the Cholesky factor of the 1D PP Laplacian.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 October 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n% N must be at least 3.\n%\n% Input, real H, the spacing between points.\n%\n% Output, real C(N,N), the Cholesky factor.\n%\n if ( n < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'L1PP_CHOLESKY - Fatal error!\\n' );\n fprintf ( 1, ' N < 3.\\n' );\n error ( 'L1PP_CHOLESKY - Fatal error!' );\n end\n\n c = zeros ( n, n );\n\n for i = 1 : n - 1\n c(i,i) = sqrt ( i + 1.0 ) / sqrt ( i );\n end\n\n for i = 1 : n - 2\n c(i,i+1) = - i / ( i + 1.0 ) * sqrt ( i + 1.0 ) / sqrt ( i );\n end\n\n for i = 1 : n - 2\n c(i,n) = - 1.0 / ( i + 1.0 ) * sqrt ( i + 1.0 ) / sqrt ( i );\n end\n\n i = n - 1;\n c(i,n) = - n / ( i + 1.0 ) * sqrt ( i + 1.0 ) / sqrt ( i );\n\n c(1:n,1:n) = c(1:n,1:n) / h;\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/laplacian/l1pp_cholesky.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8267117962054049, "lm_q1q2_score": 0.7197330315373951}} {"text": "%% To plot Basin of Attraction for a given set of equations using Newton\n% Raphson Method \n% Governing Equations are:\n% x^3-y = 0 ; y^3 - x = 0 \n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n% Warning : On running this the workspace memory will be deleted. Save if\n% any data present before running the code !!\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n%--------------------------------------------------------------------------\n% Code written by : Siva Srinivas Kolukula, PhD |\n% Structural Mechanics Laboratory |\n% Indira Gandhi Center for Atomic Research |\n% India |\n% E-mail : allwayzitzme@gmail.com |\n% web-link: https://sites.google.com/site/kolukulasivasrinivas/ |\n%--------------------------------------------------------------------------\n% Version 1 : 19 September 2013\n\nclc ; clear all\nwarning('off') % To off the warning which shows \"Matrix is close to singular \n % badly scaled\" when algorithm passes through a point where the Jacobian\n % matrix is singular\n\n% The roots of the given governing equations\nr1 = [-1 ;-1] ;\nr2 = [0 ;0] ;\nr3 = [1 ;1] ;\n% Initial conditions \nx = linspace(-2,2,200) ;\ny = linspace(-2,2,200) ;\n% Initialize the required matrices\nXr1 = [] ; Xr2 = [] ; Xr3 = [] ; Xr4 = [] ;\ntic \nfor i = 1:length(x)\n for j = 1:length(y)\n X0 = [x(i);y(j)] ;\n % Solve the system of Equations using Newton's Method\n X = NewtonRaphson(X0) ;\n % Locating the initial conditions according to error\n if norm(X-r1)<1e-8 \n Xr1 = [X0 Xr1] ;\n elseif norm(X-r2)<1e-8\n Xr2 = [X0 Xr2] ;\n elseif norm(X-r3)<1e-8\n Xr3 = [X0 Xr3] ;\n else % if not close to any of the roots\n Xr4 = [X0 Xr4] ;\n end\n \n end \nend\ntoc\nwarning('on') % Remove the warning off constraint\n\n% Initialize figure\nfigure\nset(gcf,'color','w') \nhold on\nplot(Xr1(1,:),Xr1(2,:),'.','color','r') ;\nplot(Xr2(1,:),Xr2(2,:),'.','color','b') ;\nplot(Xr3(1,:),Xr3(2,:),'.','color','g') ;\nplot(Xr4(1,:),Xr4(2,:),'.','color','k') ;\ntitle('Basin of attraction for f(x,y) = x^3-y = 0 and y^3-x=0')", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43564-basins-of-attraction/Basins of Attraction/BasinsofAttraction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7197330259619209}} {"text": "function value = r8_scinvchi_sample ( df, s )\n\n%*****************************************************************************80\n%\n%% R8_SCINVCHI_SAMPLE: sample a scaled inverse chi-squared distribution.\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% John Burkardt\n%\n% Parameters:\n%\n% Input, real DF, the degrees of freedom.\n% 0.0 < DF.\n%\n% Input, real S, the scale factor.\n% 0.0 < S.\n%\n% Input, real VALUE, a sample value.\n%\n a = 0.5 * df * s;\n b = 0.5 * df;\n\n value = r8_gamma_sample ( a, b );\n\n if ( value ~= 0.0 )\n value = 1.0 / value;\n end\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/pdflib/r8_scinvchi_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.7197330167178047}} {"text": "% Stability domain of Adams-Bashforth_Euler scheme\n\n% Copyright 2001 P. Wesseling\n% This program and its subprograms may be freely used, modified and distributed\n% under the GNU General Public License: http://www.gnu.org/copyleft/gpl.html\n\n% Theory is given in Section 5.8 of\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 generates Fig. 5.5 in the book\n\nfigure(1), clf, hold on\n\n\t\t% Plot of stability domain\ntheta = 0:0.01:1; theta = theta*pi;\nz = - 2*(1-cos(theta)).^2./(3-cos(theta)) + i*2*sin(theta)./(3-cos(theta));\nplot(z)\n\n\t\t% Stability domain of second order Adams-Bashforth scheme\nz = exp(2*i*theta) - exp(i*theta); z = z./(1.5*exp(i*theta) - 0.5); plot(z,'-.')\n\n\t\t% Plot of oval\nb = 1; a = 1; z = - a*(1-cos(theta)) + i*b*(sin(theta)).^0.5; plot(z,'--')\n\n\t\t% Plot of half ellipse\na = 2.0; b = sqrt(1/3); theta = -pi/2 +0.5*theta;\nz = - a*cos(theta) - i*b*sin(theta); plot(z,'.')\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/chap5.8/Adams_Bashforth_Euler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.7197080191359865}} {"text": "function [Y, R, E] = IsomapII(D, n_fcn, n_size, options)\n% ISOMAPII Computes Isomap embedding using an advanced version of\n% the algorithm in Tenenbaum, de Silva, and Langford (2000), \n% which can take advantage of sparsity in the graph and \n% redundancy in the distances. \n%\n% [Y, R, E] = isomapII(D, n_fcn, n_size, options); \n%\n% Input:\n% D = input-space distances between pairs of N points, which can \n% take 1 of 3 forms: \n% (1) a full N x N matrix (as in isomap.m) \n% (2) a sparse N x N matrix (missing entries are treated as INF)\n% (3) the name of a function (e.g. 'd_fun') that takes\n% one argument, i, and returns a row vector containng the \n% distances from all N points to point i. \n%\n% n_fcn = neighborhood function ('epsilon' or 'k') \n% n_size = neighborhood size (value for epsilon or k) \n%\n% options = optional structure of options:\n% options.dims = (row) vector of embedding dimensionalities to use\n% (1:10 = default)\n% options.comp = which connected component to embed, if more than one. \n% (1 = largest (default), 2 = second largest, ...)\n% options.display = plot residual variance and 2-D embedding?\n% (1 = yes (default), 0 = no)\n% options.overlay = overlay graph on 2-D embedding? \n% (1 = yes (default), 0 = no)\n% options.verbose = display progress reports? \n% (1 = yes (default), 0 = no)\n% options.dijkstra = use dijkstra's algorithm for shortest paths with\n% full N x N distance matrix. \n% (1 = yes (default), 0 = use Floyd; Floyd should\n% be used only if you are unable to MEX dijkstra.cpp)\n% options.Kmax = maximum number of neighbors (used for sparse versions\n% of epsilon; by default, estimated by random sample)\n% options.landmarks = (row) vector of landmark points to use in MDS. \n% (MDS finds the configuration that best approximates\n% the distances from all points to the landmark points.\n% The default landmark points are 1:N (i.e. all the points), \n% which is equivalent to classical MDS. Good \n% results may often be obtained using a number of\n% landmarks that is much smaller than N, but much\n% larger than the data's intrinsic dimensionality.\n% Note that this extension is experimental! For\n% discussion, see Steyvers, de Silva, and Tenenbaum\n% (in preparation).)\n%\n% Output: \n% Y = Y.coords is a cell array, with coordinates for d-dimensional embeddings\n% in Y.coords{d}. Y.index contains the indices of the points embedded.\n% R = residual variances for embeddings in Y\n% E = edge matrix for neighborhood graph\n%\n\n% BEGIN COPYRIGHT NOTICE\n%\n% Isomap II code -- (c) 1998-2000 Josh Tenenbaum\n%\n% This code is provided as is, with no guarantees except that \n% bugs are almost surely present. Published reports of research \n% using this code (or a modified version) should cite the \n% article that describes the algorithm: \n%\n% J. B. Tenenbaum, V. de Silva, J. C. Langford (2000). A global\n% geometric framework for nonlinear dimensionality reduction. \n% Science 290 (5500): 2319-2323, 22 December 2000. \n%\n% Comments and bug reports are welcome. Email to jbt@psych.stanford.edu. \n% I would also appreciate hearing about how you used this code, \n% improvements that you have made to it, or translations into other\n% languages. \n%\n% You are free to modify, extend or distribute this code, as long \n% as this copyright notice is included whole and unchanged. \n%\n% END COPYRIGHT NOTICE\n%\n% Modified by Ramon Casero , University of Oxford.\n%\n% Version: 0.1.1\n%\n% This file is distributed as a derivative work of a third-party function\n% with project Gerardus.\n%\n% http://code.google.com/p/gerardus/\n%\n% Original code downloaded from the Isomap Homepage\n%\n% http://isomap.stanford.edu/\n\n\n%%%%% Step 0: Initialization and Parameters %%%%%\n\nif nargin < 3\n error('Too few input arguments'); \nelseif nargin < 4\n options = struct('dims',1:10,'overlay',1,'comp',1,'display',1,'dijkstra',1,'verbose',1); \nend\n\nif isa(D, 'function_handle')\n mode = 3; \n d_func = D; \n N = length(d_func(1)); \nelseif issparse(D) \n mode = 2; \n N = size(D,1); \n if ~(N==size(D,2))\n error('D must be a square matrix'); \n end; \nelse \n mode = 1; \n N = size(D,1); \n if ~(N==size(D,2))\n error('D must be a square matrix'); \n end; \nend\n\nif strcmp(n_fcn, 'k')\n K = n_size; \n if ~(K==round(K))\n error('Number of neighbors for k method must be an integer');\n end\n if ((mode==2) && ~(min(sum(D'>0))>=K))\n error('Sparse D matrix must contain at least K nonzero entries in each row');\n end\nelseif strcmp(n_fcn, 'epsilon')\n epsilon = n_size; \n if isfield(options,'Kmax')\n K = options.Kmax; \n elseif (mode==3) %% estimate maximum equivalent K %% \n tmp = zeros(10,N); \n for i=1:10\n tmp(i,:) = d_func(ceil(N*rand)); \n end\n K = 2*max(sum(tmp'n_comps) \n comp=1; %% default: use largest component\nend\nY.index = find(firsts==comps(comp)); %% list of points in relevant component\nY.index = setdiff(Y.index,find(isinf(min(D)))); % prune points that don't connect\n % to any landmarks\nN = length(Y.index); \n[tmp, landmarks, land_ind] = intersect(landmarks,Y.index); \n % list of landmarks in component\nnl = length(landmarks); \nD = full(D(landmarks,Y.index))'; \ndisp([' Number of connected components in graph: ' num2str(n_comps)]); \ndisp([' Embedding component ' num2str(comp) ' with ' num2str(length(Y.index)) ' points.']); \n\ndims = unique(min(dims,nl-1)); % don't embed in more dimensions than landmarks-1\nif (nl==N)\n opt.disp = 0; \n [vec, val] = eigs(-.5*(D.^2 - sum(D.^2)'*ones(1,N)/N - ones(N,1)*sum(D.^2)/N + sum(sum(D.^2))/(N^2)), max(dims), 'LR', opt); \nelse\n subB = -.5*(D.^2 - sum(D'.^2)'*ones(1,nl)/nl - ones(N,1)*sum(D.^2)/N+sum(sum(D.^2))/(N*nl));\n opt.disp = 0; \n [alpha,beta] = eigs(subB'*subB, max(dims), 'LR', opt); \n val = beta.^(1/2); \n vec = subB*alpha*inv(val); \n clear subB alpha beta; \nend\nh = real(diag(val)); \n[foo,sorth] = sort(h); sorth = sorth(end:-1:1); \nval = real(diag(val(sorth,sorth))); \nvec = vec(:,sorth); \n\nD = reshape(D,N*nl,1); \nfor di = 1:length(dims)\n Y.coords{di} = real(vec(:,1:dims(di)).*(ones(N,1)*sqrt(val(1:dims(di)))'))'; \n r2 = 1-corrcoef(reshape(real(L2_distance(Y.coords{di}, Y.coords{di}(:,land_ind))),N*nl,1),D).^2; \n R(di) = r2(2,1); \n if (verbose == 1)\n disp([' Isomap on ' num2str(N) ' points with dimensionality ' num2str(dims(di)) ' --> residual variance = ' num2str(R(di))]); \n end\nend\n\nclear D; \n\n%%%%%%%%%%%%%%%%%% Graphics %%%%%%%%%%%%%%%%%%\n\nif (displ==1)\n %%%%% Plot fall-off of residual variance with dimensionality %%%%%\n figure;\n hold on\n plot(dims, R, 'bo'); \n plot(dims, R, 'b-'); \n hold off\n ylabel('Residual variance'); \n xlabel('Isomap dimensionality'); \n\n %%%%% Plot two-dimensional configuration %%%%%\n twod = find(dims==2); \n if ~isempty(twod)\n figure;\n hold on;\n plot(Y.coords{twod}(1,:), Y.coords{twod}(2,:), 'ro'); \n if (overlay == 1)\n gplot(E(Y.index, Y.index), [Y.coords{twod}(1,:); Y.coords{twod}(2,:)]'); \n title('Two-dimensional Isomap embedding (with neighborhood graph).'); \n else\n title('Two-dimensional Isomap.'); \n end\n hold off;\n end\nend\n\nreturn;\n\n\n\n\n\n\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/IsomapII.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7196788078643894}} {"text": "%otyp==0->cont, otyp==1->disc\nfunction [A N]=sys_ned_dcm(llh, vel_n, Cbn, acc, otyp, dt)\n% position (1-3)\n% velocity (4-6)\n% attitude (7-9) \n\n%system disturbance coefs\nN=zeros(9,6);\nN(7:9,4:6)=-Cbn; %attitude\nN(4:6,1:3)=Cbn; %velocity\n\n%system matrix\nA=zeros(9);\n[Rn, Re, g, sL, cL, WIE_E]=geoparam_v000(llh);\ntL=sL/cL;\nRn_h=Rn+llh(3);\nRe_h=Re+llh(3);\nacc_n=Cbn*acc;\n\nA(1,3)=-vel_n(1)/(Rn_h)^2; \nA(1,4)=1/(Rn_h);\n\nA(2,1)=vel_n(2)*tL/(Re_h)/cL;\nA(2,3)=-vel_n(2)/(Re_h)/(Re_h)/cL;\nA(2,5)=1/(Re_h)/cL;\n\nA(3,6)=-1;\n\nA(4,1)=-(2*WIE_E*cL*vel_n(2)+vel_n(2)*vel_n(2)/(Re_h)/cL/cL);\nA(4,3)=(-vel_n(1)*vel_n(3)/(Rn_h)/(Rn_h)+vel_n(2)*vel_n(2)*tL/(Re_h)/(Re_h));\nA(4,4)=vel_n(3)/(Rn_h);\nA(4,5)=-(2*WIE_E*sL+2*vel_n(2)*tL/(Re_h));\nA(4,6)=vel_n(1)/(Rn_h);\nA(4,8)=-acc_n(3);\nA(4,9)=acc_n(2);\n\nA(5,1)=(2*WIE_E*cL*vel_n(1)-2*WIE_E*sL*vel_n(3)+vel_n(2)*vel_n(1)/(Re_h)/cL/cL);\nA(5,3)=-(vel_n(2)*vel_n(3)+vel_n(2)*vel_n(1)*tL)/(Re_h)/(Re_h);\nA(5,4)=(2*WIE_E*sL+vel_n(2)*tL/(Re_h));\nA(5,5)=(vel_n(3)+vel_n(1)*tL)/(Re_h);\nA(5,6)=(2*WIE_E*cL+vel_n(2)/(Re_h));\nA(5,7)=acc_n(3);\nA(5,9)=-acc_n(1);\n\nA(6,1)=2*WIE_E*sL*vel_n(2);\nA(6,3)=(vel_n(1)*vel_n(1)/(Rn_h)/(Rn_h)+vel_n(2)*vel_n(2)/(Re_h)/(Re_h));\nA(6,4)=-2*vel_n(1)/(Rn_h);\nA(6,5)=-2*(WIE_E*cL+vel_n(2)/(Re_h));\nA(6,7)=-acc_n(2);\nA(6,8)=acc_n(1);\n\n\nA(7,1)=-WIE_E*sL;\nA(7,3)=-vel_n(2)/(Re_h)/(Re_h);\nA(7,5)=1/(Re_h);\nA(7,8)=-(WIE_E*sL+vel_n(2)*tL/(Re_h));\nA(7,9)=vel_n(1)/(Rn_h);\n\nA(8,3)=vel_n(1)/(Rn_h)/(Rn_h);\nA(8,4)=-1/(Rn_h);\nA(8,7)=(WIE_E*sL+vel_n(2)*tL/(Re_h));\nA(8,9)=(WIE_E*cL+vel_n(2)/(Re_h));\n\nA(9,1)=-(WIE_E*cL+vel_n(2)/(Re_h)/cL/cL);\nA(9,3)=vel_n(2)*tL/(Re_h)/(Re_h);\nA(9,5)=-tL/(Re_h);\nA(9,7)=-vel_n(1)/(Rn_h);\nA(9,8)=-(WIE_E*cL+vel_n(2)/(Re_h));\n\n\n%discretize A;\nif (otyp==0)\n A=A;\nelseif(otyp==1)\n A=expm(A*dt);\nend\n\n\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/INS/sys_ned_dcm_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750373915658, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.7196416018210193}} {"text": "function xp = spm_dirichlet_exceedance(alpha,Nsamp)\n% Compute exceedance probabilities for a Dirichlet distribution\n% FORMAT xp = spm_dirichlet_exceedance(alpha,Nsamp)\n% \n% Input:\n% alpha - Dirichlet parameters\n% Nsamp - number of samples used to compute xp [default = 1e6]\n% \n% Output:\n% xp - exceedance probability\n%__________________________________________________________________________\n%\n% This function computes exceedance probabilities, i.e. for any given model\n% k1, the probability that it is more likely than any other model k2. \n% More formally, for k1=1..Nk and for all k2~=k1, it returns p(x_k1>x_k2) \n% given that p(x)=dirichlet(alpha).\n% \n% Refs:\n% Stephan KE, Penny WD, Daunizeau J, Moran RJ, Friston KJ\n% Bayesian Model Selection for Group Studies. NeuroImage (in press)\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny & Klaas Enno Stephan\n% $Id: spm_dirichlet_exceedance.m 3118 2009-05-12 17:37:32Z guillaume $\n\nif nargin < 2\n Nsamp = 1e6;\nend\n\nNk = length(alpha);\n\n% Perform sampling in blocks\n%--------------------------------------------------------------------------\nblk = ceil(Nsamp*Nk*8 / 2^28);\nblk = floor(Nsamp/blk * ones(1,blk));\nblk(end) = Nsamp - sum(blk(1:end-1));\n\nxp = zeros(1,Nk);\nfor i=1:length(blk)\n \n % Sample from univariate gamma densities then normalise\n % (see Dirichlet entry in Wikipedia or Ferguson (1973) Ann. Stat. 1,\n % 209-230)\n %----------------------------------------------------------------------\n r = zeros(blk(i),Nk);\n for k = 1:Nk\n r(:,k) = spm_gamrnd(alpha(k),1,blk(i),1);\n end\n sr = sum(r,2);\n for k = 1:Nk\n r(:,k) = r(:,k)./sr;\n end\n \n % Exceedance probabilities:\n % For any given model k1, compute the probability that it is more\n % likely than any other model k2~=k1\n %----------------------------------------------------------------------\n [y, j] = max(r,[],2);\n xp = xp + histc(j, 1:Nk)';\n \nend\nxp = xp / Nsamp;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_dirichlet_exceedance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7195947307556417}} {"text": "function cube_exactness_test01 ( )\n\n%*****************************************************************************80\n%\n%% CUBE_EXACTNESS_TEST01 tests product Gauss-Legendre rules for the Legendre 3D integral.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 August 2014\n%\n% Author:\n%\n% John Burkardt\n%\n a(1:3) = -1.0;\n b(1:3) = +1.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CUBE_EXACTNESS_TEST01\\n' );\n fprintf ( 1, ' Product Gauss-Legendre rules for the 3D Legendre integral.\\n' );\n fprintf ( 1, ' Density function rho(x) = 1.\\n' );\n fprintf ( 1, ' Region: -1 <= x <= +1.\\n' );\n fprintf ( 1, ' -1 <= y <= +1.\\n' );\n fprintf ( 1, ' -1 <= z <= +1.\\n' );\n fprintf ( 1, ' Level: L\\n' );\n fprintf ( 1, ' Exactness: 2*L+1\\n' );\n fprintf ( 1, ' Order: N = (L+1)*(L+1)*(L+1)\\n' );\n\n for l = 0 : 5\n\n nx = l + 1;\n ny = l + 1;\n nz = l + 1;\n n = nx * ny * nz;\n t = 2 * l + 1;\n\n [ x, y, z, w ] = legendre_3d_set ( a, b, nx, ny, nz );\n\n p_max = t + 1;\n legendre_3d_exactness ( a, b, n, x, y, z, w, p_max );\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/cube_exactness/cube_exactness_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7194373771215631}} {"text": "function varargout = revolutionSurface(varargin)\n%REVOLUTIONSURFACE Create a surface of revolution from a planar curve.\n%\n% usage \n% [X Y Z] = revolutionSurface(C1, C2, N);\n% create the surface of revolution of parametrized function (xt, yt),\n% with N+1 equally spaced slices, around the Oz axis.\n% It assumed that C1 corresponds to the x coordinate, and that C2\n% corresponds to the Oz coordinate.\n%\n% [X Y Z] = revolutionSurface(CURVE, N);\n% is the same, but generating curve is given in a single parameter CURVE,\n% which is a [Nx2] array of 2D points.\n%\n% [X Y Z] = revolutionSurface(..., THETA)\n% where THETA is a vector, uses values of THETA for computing revolution\n% angles.\n%\n% [X Y Z] = revolutionSurface(..., LINE);\n% where LINE is a 1x4 array, specifes the revolution axis in the\n% coordinate system of the curve. LINE is a row vector of 4 parameters,\n% containing [x0 y0 dx dy], where (x0,y0) is the origin of the line and\n% (dx,dy) is a direction vector of the line.\n% The resulting revolution surface still has Oz axis as symmetry axis. It\n% can be transformed using transformPoint3d function.\n% Surface can be displayed using :\n% H = surf(X, Y, Z);\n% H is a handle to the created patch.\n%\n% revolutionSurface(...);\n% by itself, directly shows the created patch.\n%\n% Example\n% % draws a piece of torus\n% circle = circleAsPolygon([10 0 3], 50);\n% [x y z] = revolutionSurface(circle, linspace(0, 4*pi/3, 50));\n% surf(x, y, z);\n% axis equal;\n%\n%\n%\n% See also\n% surf, transformPoint3d, drawSphere, drawTorus, drawEllipsoid\n% surfature (on Matlab File Exchange)\n%\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2004-04-09\n% Copyright 2005 INRA - CEPIA Nantes - MIAJ Jouy-en-Josas.\n\n% based on function cylinder from matlab\n% 31/06/2006 fix bug when passing 3 parameters\n% 20/04/2007 rewrite processing of input parameters, add psb to specify\n% revolution axis\n% 24/10/2008 fix angle vector\n% 29/07/2010 doc update\n\n\n%% Initialisations\n\n% default values\n\n% use revolution using the full unit circle, decomposed into 24 angular\n% segments (thus, some vertices correspond to particular angles 30°,\n% 45°...)\ntheta = linspace(0, 2*pi, 25);\n\n% use planar vertical axis as default revolution axis\nrevol = [0 0 0 1];\n\n% extract the generating curve\nvar = varargin{1};\nif size(var, 2)==1\n xt = var;\n yt = varargin{2};\n varargin(1:2) = [];\nelse\n xt = var(:,1);\n yt = var(:,2);\n varargin(1) = [];\nend\n\n% extract optional parameters: angles, axis of revolution\n% parameters are identified from their length\nwhile ~isempty(varargin)\n var = varargin{1};\n \n if length(var) == 4\n % axis of rotation in the base plane\n revol = var;\n \n elseif length(var) == 1\n % number of points -> create row vector of angles\n theta = linspace(0, 2*pi, var);\n \n else\n % use all specified angle values\n theta = var(:)';\n \n end\n varargin(1) = [];\nend\n\n\n%% Create revolution surface\n\n% ensure length is enough\nm = length(xt);\nif m==1\n xt = [xt xt];\nend\n\n% ensure x and y are vertical vectors\nxt = xt(:);\nyt = yt(:);\n\n% transform xt and yt to replace in the reference of the revolution axis\ntra = createTranslation(-revol(1:2));\nrot = createRotation(pi/2 - lineAngle(revol));\n[xt, yt] = transformPoint(xt, yt, tra*rot);\n\n% compute surface vertices\nx = xt * cos(theta);\ny = xt * sin(theta);\nz = yt * ones(size(theta));\n\n\n%% Process output arguments\n\n% format output depending on how many output parameters are required\nif nargout == 0\n % draw the revolution surface\n surf(x, y, z);\n \nelseif nargout == 1\n % draw the surface and return a handle to the shown structure\n h = surf(x, y, z);\n varargout{1} = h;\n \nelseif nargout == 3\n % return computed mesh\n varargout = {x, y, z};\nend\n\n\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/revolutionSurface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7194373664558033}} {"text": "% Copyright (C) Daphne Koller, Stanford University, 2012\n\nfunction [MEU OptimalDecisionRule] = OptimizeWithJointUtility( I )\n % Inputs: An influence diagram I with a single decision node and one or more utility nodes.\n % I.RandomFactors = list of factors for each random variable. These are CPDs, with\n % the child variable = D.var(1)\n % I.DecisionFactors = factor for the decision node.\n % I.UtilityFactors = list of factors representing conditional utilities.\n % Return value: the maximum expected utility of I and an optimal decision rule \n % (represented again as a factor) that yields that expected utility.\n % You may assume that there is a unique optimal decision.\n \n % This is similar to OptimizeMEU except that we must find a way to \n % combine the multiple utility factors. Note: This can be done with very\n % little code.\n \n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n %\n % YOUR CODE HERE\n %\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n Uti = I.UtilityFactors(1);\n for i = 2:length(I.UtilityFactors)\n\t Uti = FactorSum(Uti,I.UtilityFactors(i));\n end\n I.UtilityFactors = Uti;\n[MEU OptimalDecisionRule] = OptimizeMEU(I);\n \nend\n", "meta": {"author": "anhncs", "repo": "Probabilistic-Graphical-Models", "sha": "7fd4ef255db59ecbfe1a134cadbc4be5ca839894", "save_path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models", "path": "github-repos/MATLAB/anhncs-Probabilistic-Graphical-Models/Probabilistic-Graphical-Models-7fd4ef255db59ecbfe1a134cadbc4be5ca839894/6.Decision Making/OptimizeWithJointUtility.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7853085859124003, "lm_q1q2_score": 0.7194287469873271}} {"text": "% BOOSTING_EXAMPLE\n%\n% Constructs a 2-dimensional dataset classifiable by boosting, but not any\n% simple linear classifier, because of the thresholding nature of the data.\n\nrand('seed', 0);\n\n% m datapoints in 2-dimensions\nmm = 150;\nX = rand(mm, 2);\n\nthresh_pos = .6;\ny = [X(:, 1) < thresh_pos & X(:, 2) < thresh_pos];\ny = 2 * y - 1;\n\nfor T = [2, 4, 5, 10]\n figure;\n hpos = plot(X(y == 1, 1), X(y == 1, 2), 'o');\n hold on;\n hneg = plot(X(y == -1, 1), X(y == -1, 2), 'x');\n set(hpos, 'linewidth', 2);\n set(hneg, 'linewidth', 2);\n\n [theta, feature_inds, thresholds] = stump_booster(X, y, T);\n\n x1_coords = linspace(0, 1, 100);\n x2_coords = linspace(0, 1, 100);\n Z = zeros(100);\n for ii = 1:100\n for jj = 1:100\n pred = (sign(x1_coords(ii) - thresholds(feature_inds == 1))' * ...\n theta(feature_inds == 1)) + ...\n (sign(x2_coords(jj) - thresholds(feature_inds == 2))' * ...\n theta(feature_inds == 2));\n Z(jj, ii) = sign(pred);\n end\n end\n\n C = contourc(x1_coords, x2_coords, Z, [0 0]);\n h = plot(C(1, 2:end), C(2, 2:end), 'k-');\n set(h, 'linewidth', 2);\n title(sprintf('Iterations = %d', T));\n set(gca, 'fontsize', 18);\n print('-depsc2', sprintf('boost_plot_%d.eps', T));\nend\n\n%% Now solve the logistic regression problem directly\n\nmm = 200;\nX = rand(mm, 2);\ny = [X(:, 1) < thresh_pos & X(:, 2) < thresh_pos];\ny = 2 * y - 1;\n\ntheta_log = zeros(3, 1);\nX_logit = [ones(mm, 1), X];\nfor iter = 1:1000\n risk = (1/mm) * sum(log(1 + exp(-y .* (X_logit * theta_log))));\n if (mod(iter, 50) == 0)\n fprintf(1, 'Iter %d, loss %1.4f\\n', iter, risk);\n end\n p = 1 ./ (1 + exp(y .* (X_logit * theta_log)));\n g = -(1/mm) * X_logit' * (p .* y);\n theta_log = theta_log - 2 * g;\nend\n\nx1_coord = linspace(0, 1, 100);\nx2_coord = -(theta_log(1) + theta_log(2) * x1_coord) / theta_log(3);\n\nfigure;\nhpos = plot(X(y == 1, 1), X(y == 1, 2), 'o');\nhold on;\nhneg = plot(X(y == -1, 1), X(y == -1, 2), 'x');\nset(hpos, 'linewidth', 2);\nset(hneg, 'linewidth', 2);\nh = plot(x1_coord, x2_coord, 'k-', 'linewidth', 2);\naxis([0 1 0 1]);\nset(gca, 'fontsize', 18);\nprint -depsc2 'logistic_plot.eps';\n", "meta": {"author": "cycleuser", "repo": "Stanford-CS-229-CN", "sha": "4b4b6f0439e8b8b5fcdb5327b21fb1e2976fcaf2", "save_path": "github-repos/MATLAB/cycleuser-Stanford-CS-229-CN", "path": "github-repos/MATLAB/cycleuser-Stanford-CS-229-CN/Stanford-CS-229-CN-4b4b6f0439e8b8b5fcdb5327b21fb1e2976fcaf2/CS229官网当前文档/extra-notes/boosting_example.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.7853085783754369, "lm_q1q2_score": 0.7194287454786347}} {"text": "function [r, v] = orb2eci(mu, oev)\n\n% convert classical orbital elements to eci state vector\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% output\n\n% r = eci position vector (kilometers)\n% v = eci velocity vector (kilometers/second)\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nr = zeros(3, 1);\nv = zeros(3, 1);\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\nslr = sma * (1 - ecc * ecc);\n\nrm = slr / (1 + ecc * cos(tanom));\n \narglat = argper + tanom;\n\nsarglat = sin(arglat);\ncarglat = cos(arglat);\n \nc4 = sqrt(mu / slr);\nc5 = ecc * cos(argper) + carglat;\nc6 = ecc * sin(argper) + sarglat;\n\nsinc = sin(inc);\ncinc = cos(inc);\n\nsraan = sin(raan);\ncraan = cos(raan);\n\n% position vector\n\nr(1) = rm * (craan * carglat - sraan * cinc * sarglat);\nr(2) = rm * (sraan * carglat + cinc * sarglat * craan);\nr(3) = rm * sinc * sarglat;\n\n% velocity vector\n\nv(1) = -c4 * (craan * c6 + sraan * cinc * c5);\nv(2) = -c4 * (sraan * c6 - craan * cinc * c5);\nv(3) = c4 * c5 * sinc;\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/orb2eci.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012747599251, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.7194243620809221}} {"text": "function [xi,w]=thirdOrderTetrahedronCubPoints()\n%%THIRDORDERTETRAHEDRONCUBPOINTS Obtain third-order cubature points\n% for integration over a tetrahedron in 3D. The points and weights are\n% for the tetrahedron with vertices (1,0,0), (0,1,0), (0,0,1), and\n% (0,0,0), but can be transformed to any tetrahedron using\n% transformSimplexTetrahedronPts.\n%\n%INPUTS: None\n%\n%OUTPUTS: xi This is a 3XnumCubPoints set of points for the standard\n% tetrahedron.\n% w A 1XnumCubPoints set of cubature weights. This sums to the\n% volume of the standard tetrahedron (1/6).\n%\n%This function implements the points given in [1] (8 points).\n%\n%EXAMPLE:\n%Given the vertices of the simplex, we compare a third-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]=thirdOrderTetrahedronCubPoints();\n% alpha=[1;1;1];\n% theMoment=findMomentFromSamp(alpha,xi,w);\n% intVal=monomialIntSimplex(alpha);\n% RelErr=(theMoment-intVal)/intVal\n%\n%REFERENCES:\n%[1] 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\nM=[-0.34367339496723662642072827083693243093, -0.34367339496723662642072827083693243093, -0.9689798150982901207378151874892027072, 0.18162379004944980942342872025562069427;\n -0.34367339496723662642072827083693243093, -0.9689798150982901207378151874892027072, -0.34367339496723662642072827083693243093, 0.18162379004944980942342872025562069427;\n -0.9689798150982901207378151874892027072, -0.34367339496723662642072827083693243093, -0.34367339496723662642072827083693243093, 0.18162379004944980942342872025562069427;\n -0.34367339496723662642072827083693243093, -0.34367339496723662642072827083693243093, -0.34367339496723662642072827083693243093, 0.18162379004944980942342872025562069427;\n -0.78390550020314279176487322158837338344, -0.78390550020314279176487322158837338344, 0.35171650060942837529461966476512015033, 0.15170954328388352390990461307771263906;\n -0.78390550020314279176487322158837338344, 0.35171650060942837529461966476512015033, -0.78390550020314279176487322158837338344, 0.15170954328388352390990461307771263906;\n 0.35171650060942837529461966476512015033, -0.78390550020314279176487322158837338344, -0.78390550020314279176487322158837338344, 0.15170954328388352390990461307771263906;\n -0.78390550020314279176487322158837338344, -0.78390550020314279176487322158837338344, -0.78390550020314279176487322158837338344, 0.15170954328388352390990461307771263906];\nw=M(:,4);\nxi=M(:,1:3)';\n%Transform the points to the standard tetrahedron.\nv1=[-1, 1,-1,-1;\n -1,-1,-1, 1;\n -1,-1, 1, -1];\nv2=[1,0,0,0;\n 0,1,0,0;\n 0,0,1,0];\n[A,d]=affineTransBetweenTetrahedra(v1,v2);\nxi=bsxfun(@plus,A*xi,d);\nw=w/8;\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/Tetrahedra/thirdOrderTetrahedronCubPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7194175786596411}} {"text": "function dx = susp_sys(x,u)\n\n% Dynamics of the syspension system\nx1 = x(1);\nx2 = x(2);\nx3 = x(3);\nx4 = x(4);\n\n% Coefficients\nmb = 300; % kg\nmw = 60; % kg\nbs = 1000; % N/m/s\nks = 16000 ; % N/m\nkt = 190000; % N/m\nkn = ks/10; % N/m\n\n% System Dynamics\ndx1 = x2;\ndx2 = -(ks*(x1-x3)+kn*(x1-x3)^3)/mb - (bs*(x2-x4)-10000*u)/mb;\ndx3 = x4;\ndx4 = (ks*(x1-x3)+kn*(x1-x3)^3)/mw + (bs*(x2-x4)-kt*x3-10000*u)/mw;\n\n% Combine the output\ndx = [dx1;\n\t dx2;\n\t dx3;\n\t dx4];\nend", "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/Chapter3_Example1/susp_sys.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9566342037088041, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.719400960311323}} {"text": "function g = p13_g ( n, x )\n\n%*****************************************************************************80\n%\n%% P13_G evaluates the gradient for problem 13.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 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 s1 = sum ( cos ( x(1:n) ) );\n\n s2 = 0.0;\n for j = 1 : n\n t = ( n + j ) - sin ( x(j) ) - s1 - j * cos ( x(j) );\n s2 = s2 + t;\n g(j) = ( j * sin ( x(j) ) - cos ( x(j) ) ) * t;\n end\n\n for j = 1 : n\n g(j) = 2.0 * ( g(j) + sin ( x(j) ) * s2 );\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/p13_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.8152324938410783, "lm_q1q2_score": 0.7193838802872181}} {"text": "function im = UpsampleImage(img, line_factor, elem_factor)\n% Returns an FFT upsampled image.\n%\n% Returns an image which is upsampled by the inverse FFTing, zero padding\n% by the supplied amount (line_factor and elem_factor) and FFTing back.\n%\n% Usage:\n% im = UpsampleImage(img, line_factor, elem_factor)\n%\n% Example:\n% im = UpsampleImage(some_image data, 1.5, 1.5);\n%\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\n [rows,cols] = size(img);\n\n % Inverse FFT\n sp = fftshift(ifft2(fftshift(img))) / (rows*cols);\n %%%sp = ifft2(img) / (rows*cols);\n\n padded_data = zeros( floor(rows*line_factor), floor(cols*elem_factor) );\n if (line_factor < 1 && elem_factor < 1)\n row_start = floor((rows-(rows*line_factor))/2);\n row_length = size(padded_data,1);\n col_start = floor((cols-(cols*elem_factor))/2);\n col_length = size(padded_data,2);\n padded_data = sp(row_start:(row_start+row_length), ...\n col_start:(col_start+col_length));\n else\n % Zero pad around the edges\n off_line = floor((rows*line_factor - rows)/2.0);\n off_elem = floor((cols*elem_factor - cols)/2.0) ;\n padded_data(off_line:off_line+rows-1, off_elem:off_elem+cols-1) = sp;\n end\n\n % Then just FFT back to get the image.\n im = fftshift(fft2(fftshift(padded_data))) * (rows*cols);\n %%%im = fft2(padded_data) / (rows*cols);\nend\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Processing/filtering/UpsampleImage.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.7193565147398485}} {"text": "% Weighted random sampling.\n% \n% INPUTs: number of draws from a discrete distribution (n)\n% possible values to pick from, (P)\n% set of normalized weights/probabilities, (W)\n% OUTPUTs: s - set of n numbers drawn from P\n% according to the weights in W\n%\n% GB: last updated, Oct 31 2012\n\n\nfunction s = weightedRandomSample(n,P,W)\n\ns = [];\n\nif abs(sum(W)-1)>10**(-8); \n printf('The probabilities do not sum up to 1.\\n');\n s = 'probabilities do not sum up to 1';\n return; \nend\n\n% divide the unit interval into |P| segments each with length W_i\nunit = [0,W(1)];\nfor w=2:length(W)\n unit = [unit W(w)+unit(length(unit))];\nend\n\n% draw a random number in the unit interval uniformly - where does it fall?\nwhile length(s) 1, the PCA step\n% will keep exactly PCARatio principle\n% components (does not exceed the\n% exact number of non-zero components). \n%\n%\n% Output:\n% eigvector - Each column is an embedding function, for a new\n% sample vector (row vector) x, y = x*eigvector\n% will be the embedding result of x.\n% eigvalue - The sorted eigvalue of the eigen-problem.\n% elapse - Time spent on different steps \n% \n% \n%\n% Examples:\n%\n% See also LPP, NPE, IsoProjection, LSDA.\n%\n%\n%Reference:\n%\n% 1. Deng Cai, Xiaofei He, Jiawei Han, \"Spectral Regression for Efficient\n% Regularized Subspace Learning\", IEEE International Conference on\n% Computer Vision (ICCV), Rio de Janeiro, Brazil, Oct. 2007. \n%\n% 2. Deng Cai, Xiaofei He, Yuxiao Hu, Jiawei Han, and Thomas Huang, \n% \"Learning a Spatially Smooth Subspace for Face Recognition\", CVPR'2007\n% \n% 3. Deng Cai, Xiaofei He, Jiawei Han, \"Spectral Regression: A Unified\n% Subspace Learning Framework for Content-Based Image Retrieval\", ACM\n% Multimedia 2007, Augsburg, Germany, Sep. 2007.\n%\n% 4. Deng Cai, \"Spectral Regression: A Regression Framework for\n% Efficient Regularized Subspace Learning\", PhD Thesis, Department of\n% Computer Science, UIUC, 2009. \n%\n% version 3.0 --Dec/2011 \n% version 2.1 --June/2007 \n% version 2.0 --May/2007 \n% version 1.0 --Sep/2006 \n%\n% Written by Deng Cai (dengcai AT gmail.com)\n%\n\nMAX_MATRIX_SIZE = 1600; % You can change this number according your machine computational power\nEIGVECTOR_RATIO = 0.1; % You can change this number according your machine computational power\n\nif (~exist('options','var'))\n options = [];\nend\n\nReducedDim = 30;\nif isfield(options,'ReducedDim')\n ReducedDim = options.ReducedDim;\nend\n\nif ~isfield(options,'Regu') || ~options.Regu\n bPCA = 1;\n if ~isfield(options,'PCARatio')\n options.PCARatio = 1;\n end\nelse\n bPCA = 0;\n if ~isfield(options,'ReguType')\n options.ReguType = 'Ridge';\n end\n if ~isfield(options,'ReguAlpha')\n options.ReguAlpha = 0.1;\n end\nend\n\nbD = 1;\nif ~exist('D','var') || isempty(D)\n bD = 0;\nend\n\n\n[nSmp,nFea] = size(data);\nif size(W,1) ~= nSmp\n error('W and data mismatch!');\nend\nif bD && (size(D,1) ~= nSmp)\n error('D and data mismatch!');\nend\n\nbChol = 0;\nif bPCA && (nSmp > nFea) && (options.PCARatio >= 1)\n if bD\n DPrime = data'*D*data;\n else\n DPrime = data'*data;\n end\n DPrime = full(DPrime);\n DPrime = max(DPrime,DPrime');\n [R,p] = chol(DPrime);\n if p == 0\n bPCA = 0;\n bChol = 1;\n end\nend\n\n%======================================\n% SVD\n%======================================\n\nif bPCA \n [U, S, V] = mySVD(data);\n [U, S, V]=CutonRatio(U,S,V,options);\n eigvalue_PCA = full(diag(S));\n if bD\n data = U*S;\n eigvector_PCA = V;\n\n DPrime = data'*D*data;\n DPrime = max(DPrime,DPrime');\n else\n data = U;\n eigvector_PCA = V*spdiags(eigvalue_PCA.^-1,0,length(eigvalue_PCA),length(eigvalue_PCA));\n end\nelse\n if ~bChol\n if bD\n DPrime = data'*D*data;\n else\n DPrime = data'*data;\n end\n\n switch lower(options.ReguType)\n case {lower('Ridge')}\n if options.ReguAlpha > 0\n for i=1:size(DPrime,1)\n DPrime(i,i) = DPrime(i,i) + options.ReguAlpha;\n end\n end\n case {lower('Tensor')}\n if options.ReguAlpha > 0\n DPrime = DPrime + options.ReguAlpha*options.regularizerR;\n end\n case {lower('Custom')}\n if options.ReguAlpha > 0\n DPrime = DPrime + options.ReguAlpha*options.regularizerR;\n end\n otherwise\n error('ReguType does not exist!');\n end\n\n DPrime = max(DPrime,DPrime');\n end\nend\n\nWPrime = data'*W*data;\nWPrime = max(WPrime,WPrime');\n\n\n\n%======================================\n% Generalized Eigen\n%======================================\n\ndimMatrix = size(WPrime,2);\n\nif ReducedDim > dimMatrix\n ReducedDim = dimMatrix; \nend\n\n\nif isfield(options,'bEigs')\n bEigs = options.bEigs;\nelse\n if (dimMatrix > MAX_MATRIX_SIZE) && (ReducedDim < dimMatrix*EIGVECTOR_RATIO)\n bEigs = 1;\n else\n bEigs = 0;\n end\nend\n\n\nif bEigs\n %disp('use eigs to speed up!');\n option = struct('disp',0);\n if bPCA && ~bD\n [eigvector, eigvalue] = eigs(WPrime,ReducedDim,'la',option);\n else\n if bChol\n option.cholB = 1;\n [eigvector, eigvalue] = eigs(WPrime,R,ReducedDim,'la',option);\n else\n [eigvector, eigvalue] = eigs(WPrime,DPrime,ReducedDim,'la',option);\n end\n end\n eigvalue = diag(eigvalue);\nelse\n if bPCA && ~bD \n [eigvector, eigvalue] = eig(WPrime);\n else\n [eigvector, eigvalue] = eig(WPrime,DPrime);\n end\n eigvalue = diag(eigvalue);\n \n [junk, index] = sort(-eigvalue);\n eigvalue = eigvalue(index);\n eigvector = eigvector(:,index);\n\n if ReducedDim < size(eigvector,2)\n eigvector = eigvector(:, 1:ReducedDim);\n eigvalue = eigvalue(1:ReducedDim);\n end\nend\n\n\nif bPCA\n eigvector = eigvector_PCA*eigvector;\nend\n\nfor i = 1:size(eigvector,2)\n eigvector(:,i) = eigvector(:,i)./norm(eigvector(:,i));\nend\n\n \n\n\n\nfunction [U, S, V]=CutonRatio(U,S,V,options)\n if ~isfield(options, 'PCARatio')\n options.PCARatio = 1;\n end\n\n eigvalue_PCA = full(diag(S));\n if options.PCARatio > 1\n idx = options.PCARatio;\n if idx < length(eigvalue_PCA)\n U = U(:,1:idx);\n V = V(:,1:idx);\n S = S(1:idx,1:idx);\n end\n elseif options.PCARatio < 1\n sumEig = sum(eigvalue_PCA);\n sumEig = sumEig*options.PCARatio;\n sumNow = 0;\n for idx = 1:length(eigvalue_PCA)\n sumNow = sumNow + eigvalue_PCA(idx);\n if sumNow >= sumEig\n break;\n end\n end\n U = U(:,1:idx);\n V = V(:,1:idx);\n S = S(1:idx,1:idx);\n end\n", "meta": {"author": "ZJULearning", "repo": "MatlabFunc", "sha": "97504df0f597c1980ab76ddc0c9c5d669043c6c9", "save_path": "github-repos/MATLAB/ZJULearning-MatlabFunc", "path": "github-repos/MATLAB/ZJULearning-MatlabFunc/MatlabFunc-97504df0f597c1980ab76ddc0c9c5d669043c6c9/SubspaceLearning/LGE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.7193090735116972}} {"text": "%KDOG Difference of Gaussian kernel\n%\n% K = KDOG(SIGMA1) is a 2-dimensional difference of Gaussian kernel equal \n% to KGAUSS(SIGMA1) - KGAUSS(SIGMA2), where SIGMA1 > SIGMA2. By default\n% SIGMA2 = 1.6*SIGMA1. The kernel is centred within the matrix K whose \n% half-width H = 3xSIGMA and W=2xH+1.\n% \n% K = KDOG(SIGMA1, SIGMA2) as above but SIGMA2 is specified directly.\n%\n% K = KDOG(SIGMA1, SIGMA2, H) as above but the kernel half-width is specified.\n%\n% Notes::\n% - This kernel is similar to the Laplacian of Gaussian and is often used\n% as an efficient approximation.\n%\n% See also KGAUSS, KDGAUSS, KLOG, ICONV.\n\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB 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% MVTB 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 MVTB. If not, see .\n\nfunction m = kdog(sigma1, sigma2, w)\n\n % sigma1 > sigma2\n if nargin == 1\n sigma2 = 1.6*sigma1;\n w = ceil(2*sigma2);\n elseif nargin == 2\n sigma2 = 1.6*sigma1;\n w = ceil(2*sigma2);\n elseif nargin == 3\n if sigma2 < sigma1\n t = sigma1;\n sigma1 = sigma2;\n sigma2 = t;\n end\n end\n\tif nargin < 3\n w = ceil(3*sigma1);\n\tend\n\n % sigma2 > sigma1\n m1 = kgauss(sigma1, w); % thin kernel\n m2 = kgauss(sigma2, w); % wide kernel\n\n m = m2 - m1;\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/kdog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7192171906695615}} {"text": "function stat_ds=cosmo_stat(ds, stat_name, output_stat_name)\n% compute t-test or F-test (ANOVA) statistic\n%\n% stat_ds=cosmo_stats(ds, stat_name[, output_stat_name])\n%\n% Inputs:\n% ds dataset struct with\n% .samples PxQ, for P observations on Q features\n% .sa.targets Px1 observation conditions (classes)\n% .sa.chunks Px1 observation chunks (e.g. subjects).\n% stat_name One of [*]:\n% 't' : one-sample t-test against zero (nclasses==1),\n% or paired t-test (nclasses==2)\n% 't2': two-sample t-test with equal variance,\n% (nclasses==2) contrasting samples with unq(1)\n% minus unq(2) where unq=unique(ds.sa.targets)\n% 'F' : one-way ANOVA or repeated measures ANOVA\n% (nclasses>=2)\n% [*] nclasses is the number of unique values in\n% ds.sa.targets\n% output_stat_name (optional) 'left', 'right', 'both', 'z', 'p', or\n% the empty string '' (default).\n% - 'left', 'right', and 'both' return a p-value with\n% the specified tail.\n% - 'p' returns a p-value, with tail='right' if\n% stat_name='F' and tail='both' otherwise.\n% - 'z' returns a z-score corresponding to the p-value\n% - '' (empty) returns the t or F statistic.\n% Missing values can be indicated by NaNs; if these are\n% present and a p-value or z-score is returned, then\n% these values are computed with a possible variable\n% number of degrees of freedom across features.\n%\n% Returns:\n% stat_ds dataset struct with fields:\n% .samples 1xQ statistic value, or (if output_stat_name is\n% non-empty) z-score or p-value. See the Notes below\n% for interpreting p-values.\n% .sa struct with field:\n% .stats One of 'Ftest(df1,df2)', 'Ttest(df)', 'Zscore()', or\n% 'Pval()', where df* are the degrees of freedom\n% .[f]a identical to the input ds.[f]a, if present.\n%\n% Examples:\n% % one-sample t-test\n% % make a simple dataset\n% ds=struct();\n% ds.samples=reshape(mod(1:7:(12*3*7),13)',[],3)-3;\n% ds.sa.targets=ones(12,1);\n% ds.sa.chunks=(1:12)';\n% cosmo_disp(ds.samples);\n% %|| [ -2 4 -3\n% %|| 5 -2 4\n% %|| -1 5 -2\n% %|| : : :\n% %|| 9 2 8\n% %|| 3 9 2\n% %|| -3 3 9 ]@12x3\n% %\n% % run one-sample t-test\n% s=cosmo_stat(ds,'t');\n% cosmo_disp(s);\n% %|| .samples\n% %|| [ 2.49 3.36 2.55 ]\n% %|| .sa\n% %|| .stats\n% %|| { 'Ttest(11)' }\n% %\n% % compute z-score of t-test\n% s=cosmo_stat(ds,'t','z');\n% cosmo_disp(s);\n% %|| .samples\n% %|| [ 2.17 2.73 2.21 ]\n% %|| .sa\n% %|| .stats\n% %|| { 'Zscore()' }\n% %\n% % compute (two-tailed) p-value of t-test\n% s=cosmo_stat(ds,'t','p');\n% cosmo_disp(s);\n% %|| .samples\n% %|| [ 0.03 0.00633 0.0268 ]\n% %|| .sa\n% %|| .stats\n% %|| { 'Pval()' }\n% %\n% % compute left-tailed p-value of t-test\n% s=cosmo_stat(ds,'t','left');\n% cosmo_disp(s);\n% %|| .samples\n% %|| [ 0.985 0.997 0.987 ]\n% %|| .sa\n% %|| .stats\n% %|| { 'Pval()' }\n%\n% % one-way ANOVA\n% % each observation is independent and thus each chunk is unique;\n% % there are three conditions with four observations per condition\n% ds=struct();\n% ds.samples=reshape(mod(1:7:(12*3*7),13)',[],3)-3;\n% ds.sa.targets=repmat(1:3,1,4)';\n% ds.sa.chunks=(1:12)';\n% s=cosmo_stat(ds,'F');\n% cosmo_disp(s);\n% %|| .samples\n% %|| [ 0.472 0.0638 0.05 ]\n% %|| .sa\n% %|| .stats\n% %|| { 'Ftest(2,9)' }\n% % compute z-score\n% s=cosmo_stat(ds,'F','z'); % convert to z-score\n% cosmo_disp(s);\n% %|| .samples\n% %|| [ -0.354 -1.54 -1.66 ]\n% %|| .sa\n% %|| .stats\n% %|| { 'Zscore()' }\n%\n%\n% % two-sample t-test\n% % each observation is independent and thus each chunk is unique;\n% % there are two conditions with four observations per condition\n% ds=struct();\n% ds.samples=reshape(mod(1:7:(12*3*7),13)',[],3)-3;\n% ds.sa.targets=repmat(1:2,1,6)';\n% ds.sa.chunks=(1:12)';\n% s=cosmo_stat(ds,'t2','p'); % return p-value\n% cosmo_disp(s);\n% %|| .samples\n% %|| [ 0.0307 0.000242 7.07e-05 ]\n% %|| .sa\n% %|| .stats\n% %|| { 'Pval()' }\n% %\n% % for illustration, this test gives the same p-values as a\n% % repeated measures ANOVA\n% s=cosmo_stat(ds,'F','p');\n% cosmo_disp(s);\n% %|| .samples\n% %|| [ 0.0307 0.000242 7.07e-05 ]\n% %|| .sa\n% %|| .stats\n% %|| { 'Pval()' }\n%\n% Notes:\n% - If output_stat_name is not provided or empty, then this function runs\n% considerably faster than the builtin matlab functions\n% (ttest, ttest2, or anova1).\n% - When output_stat_name=='p' then the p-values returned are the same as\n% the builtin matlab functions anova1, ttest, and ttest2 with the\n% default tails.\n% - To run a one-sample t-tests against x (if x~=0), one has to\n% subtract x from ds.samples before using ds as input to this function\n% - The .sa.chunks and .sa.targets determine which test is performed:\n% * statname=='t': all chunks are unique => one-sample t-test\n% : each chunk present twice => paired-sample t-test\n% * statname=='F': all chunks are unique => one-way ANOVA\n% : each chunk present N times => repeated measures ANOVA\n% See cosmo_montecarlo_cluster_stat for examples on how .sa.targets and\n% .sa.chunks should be set for different statistics.\n% - Missing values can be indicated by NaNs, and if the output is a\n% p-value (or a z-score based on the p-value), then the output is\n% computed for different features using varying degrees of freedom.\n% For example, if the dataset has 10 samples and a one-sample t-test is\n% used, z-scores for samples with no NaN values is based on the\n% t-statistic with df=9, but those with two missing values (NaN values)\n% are based on the t-statistic with df=7. A use case is computing fMRI\n% group statistics where overlap across brains is not perfect at the\n% voxel-by-voxel level, in as imilar approach as AFNI's 3dttest++ with\n% the '-toz' option.\n% - This function computes feature-wise statistics that are not corrected\n% for multiple comparisons. To correct for multiple comparisons, see\n% cosmo_montecarlo_cluster_stat.\n%\n% See also: anova1, ttest, ttest2, cosmo_montecarlo_cluster_stat\n%\n% # For CoSMoMVPA's copyright information and license terms, #\n% # see the COPYING file distributed with CoSMoMVPA. #\n\n if nargin<3\n output_stat_name='';\n end\n\n [output_stat_name,tail]=get_stat_definition(stat_name,...\n output_stat_name);\n [samples,targets,chunks,type]=get_descriptors(ds);\n\n % run specified helper function\n if isfield(ds.sa,'contrast')\n contrast=ds.sa.contrast;\n else\n contrast=[];\n end\n\n % ensure stat_name matches the number of classes\n verify_class_count(stat_name,targets);\n\n % get ttest1, ttest2 or Ftest function handle\n stat_func=get_stat_func(stat_name);\n\n % apply statistic function handle\n [stat,df_struct,stat_label]=apply_stat_func(stat_func,...\n samples,targets,chunks,type,contrast);\n\n % convert to p-value or z-score, if necessary\n [stat,stat_label]=compute_output_stat(stat,df_struct,stat_label,...\n tail,output_stat_name);\n\n % store output\n stat_ds=struct();\n if isfield(ds,'a'), stat_ds.a=ds.a; end\n if isfield(ds,'fa'), stat_ds.fa=ds.fa; end\n stat_ds.samples=stat;\n stat_ds.sa.stats={stat_label};\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% helper functions\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [stat,df_struct,stat_label]=apply_stat_func(stat_func,...\n samples,targets,chunks,...\n type,contrast)\n% applies the stat_func to samples, taking into account missing values\n% (indicated by NaN) in samples\n samples_nan_msk=isnan(samples);\n has_missing=any(any(samples_nan_msk,1) & ~all(samples_nan_msk,1));\n if ~has_missing\n [stat,df_struct,stat_label]=apply_stat_func_no_nans(stat_func,...\n samples,targets,chunks,...\n type,contrast);\n return;\n end\n\n [nsamples,nfeatures]=size(samples);\n stat=zeros(1,nfeatures);\n\n zeroed_samples=samples;\n zeroed_samples(~samples_nan_msk)=0;\n\n nan_counts=sum(samples_nan_msk,1);\n unq_counts=unique(nan_counts);\n\n % build indicator matrix, so that a value in zeroed_samples(i,j)=v\n % - v=0 means that samples(i,j) is not NaN\n % - v=k, k>0 means that samples(i,j) is the k-th NaN value in that\n % column\n for c=1:numel(unq_counts)\n count=unq_counts(c);\n col_msk=nan_counts==count;\n\n msk=bsxfun(@and, samples_nan_msk, col_msk);\n zeroed_samples(msk)=repmat((1:count)',1,sum(col_msk));\n end\n\n % using the indicator matrix, split up the samples in blocks so that\n % in each block, the same rows in samples are NaN. Each block is\n % processed seperately in the 'for' loop below.\n\n [indices, zeroed_unq]=cosmo_index_unique(zeroed_samples');\n\n nclasses=max(targets);\n\n for k=1:numel(indices)\n zeroed=zeroed_unq(k,:)';\n cols=indices{k};\n\n nan_msk=zeroed>0;\n\n % keep samples where there are non-NaN values for the corresponding\n % chunk\n keep_msk=any(bsxfun(@eq,chunks(:),chunks(~nan_msk)'),2);\n keep_samples=samples(keep_msk,cols);\n\n % ensure chunks are numbered 1:max(chunks)\n [unused,unused,keep_chunks]=unique(chunks(keep_msk));\n\n % select targets\n keep_targets=targets(keep_msk);\n\n % compute t or F statistic\n [stat_k,df,stat_label_k]=stat_func(keep_samples,...\n keep_targets,...\n keep_chunks,...\n type,contrast);\n\n % if for some samples in a chunk the value was NaN and for others\n % it was not NaN, then the output is NaN\n has_mixed_nan_and_non_nan=any(nan_msk(keep_msk));\n\n % if a target value was completely non-present, then\n % the output is NaN\n keep_targets_msk=false(1,nclasses);\n keep_targets_msk(targets(keep_msk))=true;\n\n if has_mixed_nan_and_non_nan || any(~keep_targets_msk)\n stat_k(:)=NaN;\n end\n\n % store stat val\n stat(cols)=stat_k;\n\n if k==1\n % allocate space\n df_count=numel(df);\n df_matrix=zeros(df_count,nfeatures);\n stat_label=stat_label_k;\n else\n % stat label must always be the same\n assert(isequal(stat_label,stat_label_k));\n end\n\n ncols=numel(cols);\n\n df_matrix(:,cols)=repmat(df(:),1,ncols);\n end\n\n single_sample=samples(:,1);\n single_sample(:)=0;\n\n [unused,max_df]=stat_func(single_sample,targets,chunks,...\n type,contrast);\n\n df_struct=struct();\n df_struct.max_df=max_df(:);\n df_struct.feature_wise_df=df_matrix;\n\n\nfunction [stat,df_struct,stat_label]=apply_stat_func_no_nans(stat_func,...\n samples,targets,chunks,...\n type,contrast)\n % much faster computation of statistics, if there are no NaNs\n [stat,max_df,stat_label]=stat_func(samples,targets,chunks,...\n type,contrast);\n\n nfeatures=size(samples,2);\n\n df_struct=struct();\n df_struct.max_df=max_df(:);\n df_struct.feature_wise_df=repmat(max_df(:),1,nfeatures);\n\n\n\nfunction f=get_stat_func(stat_name)\n stat_name2func=struct();\n stat_name2func.t=@ttest1_wrapper;\n stat_name2func.t2=@ttest2_wrapper;\n stat_name2func.F=@ftest_wrapper;\n\n assert(isfield(stat_name2func,stat_name))\n\n f=stat_name2func.(stat_name);\n\nfunction verify_class_count(stat_name,targets)\n stat_name2interval=struct();\n stat_name2interval.t=[1,2];\n stat_name2interval.t2=[2,2];\n stat_name2interval.F=[2,Inf];\n\n if ~isfield(stat_name2interval,stat_name)\n error('illegal statname ''%s'', supported are: %s',stat_name,...\n cosmo_strjoin(fieldnames(stat_name2interval),', '));\n end\n\n valid_interval=stat_name2interval.(stat_name);\n\n count=max(targets);\n assert(count==numel(unique(targets)));\n\n min_count=valid_interval(1);\n if countmax_count\n error('statname ''%s'' requires at most %d unique targets',...\n stat_name,max_count);\n end\n\n\n\nfunction [stat,stat_label]=compute_output_stat(stat,df_struct,stat_name,...\n tail,output_stat_name)\n% transform output is required\n\n if isempty(output_stat_name)\n % raw t or F value\n stat_fa_name=stat_name;\n\n % features with missing values (as indicated by df values that\n % are different from the maximum df possible) are set to NaN\n df_is_max_msk=bsxfun(@eq,df_struct.max_df,...\n df_struct.feature_wise_df);\n has_missing=~all(df_is_max_msk,1);\n stat(has_missing)=NaN;\n\n % set degrees of freedom\n df_str=arrayfun(@(x) sprintf('%d',x), df_struct.max_df,...\n 'UniformOutput',false);\n stat_label=sprintf('%s(%s)',stat_fa_name,...\n cosmo_strjoin(df_str,','));\n else\n % transform to left-tailed p-value for each unique combination\n % of degrees of freedom\n stat=apply_cdf_wrapper_different_dfs(stat_name,stat,df_struct);\n\n switch output_stat_name\n case 'z'\n % transform to z-score\n stat=cosmo_norminv(stat);\n stat_fa_name='Zscore';\n case 'p'\n switch tail\n case 'left'\n % do nothing\n case 'right'\n % invert p-value\n stat=1-stat;\n case 'both'\n % take whichever tail is more extreme\n stat=(.5-abs(stat-.5))*2;\n otherwise\n assert(false,'this should not happen');\n end\n stat_fa_name='Pval';\n otherwise\n error('illegal output type %s', output_stat_name);\n end\n\n stat_label=sprintf('%s()',stat_fa_name);\n end\n\n\nfunction cdf_stat=apply_cdf_wrapper_different_dfs(stat_name,stat,df_struct)\n % applies the cdf wrapper to each unique combination of degrees of\n % freedom stored in df_struct.feature_wise_df\n\n [idx, unique_dfs]=cosmo_index_unique(df_struct.feature_wise_df');\n\n % allocate space for output\n cdf_stat=zeros(size(stat))+NaN;\n\n % compute result\n for k=1:numel(idx)\n cols=idx{k};\n df_cell=num2cell(unique_dfs(k,:));\n\n col_stat=stat(cols);\n msk=~isnan(col_stat);\n\n cdf_stat(cols(msk))=cdf_wrapper(stat_name,col_stat(msk),df_cell{:});\n end\n\nfunction y=cdf_wrapper(name, x, df1, df2)\n ensure_has_stats_functions();\n if ~(df1>0)\n y=zeros(size(x))+NaN;\n return;\n end\n\n switch name\n case 'Ttest'\n assert(nargin==3);\n y=tcdf(x, df1);\n\n case 'Ftest'\n assert(nargin==4);\n if ~(df2>0)\n y=zeros(size(x))+NaN;\n return;\n end\n\n y=fcdf(x, df1, df2);\n\n otherwise\n assert(false);\n end\n\n\n\nfunction [stat,df,stat_label]=ttest1_wrapper(samples,targets,chunks,...\n type,contrast)\n if ~isempty(contrast)\n error('contrast is not supported for t-stat');\n end\n\n nclasses=max(targets);\n if nclasses==2\n samples=pairwise_differences(samples,targets,chunks);\n nclasses=1;\n end\n\n if nclasses~=1\n error('t-stat: expected 1 or 2 classes, found %d',...\n nclasses);\n end\n\n [stat,df]=quick_ttest(samples);\n stat_label='Ttest';\n\nfunction [stat,df,stat_label]=ttest2_wrapper(samples,targets,chunks,...\n type,contrast)\n if ~isempty(contrast)\n error('contrast is not supported for t-stat');\n end\n\n\n\n if strcmp(type,'within')\n error(['ttest2 stat: the values in chunks and targets suggest '...\n 'a within-subject design. If you want to '...\n 'run a paired-test, use ''t'' (not ''t2'') ',...\n 'as the second argument']);\n end\n\n m1=targets==1;\n m2=targets==2;\n\n [stat,df]=quick_ttest2(samples(m1,:),...\n samples(m2,:));\n nclasses=max(targets);\n if nclasses~=2\n % missing targets, set all to NaN\n assert(nclasses<2)\n stat(:)=NaN;\n end\n\n stat_label='Ttest';\n\nfunction [stat,df,stat_label]=ftest_wrapper(samples,targets,chunks,...\n type,contrast)\n nclasses=max(targets);\n\n if nclasses<2\n error('F stat: expected >=2 classes, found %d',nclasses);\n end\n\n switch type\n case 'between'\n [stat,df]=quick_ftest_between(samples, targets, ...\n chunks,contrast);\n case 'within'\n [stat,df]=quick_ftest_within(samples, targets, ...\n chunks,contrast);\n\n end\n stat_label='Ftest';\n\n\nfunction [f,df]=quick_ftest_between(samples,targets,chunks,contrast)\n % one-way ANOVA\n has_contrast=~isempty(contrast);\n contrast_sum=0;\n\n nclasses=max(targets);\n\n [ns,nf]=size(samples);\n mu=sum(samples,1)/ns; % grand mean\n\n b=zeros(nclasses,nf); % between-class sum of squares\n nsc=zeros(nclasses,1);\n wss=0; % within-class sum of squares\n\n for k=1:nclasses\n msk=k==targets;\n\n nsc(k)=sum(msk); % number of samples in this class\n sample=samples(msk,:);\n muc=sum(sample,1)/nsc(k); % class mean\n\n % between- and within-class sum of squares\n if has_contrast\n cmsk=contrast(msk);\n if ~all(cmsk(1)==cmsk)\n error('Contrast has differerent values in level %d',k);\n end\n contrast_sum=contrast_sum+cmsk(1);\n b(k,:)=sum(bsxfun(@times,contrast(msk),mu-muc),1);\n else\n b(k,:)=(mu-muc);\n end\n wss=wss+sum(bsxfun(@minus,muc,sample).^2,1);\n end\n\n if has_contrast\n if contrast_sum~=0\n error('contrast has sum %d, should be 0', contrast_sum);\n end\n bss=sum(b,1).^2/sum(contrast.^2);\n df1=1;\n else\n bss=sum(bsxfun(@times,nsc,b.^2),1);\n df1=nclasses-1;\n end\n\n df=[df1,ns-nclasses];\n\n mbss=bss/df(1);\n mwss=wss/df(2);\n\n f=zeros(1,nf)+NaN;\n msk=mbss>0;\n f(msk)=mbss(msk)./mwss(msk);\n\nfunction [f,df]=quick_ftest_within(samples,targets,chunks,contrast)\n % repeated measures anova\n if ~isempty(contrast)\n error('contrast is not supported for within-subject design');\n end\n\n nchunks=max(chunks);\n nclasses=max(targets);\n\n nfeatures=size(samples,2);\n gm=mean(samples,1); % grand mean\n\n sst=zeros(1,nfeatures);\n ssw=zeros(1,nfeatures);\n for k=1:nclasses\n xk=samples(k==targets,:);\n n=size(xk,1);\n\n if n==0\n ssw(:)=NaN;\n break;\n end\n\n mu=sum(xk,1)/n;\n sst=sst+n*(gm-mu).^2;\n ssw=ssw+sum(bsxfun(@minus,mu,xk).^2);\n end\n\n sss=zeros(1,nfeatures);\n for k=1:nchunks\n xk=samples(k==chunks,:);\n n=size(xk,1);\n mu=mean(xk,1);\n sss=sss+n*(gm-mu).^2;\n end\n\n df1=(nclasses-1);\n mst=sst/df1;\n\n df2=df1*(nchunks-1);\n sse=ssw-sss;\n mse=sse/df2;\n\n msk=mse>0;\n f=zeros(1,nfeatures)+NaN;\n f(msk)=mst(msk)./mse(msk);\n df=[df1 df2];\n\n\n\nfunction [t,df]=quick_ttest(x)\n % one-sample t-test against zero\n\n [ns,nf]=size(x);\n mu=sum(x,1)/ns; % grand mean\n\n df=ns-1;\n scaling=ns*df;\n\n % sum of squares\n ss=sum(bsxfun(@minus,x,mu).^2,1);\n\n t=zeros(1,nf)+NaN;\n msk=ss>0;\n t(msk)=mu(msk).*sqrt(scaling./ss(msk));\n\n\nfunction [t,df]=quick_ttest2(x,y)\n % two-sample t-test with equal variance assumption\n\n [nx,nf]=size(x);\n ny=size(y,1);\n\n df=nx+ny-2;\n if nx==0 || ny==0\n t=zeros(1,nf)+NaN;\n return;\n end\n\n mux=sum(x,1)/nx; % mean of class x\n muy=sum(y,1)/ny; % \" \" y\n\n scaling=(nx*ny)*df/(nx+ny);\n\n % sum of squares\n ss=sum([bsxfun(@minus,x,mux);bsxfun(@minus,y,muy)].^2,1);\n\n t=zeros(1,nf)+NaN;\n msk=ss>0;\n t(msk)=(mux(msk)-muy(msk)) .* sqrt(scaling./ss(msk));\n\n\n\nfunction ensure_has_stats_functions()\n % - Octave has the required functionality in the octave-forge\n % statistics toolbox and will raise an error if it is not installed.\n % - Matlab will raise an error message that the statistics toolbox is\n % required\n persistent cached_has_stat_funcs;\n\n if isequal(cached_has_stat_funcs,[])\n if cosmo_wtf('is_matlab') ...\n && isempty(which('tinv')) ...\n && isempty(which('fcdf'))\n raise_exception_if_absent=true;\n cached_has_stat_funcs=cosmo_check_external('@stats', ...\n raise_exception_if_absent);\n else\n cached_has_stat_funcs=false;\n end\n end\n\nfunction [samples,targets,chunks,type]=get_descriptors(ds)\n cosmo_isfield(ds,{'samples','sa.chunks','sa.targets'},true);\n\n samples=ds.samples;\n\n % unique targets\n [unused,unusued,targets]=unique(ds.sa.targets);\n\n % unique chunks\n [unq_chunks,unusued,chunks]=unique(ds.sa.chunks);\n nc=max(chunks);\n\n if isequal(sort(ds.sa.chunks),unq_chunks)\n type='between';\n else\n combis=(targets-1)*nc+chunks;\n if isequal(sort(combis),(1:numel(combis))')\n type='within';\n else\n error(['Either all chunks must be unique, or each chunk '...\n 'must contain the same targets']);\n end\n end\n\nfunction delta=pairwise_differences(samples,targets,chunks)\n % for one-sample t-test: compute differences between first and second\n % target\n n=size(samples,1);\n assert(numel(targets)==n);\n assert(numel(chunks)==n);\n\n assert(mod(n,2)==0);\n n2=n/2;\n\n idxs=zeros(n2,2);\n for k=1:n\n assert(idxs(chunks(k),targets(k))==0);\n idxs(chunks(k),targets(k))=k;\n end\n assert(isequal(size(idxs),[n2,2]));\n assert(all(idxs(:)>0));\n\n delta=samples(idxs(:,1),:)-samples(idxs(:,2),:);\n\nfunction [output_stat_name,tail]=get_stat_definition(stat_name,...\n output_stat_name)\n if any(cosmo_match({'left','right','both'},output_stat_name))\n tail=output_stat_name;\n output_stat_name='p';\n elseif strcmp(output_stat_name,'p')\n switch stat_name\n case 'F'\n tail='right'; % show anova1 behaviour w.r.t. p-values\n otherwise\n tail='both'; % show ttest[2] \" \"\n end\n else\n tail='both';\n end\n\n", "meta": {"author": "CoSMoMVPA", "repo": "CoSMoMVPA", "sha": "5de75a1b4bef89b082d39d69e2b99d7f894ad717", "save_path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA", "path": "github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA/CoSMoMVPA-5de75a1b4bef89b082d39d69e2b99d7f894ad717/mvpa/cosmo_stat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.719130030850834}} {"text": "function a = moler1_inverse ( alpha, n )\n\n%*****************************************************************************80\n%\n%% MOLER1_INVERSE returns the inverse of the MOLER1 matrix.\n%\n% Formula:\n%\n% if ( I = J )\n% A(I,J) = min ( N-I, N-J ) * ALPHA^2 + 1\n% else\n% A(I,J) = (-1)^(I+J) * min ( N-I, N-J ) * ALPHA^2 + ALPHA\n%\n% Example:\n%\n% ALPHA = 2, N = 5\n%\n% 17 -14 10 -6 2\n% -14 13 -10 6 -2\n% 10 -10 9 -6 2\n% -6 6 -6 5 -2\n% 2 -2 2 -2 1\n%\n% Properties:\n%\n% The matrix is symmetric.\n%\n% Successive elements of each diagonal decrease by ALPHA**2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real ALPHA, the scalar that defines the inverse \n% Moler matrix.\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n v = zeros ( n, 1 );\n v(1) = 1.0;\n v(2) = - alpha;\n for i = 3 : n\n v(i) = - ( alpha - 1.0 ) * v(i-1);\n end\n\n for i = 1 : n\n for j = 1 : n\n if ( i <= j )\n a(i,j) = v(1+j-i:n+1-i)' * v(1 :n+1-j);\n else\n a(i,j) = v(1 :n+1-i)' * v(1+i-j:n+1-j);\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/moler1_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7191249868504251}} {"text": "% Sample Code to test the Tensor Completion program :\n\nclear;\n\nn1 = 50; \nn2 = 50; \nn3 = 50; \nr = 5;\ntol = [];\nnitr = []; \nninit = [];\n\n% generate random low-rank orthogonal tensor\nU01 = randn(n1,r);U02 = randn(n2,r);U03 = randn(n3,r);\n[U1 temp] = qr(U01);[U2 temp] = qr(U02);[U3 temp] = qr(U03);\nU1=U1(:,1:r);U2=U2(:,1:r);U3=U3(:,1:r);\nT = zeros(n1,n2,n3);\nfor i=1:n3\n T(:,:,i) = U1*diag(U3(i,:))*U2';\nend\n\n% sample entries \np = 2*(r^0.5*log(n1*n2*n3))/sqrt(n1*n2*n3); \nE = ceil(rand(n1,n2,n3)-1+p);\nTE = T.*E;\n\n% exact tensor completion\nfprintf(1,'exact tensor completion using alternating minimization\\n');\n[V1 V2 V3 S dist] = TenALS(TE, E, r, ninit, nitr, tol);\nrmse=0;\nfor i3=1:n3 \n A1 = U1;\n A2 = U2*diag(U3(i3,:));\n B1 = V1;\n B2 = V2*diag(V3(i3,:).*S(:)');\n rmse = rmse + trace(A1'*A1*A2'*A2) + trace(B1'*B1*B2'*B2) -2*trace(B1'*A1*A2'*B2) ;\nend\nfprintf(1,'root mean squared error = %e\\n',sqrt(rmse/r));\n\n% noisy tensor completion\nfprintf(1,'\\nnoisy tensor completion using alternating minimization\\n');\n[V1 V2 V3 S dist] = TenALS(TE+(0.0001/sqrt(n1*n2*n3)*randn(n1,n2,n3).*E), E, r, ninit, nitr, tol);\nrmse=0;\nfor i3=1:n3 \n A1 = U1;\n A2 = U2*diag(U3(i3,:));\n B1 = V1;\n B2 = V2*diag(V3(i3,:).*S(:)');\n rmse = rmse + trace(A1'*A1*A2'*A2) + trace(B1'*B1*B2'*B2) -2*trace(B1'*A1*A2'*B2) ;\nend\nfprintf(1,'root mean squared error = %e\\n',sqrt(rmse/r));\n\n", "meta": {"author": "andrewssobral", "repo": "mctc4bmi", "sha": "fbcbcd25654b818646387c3d6a64304fb60e12dd", "save_path": "github-repos/MATLAB/andrewssobral-mctc4bmi", "path": "github-repos/MATLAB/andrewssobral-mctc4bmi/mctc4bmi-fbcbcd25654b818646387c3d6a64304fb60e12dd/algs_tc/TenALS/testing.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.719092495205957}} {"text": "function M0 = matching_ind_und(CIJ)\n%MATCHING_IND_UND matching index\n%\n% M0 = MATCHING_IND_UND(CIJ) computes matching index for undirected\n% graph specified by adjacency matrix CIJ. Matching index is a measure of\n% similarity between two nodes' connectivity profiles (excluding their\n% mutual connection, should it exist).\n%\n% Inputs: CIJ, undirected adjacency matrix\n%\n% Outputs: M0, matching index matrix.\n%\n% Richard Betzel, Indiana University, 2013\n%\nCIJ0 = CIJ;\nK = sum(CIJ0);\nR = K ~= 0;\nN = sum(R);\nCIJ = CIJ0(R,R);\nI = ~eye(N);\nM = zeros(N,N);\nfor i = 1:N\n \n c1 = CIJ(i,:);\n use = bsxfun(@or,c1,CIJ);\n use(:,i) = 0;\n use = use.*I;\n \n ncon1 = bsxfun(@times,use,c1);\n ncon2 = bsxfun(@times,use,CIJ);\n ncon = sum(ncon1 + ncon2,2);\n \n M(:,i) = 2*sum(ncon1 & ncon2,2)./ncon;\n \nend\nM = M.*I;\nM(isnan(M)) = 0;\nM0 = zeros(size(CIJ0));\nM0(R,R) = M;", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bct/matching_ind_und.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7190924810612875}} {"text": "function x = r8pbu_sl ( n, mu, a_lu, b )\n\n%*****************************************************************************80\n%\n%% R8PBU_SL solves a R8PBU system factored by R8PBU_FA.\n%\n% Discussion:\n%\n% The R8PBU storage format is for a symmetric positive definite band matrix.\n%\n% To save storage, only the diagonal and upper triangle of A is stored,\n% in a compact diagonal format that preserves columns.\n%\n% The diagonal is stored in row MU+1 of the array.\n% The first superdiagonal in row MU, columns 2 through N.\n% The second superdiagonal in row MU-1, columns 3 through N.\n% The MU-th superdiagonal in row 1, columns MU+1 through N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 March 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, Philadelphia, 1979.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, integer MU, the number of superdiagonals of the matrix.\n% MU must be at least 0 and no more than N-1.\n%\n% Input, real A_LU(MU+1,N), the matrix, as factored by R8PBU_FA.\n%\n% Input, real B(N), the right hand side of the linear system.\n%\n% Output, real X(N), the solution vector.\n%\n x(1:n) = b(1:n);\n%\n% Solve L * Y = B.\n%\n for k = 1 : n\n ilo = max ( 1, k - mu );\n x(k) = ( x(k) - x(ilo:k-1) * a_lu(mu+1+ilo-k:mu,k) ) ...\n / a_lu(mu+1,k);\n end\n%\n% Solve U * X = Y.\n%\n for k = n : -1 : 1\n\n x(k) = x(k) / a_lu(mu+1,k);\n\n ilo = max ( 1, k - mu );\n for i = ilo : k-1\n x(i) = x(i) - x(k) * a_lu(mu+1+i-k,k);\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/r8pbu_sl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7190606149445131}} {"text": "function [ o, x, w ] = cn_jac_02_xiu ( n, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CN_JAC_02_XIU implements the Xiu rule for region CN_JAC.\n%\n% Discussion:\n%\n% The rule has order\n%\n% O = N + 1.\n%\n% The rule has precision P = 2.\n%\n% CN is the cube [-1,+1]^N with the Jacobi (beta) weight function\n%\n% w(alpha,beta;x) = product ( 1 <= i <= n ) (1-x(i))^beta (1+x(i))^alpha.\n%\n% with -1 < alpha, -1 < beta.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 March 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, real ALPHA, BETA, the parameters.\n% -1.0 < ALPHA, -1.0 < BETA.\n%\n% Output, integer O, the order.\n%\n% Output, real X(N,O), the abscissas.\n%\n% Output, real W(O), the weights.\n%\n if ( alpha <= -1.0 )\n fprint ( 1, '\\n' );\n fprint ( 1, 'CN_JAC_02_XIU - Fatal error!\\n' );\n fprint ( 1, ' ALPHA <= -1.0\\n' );\n error ( 'CN_JAC_02_XIU - Fatal error!' );\n end\n\n if ( beta <= -1.0 )\n fprint ( 1, '\\n' );\n fprint ( 1, 'CN_JAC_02_XIU - Fatal error!\\n' );\n fprint ( 1, ' BETA <= -1.0\\n' );\n error ( 'CN_JAC_02_XIU - Fatal error!' );\n end\n\n o = n + 1;\n\n x = zeros ( n, o );\n w = zeros ( o, 1 );\n\n for j = 1 : o\n\n i = 0;\n for r = 1 : floor ( n / 2 )\n arg = 2 * r * ( j - 1 ) * pi / ( n + 1 );\n i = i + 1;\n x(i,j) = sqrt ( 2.0 ) * cos ( arg );\n i = i + 1;\n x(i,j) = sqrt ( 2.0 ) * sin ( arg );\n end\n\n if ( i < n )\n i = i + 1;\n x(i,j) = r8_mop ( j - 1 );\n end\n\n end\n\n gamma0 = ( alpha + beta + 2.0 ) / 2.0;\n delta0 = ( alpha - beta ) / 2.0;\n c1 = 2.0 * ( alpha + 1.0 ) * ( beta + 1.0 ) / ( alpha + beta + 3.0 ) ...\n / ( alpha + beta + 2.0 );\n\n x(1:n,1:o) = ( sqrt ( gamma0 * c1 ) * x(1:n,1:o) - delta0 ) / gamma0;\n\n expon = 0;\n volume_1d = c1_jac_monomial_integral ( alpha, beta, expon );\n volume = volume_1d ^ n;\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_jac_02_xiu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7190606141715503}} {"text": "function exact = p37_exact ( )\n\n%*****************************************************************************80\n%\n%% P37_EXACT returns the exact integral for problem 37.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 November 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real EXACT, the value of the integral.\n%\n alpha = p37_param_get ( );\n\n exact = atan ( ( 4.0 - pi ) * 4.0^( alpha - 1.0 ) ) ...\n + atan ( pi * 4.0^( alpha - 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_int/p37_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7190493192483144}} {"text": "function inds = graphPeripheralVertices(v, e, l)\n%GRAPHPERIPHERALVERTICES Peripheral vertices of a graph\n%\n% INDS = graphPeripheralVertices(V, E)\n% Return indices of peripheral vertices, that is, vertices whose\n% eccentricity is maximal and equal to the diameter of the graph.\n%\n% INDS = graphPeripheralVertices(V, E, L)\n% Specify length of each edge. Default is 1 for each edge.\n%\n%\n% Example\n% nodes = [20 20;20 50;20 80;50 50;80 20;80 50;80 80];\n% edges = [1 2;2 3;2 4;4 6;5 6;6 7];\n% figure; drawGraph(nodes, edges);\n% axis([0 100 0 100]); axis equal; hold on\n% INDP = graphPeripheralVertices(nodes, edges);\n% INDP = \n% 1\n% 3\n% 5\n% 7\n% \n%\n% See Also\n% grPropagateDistance, grVertexEccentricity\n% graphCenter, graphDiameter, graphRadius\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-09-07, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n% ensure there is a valid length array\nif nargin<3\n l = ones(size(e,1), 1);\nend\n\ng = grVertexEccentricity(v, e, l);\n\ninds = find(g==max(g));\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/graphs/graphPeripheralVertices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7190266929296243}} {"text": "\n\n% Copyright (C) 1993-2017, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\n%%begin\n\n% In the field of robotics there are many possible ways of representing \n% orientations of which the most common are: \n% - orthonormal rotation matrices (3x3),\n% - three angles (1x3), and\n% - quaternions.\n\n% A rotation of pi/2 about the x-axis can be represented as an orthonormal rotation\n% matrix\n\nR = rotx(pi/2)\n% which we can see is a 3x3 matrix.\n\n% Such a matrix has the property that it's columns (and rows) are sets of orthogonal\n% unit vectors. The determinant of such a matrix is always 1\n\ndet(R)\n\n% Let's create a more complex rotation\n\nR = rotx(30, 'deg') * roty(50, 'deg') * rotz(10, 'deg')\n% where this time we have specified the rotation angle in degrees.\n\n% Any rotation can be expressed in terms of a single rotation about some axis\n% in space\n\n[theta,vec] = tr2angvec(R)\n% where theta is the angle (in radians) and vec is unit vector representing the\n% direction of the rotation axis.\n\n% Commonly rotations are represented by Euler angles\n\neul = tr2eul(R)\n% which are three angles such that R = rotz(a)*roty(b)*rotz(c), ie. the rotations\n% required about the Z, then then the Y, then the Z axis.\n\n% Rotations are also commonly represented by roll-pitch-yaw angles\n\nrpy = tr2rpy(R)\n% which are three angles such that R = rotx(r)*roty(p)*rotz(y), ie. the rotations\n% required about the X, then then the Y, then the Z axis.\n\n% We can investigate the effects of rotations about different axes\n% using this GUI based demonstration. The menu buttons allow the rotation\n% axes to be varied\n% *** close the window when you are done.\ntripleangle('rpy', 'wait')\n\n% The final useful form is the quaternion which comprises 4 numbers. We can create\n% a quaternion from an orthonormal matrix\n\nq = Quaternion(R)\n% where we can see that it comprises a scalar part and a vector part. To convert back\n\nq.R\n% which is the same of the value of R we determined above.\n\n% Quaternions are a class and the orientations they represent can be compounded, just\n% as we do with rotation matrices by multiplication.\n\n% First we create two quaternions\n\nq1 = Quaternion( rotx(pi/2) )\nq2 = Quaternion( roty(pi/2) )\n\n% then the rotation of q1 followed by q2 is simply\n\nq1 * q2\n\n% We can also take the inverse of a Quaternion\n\nq1 * inv(q1)\n% which results in a null rotation (zero vector part)\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/demos/rotation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571774, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7190266814615871}} {"text": "function c = he_polynomial_coefficients ( n )\n\n%*****************************************************************************80\n%\n%% HE_POLYNOMIAL_COEFFICIENTS: coefficients of He(i,x).\n%\n% Discussion:\n%\n% He(i,x) represents the probabilist's Hermite polynomial.\n%\n% First terms:\n%\n% N/K 0 1 2 3 4 5 6 7 8 9 10\n%\n% 0 1\n% 1 0 1\n% 2 -1 0 1\n% 3 0 -3 0 1\n% 4 3 0 -6 0 1\n% 5 0 15 0 -10 0 1\n% 6 -15 0 45 0 -15 0 1\n% 7 0 -105 0 105 0 -21 0 1\n% 8 105 0 -420 0 210 0 -28 0 1\n% 9 0 945 0 -1260 0 378 0 -36 0 1\n% 10 -945 0 4725 0 -3150 0 630 0 -45 0 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Parameters:\n%\n% Input, integer N, the highest order polynomial to compute.\n% Note that polynomials 0 through N will be computed.\n%\n% Output, real C(1:N+1,1:N+1), the coefficients of the Hermite polynomials.\n%\n if ( n < 0 )\n c = [];\n return\n end\n\n c(1:n+1,1:n+1) = 0.0;\n\n c(1,1) = 1.0;\n\n if ( n == 0 )\n return\n end\n\n c(2,2) = 1.0;\n \n for i = 2 : n\n c(i+1,1) = - ( i - 1 ) * c(i-1,1);\n c(i+1,2:i-1) = c(i ,1:i-2) - ( i - 1 ) * c(i-1,2:i-1);\n c(i+1, i ) = c(i , i-1);\n c(i+1, i+1) = c(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/hermite_polynomial/he_polynomial_coefficients.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7189587938438735}} {"text": "% Vm = vsh_modified_in_fast(theta,phi,l,m,p0)\n%\n% Vector spherical harmonic funtion modified from Hill's function\n% V_lm for quantum numbers l and m. Angles theta and phi should be\n% given in radians. p0 contains the values of the Legendre polynomial.\n%\nfunction Vm = vsh_modified_in_fast(theta,phi,l,m,p0)\n\n% Copyright (c) 2016, Elekta Oy\n% ---------------------------------------\n% \n% Redistribution and use of the Software in source and binary forms, with or without \n% modification, are permitted for non-commercial use.\n% \n% The Software is provided \"as is\" without warranties of any kind, either express or\n% implied including, without limitation, warranties that the Software is free of defects,\n% merchantable, fit for a particular purpose. Developer/user agrees to bear the entire risk \n% in connection with its use and distribution of any and all parts of the Software under this license.\n% \n\nscale = 1;\n\n%scale_sph = (-1)^m*sqrt((2*l+1)*prod(1:(l-m))/(4*pi*prod(1:(l+m))));\n%scale_minus = 1/((-1)^(m-1)*sqrt((2*l+1)*prod(1:(l-(m-1)))/(4*pi*prod(1:(l+(m-1))))));\n%scale_plus = 1/((-1)^(m+1)*sqrt((2*l+1)*prod(1:(l-(m+1)))/(4*pi*prod(1:(l+(m+1))))));\n\nY = spharm_fast(theta,phi,l,m,p0);\nif m > -l\n Yminus = spharm_fast(theta,phi,l,m-1,p0);\nelse\n Yminus = 0;\nend\nif m < l\n Yplus = spharm_fast(theta,phi,l,m+1,p0);\nelse\n Yplus = 0;\nend\n\ncosp = cos(phi); sinp = sin(phi);\n%dY = 0.5*scale_sph*((l+m)*(l-m+1)*scale_minus*Yminus*complex(cos(phi),sin(phi))-scale_plus*Yplus*complex(cos(-phi),sin(-phi))); % dY/dtheta\n%dY = 0.5*(-sqrt((l+m)*(l-m+1))*Yminus*complex(cos(phi),sin(phi))+sqrt((l-m)*(l+m+1))*Yplus*complex(cos(-phi),sin(-phi)));\ndY = 0.5*(-sqrt((l+m)*(l-m+1))*Yminus*complex(cosp,sinp)+sqrt((l-m)*(l+m+1))*Yplus*complex(cosp,-sinp));\nif theta == 0 % To prevent division by zero\n theta = eps;\nend\nVm(1) = scale*(-(l+1))*Y;\nVm(2) = scale*dY;\nVm(3) = scale*(i*m/sin(theta))*Y;\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/TSSS/private/vsh_modified_in_fast.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7188600275678442}} {"text": "function [a,resnorm]=Optimize_my_LM2(Loss_fun,a0,data,TolX,TolFun,MaxIter)\n\n% author Zhang Xin\n\n\ntao=1e-10;\nxk=a0;\n\nv=2;\n\n\nJacobi=Get_Jacobi(Loss_fun,xk,data);\nEk=Loss_fun(xk,data);\n\ng=Jacobi'*Ek;\n\nfound=logical(norm(g)<=TolFun);\nmou=tao*max(diag(Jacobi'*Jacobi));\n\nk=0;\nwhile (~found && k0\n \n fprintf('Iterations: %d, Residual: %d, Step: %d \\n',k,Ek'*Ek,norm(delta_x));\n k=k+1;\n \n xk=xk_new;\n Jacobi=Get_Jacobi(Loss_fun,xk,data);\n Ek=Loss_fun(xk,data);\n g=Jacobi'*Ek;\n found=(norm(g)<=TolFun);\n mou=mou*max([1/3,1-(2*rho-1)^3]);\n v=2;\n else\n mou=mou*v;\n v=2*v;\n \n end\n \n end\n\nend\n\n\nxk=xk+delta_x';\nEk=Loss_fun(xk,data);\nfprintf('Iterations: %d, Residual: %d, Step: %d \\n',k,Ek'*Ek,norm(delta_x));\n\n\n\na=xk;\n\nresnorm=Ek'*Ek;\n\n\n\n\nend\n\n\nfunction Jacobi=Get_Jacobi(Loss_fun,xk,data)\n\nscale=1e-4;\n\n%Ek=Loss_fun(xk,data);\n\nfor i=1:length(xk)\n x_temp1=xk;\n x_temp2=xk;\n if abs(x_temp1(i))>scale\n \n delta=x_temp1(i)*scale;\n else\n delta=scale;\n end\n x_temp1(i)=x_temp1(i)+delta;\n x_temp2(i)=x_temp2(i)-delta;\n\n E_temp1=Loss_fun(x_temp1,data);\n\n E_temp2=Loss_fun(x_temp2,data);\n\n Jacobi(:,i)=(E_temp1-E_temp2)/delta/2;\n\nend\n\nend\n\n\n\n", "meta": {"author": "shenshikexmu", "repo": "IMUCalibration-Gesture", "sha": "11cbf1bc018ab04a65856381674f670a48cd6b82", "save_path": "github-repos/MATLAB/shenshikexmu-IMUCalibration-Gesture", "path": "github-repos/MATLAB/shenshikexmu-IMUCalibration-Gesture/IMUCalibration-Gesture-11cbf1bc018ab04a65856381674f670a48cd6b82/Optimize_my_LM2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7188600269877702}} {"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%\ntemp= sigmoid( X*theta);\nfor i=1:m\n if temp(i) >=0.5\n p(i)=1;\n else\n p(i)=0;\n end\n \nend\n\n\n\n\n\n\n% =========================================================================\n\n\nend\n", "meta": {"author": "zzlyw", "repo": "machine-learning-exercises", "sha": "10f91ee832f4e64607dafa634a27d115e0744cb5", "save_path": "github-repos/MATLAB/zzlyw-machine-learning-exercises", "path": "github-repos/MATLAB/zzlyw-machine-learning-exercises/machine-learning-exercises-10f91ee832f4e64607dafa634a27d115e0744cb5/machine-learning-ex2/ex2/predict.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7188456674216605}} {"text": "function point_num = sphere_llt_point_num ( lat_num, long_num )\n\n%*****************************************************************************80\n%\n%% SPHERE_LLT_POINT_NUM counts points for an LLT grid on a sphere in 3D.\n%\n% Discussion:\n%\n% An LLT grid is a grid of triangles defined by latitude and longitude\n% lines over the surface of a sphere in 3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 29 April 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer LAT_NUM, LONG_NUM, the number of latitude \n% and longitude lines to draw. The latitudes do not include the North and \n% South poles, which will be included automatically, so LAT_NUM = 5, for \n% instance, will result in points along 7 lines of latitude.\n%\n% Output, integer POINT_NUM, the number of grid points.\n%\n point_num = 2 + lat_num * long_num;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sphere_llt_grid/sphere_llt_grid_point_count.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8418256393148982, "lm_q1q2_score": 0.7188456554320461}} {"text": "function [d] = spm_kl_normal (m_q,c_q,m_p,c_p)\n% KL divergence between two multivariate normal densities\n% FORMAT [d] = spm_kl_normal (m_q,c_q,m_p,c_p)\n%\n% KL (Q||P) = where avg is wrt Q\n%\n% between two Normal densities Q and P\n%\n% m_q, c_q Mean and covariance of first Normal density\n% m_p, c_p Mean and covariance of second Normal density\n%___________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: spm_kl_normal.m 2696 2009-02-05 20:29:48Z guillaume $\n\nd=length(m_q);\nm_q=m_q(:);\nm_p=m_p(:);\n\nTerm1=0.5*spm_logdet(c_p)-0.5*spm_logdet(c_q);\n\ninv_c_p=inv(c_p);\nTerm2=0.5*trace(inv_c_p*c_q)+0.5*(m_q-m_p)'*inv_c_p*(m_q-m_p);\n\nd=Term1+Term2-0.5*d;\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/spm_kl_normal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.7188108528985754}} {"text": "function x = r8mat_utsol ( n, r, b )\n\n%*****************************************************************************80\n%\n%% R8MAT_UTSOL solves R' * X = B for an upper triangular matrix R.\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% MATLAB version by 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% LC: QA214.L56.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real R(N,N), the upper triangular matrix.\n%\n% Input, real B(N), the right hand side.\n%\n% Output, real X(N), the solution.\n%\n x(1:n,1) = b(1:n);\n\n x(1,1) = x(1,1) / r(1,1);\n\n for j = 2 : n\n x(j,1) = ( x(j,1) - r(1:j-1,j)' * x(1:j-1,1) ) / r(j,j);\n end\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/pdflib/r8mat_utsol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7187909704015762}} {"text": "function [rs, eigvals, eigvecs] = pca(s, mode, maxpercent)\n\n%tstoolbox/@signal/pca\n% Syntax:\n% * [rs, eigvals, eigvecs] = pca(s) => mode='normalized' , maxpercent\n% = 95\n% * [rs, eigvals, eigvecs] = pca(s, mode) => maxpercent = 95\n% * [rs, eigvals, eigvecs] = pca(s, mode, maxpercent)\n%\n% Input arguments:\n% * each row of data is one 'observation', e.g. the sample values of\n% all channels in a multichannel measurement at one point in time\n% * mode can be one of the following : 'normalized' (default), 'mean',\n% 'raw'\n% + in mode 'normalized' each column of data is centered by\n% removing its mean and then normalized by dividing through its\n% standard deviation before the covariance matrix is calculated\n% + in mode 'mean' only the mean of every column of data is\n% removed\n% + in mode 'raw' no preprocessing is applied to data\n% * maxpercent gives the limit of the accumulated percentage of the\n% resulting eigenvalues, default is 95 %\n%\n% Principal component analysis of column orientated data set.\n%\n% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt\n\n%\n% principal component analysis of column orientated data set \n% \n% input arguments :\n%\n% - each row of data is one 'observation', e.g. the sample values of\n% all channels in a multichannel measurement at one point in time\n%\n% - mode can be one of the following : 'normalized' (default), 'mean', 'raw'\n% - in mode 'normalized' each column of data is centered by removing its mean\n% and then normalized by dividing through its standard deviation before\n% the covariance matrix is calculated\n% - in mode 'mean' only the mean of every column of data is removed\n% - in mode 'raw' no preprocessing is applied to data\n%\n% - maxpercent gives the limit of the accumulated percentage of the resulting\n% eigenvalues, default is 95 %\n%\n% [rs, eigvals, eigvecs] = pca(s) => mode='normalized' , maxpercent = 95\n% [rs, eigvals, eigvecs] = pca(s, mode) => maxpercent = 95 \n% [rs, eigvals, eigvecs] = pca(s, mode, maxpercent)\n%\n% C.Merkwirth,U.Parlitz,W.Lauterborn DPI Goettingen 1998\n\nnarginchk(1,3);\n\nif nargin < 2\n\tmode = 'normalized';\nend\nif nargin < 3\n\tmaxpercent = 95;\nend\n\nif ndim(s)~=2\n\terror('pca needs a signal with two dimensions as input')\nend\n\ndat = data(s);\nn = dlens(s,1);\nm = dlens(s,2);\n\nhtext = {''};\nhtext{end+1} = 'Applied Karhunen-Loeve Transform (pca)';\nhtext{end+1} = ['Tried to capture ' num2str(maxpercent) ' percent of total variance'];\n\nmpercent = maxpercent/100;\nmode = lower(mode); \t\t% no problems with uppercase letters \n\nif strncmp(mode, 'r',1)\n\tmode = 'raw';\n\thtext{end+1} = 'No data preprocessing';\nelseif strncmp(mode, 'm',1)\n\tmode = 'mean';\n\thtext{end+1} = 'Removed mean from data set';\n\tmn = mean(dat);\n\tdat = dat - repmat(mn, n, 1);\nelse\n\tmode = 'normalized';\n\thtext{end+1} = 'Removed mean and normalized data';\n\tmn = mean(dat);\n\tdv = std(dat);\n\tdat = dat - repmat(mn, n, 1);\n\tdat = dat ./ repmat(dv, n, 1);\nend\n\nif n>m\n\thtext{end+1} = 'Used direct method to compute covariance matrix';\n\tK = dat' * dat; % oder K = corrcoef(dat)\n\t[Q,D] = eig(K);\n else\n htext{end+1} = 'using indirect method to compute covariance matrix';\n \tC = dat * dat';\n \t[Q,D] = eig(C);\t \nend\n\n[evalues,index] = sort(diag(D));\nevalues = flipud(evalues);\nindex = flipud(index);\n\ntotal = sum(evalues);\nrlvm = min(find(cumsum(evalues) >= (total*mpercent)));\n\nif isempty(rlvm)\t\t\t% in case percentage was choosen over 100 %,\n\trlvm = length(evalues); % return all eigenvalues\nend\n\nfrvals = evalues(1:rlvm);\n\nif n>m\n\tfrvecs = Q(:, index(1:rlvm));\n\ttrnsfrmd=dat*frvecs;\nelse\n \tscalefac = 1./ sqrt(evalues(1:rlvm));\n \tfor i = 1:rlvm\n \t\tP(:,i) = Q(:,index(i)) * scalefac(i);\n \tend\n \tfrvecs = dat' * P; % '\n\ttrnsfrmd=C*P;\nend\n\na = achse(unit, 1,1);\na = setname(a, 'Mode');\n \nrs = signal(core(trnsfrmd), s);\nrs = addhistory(rs, htext);\nrs = addcommandlines(rs, 's = pca(s', mode, maxpercent);\nrs = setaxis(rs, 2, a);\n%rs = settype(rs, 'Transformed data set');\nrs = setplothint(rs, 'multigraph');\n\neigvals = signal(core(frvals),s);\neigvals = addhistory(eigvals, htext);\neigvals = addcommandlines(eigvals, '[dummy, s] = pca(s', mode, maxpercent);\neigvals = setaxis(eigvals, 1, a);\n%eigvals = settype(eigvals, 'Eigenvalues');\neigvals = setplothint(eigvals, 'bar');\n\neigvecs = signal(core(frvecs),s);\neigvecs = addhistory(eigvecs, htext);\neigvecs = addcommandlines(eigvecs, '[dummy, dummy2, s] = pca(s', mode, maxpercent);\neigvecs = setaxis(eigvecs, 2, a);\neigvecs = setaxis(eigvecs, 1, getaxis(s,2));\n%eigvecs = settype(eigvecs, 'Eigenvectors');\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/OpenTSTOOL/tstoolbox/@signal/pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.7187909638552806}} {"text": "function [G]=erdosRenyi(nv,p,Kreg)\n%Funciton [G]=edosRenyi(nv,p,Kreg) generates a random graph based on\n%the Erdos and Renyi algoritm where all possible pairs of 'nv' nodes are\n%connected with probability 'p'. \n%\n% Inputs:\n% nv - number of nodes \n% p - rewiring probability\n% Kreg - initial node degree of for regular graph (use 1 or even numbers)\n%\n% Output:\n% G is a structure inplemented as data structure in this as well as other\n% graph theory algorithms.\n% G.Adj - is the adjacency matrix (1 for connected nodes, 0 otherwise).\n% G.x and G.y - are row vectors of size nv wiht the (x,y) coordinates of\n% each node of G.\n% G.nv - number of vertices in G\n% G.ne - number of edges in G\n%\n%Created by Pablo Blinder. blinderp@bgu.ac.il\n%\n%Last update 25/01/2005\n\n%build regular lattice \nA=sparse(nv,nv);\nKreg=fix(abs(Kreg)/2);Kreg=(Kreg<1)+Kreg;\n\nfor k=1:Kreg\n A=sparse(A+diag(ones(1,length(diag(A,k))),k)+diag(ones(1,length(diag(A,nv-k))),nv-k));\nend\nne0=nnz(A);\n%find connected pairs\n[v1,v2]=find(A);\n% P=permPairs(nv);%my version is faster\nDis=(rand(length(v1),1)<=p);%pairs to disconnect\nA(v1(Dis),v2(Dis))=0;\nvDis=unique([v1(Dis),v2(Dis)]);%disconnected vertices\nnDis=ne0-nnz(A);sum(Dis);\n\n%cycle trough disconnected pairs\ndisconPairs=[v1(Dis),v2(Dis)];\nfor n=1:nDis\n %choose one of the vertices from the disconnected pair\n i=ceil(rand*size(disconPairs,1));\n j=logical(1+rand>0.5);\n vDisToRec=disconPairs(i,j);\n %find non adjacent vertices and reconnect\n adj=[find(A(:,vDisToRec)) ; find(A(vDisToRec,:))'];\n nonAdj=setdiff(1:nv,adj);\n vToRec=nonAdj(ceil(rand*length(nonAdj)));\n S=sort([vDisToRec vToRec]);\n A(S(1),S(2))=1;\nend\n[x,y]=getNodeCoordinates(nv);\n%make adjacency matrix symetric\nA=A+fliplr((flipud(triu(A))));\nG=struct('Adj',A,'x',x','y',y','nv',nv,'ne',nnz(A));\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/4206-erdos-renyi-random-graph/erdosRenyi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7187909574936054}} {"text": "% Filename: ora_foc.m\n% Oustaloup-Recursive-Approximation for fractional order differentiator\n% Reference\n% [1] Oustaloup, A.; Levron, F.; Mathieu, B.; Nanot, F.M.; \"Frequency-band \n% complex noninteger differentiator: characterization and synthesis\". \n% EEE Transactions on Circuits and Systems I: Fundamental Theory and \n% Applications, I , Volume: 47 Issue: 1, Jan. 2000, Page(s): 25 -39\n% [2] D. Xue, Y.Q. Chen and D. Atherton. \"Linear feedback control - \n% analysis and design with Matlab 6.5\". Textbook draft. Chapter 9\n% \"Fractional order control - An introduction\". PDF available upon\n% request. Send request email to \"yqchen@ieee.org\".\n% by YangQuan Chen. Nov. 2001. \n% Utah State University. http://www.csois.usu.edu/people/yqchen/\n% FOC web http://mechatronics.ece.usu.edu/foc/\n%\n% Input variables:\n% r: the fractional order as in s^r, r is a real number\n% N: order of the finite TF approximation for both (num/den)\n% (Note: 2N+1 recursive z-p pairs)\n% w_L: low frequency limit of the range of the frequency of interest\n% w_H: upper freq. limit of the range of the frequency of interest\n% Output: \n% sys_foc: continuous time transfer function system object (TF)\n% Sample values: w_L=0.1;w_H=1000; r=0.5; N=4; \n% Existing problem: Be careful when doing \"c2d\", I met some problems.\nfunction [sys_foc]=ora_foc(r,N,w_L,w_H)\nw_L=w_L*0.1;w_H=w_H*10; % enlarge the freq. range of interest for goodness\nmu=w_H/w_L; %\nw_u=sqrt(w_H*w_L);\nalpha=(mu)^(r/(2*N+1)); \neta=(mu)^((1-r)/(2*N+1)); \nk=-N:N;\nw_kp=(mu).^( (k+N+0.5-0.5*r)/(2*N+1) )*w_L;\nw_k=(mu).^( (k+N+0.5+0.5*r)/(2*N+1) )*w_L;\nD_N_K=(w_u/w_H)^r * prod(w_k) / prod(w_kp);\nD_N_P=-w_k;D_N_Z=-w_kp;\n[num,den]=zp2tf(D_N_Z',D_N_P',D_N_K); \nsys_foc=tf(num,den);\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/22196-solution-of-fractional-optimal-control-problems/ora_foc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.718777451553448}} {"text": "function constant_test ( )\n\n%*****************************************************************************80\n%\n%% CONSTANT_TEST examines the constant correlation.\n%\n% Discussion:\n%\n% This code is based substantially on a document by Toby Driscoll.\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% Reference:\n%\n% Toby Driscoll,\n% Mercer's theorem and the Karhunen-Loeve expansion,\n% Oxford University Mathematical Institute,\n% http://www2.maths.ox.ac.uk/chebfun/examples/stats/pdf/MercerKarhunenLoeve.pdf\n%\n rmpath ( '/usr/local/matlab/toolbox/datafeed/datafeed' )\n addpath ( '../chebfun' )\n\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CONSTANT_TEST:\\n' );\n fprintf ( 1, ' Demonstrate Mercer''s theorem and the KL expansion\\n' );\n fprintf ( 1, ' for the constant kernel.\\n' );\n%\n% Set the interval.\n%\n a = 0.0;\n b = +10.0;\n fprintf ( 1, ' Using interval [%g,%g]\\n', a, b );\n s_num = 21;\n s_vec = linspace ( a, b, s_num );\n%\n% FRED is a function from the CHEBFUN library.\n%\n% It constructs a \"chebop\" representing the Fredholm integral operator\n% with kernel K for functions in domain [A,B].\n%\n F = fred ( @constant_correlation, domain ( [ a, b ] ) );\n%\n% EIGS has been extended to be able to compute the eigenvalues Lambda\n% and eigenfunctions Psi of the Fredholm integral operator represented by F.\n%\n% The \"LM\" switch requests that we return the eigenvalues of largest magnitude.\n%\n% Each Psi is a CHEBFUN, that is, it takes a real number argument.\n%\n eigen_num = 20;\n [ Psi, Lambda ] = eigs ( F, eigen_num, 'lm' );\n\n eigen_found = length ( Lambda );\n fprintf ( 1, ' Requested %d eigenmodes, computed %d\\n', eigen_num, eigen_found );\n eigen_num = min ( eigen_num, eigen_found );\n%\n% Print the eigenvalues.\n%\n lambda_vec = diag ( Lambda );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I Lambda(I)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : eigen_num\n fprintf ( 1, ' %2d %10g\\n', i, lambda_vec(i) );\n end\n%\n% Plot the eigenvalues.\n%\n figure ( 1 )\n clf\n plot ( lambda_vec, 'Linewidth', 2 );\n hold on\n plot ( lambda_vec, 'b.', 'Markersize', 20 );\n title ( 'constant: Mercer eigenvalues' );\n xlabel ( '<--- N --->')\n grid on\n print -dpng 'constant_figure1.png'\n%\n% Plot selected eigenfunctions.\n%\n figure ( 2 )\n subplot ( 4, 1, 1 )\n plot ( Psi(:,1), 'Linewidth', 2 );\n title ( 'constant: Mercer eigenfunction PSI(1)' )\n grid on\n if ( 2 <= eigen_found )\n subplot ( 4, 1, 2 )\n plot ( Psi(:,2), 'Linewidth', 2 );\n title ( 'constant: Mercer eigenfunction PSI(2)' )\n grid on\n end\n if ( 3 <= eigen_found )\n subplot ( 4, 1, 3 )\n plot ( Psi(:,5), 'Linewidth', 2 );\n title ( 'constant: Mercer eigenfunction PSI(5)' )\n grid on\n end\n if ( 4 <= eigen_found )\n subplot ( 4, 1, 4 )\n plot ( Psi(:,10), 'Linewidth', 2 );\n title ( 'constant: Mercer eigenfunction PSI(10)' )\n grid on\n end\n print -dpng 'constant_figure2.png'\n%\n% Orthonormality check.\n%\n ptp = Psi' * Psi;\n error_frobenius = r8mat_is_identity ( eigen_num, ptp );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Frobenius norm of I - Psi'' * Psi = %g\\n', error_frobenius );\n%\n% K(S,S) should be exactly 1.\n% Because we are using a truncated representation of K, our estimate of K(S,S)\n% will be smaller than 1.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Truncated estimate of K(s,s) = 1 for S in the interval.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' S K(s,s) estimate\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : 21\n s = s_vec(i);\n ptlp = Psi(s,:) * Lambda * Psi(s,:)';\n fprintf ( 1, ' %10g %14g\\n', s, ptlp );\n end\n%\n% Look at eigenvalue decay.\n%\n x = diff ( log ( ( 1:eigen_num ) ) );\n y = diff ( log ( lambda_vec ) )';\n c = y ./ x;\n figure ( 3 );\n clf\n plot ( c, 'Linewidth', 2 );\n grid on\n hold on\n plot ( c, 'b.', 'Markersize', 20 );\n xlabel ( '<-- N -->' )\n title ( 'constant: Eigenvalue decay rate' );\n print -dpng 'constant_figure3.png'\n%\n% Look at eigenvalue sum.\n%\n% The trace of K(s,s) over [a,b] should be the integral of 1 over [a,b],\n% that is, b - a.\n%\n% We compare the trace to the partial sums of the lambda's to see how much\n% of the variance of the process we have captured.\n%\n trace_K = b - a;\n lambda_cum = cumsum ( lambda_vec ) / trace_K;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Index Cumulative Eigenvalue sum\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : eigen_num\n fprintf ( 1, ' %5d %10g\\n', i, lambda_cum(i) );\n end\n%\n% We decide to use the first 10 eigenfunctions.\n%\n eigen_use = min ( 10, eigen_found );\n%\n% Find 400 realizations of the process by selecting, for each realization,\n% 10 random parameters Z in the truncated KL expansion.\n%\n Z = randn ( eigen_use, 400 );\n X = Psi(:,1:eigen_use) * ( sqrt ( Lambda(1:eigen_use,1:eigen_use) ) * Z ); \n%\n% Plot 40 of the realizations;\n% Plot their mean, computed from all 400.\n%\n figure ( 4 )\n clf\n plot ( X(:,1:40) )\n mu = sum ( X, 2 ) / 400;\n hold on;\n plot ( mu, 'k', 'linewidth', 3 );\n title ( 'constant: 40 Random Realizations X(t,omega), and their Mean.' )\n print -dpng 'constant_figure4.png'\n%\n% Estimate the covariance from the data.\n%\n figure ( 5 )\n clf\n [ S, T ] = meshgrid ( s_vec, s_vec );\n C = cov ( X(s_vec,:)' );\n mesh ( S, T, C );\n hold on;\n D = constant_correlation ( S, T );\n plot3 ( S, T, D, 'k.', 'markersize', 10 )\n title ( 'constant: Covariance K(S,T) (dots), and Estimate from Realizations (mesh)' )\n print -dpng 'constant_figure5.png'\n%\n% Using just 10 functions in the expansion,\n% reduce the correlation length,\n% and examine the sum of the lambda's.\n%\n if ( 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Use a fixed number of eigenfunctions = %d\\n', eigen_use );\n fprintf ( 1, ' but vary the correlation length RHOBAR.\\n' );\n fprintf ( 1, ' (We used RHOBAR = 1 above.)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The sum of the eigenvalues, divided by (B-A),\\n' );\n fprintf ( 1, ' discloses the relative amount of the total variation\\n' );\n fprintf ( 1, ' that is captured by the truncated expansion.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' RHOBAR VARSUM\\n' );\n fprintf ( 1, '\\n' );\n rhobar = 4.0;\n for i = 1 : 10\n F = fred ( @constant_correlation, domain ( [ a, b ] ) );\n lambda_vec = eigs ( F, 20, 'lm' );\n varsum = sum ( lambda_vec(1:eigen_use) ) / ( b - a );\n fprintf ( 1, ' %10g %10g\\n', rhobar, varsum );\n rhobar = rhobar / 2.0;\n end\n\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CONSTANT_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n rmpath ( '../chebfun' )\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/correlation_chebfun/constant_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.7187679631215215}} {"text": "function [CMerged,omega,xMerged]=covarianceIntersect(C1,C2,optCrit,x1,x2)\n%%COVARIANCEINTERSECT Perform covariance intersection. This is a method of\n% fusing the first two moments of estimates when the\n% correlation between the estimates is unknown. Given\n% the covariance matrices of the estimates, this\n% function returns a covariance matrix and a scaling\n% factor, which can be used to fuse estimates.\n% Alternatively, if the estimates themselves are given,\n% this function can also return the merged estimate.\n% Compare this function to ellipsoidIntersect.\n%\n%INPUTS: C1 The nXn positive definite covariance matrix of the first\n% estimate.\n% C2 The nXn positive definite covariance matrix of the second\n% estimate.\n% optCrit An optional parameter specifying the optimization criterion \n% for the fusion. Possible values are\n% 'det' (The default if omitted or an empty matrix is passed) The\n% fusion is performed to optimize the determinant of the\n% matrix on the output.\n% 'trace' The fusion is performed to minimize the trace of the\n% output matrix.\n% x1,x2 The optional nX1 estimate vectors to be merged. These are only\n% used if xMerged is requested on the output.\n%\n%OUTPUTS: CMerged The nXn fused covariance matrix.\n% omega The weighting that played a role in the fusion of the\n% covariance matrix/ state estimates. Specifically,\n% CMerged=inv(omega*inv(C1)+(1-omega)*inv(C2))\n% and the merged estimates are\n% xMerged=CMerged*(omega*inv(C1)*x1+(1-omega)*inv(C2)*x2)\n% xMerged The merged estimate. This requires x1,x2 to be given on\n% the input. The covariance matrix associated with the\n% merged estimate is CMerged.\n%\n%The first (non-dissertation) publication of covariance intersection for\n%fusing measurements having unknown correlations is [2]. Various optimality\n%criteria are derived in [3]. However, the most practical approach is that\n%of [1], which clearly expresses the solution in terms of the solution of\n%polynomials, with some solutions given in closed form. Thus, this function\n%uses the closed form solutions, when available, and the general polynomial\n%solutions otherwise.\n%\n%Note that covariance intersection is overly convervative in its covariance\n%estimates as mentioned in Chapter 9.3.7 of [5].\n%\n%EXAMPLE:\n%Here we use the numerical values form the example for ellipsoidal\n%intersection in [1]. The plots in the paper appear to be incorrect.\n% xi=[1;-2];\n% Pi=[3,0;0,0.4];\n% xj=[-2;-1];\n% Pj=[2,-0.8;-0.8,1];\n% \n% [P,~,x]=covarianceIntersect(Pi,Pj,'det',xi,xj);\n% figure()\n% clf\n% hold on\n% drawEllipse(xi,inv(Pi),[],'--r')\n% drawEllipse(xj,inv(Pj),[],'--g')\n% drawEllipse(x,inv(P),[],'-b')\n%\n%REFERENCES:\n%[1] M. Reinhardt, B. Noack, and U. D. Hanebeck, \"Closed-form optimization\n% of covariance intersection for low-dimensional matrices,\" in \n% Proceedings of the 15th International Conference on Information\n% Fusion, Singapore, 9-12 Jun. 2012, pp. 1891-1896.\n%[2] S. J. Julier and J. K. Uhlmann, \"A non-divergent estimation algorithm\n% in the presence of unknown correlations,\" in Proceedings of the\n% American Control Conference, vol. 4, Albuquerque, NM, 4-6 Jun. 1997,\n% pp. 2369-2373.\n%[3] L. Chen, P. O. Arambel, and R. K. Mehra, \"Estimation under unknown\n% correlation: Covariance intersection revisited,\" IEEE Transactions on\n% Automatic Control, vol. 47, no. 11, pp. 1879-1882, Nov. 2002.\n%[4] J. Sijs, M. Lazar, and P. Bosch, \"State fusion with unknown\n% correlation: Ellipsoidal intersection,\" in Proceedings of the 2010\n% American Control Conference, Baltimore, MD, 30 Jun. - 2 Jul. 2010.\n%[5] Y. Bar-Shalom, P. K. Willett, and X. Tian, Tracking and Data Fusion.\n% Storrs, CT: YBS Publishing, 2011.\n%\n%August 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3||isempty(optCrit))\n optCrit='det';\nend\n\nn=length(C1);\n\n%The transformation matrix in Equation 2 of [1], but here we use an\n%SVD-based algorithm instead of an eigenvalue-based algorithm, because it\n%is numerically more stable.\nA=twoMatDiag(C1,C2);\n\n%The positive scalars d.\nd=diag(A*C2*A');\ndBar=1./d;\ndTilde=dBar./(1-dBar);\n\ninvC1=inv(C1);\ninvC2=inv(C2);\n\n%Determinant minimization\nswitch(optCrit)\n case 'det'\n if(n==1)\n if(C14\n %The pi values are given in the unnumbered equation after\n %Equation 10 in [1].\n piVals=zeros(1,n-1);\n for curPi=1:(n-1)\n piIdx=1:curPi;\n while(1)\n %Add the current product\n piVals(curPi)=piVals(curPi)+prod(dTilde(piIdx));\n \n %Increment the value in the innermost sum.\n curLevel=curPi;\n allDone=false;\n while(piIdx(curLevel)+1>(n-curPi+curLevel))\n curLevel=curLevel-1;\n if(curLevel<1)\n allDone=true;\n break;\n end\n end\n if(allDone)\n break;\n end\n %Increment the index\n piIdx(curLevel)=piIdx(curLevel)+1;\n \n %Fill in the minimum values in further nested sums.\n for k=(curLevel+1):curPi\n piIdx(k)=piIdx(k-1)+1;\n end\n end\n end\n \n %Given the pi values, build the polynomial in omega.\n poly2Solve=(n:-1:1).*[1,piVals];\n \n %Omega hypotheses are the roots of an order n-1 polynomial in\n %Equation 10 of [1].\n omega=roots(poly2Solve);\n end\n \n if(n>1)\n %Given a set of omega values, we have to choose the best solution.\n %We also have to include omega=0 and omega=1 as possibilities as\n %per Algorithm 1 in [1]. Some of the solutions might be slightly\n %imaginary due to finite precision errors. We will just discard the\n %imaginary parts. This does not affect the choice of the optimal\n %solution.\n omega=[real(omega);0;1];\n numHyp=length(omega);\n\n minCost=Inf;\n minOmega=[];\n for curHyp=1:numHyp\n if(omega(curHyp)>=0&&omega(curHyp)<=1)\n %The determinant of a matrix inverse is the inverse of\n %the determinant.\n cost=1/det(omega(curHyp)*invC1+(1-omega(curHyp))*invC2);\n\n if(cost=3\n %Use convolutions to build up the polynomial in Equation 17 in\n %[1].\n invA=inv(A);\n a=diag(invA'*invA);\n \n %The polynomial is degree 2*(n-1).\n numPolyEls=2*(n-1)+1;\n poly2Solve=zeros(numPolyEls,1);\n for i=1:n\n coeff=a(i)*(1+dTilde(i));\n \n jPoly=zeros(numPolyEls,1);\n jPoly(end)=1;\n for j=1:n\n if(j==i)\n continue;\n end\n \n jPoly=conv(jPoly,[1;2*dTilde(j);dTilde(j)^2]);\n %Get rid of zero-padding at the beginning.\n jPoly=jPoly((end-numPolyEls+1):end);\n end\n poly2Solve=poly2Solve+coeff*jPoly;\n end\n \n %omega hypotheses are the roots of the equation.\n omega=roots(poly2Solve);\n end\n \n %Given a set of omega values, we have to choose the best solution.\n %We also have to include omega=0 and omega=1 as possibilities as\n %per Algorithm 1 in [1]. Some of the solutions might be slightly\n %imaginary due to finite precision errors. We will just discard the\n %imaginary parts. This does not affect the choice of the optimal\n %solution.\n if(n>1)\n omega=[real(omega);0;1];\n numHyp=length(omega);\n\n minCost=Inf;\n minOmega=[];\n for curHyp=1:numHyp\n if(omega(curHyp)>=0&&omega(curHyp)<=1)\n cost=trace(inv(omega(curHyp)*invC1+(1-omega(curHyp))*invC2));\n\n if(cost2)\n xMerged=CMergedInv\\(omega*invC1*x1+(1-omega)*invC2*x2);\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/Correlation-Free_Fusion/covarianceIntersect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.8289388083214156, "lm_q1q2_score": 0.7187195923504938}} {"text": "function H = RS(sequence,isplot)\n%\n% 'RS' estimate the hurst parameter of a given sequence with R/S method.\n%\n% Inputs:\n% sequence: the input sequence for estimate \n% isplot: whether display the plot. without a plot if isplot equal to 0 \n% Outputs:\n% H: the estimated hurst coeffeient of the input sequence\n\n% Author: Chu Chen \n% Version 1.0, 03/10/2008\n% chen-chu@163.com\n%\n\nif nargin == 1\n isplot = 0;\nend\n\nN = length(sequence);\ndlarge = floor(N/5);\ndsmall = max(10,log10(N)^2);\nD = floor(logspace(log10(dsmall),log10(dlarge),50));\nD = unique(D);\nn = length(D);\nx = zeros(1,n);\ny = zeros(1,n);\n\nR = cell(1,n);\nS = cell(1,n);\nfor i = 1:n\n d = D(i);\n m = floor(N/d);\n R{i} = zeros(1,m);\n S{i} = zeros(1,m);\n matrix_sequence = reshape(sequence(1:d*m),d,m);\n\n Z1 = cumsum(matrix_sequence);\n Z2 = cumsum(repmat(mean(matrix_sequence),d,1));\n R{i} = (max(Z1-Z2)-min(Z1-Z2));\n S{i} = std(matrix_sequence);\n \n if min(R{i})==0 || min(S{i}) ==0\n continue;\n end\n \n x(i) = log10(d);\n y(i) = mean(log10(R{i}./S{i}));\nend\n\n% fit a line with middle part of sequence\nindex = x~=0;\nx = x(index);\ny = y(index);\nn2 = length(x);\ncut_min = ceil(3*n2/10);\ncut_max = floor(9*n2/10);\n\nX = x(cut_min:cut_max);\nY = y(cut_min:cut_max);\np1 = polyfit(X,Y,1);\nYfit = polyval(p1,X);\nH = (Yfit(end)-Yfit(1))/(X(end)-X(1));\n\nif isplot ~= 0\n figure,hold on;\n bound = ceil(log10(N));\n axis([0 bound 0 0.75*bound]);\n \n temp = (1:n).*index;\n index = temp(index);\n for i = 1:n2\n plot(x(i),log10(R{index(i)}./S{index(i)}),'b.');\n end\n \n x = linspace(0,bound,10);\n y1 = 0.5*x;\n y2 = x;\n h1 = plot(x,y1,'b--','LineWidth',2);\n h2 = plot(x,y2,'b-.','LineWidth',2);\n plot(X,Yfit,'r-','LineWidth',3);\n legend([h1,h2],'slope 1/2','slope 1',4)\n xlabel('log10(blocks of size m)'),ylabel('log10(R/S)'),title('R/S Method');\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/19148-hurst-parameter-estimate/hurst estimator/RS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7187195915344754}} {"text": "function prob_test155 ( )\n\n%*****************************************************************************80\n%\n%% TEST155 tests VON_MISES_MEAN, VON_MISES_SAMPLE, VON_MISES_CIRCULAR_VARIANCE;\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 nsample = 1000;\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST155\\n' );\n fprintf ( 1, ' For the Von Mises PDF:\\n' );\n fprintf ( 1, ' VON_MISES_MEAN computes the mean;\\n' );\n fprintf ( 1, ' VON_MISES_SAMPLE samples.\\n' );\n fprintf ( 1, ...\n ' VON_MISES_CIRCULAR_VARIANCE computes the circular variance;\\n' );\n\n a = 1.0;\n b = 2.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' PDF parameter A = %14f\\n', a );\n fprintf ( 1, ' PDF parameter B = %14f\\n', b );\n\n check = von_mises_check ( a, b );\n\n if ( ~check );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST155 - Fatal error!\\n' );\n fprintf ( 1, ' The parameters are not legal.\\n' );\n return\n end\n\n mean = von_mises_mean ( a, b );\n variance = von_mises_circular_variance ( a, b );\n\n fprintf ( 1, ' PDF mean = %14f\\n', mean );\n fprintf ( 1, ' PDF circular variance = %14f\\n', variance );\n\n for i = 1 : nsample\n [ x(i), seed ] = von_mises_sample ( a, b, seed );\n end\n\n mean = r8vec_mean ( nsample, x );\n variance = r8vec_circular_variance ( nsample, x );\n xmax = max ( x(1:nsample) );\n xmin = min ( x(1:nsample) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sample size = %6d\\n', nsample );\n fprintf ( 1, ' Sample mean = %14f\\n', mean );\n fprintf ( 1, ' Sample circular variance = %14f\\n', variance );\n fprintf ( 1, ' Sample maximum = %14f\\n', xmax );\n fprintf ( 1, ' Sample minimum = %14f\\n', xmin );\n\n return\nend\n", "meta": {"author": "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_test155.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7187195913344883}} {"text": "function [F,L,Qc,H,Pinf,dF,dQc,dPinf,params] = cf_matern52_to_ss(magnSigma2, lengthScale)\n% CF_MATERN52_TO_SS - Matern covariance functions, nu=5/2, to state space\n%\n% Syntax:\n% [F,L,Qc,H,Pinf,dF,dQc,dPinf,params] = cf_matern52_to_ss(magnSigma2, lengthScale)\n%\n% In:\n% magnSigma2 - Matern magnitude scale parameter (default: 1)\n% lengthScale - Matern distance scale parameter (default: 1)\n%\n% Out:\n% F - Feedback matrix\n% L - Noise effect matrix\n% Qc - Spectral density of white noise process w(t)\n% H - Observation model matrix\n% Pinf - Covariance of the stationary process\n% dF - Derivatives of F w.r.t. parameters\n% dQc - Derivatives of Qc w.r.t. parameters\n% dPinf - Derivatives of Pinf w.r.t. parameters\n% params - Input and output parameter information\n%\n% Description:\n% This function converts one-dimensional covariance functions of\n% the Matern class to state space models. The covariance function\n% parametrization is as follows\n%\n% k(tau) = magnSigma2 (1+sqrt(5) |tau|/lengthScale+5 |tau|^2/(3 lengthScale^2)) \n% exp(-sqrt(3) |tau|/lengthScale),\n%\n% where magnSigma2 is the magnitude scale parameter, lengthScale the \n% distance scale parameter, and tau the time difference between states, \n% tau = t-t'.\n% This function takes the covariance function parameters as inputs and\n% outputs the corresponding state space model matrices. The state space\n% model is given as follows in terms of a stochastic differential\n% equation\n%\n% df(t)/dt = F f(t) + L w(t),\n%\n% where w(t) is a white noise process with spectral denisty Qc. The\n% observation model for discrete observation y_k of f(t_k) at step k, \n% is as follows \n%\n% y_k = H f(t_k) + r_k, r_k ~ N(0, R),\n%\n% where r_k is the Gaussian measurement noise with covariance R.\n% Pinf is the stationary covariance, where the value of Pinf(i,j), \n% is defined as follows\n% \n% Pinf(i,j) = E[(f_i(t)-E[f_i(t)])(f_j(t)-E[f_j(t)])],\n%\n% where f_i(t) is component i of state vector f(t).\n% Derivatives: All have same form. For example, dF has the following\n% form:\n%\n% dF(:,:,1) = dF/d(magnSigma2 = input parameter_1),\n% dF(:,:,i) = dF/d(input parameter_i).\n%\n% References:\n%\n% [1] Simo Sarkka, Arno Solin, Jouni Hartikainen (2013).\n% Spatiotemporal learning via infinite-dimensional Bayesian\n% filtering and smoothing. IEEE Signal Processing Magazine,\n% 30(4):51-61.\n%\n% [2] Jouni Hartikainen and Simo Sarkka (2010). Kalman filtering and \n% smoothing solutions to temporal Gaussian process regression \n% models. Proceedings of IEEE International Workshop on Machine \n% Learning for Signal Processing (MLSP).\n%\n% See also:\n% COV_MATERN52, SPEC_MATERN52\n%\n% Copyright:\n% 2012-2014 Arno Solin\n% 2013-2014 Jukka Koskenranta\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%% Apply defaults\n\n % Check if magnSigm2 is given\n if nargin < 1 || isempty(magnSigma2), magnSigma2 = 1; end\n\n % Check if lengthScale is given\n if nargin < 2 || isempty(lengthScale), lengthScale = 1; end\n \n%% Form state space model\n\n % Derived constants\n lambda = sqrt(5)/lengthScale;\n\n % Feedback matrix\n F = [ 0, 1, 0;\n 0, 0, 1;\n -lambda^3, -3*lambda^2, -3*lambda];\n\n % Noise effect matrix\n L = [0; 0; 1];\n\n % Spectral density\n Qc = magnSigma2*400*sqrt(5)/3/lengthScale^5;\n\n % Observation model\n H = [1, 0, 0];\n \n \n%% Stationary covariance\n \n % Calculate Pinf only if requested\n if nargout > 4,\n \n % Derived constant\n kappa = 5/3*magnSigma2/lengthScale^2;\n \n % Stationary covariance\n Pinf = [magnSigma2, 0, -kappa;\n 0, kappa, 0;\n -kappa, 0, 25*magnSigma2/lengthScale^4];\n \n end\n \n \n%% Calculate derivatives\n\n % Calculate derivatives only if requested\n if nargout > 5\n\n % Derivative of F w.r.t. parameter magnSigma2\n dFmagnSigma2 = [0, 0, 0;\n 0, 0, 0;\n 0, 0, 0];\n \n % Derivative of F w.r.t parameter lengthScale\n dFlengthScale = [0, 0, 0;\n 0, 0, 0;\n 15*sqrt(5)/lengthScale^4, 30/lengthScale^3, 3*sqrt(5)/lengthScale^2];\n \n % Derivative of Qc w.r.t. parameter magnSigma2\n dQcmagnSigma2 = 400*sqrt(5)/3/lengthScale^5;\n \n % Derivative of Qc w.r.t. parameter lengthScale\n dQclengthScale = -magnSigma2*2000*sqrt(5)/3/lengthScale^6;\n \n % Derivative of Pinf w.r.t. parameter magnSigma2 \n dPinfmagnSigma2 = Pinf/magnSigma2;\n \n % Derivative of Pinf w.r.t. parameter lengthScale\n kappa2 = -2*kappa/lengthScale;\n dPinflengthScale = [0, 0, -kappa2;\n 0, kappa2, 0;\n -kappa2, 0, -100*magnSigma2/lengthScale^5];\n \n % Stack all derivatives\n dF = zeros(3,3,2); \n dQc = zeros(1,1,2); \n dPinf = zeros(3,3,2);\n \n dF(:,:,1) = dFmagnSigma2;\n dF(:,:,2) = dFlengthScale;\n dQc(:,:,1) = dQcmagnSigma2;\n dQc(:,:,2) = dQclengthScale;\n dPinf(:,:,1) = dPinfmagnSigma2;\n dPinf(:,:,2) = dPinflengthScale; \n \n end\n \n \n%% Return parameter names\n\n % Only return if requested\n if nargout > 8\n \n % Stationarity\n p.stationary = true;\n \n % Input parameter information\n p.in{1}.name = 'magnSigma2'; p.in{1}.default = 1; p.in{1}.opt = true;\n p.in{2}.name = 'lengthScale'; p.in{2}.default = 1; p.in{2}.opt = true;\n \n % Return parameter setup\n params = p;\n \n end\n\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/cf_matern52_to_ss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7187133541413148}} {"text": "function [ic,ik] = bspdegelev(d,c,k,t) \n% \n% Function Name: \n% \n% bspdegevel - Degree elevate a univariate B-Spline. \n% \n% Calling Sequence: \n% \n% [ic,ik] = bspdegelev(d,c,k,t) \n% \n% Parameters: \n% \n% d\t: Degree of the B-Spline. \n% \n% c\t: Control points, matrix of size (dim,nc). \n% \n% k\t: Knot sequence, row vector of size nk. \n% \n% t\t: Raise the B-Spline degree t times. \n% \n% ic\t: Control points of the new B-Spline. \n% \n% ik\t: Knot vector of the new B-Spline. \n% \n% Description: \n% \n% Degree elevate a univariate B-Spline. This function provides an \n% interface to a toolbox 'C' routine. \n \n[mc,nc] = size(c); \n % \n % int bspdegelev(int d, double *c, int mc, int nc, double *k, int nk, \n % int t, int *nh, double *ic, double *ik) \n % { \n % int row,col; \n % \n % int ierr = 0; \n % int i, j, q, s, m, ph, ph2, mpi, mh, r, a, b, cind, oldr, mul; \n % int n, lbz, rbz, save, tr, kj, first, kind, last, bet, ii; \n % double inv, ua, ub, numer, den, alf, gam; \n % double **bezalfs, **bpts, **ebpts, **Nextbpts, *alfs; \n % \n % double **ctrl = vec2mat(c, mc, nc); \n% ic = zeros(mc,nc*(t)); % double **ictrl = vec2mat(ic, mc, nc*(t+1)); \n % \nn = nc - 1; % n = nc - 1; \n % \nbezalfs = zeros(d+1,d+t+1); % bezalfs = matrix(d+1,d+t+1); \nbpts = zeros(mc,d+1); % bpts = matrix(mc,d+1); \nebpts = zeros(mc,d+t+1); % ebpts = matrix(mc,d+t+1); \nNextbpts = zeros(mc,d+1); % Nextbpts = matrix(mc,d+1); \nalfs = zeros(d,1); % alfs = (double *) mxMalloc(d*sizeof(double)); \n % \nm = n + d + 1; % m = n + d + 1; \nph = d + t; % ph = d + t; \nph2 = floor(ph / 2); % ph2 = ph / 2; \n % \n % // compute bezier degree elevation coefficeients \nbezalfs(1,1) = 1; % bezalfs[0][0] = bezalfs[ph][d] = 1.0; \nbezalfs(d+1,ph+1) = 1; % \n \nfor i=1:ph2 % for (i = 1; i <= ph2; i++) { \n inv = 1/bincoeff(ph,i); % inv = 1.0 / bincoeff(ph,i); \n mpi = min(d,i); % mpi = min(d,i); \n % \n for j=max(0,i-t):mpi % for (j = max(0,i-t); j <= mpi; j++) \n bezalfs(j+1,i+1) = inv*bincoeff(d,j)*bincoeff(t,i-j); % bezalfs[i][j] = inv * bincoeff(d,j) * bincoeff(t,i-j); \n end \nend % } \n % \nfor i=ph2+1:ph-1 % for (i = ph2+1; i <= ph-1; i++) { \n mpi = min(d,i); % mpi = min(d, i); \n for j=max(0,i-t):mpi % for (j = max(0,i-t); j <= mpi; j++) \n bezalfs(j+1,i+1) = bezalfs(d-j+1,ph-i+1); % bezalfs[i][j] = bezalfs[ph-i][d-j]; \n end \nend % } \n % \nmh = ph; % mh = ph; \nkind = ph+1; % kind = ph+1; \nr = -1; % r = -1; \na = d; % a = d; \nb = d+1; % b = d+1; \ncind = 1; % cind = 1; \nua = k(1); % ua = k[0]; \n % \nfor ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n ic(ii+1,1) = c(ii+1,1); % ictrl[0][ii] = ctrl[0][ii]; \nend % \nfor i=0:ph % for (i = 0; i <= ph; i++) \n ik(i+1) = ua; % ik[i] = ua; \nend % \n % // initialise first bezier seg \nfor i=0:d % for (i = 0; i <= d; i++) \n for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n bpts(ii+1,i+1) = c(ii+1,i+1); % bpts[i][ii] = ctrl[i][ii]; \n end \nend % \n % // big loop thru knot vector \nwhile b < m % while (b < m) { \n i = b; % i = b; \n while b < m && k(b+1) == k(b+2) % while (b < m && k[b] == k[b+1]) \n b = b + 1; % b++; \n end % \n mul = b - i + 1; % mul = b - i + 1; \n mh = mh + mul + t; % mh += mul + t; \n ub = k(b+1); % ub = k[b]; \n oldr = r; % oldr = r; \n r = d - mul; % r = d - mul; \n % \n % // insert knot u(b) r times \n if oldr > 0 % if (oldr > 0) \n lbz = floor((oldr+2)/2); % lbz = (oldr+2) / 2; \n else % else \n lbz = 1; % lbz = 1; \n end % \n \n if r > 0 % if (r > 0) \n rbz = ph - floor((r+1)/2); % rbz = ph - (r+1)/2; \n else % else \n rbz = ph; % rbz = ph; \n end % \n \n if r > 0 % if (r > 0) { \n % // insert knot to get bezier segment \n numer = ub - ua; % numer = ub - ua; \n for q=d:-1:mul+1 % for (q = d; q > mul; q--) \n alfs(q-mul) = numer / (k(a+q+1)-ua); % alfs[q-mul-1] = numer / (k[a+q]-ua); \n end \n \n for j=1:r % for (j = 1; j <= r; j++) { \n save = r - j; % save = r - j; \n s = mul + j; % s = mul + j; \n % \n for q=d:-1:s % for (q = d; q >= s; q--) \n for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n tmp1 = alfs(q-s+1)*bpts(ii+1,q+1); \n tmp2 = (1-alfs(q-s+1))*bpts(ii+1,q); \n bpts(ii+1,q+1) = tmp1 + tmp2; % bpts[q][ii] = alfs[q-s]*bpts[q][ii]+(1.0-alfs[q-s])*bpts[q-1][ii]; \n end \n end % \n \n for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n Nextbpts(ii+1,save+1) = bpts(ii+1,d+1); % Nextbpts[save][ii] = bpts[d][ii]; \n end \n end % } \n end % } \n % // end of insert knot \n % \n % // degree elevate bezier \n for i=lbz:ph % for (i = lbz; i <= ph; i++) { \n for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n ebpts(ii+1,i+1) = 0; % ebpts[i][ii] = 0.0; \n end \n mpi = min(d, i); % mpi = min(d, i); \n for j=max(0,i-t):mpi % for (j = max(0,i-t); j <= mpi; j++) \n for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n tmp1 = ebpts(ii+1,i+1); \n tmp2 = bezalfs(j+1,i+1)*bpts(ii+1,j+1); \n ebpts(ii+1,i+1) = tmp1 + tmp2; % ebpts[i][ii] = ebpts[i][ii] + bezalfs[i][j]*bpts[j][ii]; \n end \n end \n end % } \n % // end of degree elevating bezier \n % \n if oldr > 1 % if (oldr > 1) { \n % // must remove knot u=k[a] oldr times \n first = kind - 2; % first = kind - 2; \n last = kind; % last = kind; \n den = ub - ua; % den = ub - ua; \n bet = floor((ub-ik(kind)) / den); % bet = (ub-ik[kind-1]) / den; \n % \n % // knot removal loop \n for tr=1:oldr-1 % for (tr = 1; tr < oldr; tr++) { \n i = first; % i = first; \n j = last; % j = last; \n kj = j - kind + 1; % kj = j - kind + 1; \n while j-i > tr % while (j - i > tr) { \n % // loop and compute the new control points \n % // for one removal step \n if i < cind % if (i < cind) { \n alf = (ub-ik(i+1))/(ua-ik(i+1)); % alf = (ub-ik[i])/(ua-ik[i]); \n for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n tmp1 = alf*ic(ii+1,i+1); \n tmp2 = (1-alf)*ic(ii+1,i); \n ic(ii+1,i+1) = tmp1 + tmp2; % ictrl[i][ii] = alf * ictrl[i][ii] + (1.0-alf) * ictrl[i-1][ii]; \n end \n end % } \n if j >= lbz % if (j >= lbz) { \n if j-tr <= kind-ph+oldr % if (j-tr <= kind-ph+oldr) { \n gam = (ub-ik(j-tr+1)) / den; % gam = (ub-ik[j-tr]) / den; \n for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n tmp1 = gam*ebpts(ii+1,kj+1); \n tmp2 = (1-gam)*ebpts(ii+1,kj+2); \n ebpts(ii+1,kj+1) = tmp1 + tmp2; % ebpts[kj][ii] = gam*ebpts[kj][ii] + (1.0-gam)*ebpts[kj+1][ii]; \n end % } \n else % else { \n for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n tmp1 = bet*ebpts(ii+1,kj+1); \n tmp2 = (1-bet)*ebpts(ii+1,kj+2); \n ebpts(ii+1,kj+1) = tmp1 + tmp2; % ebpts[kj][ii] = bet*ebpts[kj][ii] + (1.0-bet)*ebpts[kj+1][ii]; \n end \n end % } \n end % } \n i = i + 1; % i++; \n j = j - 1; % j--; \n kj = kj - 1; % kj--; \n end % } \n % \n first = first - 1; % first--; \n last = last + 1; % last++; \n end % } \n end % } \n % // end of removing knot n=k[a] \n % \n % // load the knot ua \n if a ~= d % if (a != d) \n for i=0:ph-oldr-1 % for (i = 0; i < ph-oldr; i++) { \n ik(kind+1) = ua; % ik[kind] = ua; \n kind = kind + 1; % kind++; \n end \n end % } \n % \n % // load ctrl pts into ic \n for j=lbz:rbz % for (j = lbz; j <= rbz; j++) { \n for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n ic(ii+1,cind+1) = ebpts(ii+1,j+1); % ictrl[cind][ii] = ebpts[j][ii]; \n end \n cind = cind + 1; % cind++; \n end % } \n % \n if b < m % if (b < m) { \n % // setup for next pass thru loop \n for j=0:r-1 % for (j = 0; j < r; j++) \n for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n bpts(ii+1,j+1) = Nextbpts(ii+1,j+1); % bpts[j][ii] = Nextbpts[j][ii]; \n end \n end \n for j=r:d % for (j = r; j <= d; j++) \n for ii=0:mc-1 % for (ii = 0; ii < mc; ii++) \n bpts(ii+1,j+1) = c(ii+1,b-d+j+1); % bpts[j][ii] = ctrl[b-d+j][ii]; \n end \n end \n a = b; % a = b; \n b = b+1; % b++; \n ua = ub; % ua = ub; \n % } \n else % else \n % // end knot \n for i=0:ph % for (i = 0; i <= ph; i++) \n ik(kind+i+1) = ub; % ik[kind+i] = ub; \n end \n end \nend % } \n% End big while loop % // end while loop \n % \n % *nh = mh - ph - 1; \n % \n % freevec2mat(ctrl); \n % freevec2mat(ictrl); \n % freematrix(bezalfs); \n % freematrix(bpts); \n % freematrix(ebpts); \n % freematrix(Nextbpts); \n % mxFree(alfs); \n % \n % return(ierr); \n % } \n \n \nfunction b = bincoeff(n,k) \n% Computes the binomial coefficient. \n% \n% ( n ) n! \n% ( ) = -------- \n% ( k ) k!(n-k)! \n% \n% b = bincoeff(n,k) \n% \n% Algorithm from 'Numerical Recipes in C, 2nd Edition' pg215. \n \n % double bincoeff(int n, int k) \n % { \nb = floor(0.5+exp(factln(n)-factln(k)-factln(n-k))); % return floor(0.5+exp(factln(n)-factln(k)-factln(n-k))); \n % } \n \nfunction f = factln(n) \n% computes ln(n!) \nif n <= 1, f = 0; return, end \nf = gammaln(n+1); %log(factorial(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/26390-nurbs-toolbox-by-d-m-spink/nurbs_toolbox/bspdegelev.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7187133525381818}} {"text": "function square_symq_rule_test04 ( degree, n )\n\n%*****************************************************************************80\n%\n%% SQUARE_SYMQ_RULE_TEST04 gets a rule and tests its accuracy.\n%\n% Licensing:\n%\n% This code is distributed under the GNU GPL license.\n%\n% Modified:\n%\n% 01 July 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This 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 exactness\n% of the quadrature rule. 0 <= DEGREE <= 50.\n%\n% Input, integer N, the number of nodes to be used by the rule.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SQUARE_SYMQ_RULE_TEST04\\n' );\n fprintf ( 1, ' Get a quadrature rule for the symmetric square.\\n' );\n fprintf ( 1, ' Test its accuracy.\\n' );\n fprintf ( 1, ' Polynomial exactness degree DEGREE = %d\\n', degree );\n%\n% Retrieve a symmetric quadrature rule.\n%\n [ x, w ] = square_symq ( degree, n );\n\n npols = ( ( degree + 1 ) * ( degree + 2 ) ) / 2;\n\n rints = zeros(npols,1);\n\n for i = 1 : n\n\n z(1) = x(1,i);\n z(2) = x(2,i);\n\n pols = lege2eva ( degree, z );\n\n rints(1:npols) = rints(1:npols) + w(i) * pols(1:npols);\n \n end\n\n area = 4.0;\n\n d = 0.0;\n d = ( rints(1) - sqrt ( area ) )^2;\n for i = 2 : npols\n d = d + rints(i)^2;\n end\n d = sqrt ( d ) / npols;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' RMS 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/square_symq_rule/square_symq_rule_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.718687282467113}} {"text": "%% LP1\nclc\n%Objective & Constraints\nf = -[6 5]';\nA = ([1,4; 6,4; 2, -5]); \nb = [16;28;6]; \nlb = [0;0]; ub = [10;10];\n%Setup Options\nopts = optiset('solver','clp'); \n%Build & Solve\nOpt = opti('grad',f,'ineq',A,b,'bounds',lb,ub,'options',opts)\n[x,fval,exitflag,info] = solve(Opt) \n%Plot\nplot(Opt)\n%Check Solution\n[ok,msg] = checkSol(Opt)\n\n%% LP1 ROW\nrl = -Inf(3,1);\nru = b;\nOpt = opti('grad',f,'lin',A,rl,ru,'bounds',lb,ub,'options',opts)\n[x,fval,exitflag,info] = solve(Opt) \n%Plot\nplot(Opt)\n%Check Solution\n[ok,msg] = checkSol(Opt)\n\n%% Raw Test\nopts.debug = 1;\nopts.display = 2;\nopts.maxiter = 5;\n% rl = zeros(3,1);\nn = length(f);\nH = spalloc(n,n,0);\nAeq = spalloc(0,n,0);\nbeq = zeros(0,1);\n\n[x,fv,ef,iter,l] = ooqp([],f,sparse(A),rl,ru,[],[],lb,ub,opts)\n\n%% LP2\nclc\n%Objective & Constraints\nf = -[1 2 3]';\nA = [-1,1,1; 1,-3,1];\nb = [20,30]';\nAeq = [1 1 1]; beq = 40;\nlb = [0 0 0]'; ub = [40 inf inf]';\n%Setup Options\nopts = optiset('solver','ooqp');\n%Build & Solve\nOpt = opti('grad',f,'ineq',A,b,'eq',Aeq,beq,'bounds',lb,ub,'options',opts)\n[x,fval,exitflag,info] = solve(Opt)\n \n%% LP2 ROW\nAr = [A;Aeq];\nrl = [-Inf(2,1); beq];\nru = [b;beq];\nOpt = opti('grad',f,'lin',Ar,rl,ru,'bounds',lb,ub,'options',opts)\n[x,fval,exitflag,info] = solve(Opt) \n%Check Solution\n[ok,msg] = checkSol(Opt)\n\n%% LP2 ROW + EQ (OOQP FORMAT) (NOT SUPPORTED CURRENTLY)\n% rl = -Inf(2,1);\n% ru = b;\n% prob = optiprob('grad',f,'lin',A,rl,ru,'eq',Aeq,beq,'bounds',lb,ub);\n% Opt = opti(prob,optiset('solver','clp'))\n% [x,fval,exitflag,info] = solve(Opt) \n% %Check Solution\n% [ok,msg] = checkSol(Opt)\n\n%% LP3\nclc\n%Objective & Constraints\nf = [8,1]';\nA = [-1,-2;1,-4;3,-1;1,5;-1,1;-1,0;0,-1]; \nb = [-4,2,21,39,3,0,0]';\n%Setup Options\nopts = optiset('solver','clp');\n%Build & Solve\nx0 = [9,6]';\nOpt = opti('grad',f,'ineq',A,b,'options',opts)\n[x,fval,exitflag,info] = solve(Opt,x0)\nplot(Opt,10)\n\n%% LP3 ROW\nrl = -Inf(7,1);\nru = b;\nOpt = opti('grad',f,'lin',A,rl,ru,'options',opts)\n[x,fval,exitflag,info] = solve(Opt) \n%Check Solution\n[ok,msg] = checkSol(Opt)\n\n\n%% MILP1\nclc\n%Objective & Constraints\nf = -[6 5]';\nA = [1,4; 6,4; 2, -5]; \nb = [16;28;6]; \nlb = [0;0]; ub=[10;10];\n%Setup Options\nopts = optiset('solver','glpk');\n%Build & Solve\nOpt = opti('grad',f,'ineq',A,b,'bounds',lb,ub,'int','II','options',opts)\n[x,fval,exitflag,info] = solve(Opt)\nplot(Opt)\n\n\n%% MILP1 ROW\nrl = -Inf(3,1);\nru = b;\nOpt = opti('grad',f,'lin',A,rl,ru,'bounds',lb,ub,'int','II','options',opts)\n[x,fval,exitflag,info] = solve(Opt) \nplot(Opt)\n%Check Solution\n[ok,msg] = checkSol(Opt)\n\n\n%% MILP2\nclc\n%Objective & Constraints\nf = -[1 2 3 1]'; \nA = [-1 1 1 10; 1 -3 1 0]; \nb = [20;30]; \nAeq = [0 1 0 -3.5];\nbeq = 0;\nlb = [0 0 0 2]';\nub = [40 inf inf 3]';\nint = 'CCCI';\n%Setup Options\nopts = optiset('solver','cbc');\n%Build & Solve\nOpt = opti('grad',f,'ineq',A,b,'eq',Aeq,beq,'bounds',lb,ub,'int',int,'options',opts)\n[x,fval,exitflag,info] = solve(Opt)\n\n%% MILP2 ROW\nAr = [A;Aeq];\nrl = [-Inf(2,1); beq];\nru = [b;beq];\nOpt = opti('grad',f,'lin',Ar,rl,ru,'bounds',lb,ub,'int',int,'options',opts)\n[x,fval,exitflag,info] = solve(Opt) \n%Check Solution\n[ok,msg] = checkSol(Opt)\n\n\n%% BILP1\nclc\n%Objective & Constraints\nf = -[6 5]';\nA = [-3,5; 6,4; 3, -5; -6, -4]; \nb = [6;9;1;3]; \n%Setup Options\nopts = optiset('solver','cbc');\n%Build & Solve\nOpt = opti('grad',f,'ineq',A,b,'int','BB','options',opts)\n[x,fval,exitflag,info] = solve(Opt)\nplot(Opt,3)\n\n%% BILP1 ROW\nrl = -Inf(4,1);\nru = b;\nOpt = opti('grad',f,'lin',A,rl,ru,'int','BB','options',opts)\n[x,fval,exitflag,info] = solve(Opt) \nplot(Opt)\n%Check Solution\n[ok,msg] = checkSol(Opt)\n\n%% BILP2\nclc\n%Objective & Constraints\nf = -[9 5 6 4]';\nA = [6 3 5 2; 0 0 1 1; -1 0 1 0; 0 -1 0 1];\nb = [9; 1; 0; 0];\n%Setup Options\nopts = optiset('solver','cbc');\n%Build & Solve\nOpt = opti('grad',f,'ineq',A,b,'int','BBBB','options',opts)\n[x,fval,exitflag,info] = solve(Opt)\n\n%% NLP1 Hock & Schittkowski #71\nclc\n%Objective & Gradient\nobj = @(x) x(1)*x(4)*sum(x(1:3)) + x(3);\ngrad = @(x) [ x(1)*x(4) + x(4)*sum(x(1:3));\n x(1)*x(4);\n x(1)*x(4) + 1;\n x(1)*sum(x(1:3)) ]; \n%Linear Constraints\nlb = ones(4,1);\nub = 5*ones(4,1);\n%Nonlinear Constraints\nnlcon = @(x) [ prod(x);\n sum(x.^2)];\nnljac = @(x) [ prod(x)./x';\n 2*x' ]; \nnlrhs = [25 40]';\nnle = [1 0]'; % (>=, ==)\n%Setup Options\nopts = optiset('solver','matlab','warnings','on','display','iter');\n%Build & Solve\nx0 = [1 5 5 1]';\nOpt = opti('obj',obj,'grad',grad,'nlmix',nlcon,nlrhs,nle,'nljac',nljac,'bounds',lb,ub,'options',opts)\n[x,fval,exitflag,info]= solve(Opt,x0)\n\n\n%% NLP3 Hock & Schittkowski #51\nclc\n%Objective & Gradient\nobj = @(x) (x(1) - x(2))^2 + (x(2) + x(3) - 2)^2 + (x(4) - 1)^2 + (x(5) - 1)^2;\ngrad = @(x) 2*[ x(1) - x(2);\n x(2) + x(3) - 2 - x(1) + x(2);\n x(2) + x(3) - 2;\n x(4) - 1;\n x(5) - 1 ];\n \n%Nonlinear Constraints & Jacobian Structure\nnlcon = @(x) [ x(1) + 3*x(2);\n x(3) + x(4) - 2*x(5)];\n% x(2) - x(5)];\nnljac = @(x) sparse([ 1 3 0 0 0;\n\t 0 0 1 1 -2]);\n% \t 0 1 0 0 -1]);\nnljacstr = @() sparse([1 1 0 0 0;\n 0 0 1 1 1]);\n% 0 1 0 0 1]);\n \ncl = [4;0];\ncu = [4;0];\nnlrhs = [4 0 1 15]';\nnle = [0 0 1 -1]';\n\nA = [0 1 0 0 -1];\nrl = 1;\nru = 15;\n\n%Setup Options\nopts = optiset('solver','ipopt','display','iter','maxiter',1e4);\n%Build & Solve\nx0 = [ 2.5 0.5 2 -1 2.5 ];\nOpt = opti('obj',obj,'grad',grad,'lin',A,rl,ru,'nl',nlcon,cl,cu,'nljac',nljac,'nljacstr',nljacstr,'options',opts)\n[x,fval,exitflag,info]= solve(Opt,x0)\n\ninfo.Lambda\ninfo.Lambda.ineqlin\ninfo.Lambda.ineqnonlin\ninfo.Lambda.eqnonlin\n\n%% Test Conversion Function\n\nOpt.prob.nlcon(x0)\nfull(Opt.prob.nljac(x0))\nfull(Opt.prob.nljacstr())\n\n\n\n%% SINGLE BOUNDS NO JAC\nclc\nnlcon = @(x) [ x(1) + 3*x(2);\n x(3) + x(4) - 2*x(5);\n x(2) - x(5)];\n\ncl = [-Inf 1 2];\ncu = [4 1 Inf];\n\nx0 = [ 2.5 0.5 2 -1 1.5 ];\n\nprob = optiprob('nl',nlcon,cl,cu,'x0',x0)\nprob = nrow2mix(prob)\n\nprob.nlrhs\nprob.nle\nprob.nlcon(x0)\n\n%% SINGLE BOUNDS W JAC\nclc\nnlcon = @(x) [ x(1) + 3*x(2);\n x(3) + x(4) - 2*x(5);\n x(2) - x(5)];\n\nnljac = @(x) sparse([ 1 3 0 0 0;\n 0 0 1 1 -2;\n 0 1 0 0 -1]);\n\ncl = [-Inf 1 2];\ncu = [4 1 Inf];\n\nx0 = [ 2.5 0.5 2 -1 1.5 ];\n\nprob = optiprob('nl',nlcon,cl,cu,'nljac',nljac,'x0',x0)\nprob = nrow2mix(prob)\n\nprob.nlrhs\nprob.nle\nprob.nlcon(x0)\n\n%% DUAL BOUNDS W JAC\nclc\nnlcon = @(x) [ x(1) + 3*x(2);\n x(3) + x(4) - 2*x(5);\n x(2) - x(5);\n x(1) + 3*x(2);\n x(3) + x(4) - 5*x(5)];\n\nnljac = @(x) sparse([ 1 3 0 0 0;\n 0 0 1 1 -2;\n 0 1 0 0 -1;\n 1 3 0 0 0;\n 0 0 1 1 -5;]);\n\ncl = [-Inf 1 -Inf 2 5];\ncu = [4 1 12 16 Inf];\n\nx0 = [ 2.5 0.5 2 -1 1.5 ];\n\nprob = optiprob('nl',nlcon,cl,cu,'nljac',nljac,'x0',x0)\nprob = nrow2mix(prob)\n\nprob.nlrhs\nprob.nle\nprob.nlcon(x0)\nfull(prob.nljac(x0))\n\n%% DUAL BOUNDS W JAC & STR\nclc\nnlcon = @(x) [ x(1) + 3*x(2);\n x(3) + x(4) - 2*x(5);\n x(2) - x(5);\n x(1) + 3*x(2);\n x(3) + x(4) - 5*x(5)];\n\nnljac = @(x) sparse([ 1 3 0 0 0;\n 0 0 1 1 -2;\n 0 1 0 0 -1;\n 1 3 0 0 0;\n 0 0 1 1 -5;]);\n\nnljacstr = @() sparse([ 1 1 0 0 0; \n 0 0 1 1 1;\n 0 1 0 0 1;\n 1 1 0 0 0;\n 0 0 1 1 1]);\n\ncl = [-Inf 1 -Inf 2 5];\ncu = [4 1 12 16 Inf];\n\nx0 = [ 2.5 0.5 2 -1 1.5 ];\n\nprob = optiprob('nl',nlcon,cl,cu,'nljac',nljac,'nljacstr',nljacstr,'x0',x0)\nprob = nrow2mix(prob)\n\nprob.nlrhs\nprob.nle\nprob.nlcon(x0)\nfull(prob.nljac(x0))\nfull(prob.nljacstr())\n\n\n%% Ali Constraint Linearity Index Problem\nclc\nobj=@(x) (x)^2;\nA=1; ru=1; rl=-1; xtype='I'; x0=1;\nopt=opti('obj',obj,'xtype',xtype,'x0',x0,'lin',A,rl,ru)\nopt.prob.sizes\nsolve(opt,x0)\n\n%% Identical form of above\nclc\nobj=@(x) (x)^2;\nA=[1;-1]; b=[1;1]; xtype='I'; x0=1;\nopt=opti('obj',obj,'xtype',xtype,'x0',x0,'ineq',A,b); \nopt.prob.sizes\nsolve(opt,x0)\n\n%% Nonlinear Constraints Double Sided Row, Linear\nclc\n%Objective\nobj = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\n% Constraints\nA = [-1 1; 1 1];\nrl = [-3;5];\nru = [-1;5];\nlb = [0;0]; ub = [4;4];\n% Solve\nx0 = [2;2];\nOpt = opti('obj',obj,'ndec',2,'bounds',lb,ub,'ivars',1,'lin',A,rl,ru)\n[x,fval,ef,info] = solve(Opt,x0)\n%Plot\nplot(Opt,[],1)\n\n%% Nonlinear Constraints Double Sided Ineq, Linear\nclc\n%Objective\nobj = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\n% Constraints\nA = [-1 1; 1 -1];\nb = [-1;3];\nAeq = [1 1];\nbeq = 5;\nlb = [0;0]; ub = [4;4];\n% Solve\nx0 = [2;2];\nOpt = opti('obj',obj,'ndec',2,'bounds',lb,ub,'ivars',1,'ineq',A,b,'eq',Aeq,beq)\n[x,fval,ef,info] = solve(Opt,x0)\n%Plot\nplot(Opt,[],1)\n\n%% Nonlinear Constraints Double Sided Row, NonLinear\nclc\n%Objective\nobj = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\n% Constraints\nnlcon = @(x) [-x(1) + x(2); x(1) + x(2)];\ncl = [-3;5];\ncu = [-1;5];\nlb = [0;0]; ub = [4;4];\n% Solve\nx0 = [2;2];\nOpt = opti('obj',obj,'ndec',2,'bounds',lb,ub,'ivars',1,'nl',nlcon,cl,cu)\n[x,fval,ef,info] = solve(Opt,x0)\n%Plot\nplot(Opt,[],1)\n\n%% Nonlinear Constraints Double Sided Ineq, Nonlinear\nclc\n%Objective\nobj = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\n% Constraints\nnlcon = @(x) [-x(1) + x(2); x(1) - x(2); x(1) + x(2)];\nnlrhs = [-1;3;5];\nnle = [-1;-1;0];\nlb = [0;0]; ub = [4;4];\n% Solve\nx0 = [2;2];\nOpt = opti('obj',obj,'ndec',2,'bounds',lb,ub,'ivars',1,'nlmix',nlcon,nlrhs,nle)\n[x,fval,ef,info] = solve(Opt,x0)\n%Plot\nplot(Opt,[],1)\n\n%% Nonlinear Constraints Double Sided Ineq, Nonlinear + Linear\nclc\n%Objective\nobj = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\n% Constraints\nA = [-1 1; 1 -1];\nb = [0;2];\nnlcon = @(x) [-x(1) + x(2); x(1) - x(2); x(1) + x(2)];\nnlrhs = [-1;3;5];\nnle = [-1;-1;0];\nlb = [0;0]; ub = [4;4];\n% Solve\nx0 = [2;2];\nOpt = opti('obj',obj,'ndec',2,'bounds',lb,ub,'ivars',1,'nlmix',nlcon,nlrhs,nle,'ineq',A,b)\n[x,fval,ef,info] = solve(Opt,x0)\n%Plot\nplot(Opt,[],1)\n\n%% Nonlinear Constraints Double Sided Row, NonLinear + Linear\nclc\n%Objective\nobj = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;\n% Constraints\nA = [-1 1];\nrl = -2; ru = 0;\nnlcon = @(x) [-x(1) + x(2); x(1) + x(2)];\ncl = [-3;5];\ncu = [-1;5];\nlb = [0;0]; ub = [4;4];\n% Solve\nx0 = [2;2];\nOpt = opti('obj',obj,'ndec',2,'bounds',lb,ub,'ivars',1,'nl',nlcon,cl,cu,'lin',A,rl,ru)\n[x,fval,ef,info] = solve(Opt,x0)\n%Plot\nplot(Opt,[],1)\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Test Problems/Development/test_rowcon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7186714587532024}} {"text": "function [V,D]=spreadeigs(K,coef);\n%SPREADEIGS Eigenpairs of Spreading operator\n% Usage: h=spreadeigs(K,c);\n%\n% `spreadeigs(K,c)` computes the *K* largest eigenvalues and eigen-\n% vectors of the spreading operator with symbol *c*.\n%\n% See also: tconv, spreadfun, spreadinv, spreadadj\n\ncomplainif_argnonotinrange(nargin,2,2,mfilename);\n\nif ndims(coef)>2 || size(coef,1)~=size(coef,2)\n error('Input symbol coef must be a square matrix.');\nend;\n\nL=size(coef,1);\n\n% This version explicitly constucts the matrix representation T\n% and then applies this matrix as the final step.\ncoef=fft(coef);\n \nT=zeros(L);\nfor ii=0:L-1\n for jj=0:L-1\n T(ii+1,jj+1)=coef(ii+1,mod(ii-jj,L)+1);\n end;\nend;\n\nif nargout==2\n doV=1;\nelse\n doV=0;\nend;\n\nif doV\n [V,D]=eig(T);\nelse\n D=eig(T);\nend;\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/operators/spreadeigs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7186714474861644}} {"text": "%TRINTERP2 Interpolate SE(2) homogeneous transformations\n%\n% TRINTERP2(T0, T1, S) is a homogeneous transform (3x3) interpolated\n% between T0 when S=0 and T1 when S=1. T0 and T1 are both homogeneous\n% transforms (4x4). If S (Nx1) then T (3x3xN) is a sequence of\n% homogeneous transforms corresponding to the interpolation values in S.\n%\n% TRINTERP2(T1, S) as above but interpolated between the identity matrix\n% when S=0 to T1 when S=1.\n%\n% TRINTERP2(T0, T1, M) as above but M is a positive integer and return a\n% sequence (4x4xM) of homogeneous transforms linearly interpolating between \n% T0 and T1 in M steps.\n%\n% TRINTERP2(T1, M) as above but return a sequence (4x4xM) of\n% homogeneous interpolating between identity matrix and T1 in M steps.\n%\n% Notes::\n% - T0 or T1 can also be an SO(2) rotation matrix (2x2).\n% - Rotation angle is linearly interpolated.\n% - To obtain smooth continuous motion S should also be smooth and continuous,\n% such as computed by tpoly or lspb. \n%\n% See also TRINTERP, SE3.interp, UnitQuaternion, TPOLY, LSPB.\n\n%## 2d homogeneous trajectory\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\n\nfunction T = trinterp2(A, B, C)\n\n switch nargin\n case 2\n % trinterp(T, s)\n T1 = A; s = B;\n \n th0 = 0;\n th1 = atan2(T1(2,1), T1(1,1));\n if ~isrot2(T1)\n p0 = [0 0]';\n p1 = transl2(T1);\n end\n case 3\n % trinterp(T1, T2, s)\n T0 = A; T1 = B; s = C;\n assert(all(size(A) == size(B)), 'SMTB:trinterp2:badarg', '2 matrices must be same size');\n th0 = atan2(T0(2,1), T0(1,1));\n th1 = atan2(T1(2,1), T1(1,1));\n if ~isrot2(T0)\n p0 = transl2(T0);\n p1 =transl2(T1);\n end\n otherwise\n error('SMTB:trinterp2:badarg', 'must be 2 or 3 arguments');\n end\n \n if length(s) == 1 && s > 1 && (s == floor(s))\n % integer value\n s = [0:(s-1)] / (s-1);\n elseif any(s<0 | s>1)\n error('SMTB:trinterp2:badarg', 'values of S outside interval [0,1]');\n end\n \n if isrot2(T1)\n \n % SO(2) case\n for i=1:length(s)\n th = th0*(1-s(i)) + s(i)*th1;\n \n T(:,:,i) = rot2(th);\n end\n else\n % SE(2) case\n for i=1:length(s)\n th = th0*(1-s(i)) + s(i)*th1;\n pr = p0*(1-s(i)) + s(i)*p1;\n \n T(:,:,i) = rt2tr(rot2(th), pr);\n end\n end\n \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/trinterp2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7186714348392474}} {"text": "function CartStates=stateRuv2Cart(x)\n%%STATERUV2CART Convert a target state in 3D space in monostatic\n% r-u-v coordinates with first and possibly second time\n% derivatives of the position components into Cartesian\n% coordinates. The state has the format\n% [r;u;v;rDot;uDot;vDot;rDDot;uDDot;vDDot],\n% where two Ds indicate a second derivative with respect to\n% time. In Cartesian coordinates, the converted state has the\n% form [x;y;z;xDot;yDot;zDot;xDDot;yDDot;zDDot]. The target\n% is assumed to be in front of the radar.\n%\n%INPUTS: x The 6XN or 9XN set of r-u-v state vectors consisting of\n% position, velocity and possibly acceleration. The range is a\n% one-way range.\n%\n%OUTPUTS: CartStates The 6XN or 9XN set of target states given in Cartesian\n% coordinates.\n%\n%The derivation is given in [1]. The function aCVRuv is an implementation\n%of a related linear dynamic model.\n%\n%EXAMPLE:\n%Here we note that the results are consistent with the inverse function:\n%stateCart2Ruv.\n% x=[100;-60;200;-3;12;160;108;-116;2];\n% xRet=stateRuv2Cart(stateCart2Ruv(x));\n% max(abs(x(:)-xRet(:)))\n%One will see that the error is less than 1e-13, indicating good agreement.\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"Basic linear Cartesian dynamic models in local\n% coordinates,\" Naval Research Laboratory, Washington, DC, Tech. Rep.\n% NRL/MR/5344-19-9882, 24 Aug. 2019.\n%\n%August 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDim=size(x,1);\nN=size(x,2);\nCartStates=zeros(numDim,N);\n\nr=x(1,:);\nu=x(2,:);\nv=x(3,:);\nrDot=x(4,:);\nuDot=x(5,:);\nvDot=x(6,:);\n\nw2=max(0,1-u.^2-v.^2);\nw=sqrt(w2);\ndiffV2=1-v.^2;\ndiffV=sqrt(1-v.^2);\ndenom2=w2.*diffV2;\ndenom=sqrt(denom2);\n\nu1=[u;v;w];\nu2=[w./diffV;zeros(1,N);-u./diffV];\nu3=[-u.*v./diffV;diffV;-v.*(w./diffV)];\n\n%Position\nCartStates(1:3,:)=bsxfun(@times,r,u1);\n\nc1=(uDot.*diffV2+u.*v.*vDot)./denom;\nc2=vDot./diffV;\n\n%Velocity\nCartStates(4:6,:)=bsxfun(@times,rDot,u1)+bsxfun(@times,r.*c1,u2)+bsxfun(@times,r.*c2,u3);\n\nif(numDim>6)\n %Acceleration\n rDDot=x(7,:);\n uDDot=x(8,:);\n vDDot=x(9,:);\n\n c3=-(((w+u.^2./w).*(uDot-uDot.*v.^2+u.*v.*vDot))./diffV.^3);\n c4=v.*(-u.^2.*(1./w)-w).*(-uDot.*diffV2-u.*v.*vDot)./diffV2.^2;\n c5=-vDot./diffV;\n c6=(w./diffV).*(-v.*uDot.*diffV2-u.*vDot)./diffV.^3+u.*(diffV./w).*(-u.*v.*uDot.*diffV2-u.^2.*vDot+vDot.*diffV2.^2)./diffV.^5;\n \n c1Dot=((uDot.*diffV2+u.*v.*vDot).*(v.*vDot.*(2-u.^2-2*v.^2)+u.*uDot.*diffV2))./denom.^3 ...\n +(uDDot.*diffV2-v.*uDot.*vDot+u.*(v.*vDDot+vDot.^2))./denom;\n c2Dot=(vDDot.*diffV2+v.*vDot.^2)./diffV.^3;\n\n a1=rDDot+r.*(c1.*c3+c2.*c5);\n a2=2*rDot.*c1+r.*(c1Dot+c2.*c6);\n a3=2*rDot.*c2+r.*(c2Dot+c1.*c4);\n \n CartStates(7:9,:)=bsxfun(@times,a1,u1)+bsxfun(@times,a2,u2)+bsxfun(@times,a3,u3);\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/State_Coordinate_System_Conversion/stateRuv2Cart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7186568127771071}} {"text": "%%Ex 4 Combine looping and branching\n\nsum1 = 0;\nsum2 = 0;\nN = 9\nfor k = 1:N\n sum1 = sum1+k;\n if (mod(k,3) == 0)\n sum2 = sum2+k;\n end\nend\nsum1\nsum2\n\n\n% Output:\n% sum1 = 45\n% sum2 = 18\n% Remark: Sum1 = 1+2+3+4+5+6+7+8+9, while sum2 = 3+6+9.", "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_3(basic_branching)/program4.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7186567854889235}} {"text": "function [H,G] = make_bank_3(h,nbands)\n\n% make_bank_3 Creates Analysis/Synthesis Filters for Pseudo-QMF Filter Banks\n% \n% Standard type of cosine modulation where the phase reference is (L-1)/2\n% Arguments:\n% h Impulse response of prototype filter\n% ndands Number of subbands\n%\n% by Lee, Gan, and Kuo, 2008\n% Subband Adaptive Filtering: Theory and Implementation\n% Publisher: John Wiley and Sons, Ltd\n\nflen = max(size(h));\nH = zeros(nbands,flen);\n\n% Note: k starts from 1, thus (k-0.5) and (k-1) in the cosine modulations \n\nn = 0:flen-1;\nfor k=1:nbands\n H(k,:) = h.*cos((pi/nbands)*(k-0.5)*(n-(flen-1)/2)+ (pi/2)*(k+0.5)*(flen-1-nbands)/nbands)*2;\nend\n\n% Synthesis filters are time-reversed versions of the analysis filters\n\n% Gk(z) = z^(-L+1)H(z^-1)\nG = fliplr(H);", "meta": {"author": "CharlesThaCat", "repo": "acoustic-interference-cancellation", "sha": "edb394499ea6f9c96445a3e9613bd64a854c289e", "save_path": "github-repos/MATLAB/CharlesThaCat-acoustic-interference-cancellation", "path": "github-repos/MATLAB/CharlesThaCat-acoustic-interference-cancellation/acoustic-interference-cancellation-edb394499ea6f9c96445a3e9613bd64a854c289e/Subband processing/Common Code/make_bank_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951643678382, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.7186248495842221}} {"text": "function [lambda_vec, error_train, error_val] = ...\n validationCurve(X, y, Xval, yval)\n%VALIDATIONCURVE Generate the train and validation errors needed to\n%plot a validation curve that we can use to select lambda\n% [lambda_vec, error_train, error_val] = ...\n% VALIDATIONCURVE(X, y, Xval, yval) returns the train\n% and validation errors (in error_train, error_val)\n% for different values of lambda. You are given the training set (X,\n% y) and validation set (Xval, yval).\n%\n\n% Selected values of lambda (you should not change this)\nlambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';\n\n% You need to return these variables correctly.\nerror_train = zeros(length(lambda_vec), 1);\nerror_val = zeros(length(lambda_vec), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return training errors in\n% error_train and the validation errors in error_val. The\n% vector lambda_vec contains the different lambda parameters\n% to use for each calculation of the errors, i.e,\n% error_train(i), and error_val(i) should give\n% you the errors obtained after training with\n% lambda = lambda_vec(i)\n%\n% Note: You can loop over lambda_vec with the following:\n%\n% for i = 1:length(lambda_vec)\n% lambda = lambda_vec(i);\n% % Compute train / val errors when training linear\n% % regression with regularization parameter lambda\n% % You should store the result in error_train(i)\n% % and error_val(i)\n% ....\n%\n% end\n%\n%\n\nfor i = 1:length(lambda_vec),\n lambda = lambda_vec(i);\n theta = trainLinearReg(X, y, lambda);\n error_train(i) = linearRegCostFunction(X, y, theta, 0);\n error_val(i) = linearRegCostFunction(Xval, yval, theta, 0);\nendfor\n\n\n\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-ex5/ex5/validationCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.8840392878563336, "lm_q1q2_score": 0.7186066527981382}} {"text": "%RPY2JAC Jacobian from RPY angle rates to angular velocity\n%\n% J = RPY2JAC(EUL) is a Jacobian matrix (3x3) that maps roll-pitch-yaw angle \n% rates to angular velocity at the operating point RPY=[R,P,Y].\n%\n% J = RPY2JAC(R, P, Y) as above but the roll-pitch-yaw angles are passed\n% as separate arguments.\n%\n% Notes::\n% - Used in the creation of an analytical Jacobian.\n%\n% See also EUL2JAC, SerialLink.JACOBN.\n\n\n\n% Copyright (C) 1993-2015, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction J = rpy2jac(r, p, y)\n\n if length(r) == 3\n % rpy2jac([r,p,y])\n p = r(2);\n y = r(3);\n r = r(1);\n elseif nargin ~= 3\n error('RTB:rpy2jac:badarg', 'bad arguments');\n end\n\tJ = [\t\n 1 0 sin(p)\n 0 cos(r) -cos(p)*sin(r)\n 0 sin(r) cos(p)*cos(r)\n ];\n\t\t\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/rpy2jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7186066497496796}} {"text": "function m=v_pesq2mos(p)\n%V_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: v_pesq2mos.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 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,v_pesq2mos(pp));\n xlabel('PESQ (P.862)');\n ylabel('Mean Opimion Score (MOS)');\nend\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_pesq2mos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7186066367674943}} {"text": "function [H, pValue, KSstatistic] = kstest_2s_2d(x1, x2, alpha)\n\n% kstest_2s_2d - FUNCTION Two-sample Two-diensional Kolmogorov-Smirnov Test\n%\n% Usage:[H, pValue, KSstatistic] = kstest_2s_2d(x1, x2 <, alpha>)\n%\n% The paired-sample Kolmogorov-Smirnov test is a statistical test used to\n% determine whether two sets of data arise from the same or different\n% distributions. The null hypothesis is that both data sets were drawn\n% from the same continuous distribution.\n% \n% The algorithm in this function is taken from Peacock [1].\n% \n% 'x1' is an [Nx2] matrix, each row containing a two-dimensional sample.\n% 'x2' is an [Mx2] matrix, each row likewise containing a two-dimensional\n% sample. The optional argument 'alpha' is used to set the desired\n% significance level for rejecting the null hypothesis.\n% \n% 'H' is a logical value: true indicates that the null hypothesis should be\n% rejected. 'pValue' is an estimate for the P value of the test statistic.\n% 'KSstatistic' is the raw value for the test statistic ('D' in [1]).\n% \n% In contrast to kstest2, this function can only perform a two-tailed test.\n% This is because Peacock does not provide a method for estimating P in the\n% one-tailed case [1]. Suggestions for a one-tailed test are welcome.\n%\n% References: [1] J. A. Peacock, \"Two-dimensional goodness-of-fit testing\n% in astronomy\", Monthly Notices Royal Astronomy Society 202 (1983)\n% 615-627.\n% Available from: http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1983MNRAS.202..615P&defaultprint=YES&filetype=.pdf\n%\n\n% Author: Dylan Muir (From kstest_2s_2d by Qiuyan Peng @ ECE/HKUST) Date:\n% 13th October, 2012\n\n%%\n\nif nargin < 2\n error('stats:kstest2:TooFewInputs','At least 2 inputs are required.');\nend\n\n\n%%\n%\n% x1,x2 are both 2-column matrices\n%\n\nif ((size(x1,2)~=2)||(size(x2,2)~=2))\n error('stats:kstest2:TwoColumnMatrixRequired','The samples X1 and X2 must be two-column matrices.');\nend\nn1 = size(x1,1);\nn2 = size(x2,1);\n\n\n%%\n%\n% Ensure the significance level, ALPHA, is a scalar\n% between 0 and 1 and set default if necessary.\n%\n\nif (nargin >= 3) && ~isempty(alpha)\n if ~isscalar(alpha) || (alpha <= 0 || alpha >= 1)\n error('stats:kstest2:BadAlpha',...\n 'Significance level ALPHA must be a scalar between 0 and 1.');\n end\nelse\n alpha = 0.05;\nend\n\n\n\n%%\n%\n% Calculate F1(x) and F2(x), the empirical (i.e., sample) CDFs.\n%\n\n% - A function handle to perform comparisons in all possible directions\nfhCounts = @(x, edge)([(x(:, 1) >= edge(1)) & (x(:, 2) >= edge(2))...\n (x(:, 1) <= edge(1)) & (x(:, 2) >= edge(2))...\n (x(:, 1) <= edge(1)) & (x(:, 2) <= edge(2))...\n (x(:, 1) >= edge(1)) & (x(:, 2) <= edge(2))]);\n\nKSstatistic = -inf;\n\nfor iX = 1:(n1+n2)\n % - Choose a starting point\n if (iX<=n1)\n edge = x1(iX,:);\n else\n edge = x2(iX-n1,:);\n end\n \n % - Estimate the CDFs for both distributions around this point\n vfCDF1 = sum(fhCounts(x1, edge)) ./ n1;\n vfCDF2 = sum(fhCounts(x2, edge)) ./ n2;\n \n % - Two-tailed test statistic\n vfThisKSTS = abs(vfCDF1 - vfCDF2);\n fKSTS = max(vfThisKSTS);\n \n % - Final test statistic is the maximum absolute difference in CDFs\n if (fKSTS > KSstatistic)\n KSstatistic = fKSTS;\n end\nend\n\n\n%% Peacock Z calculation and P estimation\n\nn = n1 * n2 /(n1 + n2);\nZn = sqrt(n) * KSstatistic;\nZinf = Zn / (1 - 0.53 * n^(-0.9));\npValue = 2 * exp(-2 * (Zinf - 0.5).^2);\n\n% Clip invalid values for P\nif (pValue > 0.2)\n pValue = 0.2;\nend\n\nH = (pValue <= alpha);\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/38617-two-dimensional-2d-paired-kolmogorov-smirnov-test/kstest_2s_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7186066367674943}} {"text": "% MTSP_GA Multiple Traveling Salesmen Problem (M-TSP) Genetic Algorithm (GA)\n% Finds a (near) optimal solution to the M-TSP by setting up a GA to search\n% for the shortest route (least distance needed for the salesmen to travel\n% to each city exactly once and return to their starting locations)\n%\n% Summary:\n% 1. Each salesman travels to a unique set of cities and completes the\n% route by returning to the city he started from\n% 2. Each city is visited by exactly one salesman\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 city-to-city distances or costs\n% NSALESMEN (scalar integer) is the number of salesmen to visit the cities\n% MINTOUR (scalar integer) is the minimum tour length for any of the salesmen\n% POPSIZE (scalar integer) is the size of the population (should be divisible by 8)\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% OPTBREAK (integer array) is the list of route break points (these specify the indices\n% into the route used to obtain the individual salesman routes)\n% MINDIST (scalar float) is the total distance traveled by the salesmen\n%\n% Route/Breakpoint Details:\n% If there are 10 cities and 3 salesmen, a possible route/break\n% combination might be: rte = [5 6 9 1 4 2 8 10 3 7], brks = [3 7]\n% Taken together, these represent the solution [5 6 9][1 4 2 8][10 3 7],\n% which designates the routes for the 3 salesmen as follows:\n% . Salesman 1 travels from city 5 to 6 to 9 and back to 5\n% . Salesman 2 travels from city 1 to 4 to 2 to 8 and back to 1\n% . Salesman 3 travels from city 10 to 3 to 7 and back to 10\n%\n% Example:\n% n = 35;\n% xy = 10*rand(n,2);\n% nSalesmen = 5;\n% minTour = 3;\n% popSize = 80;\n% numIter = 5e3;\n% a = meshgrid(1:n);\n% dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);\n% [optRoute,optBreak,minDist] = mtsp_ga(xy,dmat,nSalesmen,minTour, ...\n% popSize,numIter,1,1);\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% nSalesmen = 5;\n% minTour = 3;\n% popSize = 80;\n% numIter = 1e4;\n% a = meshgrid(1:n);\n% dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);\n% [optRoute,optBreak,minDist] = mtsp_ga(xy,dmat,nSalesmen,minTour, ...\n% popSize,numIter,1,1);\n%\n% Example:\n% n = 35;\n% xyz = 10*rand(n,3);\n% nSalesmen = 5;\n% minTour = 3;\n% popSize = 80;\n% numIter = 5e3;\n% a = meshgrid(1:n);\n% dmat = reshape(sqrt(sum((xyz(a,:)-xyz(a',:)).^2,2)),n,n);\n% [optRoute,optBreak,minDist] = mtsp_ga(xyz,dmat,nSalesmen,minTour, ...\n% popSize,numIter,1,1);\n%\n% See also: tsp_ga, mtspf_ga, mtspo_ga, mtspof_ga, mtspofs_ga, mtspv_ga, distmat\n%\n% Author: Joseph Kirk\n% Email: jdkirk630@gmail.com\n% Release: 1.5\n% Release Date: 11/07/11\nfunction varargout = mtsp_ga(xy,dmat,nSalesmen,minTour,popSize,numIter,showProg,showResult)\n\n% Process Inputs and Initialize Defaults\nnargs = 8;\nfor k = nargin:nargs-1\n switch k\n case 0\n xy = 10*rand(40,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 nSalesmen = 5;\n case 3\n minTour = 3;\n case 4\n popSize = 80;\n case 5\n numIter = 5e3;\n case 6\n showProg = 1;\n case 7\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;\n\n% Sanity Checks\nnSalesmen = max(1,min(n,round(real(nSalesmen(1)))));\nminTour = max(1,min(floor(n/nSalesmen),round(real(minTour(1)))));\npopSize = max(8,8*ceil(popSize(1)/8));\nnumIter = max(1,round(real(numIter(1))));\nshowProg = logical(showProg(1));\nshowResult = logical(showResult(1));\n\n% Initializations for Route Break Point Selection\nnBreaks = nSalesmen-1;\ndof = n - minTour*nSalesmen; % degrees of freedom\naddto = ones(1,dof+1);\nfor k = 2:nBreaks\n addto = cumsum(addto);\nend\ncumProb = cumsum(addto)/sum(addto);\n\n% Initialize the Populations\npopRoute = zeros(popSize,n); % population of routes\npopBreak = zeros(popSize,nBreaks); % population of breaks\npopRoute(1,:) = (1:n);\npopBreak(1,:) = rand_breaks();\nfor k = 2:popSize\n popRoute(k,:) = randperm(n);\n popBreak(k,:) = rand_breaks();\nend\n\n% Select the Colors for the Plotted Routes\npclr = ~get(0,'DefaultAxesColor');\nclr = [1 0 0; 0 0 1; 0.67 0 1; 0 1 0; 1 0.5 0];\nif nSalesmen > 5\n clr = hsv(nSalesmen);\nend\n\n% Run the GA\nglobalMin = Inf;\ntotalDist = zeros(1,popSize);\ndistHistory = zeros(1,numIter);\ntmpPopRoute = zeros(8,n);\ntmpPopBreak = zeros(8,nBreaks);\nnewPopRoute = zeros(popSize,n);\nnewPopBreak = zeros(popSize,nBreaks);\nif showProg\n pfig = figure('Name','MTSP_GA | Current Best Solution','Numbertitle','off');\nend\nfor iter = 1:numIter\n % Evaluate Members of the Population\n for p = 1:popSize\n d = 0;\n pRoute = popRoute(p,:);\n pBreak = popBreak(p,:);\n rng = [[1 pBreak+1];[pBreak n]]';\n for s = 1:nSalesmen\n d = d + dmat(pRoute(rng(s,2)),pRoute(rng(s,1)));\n for k = rng(s,1):rng(s,2)-1\n d = d + dmat(pRoute(k),pRoute(k+1));\n end\n end\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 = popRoute(index,:);\n optBreak = popBreak(index,:);\n rng = [[1 optBreak+1];[optBreak n]]';\n if showProg\n % Plot the Best Route\n figure(pfig);\n for s = 1:nSalesmen\n rte = optRoute([rng(s,1):rng(s,2) rng(s,1)]);\n if dims > 2, plot3(xy(rte,1),xy(rte,2),xy(rte,3),'.-','Color',clr(s,:));\n else plot(xy(rte,1),xy(rte,2),'.-','Color',clr(s,:)); end\n title(sprintf('Total Distance = %1.4f, Iteration = %d',minDist,iter));\n hold on\n end\n hold off\n end\n end\n\n % Genetic Algorithm Operators\n randomOrder = randperm(popSize);\n for p = 8:8:popSize\n rtes = popRoute(randomOrder(p-7:p),:);\n brks = popBreak(randomOrder(p-7:p),:);\n dists = totalDist(randomOrder(p-7:p));\n [ignore,idx] = min(dists); %#ok\n bestOf8Route = rtes(idx,:);\n bestOf8Break = brks(idx,:);\n routeInsertionPoints = sort(ceil(n*rand(1,2)));\n I = routeInsertionPoints(1);\n J = routeInsertionPoints(2);\n for k = 1:8 % Generate New Solutions\n tmpPopRoute(k,:) = bestOf8Route;\n tmpPopBreak(k,:) = bestOf8Break;\n switch k\n case 2 % Flip\n tmpPopRoute(k,I:J) = tmpPopRoute(k,J:-1:I);\n case 3 % Swap\n tmpPopRoute(k,[I J]) = tmpPopRoute(k,[J I]);\n case 4 % Slide\n tmpPopRoute(k,I:J) = tmpPopRoute(k,[I+1:J I]);\n case 5 % Modify Breaks\n tmpPopBreak(k,:) = rand_breaks();\n case 6 % Flip, Modify Breaks\n tmpPopRoute(k,I:J) = tmpPopRoute(k,J:-1:I);\n tmpPopBreak(k,:) = rand_breaks();\n case 7 % Swap, Modify Breaks\n tmpPopRoute(k,[I J]) = tmpPopRoute(k,[J I]);\n tmpPopBreak(k,:) = rand_breaks();\n case 8 % Slide, Modify Breaks\n tmpPopRoute(k,I:J) = tmpPopRoute(k,[I+1:J I]);\n tmpPopBreak(k,:) = rand_breaks();\n otherwise % Do Nothing\n end\n end\n newPopRoute(p-7:p,:) = tmpPopRoute;\n newPopBreak(p-7:p,:) = tmpPopBreak;\n end\n popRoute = newPopRoute;\n popBreak = newPopBreak;\nend\n\nif showResult\n% Plots\n figure('Name','MTSP_GA | Results','Numbertitle','off');\n subplot(2,2,1);\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(optRoute,optRoute));\n title('Distance Matrix');\n subplot(2,2,3);\n rng = [[1 optBreak+1];[optBreak n]]';\n for s = 1:nSalesmen\n rte = optRoute([rng(s,1):rng(s,2) rng(s,1)]);\n if dims > 2, plot3(xy(rte,1),xy(rte,2),xy(rte,3),'.-','Color',clr(s,:));\n else plot(xy(rte,1),xy(rte,2),'.-','Color',clr(s,:)); end\n title(sprintf('Total Distance = %1.4f',minDist));\n hold on;\n end\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} = optBreak;\n varargout{3} = minDist;\nend\n\n % Generate Random Set of Break Points\n function breaks = rand_breaks()\n if minTour == 1 % No Constraints on Breaks\n tmpBreaks = randperm(n-1);\n breaks = sort(tmpBreaks(1:nBreaks));\n else % Force Breaks to be at Least the Minimum Tour Length\n nAdjust = find(rand < cumProb,1)-1;\n spaces = ceil(nBreaks*rand(1,nAdjust));\n adjust = zeros(1,nBreaks);\n for kk = 1:nBreaks\n adjust(kk) = sum(spaces == kk);\n end\n breaks = minTour*(1:nBreaks) + cumsum(adjust);\n end\n end\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/19049-multiple-traveling-salesmen-problem-genetic-algorithm/mtsp_ga.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7185459226888201}} {"text": "function [PR, PN, PC, PL] = subspaceProjector(A, printLevel, sub_space)\n% Returns the matrix for projection onto the subspace of matrix A,\n% specified by `sub_space`\n% * 'all'\n% * 'R' row space i.e. range(A')\n% * 'N' nullspace i.e. null(A)\n% * 'C' column space i.e. range(A)\n% * 'L' left nullspace i.e. null(A')\n%\n% Let M denote the Moore-Penrose pseudoinverse of the A and the subscripts are the following\n% `_R` row space i.e. range(A')\n% `_N` nullspace i.e. null(A)\n% `_C` column space i.e. range(A)\n% `_L` left nullspace i.e. null(A')\n%\n% Let\n%\n% .. math::\n% v &= v_R + v_N \\\\\n% v_R &= M A v = PR v \\\\\n% v_N &= (I - M A) v = PN v\n%\n% Let\n%\n% .. math::\n% u &= u_C + u_L \\\\\n% u_C &= A M u = PC u \\\\\n% u_L &= (I - A M) u = PL u\n%\n% Examples:\n%\n% Given :math:`A v = b`, then :math:`v_R = M b`\n%\n% Given :math:`A^Tu = q`, then :math:`u_C = M^T q`\n%\n% USAGE:\n%\n% [PR, PN, PC, PL] = subspaceProjector(model, printLevel, sub_space)\n%\n% INPUT:\n% A `m x n` matrix\n%\n% OPTIONAL INPUTS:\n% printLevel: {(1), 0}, 1 = print diagnostics, 0 = silent\n% sub_space: returns projection matrices onto all or one select\n%\n% * sub_space\n% * 'all'\n% * 'R' row space\n% * 'N' nullspace\n% * 'C' column space\n% * 'L' left nullspace\n%\n% OUTPUTS:\n% [PR, PN, PC, PL]: matrices for projection onto the row, null, \n% column and left nullspace of A, respectively\n%\n% .. Author:\n% - 10 July 2009 : Ronan Fleming. First Version.\n% - 10 Aug 2009 : Changed to use Micheal Saunders faster approach\n% - Jan 2018 : Changed to take a matrix A \n\nif ~exist('printLevel','var')\n printLevel=1;\nend\n\nif ~exist('sub_space','var')\n sub_space='all';\nend\n\n[nMet,nRxn]=size(A);\n\narchstr = computer('arch');\nswitch archstr\n case {'glnx86','glnxa64'}\n %A = U1*D1*V1'\n if printLevel\n fprintf('%s','Calculating SVD ...');\n tic\n end\n %Michael Saunders code\n [U1,D1,V1,r] = subspaceSVD(A);\n if printLevel\n fprintf('%s\\n',[' finished. toc = ' num2str(toc)]);\n end\n PR=[];PN=[];PC=[];PL=[];\n if strcmp(sub_space,'R')\n PR=V1*V1';\n elseif strcmp(sub_space,'N')\n PN=eye(nRxn) - V1*V1';\n elseif strcmp(sub_space,'C')\n PC=U1*U1';\n elseif strcmp(sub_space,'L')\n PL=eye(nMet) - U1*U1';\n elseif strcmp(sub_space,'all')\n PR=V1*V1';\n PN=eye(nRxn) - V1*V1';\n PC=U1*U1';\n PL=eye(nMet) - U1*U1';\n end\n otherwise\n %for other architectures calculate the Moore-Penrose Pseudoinverse\n if printLevel\n fprintf('%s','Calculating the Moore-Penrose Pseudoinverse...');\n tic\n end\n M=pinv(full(A));\n if printLevel\n fprintf('%s\\n',[' finished. toc = ' num2str(toc)]);\n end\n\n PR=[];PN=[];PC=[];PL=[];\n if strcmp(sub_space,'R')\n PR=M*A;\n elseif strcmp(sub_space,'N')\n PN=eye(nRxn)-M*A;\n elseif strcmp(sub_space,'C')\n PC=A*M;\n elseif strcmp(sub_space,'L')\n PL=eye(nMet)-A*M;\n elseif strcmp(sub_space,'all')\n PR=M*A;\n PN=eye(nRxn)-M*A;\n PC=A*M;\n PL=eye(nMet)-A*M;\n end\nend", "meta": {"author": "opencobra", "repo": "cobratoolbox", "sha": "e60274d127f65d518535fd0814d20c53dc530f73", "save_path": "github-repos/MATLAB/opencobra-cobratoolbox", "path": "github-repos/MATLAB/opencobra-cobratoolbox/cobratoolbox-e60274d127f65d518535fd0814d20c53dc530f73/src/analysis/subspaces/subspaceProjection/subspaceProjector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.718545919665235}} {"text": "function [pID,pN] = FDR(p,q)\n% :Usage:\n% ::\n%\n% pt = FDR(p,q)\n%\n% :Inputs:\n%\n% **p:**\n% vector of p-values\n%\n% **q:**\n% False Discovery Rate level\n%\n% :Outputs:\n%\n% **pID:**\n% p-value threshold based on independence or positive dependence\n%\n% **pN:**\n% Nonparametric p-value threshold\n%\n% ..\n% % @(#)FDR.m\t1.3 Tom Nichols 02/01/18\n%\n% The checking code below was added by Tor Wager\n% ..\n\n p(isnan(p)) = [];\n\n if any(p == 0)\n disp('******************************************')\n disp('Warning! Some p-values are zero.')\n disp('FDR.m will interpret these as ineligible voxels.')\n disp('If these are valid p-values, they should have some not-exactly-zero value.')\n p(p == 0) = [];\n disp('******************************************')\n\n end\n\n p = sort(p(:));\n V = length(p);\n I = (1:V)';\n\n cVID = 1;\n cVN = sum(1./(1:V));\n\n pID = p(max(find(p<=I/V*q/cVID)));\n pN = p(max(find(p<=I/V*q/cVN)));\n\n return\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/Image_thresholding/FDR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.7185459116125726}} {"text": "function [ n_data, n, fn ] = i4_factorial_values ( n_data )\n\n%*****************************************************************************80\n%\n%% I4_FACTORIAL_VALUES returns values of the factorial function.\n%\n% Discussion:\n%\n% 0! = 1\n% I! = Product ( 1 <= J <= I ) I\n%\n% In Mathematica, the function can be evaluated by:\n%\n% n!\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, integer N, the argument of the function.\n%\n% Output, integer FN, the value of the function.\n%\n n_max = 13;\n\n fn_vec = [ ...\n 1, ...\n 1, ...\n 2, ...\n 6, ...\n 24, ...\n 120, ... \n 720, ...\n 5040, ...\n 40320, ...\n 362880, ...\n 3628800, ...\n 39916800, ...\n 479001600 ];\n\n n_vec = [ ...\n 0, 1, 2, 3, ...\n 4, 5, 6, 7, ...\n 8, 9, 10, 11, ...\n 12 ];\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 fn = 0;\n else\n n = n_vec(n_data);\n fn = fn_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/i4_factorial_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7184836930028715}} {"text": "% Detailed description of the factor data structure and related functions\n% -----------------------------------------------------------------------\n% We will use structures to implement the factor datatype. The code\n%\n% phi = struct('var', [3 1 2], 'card', [2 2 2], 'val', ones(1, 8));\n%\n% creates a factor over variables X_3, X_1, X_2, which are all binary\n% valued, because phi.card(1) (the cardinality of X_3, |Val(X_3)|) is 2, \n% and likewise for X_1 and X_2. phi has been initialized so that \n% phi(X_3, X_1, X_2) = 1 for any assignment to the variables.\n%\n% A factor's values are stored in a row vector in the .val field \n% using an ordering such that the left-most variables as defined in the \n% .var field cycle through their values the fastest. More concretely, for \n% the factor phi defined above, we have the following mapping from variable \n% assignments to the index of the row vector in the .val field:\n%\n% -+-----+-----+-----+-------------------+ \n% | X_3 | X_1 | X_2 | phi(X_3, X_1, X_2)|\n% -+-----+-----+-----+-------------------+\n% | 1 | 1 | 1 | phi.val(1) |\n% -+-----+-----+-----+-------------------+\n% | 2 | 1 | 1 | phi.val(2) |\n% -+-----+-----+-----+-------------------+\n% | 1 | 2 | 1 | phi.val(3) |\n% -+-----+-----+-----+-------------------+\n% | 2 | 2 | 1 | phi.val(4) |\n% -+-----+-----+-----+-------------------+\n% | 1 | 1 | 2 | phi.val(5) |\n% -+-----+-----+-----+-------------------+\n% | 2 | 1 | 2 | phi.val(6) |\n% -+-----+-----+-----+-------------------+\n% | 1 | 2 | 2 | phi.val(7) |\n% -+-----+-----+-----+-------------------+\n% | 2 | 2 | 2 | phi.val(8) |\n% -+-----+-----+-----+-------------------+\n%\n%\n% We have provided the AssignmentToIndex and IndexToAssignment functions\n% that compute the mapping between the assignments A and the variable indices I,\n% given D, the cardinality of the variables. Concretely, given a factor phi, if\n% phi.val(I) corresponds to the assignment A, i.e. phi(X = A) = phi.val(I) then\n% \n% I = AssignmentToIndex(A, D)\n% A = IndexToAssignment(I, D)\n%\n% For instance, for the factor phi as defined above, with the assignment \n%\n% A = [2 1 2] \n%\n% to X_3, X_1 and X_2 respectively (as defined by phi.var = [3 1 2]), I = 6 \n% as phi.val(6) corresponds to the value of phi(X_3 = 2, X_1 = 1, X_2 = 2).\n% Thus, AssignmentToIndex([2 1 2], [2 2 2]) returns 6, and conversely, \n% IndexToAssignment(6, [2 2 2]) returns the vector [2 1 2]. The second\n% argument in the function calls corresponds to the cardinality of the\n% sample factor phi, phi.card, which is [2 2 2].\n%\n% More generally, the assignment vector A is a row vector that corresponds\n% to assignments to the variables in a factor, with an understanding that the\n% variables for which the assignments refer to are given by the .var field\n% of the factor. \n%\n% Giving AssignmentToIndex a matrix A, one assignment per row, will cause it\n% to return a vector of indices I, such that I(k) is the index\n% corresponding to the assignment in A(k, :) (row k). \n% \n% Similarly, giving IndexToAssignment a vector I of indices will yield a\n% matrix A of assignments, one per row, such that A(k, :) (the kth row of A)\n% corresponds to the assignment mapped to by index I(k).\n%\n% Getting and setting values to factors\n% -------------------------------------\n%\n% We have provided the convenience functions GetValueOfAssignment and\n% SetValueOfAssignment so you do not need to manipulate the .val field\n% directly for getting and setting values.\n%\n% For instance, calling \n%\n% GetValueOfAssignment(phi, [1 2 1]) \n%\n% yields the value phi(X_3 = 1, X_1 = 2, X_2 = 1). Again, the variables for \n% which the assignments refer to are given by the .var field of the factor.\n%\n% Similarly, executing \n%\n% phi = SetValueOfAssignment(phi, [2 2 1], 6) \n%\n% causes the value of phi(X_3 = 2, X_1 = 2, X_2 = 1) to be set to 6. Note \n% that because MATLAB/Octave passes function arguments by value (not by \n% reference), SetValueOfAssignment *does not modify* the factor that you \n% passed in. Instead, it returns a new factor with the modified value for \n% the specified assignment; this is why we reassigned phi to the result of\n% SetValueOfAssignment.\n%\n% More details about these functions are provided in their respective .m\n% files.\n\n% Sample Factors and Outputs\n% --------------------------\n%\n% In the following, we have provided you with some sample input factors, as \n% well as the output that you should receive when various operations are\n% performed on these factors. You may find these sample inputs and outputs\n% helpful in debugging your implementation. For instance, FACTORS.PRODUCT \n% is the factor you should get when you execute \n%\n% FactorProduct(FACTORS.INPUT(1), FACTORS.INPUT(2))\n%\n% These sample factors define a simple chain Bayesian network over binary \n% variables: X_1 -> X_2 -> X_3\n%\n\n% FACTORS.INPUT(1) contains P(X_1)\nFACTORS.INPUT(1) = struct('var', [1], 'card', [2], 'val', [0.11, 0.89]);\n\n% FACTORS.INPUT(2) contains P(X_2 | X_1)\nFACTORS.INPUT(2) = struct('var', [2, 1], 'card', [2, 2], 'val', [0.59, 0.41, 0.22, 0.78]);\n\n% FACTORS.INPUT(3) contains P(X_3 | X_2)\nFACTORS.INPUT(3) = struct('var', [3, 2], 'card', [2, 2], 'val', [0.39, 0.61, 0.06, 0.94]);\n\n% Factor Product\n% FACTORS.PRODUCT = FactorProduct(FACTORS.INPUT(1), FACTORS.INPUT(2));\n% The factor defined here is correct to 4 decimal places.\nFACTORS.PRODUCT = struct('var', [1, 2], 'card', [2, 2], 'val', [0.0649, 0.1958, 0.0451, 0.6942]);\n\n% Factor Marginalization\n% FACTORS.MARGINALIZATION = FactorMarginalization(FACTORS.INPUT(2), [2]);\nFACTORS.MARGINALIZATION = struct('var', [1], 'card', [2], 'val', [1 1]); \n\n% Observe Evidence\n% FACTORS.EVIDENCE = ObserveEvidence(FACTORS.INPUT, [2 1; 3 2]);\nFACTORS.EVIDENCE(1) = struct('var', [1], 'card', [2], 'val', [0.11, 0.89]);\nFACTORS.EVIDENCE(2) = struct('var', [2, 1], 'card', [2, 2], 'val', [0.59, 0, 0.22, 0]);\nFACTORS.EVIDENCE(3) = struct('var', [3, 2], 'card', [2, 2], 'val', [0, 0.61, 0, 0]);\n\n% Compute Joint Distribution\n% FACTORS.JOINT = ComputeJointDistribution(FACTORS.INPUT);\nFACTORS.JOINT = struct('var', [1, 2, 3], 'card', [2, 2, 2], 'val', [0.025311, 0.076362, 0.002706, 0.041652, 0.039589, 0.119438, 0.042394, 0.652548]);\n\n% Compute Marginal\n%FACTORS.MARGINAL = ComputeMarginal([2, 3], FACTORS.INPUT, [1, 2]);\nFACTORS.MARGINAL = struct('var', [2, 3], 'card', [2, 2], 'val', [0.0858, 0.0468, 0.1342, 0.7332]);\n\n\n%p = ComputeJointDistribution(FACTORS.INPUT)\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/1.Intro to Bayesian Networks/FactorTutorial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7184836906044663}} {"text": "function x = ffwt ( n, x )\n\n%*****************************************************************************80\n%\n%% FFWT performs an in-place fast Walsh transform.\n%\n% Discussion:\n%\n% This routine performs a fast Walsh transform on an input series X\n% leaving the transformed results in X.\n% X is dimensioned N, which must be a power of 2.\n% The results of this Walsh transform are in sequency order.\n%\n% The output sequence could be normalized by dividing by N.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 March 2011\n%\n% Author:\n%\n% Ken Beauchamp\n%\n% Reference:\n%\n% Ken Beauchamp,\n% Walsh functions and their applications,\n% Academic Press, 1975,\n% ISBN: 0-12-084050-2,\n% LC: QA404.5.B33.\n%\n% Parameters:\n%\n% Input, integer N, the number of items in X.\n% N must be a power of 2.\n%\n% Input, real X(N), the data to be transformed.\n%\n% Output, real X(N), the transformed data.\n%\n m = i4_log_2 ( n );\n\n for i = 1 : m\n two_power(i) = 2^( m - i );\n end\n\n for l = 1 : m\n\n nz = 2^( l - 1 );\n nzi = 2 * nz;\n nzn = floor ( n / nzi );\n nz2 = floor ( nz / 2 );\n if ( nz2 == 0 )\n nz2 = 1;\n end\n\n for i = 1 : nzn\n\n js = ( i - 1 ) * nzi;\n z = 1.0;\n\n for ii = 1 : 2\n\n for j = 1 : nz2\n js = js + 1;\n j2 = js + nz;\n hold = x(js) + z * x(j2);\n z = - z;\n x(j2) = x(js) + z * x(j2);\n x(js) = hold;\n z = - z;\n end\n\n if ( l == 1 )\n break\n end\n\n z = - 1.0;\n\n end\n\n end\n end\n%\n% Bit reversal section.\n%\n nw = 0;\n for k = 1 : n\n%\n% Choose correct index and switch elements if not already switched.\n%\n if ( k < nw + 1 )\n hold = x(nw+1);\n x(nw+1) = x(k);\n x(k) = hold;\n end\n%\n% Bump up series by 1.\n%\n for i = 1 : m\n\n ii = i;\n if ( nw < two_power(i) )\n break\n end\n mw = floor ( nw / two_power(i) );\n mw1 = floor ( mw / 2 );\n if ( mw <= 2 * mw1 )\n break\n end\n\n nw = nw - two_power(i);\n\n end\n\n nw = nw + two_power(ii);\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/walsh/ffwt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7184836842976794}} {"text": "function [F,L,Qc,H,Pinf,dF,dQc,dPinf,params] = cf_matern32_to_ss(magnSigma2, lengthScale)\n% CF_MATERN32_TO_SS - Matern covariance functions, nu = 3/2, to state space\n%\n% Syntax:\n% [F,L,Qc,H,Pinf,dF,dQc,dPinf,params] = cf_matern32_to_ss(magnSigma2, lengthScale)\n%\n% In:\n% magnSigma2 - Matern magnitude scale parameter (default: 1)\n% lengthScale - Matern distance scale parameter (default: 1)\n%\n% Out:\n% F - Feedback matrix\n% L - Noise effect matrix\n% Qc - Spectral density of white noise process w(t)\n% H - Observation model matrix\n% Pinf - Covariance of the stationary process\n% dF - Derivatives of F w.r.t. parameters\n% dQc - Derivatives of Qc w.r.t. parameters\n% dPinf - Derivatives of Pinf w.r.t. parameters\n% params - Input and output parameter information\n%\n% Description:\n% This function converts one-dimensional covariance functions of\n% the Matern class to state space models. The covariance function\n% parametrization is as follows\n%\n% k(tau) = magnSigma2 (1+sqrt(3) |tau|/lengthScale) exp(-sqrt(3) |tau|/lengthScale),\n%\n% where magnSigma2 is the magnitude scale parameter, lengthScale the \n% distance scale parameter, and tau the time difference between states, \n% tau = t-t'.\n% This function takes the covariance function parameters as inputs and\n% outputs the corresponding state space model matrices. The state space\n% model is given as follows in terms of a stochastic differential\n% equation\n%\n% df(t)/dt = F f(t) + L w(t),\n%\n% where w(t) is a white noise process with spectral denisty Qc. The\n% observation model for discrete observation y_k of f(t_k) at step k, \n% is as follows \n%\n% y_k = H f(t_k) + r_k, r_k ~ N(0, R),\n%\n% where r_k is the Gaussian measurement noise with covariance R.\n% Pinf is the stationary covariance, where the value of Pinf(i,j), \n% is defined as follows\n% \n% Pinf(i,j) = E[(f_i(t)-E[f_i(t)])(f_j(t)-E[f_j(t)])],\n%\n% where f_i(t) is component i of state vector f(t).\n% Derivatives: All have same form. For example, dF has the following\n% form:\n%\n% dF(:,:,1) = dF/d(magnSigma2 = input parameter_1),\n% dF(:,:,i) = dF/d(input parameter_i).\n%\n% References:\n%\n% [1] Simo Sarkka, Arno Solin, Jouni Hartikainen (2013).\n% Spatiotemporal learning via infinite-dimensional Bayesian\n% filtering and smoothing. IEEE Signal Processing Magazine,\n% 30(4):51-61.\n%\n% [2] Jouni Hartikainen and Simo Sarkka (2010). Kalman filtering and \n% smoothing solutions to temporal Gaussian process regression \n% models. Proceedings of IEEE International Workshop on Machine \n% Learning for Signal Processing (MLSP).\n%\n% See also:\n% COV_MATERN32, SPEC_MATERN32\n%\n% Copyright:\n% 2012-2014 Arno Solin\n% 2013-2014 Jukka Koskenranta\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%% Apply defaults\n\n % Check if magnSigma2 is given\n if nargin < 1 || isempty(magnSigma2), magnSigma2 = 1; end\n\n % Check if lengthScale is given\n if nargin < 2 || isempty(lengthScale), lengthScale = 1; end\n \n \n%% Form state space model\n \n % Derived constants\n lambda = sqrt(3)/lengthScale;\n \n % Feedback matrix\n F = [0, 1;\n -lambda^2, -2*lambda];\n\n % Noise effect matrix\n L = [0; 1];\n\n % Spectral density\n Qc = 12*sqrt(3)/lengthScale^3*magnSigma2;\n\n % Observation model\n H = [1, 0];\n \n\n%% Stationary covariance\n \n % Calculate Pinf only if requested\n if nargout > 4,\n \n Pinf = [magnSigma2, 0;\n 0, 3*magnSigma2/lengthScale^2];\n \n end\n \n \n%% Calculate derivatives\n\n % Calculate derivatives only if requested\n if nargout > 5\n \n % Derivative of F w.r.t. parameter magnSigma2\n dFmagnSigma2 = [0, 0;\n 0, 0];\n \n % Derivative of F w.r.t parameter lengthScale\n dFlengthScale = [0, 0;\n 6/lengthScale^3, 2*sqrt(3)/lengthScale^2];\n % Derivative of Qc w.r.t. parameter magnSigma2\n dQcmagnSigma2 = 12*sqrt(3)/lengthScale^3;\n \n % Derivative of Qc w.r.t. parameter lengthScale\n dQclengthScale = -3*12*sqrt(3)/lengthScale^4*magnSigma2;\n \n % Derivative of Pinf w.r.t. parameter magnSigma2\n dPinfmagnSigma2 = [1,0;\n 0,3/lengthScale^2];\n \n % Derivative of Pinf w.r.t. parameter lengthScale\n dPinflengthScale = [0,0;\n 0,-6*magnSigma2/lengthScale^3];\n \n % Stack all derivatives\n dF = zeros(2,2,2); \n dQc = zeros(1,1,2); \n dPinf = zeros(2,2,2);\n \n dF(:,:,1) = dFmagnSigma2;\n dF(:,:,2) = dFlengthScale;\n dQc(:,:,1) = dQcmagnSigma2;\n dQc(:,:,2) = dQclengthScale;\n dPinf(:,:,1) = dPinfmagnSigma2;\n dPinf(:,:,2) = dPinflengthScale;\n \n end\n \n \n%% Return parameter names\n\n % Only return if requested\n if nargout > 8\n \n % Stationarity\n p.stationary = true;\n \n % Input parameter information\n p.in{1}.name = 'magnSigma2'; p.in{1}.default = 1; p.in{1}.opt = true;\n p.in{2}.name = 'lengthScale'; p.in{2}.default = 1; p.in{2}.opt = true;\n \n % Return parameter setup\n params = p;\n \n end\n\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/cf_matern32_to_ss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7184716756632407}} {"text": "function R = rotz(alpha)\n\n % ROTZ computes a rotation along the z axis (rotation matrix).\n %\n % FORMAT: R = rotz(alpha) \n %\n % INPUT: - alpha = angle in radians\n %\n % OUTPUT: - R = [3 * 3] rotation matrix along z axis\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 R = [cos(alpha), -sin(alpha), 0;\n sin(alpha), cos(alpha), 0;\n 0, 0, 1];\n\nend\n", "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/rotz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7183353131427919}} {"text": "function accuracy = ldrc(TrainSet, TestSet, train_num, test_num, class_num, reduce_dimension, options)\n% Linear discriminant regression classificatoin (LDRC) algorithm\n%\n% Inputs:\n% TrainSet train sets of size dxn, where d is dimension and n is number of sets \n% TestSet test sets of size dxn, where d is dimension and n is number of sets\n% test_num numner of test sets\n% class_num numner of classes\n% options options\n% Output:\n% accuracy classification accurary\n%\n% References:\n% S.-M. Huang and J.-F. Yang,\n% \"Linear discriminant regression classification for face recognition,\"\n% IEEE Signal Processing Letters, vol.20, no.1, pp.91-94, 2013.\n%\n%\n% Created by H.Kasai on July 05, 2017\n\n\n % extract options\n if ~isfield(options, 'verbose')\n verbose = false;\n else\n verbose = options.verbose;\n end\n\n\n if verbose\n fprintf('# LDRC: calculate projection matrix U ...');\n end\n Eb = 0;\n Ew = 0;\n for j = 1 : train_num\n\n j_class = TrainSet.y(1, j);\n\n % calcuate Ew\n intra_class_index = find(TrainSet.y == j_class);\n intra_class_index(intra_class_index == j) = [];\n X_intra_wo_j = TrainSet.X(:, intra_class_index); % X^{intra}\n for k = 1 : size(X_intra_wo_j, 2)\n error_intra = TrainSet.X(:,j) - X_intra_wo_j(:,k); \n Ew = Ew + error_intra * error_intra'; % Eq.(14) \n end\n\n % calcuate Eb\n inter_class_index = find(TrainSet.y ~= j_class);\n X_inter = TrainSet.X(:, inter_class_index); % X^{inter}\n\n for k = 1 : size(X_inter, 2)\n error_inter = TrainSet.X(:,j) - X_inter(:,k); \n end\n Eb = Eb + error_inter * error_inter'; % Eq.(13)\n end\n\n % calc\n Ew = Ew/train_num; % Eq.(14)\n Eb = Eb/(train_num * (class_num-1)); % Eq.(13)\n epsilon = 0.001;\n Ew = Ew + epsilon*eye(size(Ew,2));\n\n [V, ~] = eig(Eb, Ew); % Eq.(18)\n for i = 1:reduce_dimension\n U(:,i) = V(:,size(V,2)+1-i);\n end\n if verbose\n fprintf('done\\n');\n end \n\n \n % reduce dimention\n TrainSet.X_red = U' * TrainSet.X;\n TestSet.X_red = U' * TestSet.X; \n\n\n % prepare projection matrix (hat matrix)\n H = cell(1, class_num);\n for i = 1 : class_num\n class_index = find(TrainSet.y == i);\n\n X_i = TrainSet.X_red(:, class_index);\n alpha_i = pinv(X_i' * X_i) * X_i';\n H{i} = X_i * alpha_i;\n\n if verbose\n fprintf('# LDRC: calc Hi for class : %03d/%03d (samples: %03d)\\n', i, class_num, length(class_index));\n end\n end\n\n \n % prepare predicted label array\n identity = zeros(1, test_num); \n \n \n % predict the class\n for j = 1 : test_num\n\n dis = zeros(1, class_num);\n y = TestSet.X_red(:, j);\n for i = 1 : class_num\n y_pred = H{i} * y;\n dis(1, i) = norm(y - y_pred);\n end\n [~, label] = min(dis);\n identity(j) = label; \n\n if verbose\n correct = (label == TestSet.y(1, j));\n fprintf('# LDRC: test:%03d, predict class: %03d --> ground truth :%03d (%d)\\n', j, label, TestSet.y(1, j), correct);\n end \n end\n \n \n % calculate accuracy\n correct_num = sum(identity == TestSet.y); \n accuracy = correct_num / test_num;\nend\n\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/algorithm/ldrc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7183353018793075}} {"text": "function [ vX, mX ] = SolveLsL1ComplexIrls( mA, vB, lambdaFctr, numIterations )\n% ----------------------------------------------------------------------------------------------- %\n%[ vX, mX ] = SolveLsL1ComplexIrls( mA, vB, lambdaFctr, numIterations )\n% Solves the 0.5 * || A x - b ||_2 + \\lambda || x ||_1 problem using Fixed\n% Point Iteration Method. The model allows A, b and x to be Complex.\n% Input:\n% - mA - Model Matrix.\n% The model matrix.\n% Structure: Matrix (m X n).\n% Type: 'Single' / 'Double' (Complex).\n% Range: (-inf, inf).\n% - vB - Input Vector.\n% The model known data.\n% Structure: Vector (m X 1).\n% Type: 'Single' / 'Double' (Complex).\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 Fixed Point Iteration Method - https://en.wikipedia.org/wiki/Fixed-point_iteration.\n% Remarks:\n% 1. A\n% Known Issues:\n% 1. A\n% TODO:\n% 1. B\n% Release Notes:\n% - 1.0.000 07/11/2016\n% * First realease version.\n% ----------------------------------------------------------------------------------------------- %\n\nparamEps = 1e-9;\n\n% vX = mAA \\ vAb;\nvX = pinv(mA) * vB; %1\n Dt=ts(l)-ts(l-1);\n end\n D_Diff(:,l)=m*Dt + s*sqrt(Dt)*randn(J,1);\nend\n\nX=[zeros(J,1) cumsum(D_Diff,2)+Jumps];", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/23554-review-of-discrete-and-continuous-processes-in-finance/Matlab/01RandomWalk/Theory/JumpDiffusionMerton.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.7182777086032376}} {"text": "% Purpose: Matlab script to compute the advection terms for incompressible Navier-Stokes\n\n% evaluate flux vectors\nfxUx = Ux.^2; fyUx = Ux.*Uy; fxUy = Ux.*Uy; fyUy = Uy.^2;\n\n% save old nonlinear terms\nNUxold = NUx; NUyold = NUy; \n\n% evaluate inner-product of test function gradient and flux functions\nNUx = Div2D(fxUx, fyUx); NUy = Div2D(fxUy, fyUy);\n\n% interpolate velocity to face nodes on element faces\nUxM = zeros(Nfp*Nfaces, K); UxP = zeros(Nfp*Nfaces, K); \nUyM = zeros(Nfp*Nfaces, K); UyP = zeros(Nfp*Nfaces, K); \nUxM(:) = Ux(vmapM); UyM(:) = Uy(vmapM); UxP(:) = Ux(vmapP); UyP(:) = Uy(vmapP);\n\n% set '+' trace of velocity at boundary face nodes\nUxP(mapI) = bcUx(mapI); UxP(mapW) = bcUx(mapW); UxP(mapC) = bcUx(mapC); \nUyP(mapI) = bcUy(mapI); UyP(mapW) = bcUy(mapW); UyP(mapC) = bcUy(mapC);\n\n% evaluate flux vectors at '-' and '+' traces at face nodes\nfxUxM = UxM.^2; fyUxM = UxM.*UyM; fxUyM = UxM.*UyM; fyUyM = UyM.^2;\nfxUxP = UxP.^2; fyUxP = UxP.*UyP; fxUyP = UxP.*UyP; fyUyP = UyP.^2;\n\n% evaluate dot product of normal and velocity at face nodes\nUDotNM = UxM.*nx + UyM.*ny; UDotNP = UxP.*nx + UyP.*ny;\nmaxvel = max(abs(UDotNM), abs(UDotNP)) ;\n\n% evaluate maximum normal velocity at face face nodes\nmaxvel = reshape(maxvel, Nfp, Nfaces*K);\nmaxvel = ones(Nfp, 1)*max(maxvel, [], 1); \nmaxvel = reshape(maxvel, Nfp*Nfaces, K);\n\n% form local Lax-Friedrichs/Rusonov fluxes\nfluxUx = 0.5*( -nx.*(fxUxM-fxUxP) - ny.*(fyUxM-fyUxP) - maxvel.*(UxP - UxM));\nfluxUy = 0.5*( -nx.*(fxUyM-fxUyP) - ny.*(fyUyM-fyUyP) - maxvel.*(UyP - UyM));\n\n% put volume and surface terms together\nNUx = NUx + LIFT*(Fscale.*fluxUx); NUy = NUy + LIFT*(Fscale.*fluxUy);\n\n% compute (U~,V~)\nUxT = ((a0*Ux+a1*Uxold) - dt*(b0*NUx + b1*NUxold))/g0; \nUyT = ((a0*Uy+a1*Uyold) - dt*(b0*NUy + b1*NUyold))/g0; \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/INSAdvection2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7182777022728148}} {"text": "function [p,y,a] = qint(ym1,y0,yp1) \n%QINT Quadratic interpolation of 3 uniformly spaced samples\n%\n% [p,y,a] = qint(ym1,y0,yp1) \n%\n% returns extremum-location p, height y, and curvature a\n% of a parabolic fit through three points. \n% The parabola is given by y(x) = a*(x-p)^2+b, \n% where y(-1)=ym1, y(0)=y0, y(1)=yp1. \n\n p = (yp1 - ym1)/(2*(2*y0 - yp1 - ym1)); \n if nargout>1\n y = y0 - 0.25*(ym1-yp1)*p;\n end;\n if nargout>2\n a = 0.5*(ym1 - 2*y0 + yp1);\n end;", "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/qint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897442783526, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7182776896119691}} {"text": "function gauss_seidel_poisson_1d ( k )\n\n%*****************************************************************************80\n%\n%% GAUSS_SEIDEL_POISSON_1D uses Gauss-Seidel iteration for 1D Poisson equation.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Commandline input, integer K, the grid index.\n% K specifies the number of nodes, by the formula NK = 2^K + 1.\n% K must be at least 0.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GAUSS_SEIDEL_POISSON_1D:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Use Gauss-Seidel iteration for the 1D Poisson equation.\\n' );\n\n if ( nargin < 1 )\n k = input ( ' Enter K >= 0, the grid index, so that NK = 2^K + 1: ' );\n elseif ( ischar ( k ) )\n k = str2num ( k );\n end\n%\n% Set boundaries.\n%\n a = 0.0;\n b = 1.0;\n%\n% Set boundary conditions.\n%\n ua = 0.0;\n ub = 0.0;\n%\n% Get NK.\n%\n nk = 2^k + 1;\n%\n% Set XK.\n%\n xk = ( linspace ( a, b, nk ) )';\n%\n% Get HK.\n%\n hk = ( b - a ) / ( nk - 1 );\n%\n% Set FK.\n%\n fk = force ( xk );\n fk(1) = ua;\n fk(nk) = ub;\n%\n% Set the -1/2/-1 entries of Ak.\n%\n% In order that the operator Ak approximate the Poisson operator,\n% and in order that we can compare linear systems for successive grids,\n% we should NOT multiply through by hk^2.\n%\n Uk = sparse ( 2:nk-1, 3:nk, -1.0, nk, nk ) / hk^2;\n Dk = sparse ( 2:nk-1, 2:nk-1, 2.0, nk, nk ) / hk^2;\n Dk(1,1) = 1.0;\n Dk(nk,nk) = 1.0;\n Lk = sparse ( 2:nk-1, 1:nk-2, -1.0, nk, nk ) / hk^2;\n Ak = Uk + Dk + Lk;\n%\n% Just because we can, ask MATLAB to get the exact solution of the linear system\n% directly.\n%\n udk = Ak \\ fk;\n%\n% Sample the solution to the continuous problem.\n%\n uek = exact ( xk );\n%\n% Use Gauss-Seidel iteration to solve the linear system to the given tolerance.\n%\n ujk = zeros ( nk, 1 );\n it_max = 10000000;\n res_max = 0.000001;\n\n [ ujk, it_num, res_norm ] = gauss_seidel ( nk, Lk, Dk, Uk, fk, ujk, it_max, ...\n res_max );\n%\n% Examine errors:\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Using grid index K = %d\\n', k );\n fprintf ( 1, ' System size NK was %d\\n', nk );\n fprintf ( 1, ' Tolerance for linear residual %g\\n', res_max );\n fprintf ( 1, ' RMS of linear residual %g\\n', res_norm );\n fprintf ( 1, ' Number of GS iterations taken was %d\\n', it_num );\n fprintf ( 1, ' RMS GS error in solution of linear system = %g\\n', ...\n norm ( udk - ujk ) / sqrt ( nk ) );\n fprintf ( 1, ' RMS discretization error in Poisson solution = %g\\n', ...\n norm ( uek - ujk ) / sqrt ( nk ) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I X U_Exact U_Direct U_GS\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : nk\n fprintf ( 1, ' %4d %10.4f %10.4g %10.4g %10.4g\\n', ...\n i, xk(i), uek(i), udk(i), ujk(i) );\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GAUSS_SEIDEL_POISSON_1D:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction uex = exact ( x )\n\n%*****************************************************************************80\n%\n%% UEX evaluates the solution of the continuous problem.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X(*), the evaluation points.\n%\n% Output, real UEX(*), the solution of the continuous problem \n% at the evaluation points.\n%\n uex = x .* ( x - 1 ) .* exp ( x );\n\n return\nend\nfunction f = force ( x )\n\n%*****************************************************************************80\n%\n%% FORCE evaluates the forcing term.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X(*), the evaluation points.\n%\n% Output, real F(*), the forcing term at the evaluation points.\n%\n f = - x .* ( x + 3 ) .* exp ( x );\n\n return\nend\nfunction [ u, it_num, res_norm ] = gauss_seidel ( n, Lk, Dk, Uk, f, u, ...\n it_max, res_max )\n\n%*****************************************************************************80\n%\n%% GAUSS_SEIDEL carries out the Gauss-Seidel iteration.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 November 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real sparse Lk(*,*), Dk(*,*), Uk(*,*), the strict lower triangle,\n% the diagonal, and the strict upper triangle of A.\n%\n% Input, real F(N), the right hand side.\n%\n% Input, real U(N), the estimated solution.\n%\n% Input, integer IT_MAX, the maximum number of iterations.\n%\n% Input, real RES_MAX, a convergence tolerance on the residual.\n%\n% Output, real U(N), the improved estimate of the solution.\n%\n% Output, integer IT_NUM, the number of iterations taken.\n%\n% Output, real RES_NORM, the RMS norm of the residual.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Step Residual Change\\n' );\n fprintf ( 1, '\\n' );\n\n it_num = it_max;\n\n for it = 1 : it_max\n\n u_old = u;\n u = ( Lk + Dk ) \\ ( f - Uk * u_old );\n r = ( Lk + Dk + Uk ) * u - f;\n res_norm = norm ( r ) / sqrt ( n );\n\n fprintf ( 1, ' %6d %10.4g %10.4g\\n', ...\n it, res_norm, norm ( u - u_old ) / sqrt ( n ) );\n\n if ( res_norm <= res_max )\n it_num = it;\n break;\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/gauss_seidel_poisson_1d/gauss_seidel_poisson_1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.7182693326420775}} {"text": "% HNORMALISE - Normalises array of homogeneous coordinates to a scale of 1\n%\n% Usage: nx = hnormalise(x)\n%\n% Argument:\n% x - an Nxnpts array of homogeneous coordinates.\n%\n% Returns:\n% nx - an Nxnpts array of homogeneous coordinates rescaled so\n% that the scale values nx(N,:) are all 1.\n%\n% Note that any homogeneous coordinates at infinity (having a scale value of\n% 0) are left unchanged.\n\n% Peter Kovesi \n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% http://www.csse.uwa.edu.au/~pk\n%\n% February 2004\n\nfunction nx = hnormalise(x)\n \n [rows,npts] = size(x);\n nx = x;\n\n % Find the indices of the points that are not at infinity\n finiteind = find(abs(x(rows,:)) > eps);\n\n %if length(finiteind) ~= npts\n % warning('Some points are at infinity');\n %end\n\n % Normalise points not at infinity\n for r = 1:rows-1\n\tnx(r,finiteind) = x(r,finiteind)./x(rows,finiteind);\n end\n nx(rows,finiteind) = 1;\n \n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/align2RGBD/align2RGBD/lib/peter/hnormalise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7182349127563749}} {"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 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 [ 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": "sccn", "repo": "eeglab", "sha": "36d3982a63cde83fb279ab465b7a026ec2807c0a", "save_path": "github-repos/MATLAB/sccn-eeglab", "path": "github-repos/MATLAB/sccn-eeglab/eeglab-36d3982a63cde83fb279ab465b7a026ec2807c0a/functions/sigprocfunc/realproba.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7182094179222253}} {"text": "function [fds, ics, averFD, averIC] = fdvolfft(im)\n% FDVOLFFT Compute fractal dimensions FDS and intercepts ICS of a 3D image\n% IM using FFT and draw rose plots of FDS and ICS \n% IM: input 3D array of a 3D image (grayvalue)\n% FDS: a 2D array of size 24x12 which stores the FDs in 24x12 directions\n% ICS: a 2D array of size 24x12 which stores the average intercepts in\n% 24x12 directions\n% AVERFD: average fractal dimension for all directions\n% AVERIC: average intercept for all directions\n%\n%\n% This script is free to use except for commercial purpose\n% Written by Mr. Jianbo ZHANG, J.Zhang@ewi.utwente.nl\n% 19 Jan, 2005\n%\n%\n% for example, the following script can compute the fractal dimension of\n% an MRI image volume\n%\n% load mri\n% D = squeeze(D) ;\n% image_num = 8;\n% image(D(:,:,image_num))\n% axis image\n% colormap(map)\n% title('Image of MRI slice No. 8 ')\n% [fds ics averFD averIC]= fdvolfft(D)\n% \n% Note: Since an MRI image is a self-affine, not self-similiar volume, its \n% fractal dimensions do not necessarily lie between 3 and 4.\n\n\ntic\nNUM_AZI = 24; % number of azimuth directions\n % that the frequency space is evenly divided\nNUM_ZEN = 12; % number of zenith directions\n % that the frequency space is evenly divided\nNUM_RAD = 30; % number of points that the radial line is evenly divided\n\nif nargin < 1, \n error('Missed input argument which must be a 3D array!')\nend\n\n[M N P] = size(im);\nxctr = 1 + bitshift(N, -1); % x coordinate of center point\nyctr = 1 + bitshift(M, -1); % y coordinate of center point\nzctr = 1 + bitshift(P, -1); % z coordinate of center point\nimMean = mean(im(:));\nfim = fftshift(fftn(double(im) - imMean)); \npsd = log(fim .* conj(fim) + 10^(-6)); \nsumBrite = zeros(NUM_AZI, NUM_ZEN, NUM_RAD); %accumulation PSD\n %for along each direction and\n %radius\nnCount = zeros(NUM_AZI, NUM_ZEN, NUM_RAD); % PSD count\nradius = zeros(2 * NUM_RAD,1); %accumulation PSD for all directions \nradCount = zeros(2 * NUM_RAD,1); % number of PSD for all directions\n\n%Compute phase distribution\nphase = zeros(180);\nfor k = 1:P\n for j = 1:M\n for i = 1:N\n realv = real(fim(j,i,k));\n imagv = imag(fim(j,i,k));\n if realv == 0\n value = pi/2;\n else\n value = atan((imagv / realv));\n ang = floor(180 * (pi / 2 + value) / pi);\n end\n if ang < 0\n ang = 0;\n end\n if ang > 179\n ang = 179;\n end\n phase(ang + 1) = phase(ang + 1) + 1;\n end\n end\nend\nmaxphase = max(phase);\nfigure, plot(phase / maxphase);\ntitle('Phase histogram (0...2 \\pi)');% \naxis off\n\n%accumulation of PSD for each direction and radius\nrmax = log(min(min(M,N),P)/2);% maximum radius\nfor k = 1:P\n if k ~= zctr\n zval = zctr - k;\n z2 = zval * zval;\n for j = 1:M\n if j ~= yctr\n yval = yctr - j;\n y2 = yval * yval;\n for i = 1:N\n if i ~= xctr\n xval = i - xctr;\n r = sqrt(z2 + y2 + xval * xval);\n rho = log(r);\n if rho > 0 & rho <= rmax\n mval = psd(j,i,k);\n temp1 = yval / xval;\n temp2 = zval / r;\n theta = atan(temp1);\n phi = acos(temp2);\n if xval < 0\n theta = theta + pi;\n end\n if theta < 0\n theta = theta + 2 * pi;\n end\n\n aziSN = floor(NUM_AZI * theta /(2 * pi));\n if aziSN > NUM_AZI - 1 | aziSN < 0\n aziSN = NUM_AZI - 1;\n end\n zenSN = floor(NUM_ZEN * phi / pi);\n if zenSN > NUM_ZEN - 1 | zenSN < 0\n zenSN = NUM_ZEN - 1;\n end\n radSN = floor(2 * NUM_RAD * rho / rmax);\n h = floor(radSN/2);\n if radSN > 2 * NUM_RAD - 1\n h = NUM_RAD - 1;\n radSN = 2 * NUM_RAD - 1;\n end\n\n if h >= 5\n if zenSN == 0 | zenSN == NUM_ZEN-1\n sumBrite(:, zenSN + 1, h + 1) = sumBrite(:, zenSN + 1, h + 1) + mval;\n nCount(:, zenSN + 1, h + 1) = nCount(:,zenSN + 1, h + 1) + 1;\n else\n sumBrite(aziSN + 1,zenSN + 1, h + 1) = sumBrite(aziSN + 1, zenSN + 1, h + 1) + mval;\n nCount(aziSN + 1, zenSN + 1, h + 1) = nCount(aziSN + 1,zenSN + 1, h + 1) + 1;\n end\n end\n if radSN >= 5\n radius(radSN + 1) = radius(radSN + 1) + mval;\n radCount(radSN + 1) = radCount(radSN + 1) + 1;\n end\n end\n end\n end\n end\n end\n end\nend\n\n%linear regression\nfor aziSN = 1:NUM_AZI\n for zenSN = 1: NUM_ZEN\n sumx = 0;\n sumy = 0;\n sumx2 = 0;\n sumxy = 0;\n sumn = 0;\n for range = 6:NUM_RAD\n if nCount(aziSN, zenSN, range) > 0\n yval = sumBrite(aziSN, zenSN, range)/nCount(aziSN, zenSN, range);\n xval = (range -1) * rmax / NUM_RAD;\n sumx = sumx + xval;\n sumy = sumy + yval;\n sumx2 = sumx2 + xval * xval;\n sumxy = sumxy + xval * yval;\n sumn = sumn + 1;\n end\n end\n slope(aziSN, zenSN) = (sumn * sumxy - sumx * sumy) / (sumn * sumx2 - sumx * sumx);\n ics(aziSN, zenSN) = (sumy - slope(aziSN, zenSN) * sumx) / sumn;\n fds(aziSN, zenSN) = (11 + slope(aziSN, zenSN))/2;\n end\nend\n\n%compute average slope over all directions and radius\nsumn = 0;\nfor radSN = 6:(2 * NUM_RAD)\n if radCount(radSN) > 0\n sumn = sumn + 1;\n yval(sumn) = radius(radSN) / radCount(radSN);\n tempr(sumn) = (radSN -1) * rmax / (2 * NUM_RAD);\n end\nend\np = polyfit(tempr,yval,1);\naverFD =(11+ p(1))/2; % Overall average fractal dimension\naverIC = p(2); % Overall average intercept\nfitln = polyval(p,tempr);\nfigure; plot(tempr,yval,tempr,fitln,'r-');\ntitle('Log Log plot of PSD. vs Freq.');\nylabel('Log PSD');\nxlabel('Log Frequency');\nlegend('data','LSE fit line');\n\n% draw hedgehog plot of fractal dimension and intercept\n% I personally prefer to call these 3D visulization plots of fractal\n% dimension and intercept as 'hedgehog' plot\nfd = [fds; fds(1,:)];\nfd = [fd, fd(:,1)];\naziSN = (1:NUM_AZI + 1)';\nzenSN = 1:(NUM_ZEN + 1);\n[ph th] = meshgrid(pi/2 - ((zenSN - 1) * pi / NUM_ZEN) , 2 * pi / NUM_AZI / 2 + (aziSN - 1) * 2 * pi / NUM_AZI);\n[x,y,z] = sph2cart(th,ph, fd);\nfigure, surf(x,y,z,fd); colorbar\ntitle('Hedgehog plot of fractal dimension');\n \nic = [ics; ics(1,:)];\nic = abs([ic, ic(:,1)]); % ic stores the absolue value of ics \naziSN = (1:NUM_AZI + 1)';\nzenSN = 1:(NUM_ZEN + 1);\n[ph th] = meshgrid(pi/2 - ((zenSN - 1) * pi / NUM_ZEN) , 2 * pi / NUM_AZI / 2 + (aziSN - 1) * 2 * pi / NUM_AZI);\n[x,y,z] = sph2cart(th,ph, ic);\nfigure, surf(x,y,z, ic); colorbar\ntitle('Hedgehog plot of intercept');\n\ndisp(['Elapsed time: ' num2str(toc)]);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6964-calculation-of-fractal-dimension-of-a-3d-volume-using-fft/fdvolfft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7182094145313408}} {"text": "% Calculate the eigenvalues of massive 3x3 real symmetric matrices.\n% Computation is based on matrix operation and GPU computation is \n% supported.\n% Syntax:\n% [eigenvalue1,eigenvalue2,eigenvalue3] = eigenvaluefield33( a11, a12, a13, a22, a23, a33)\n% a11, a12, a13, a22, a23 and a33 specify the symmetric 3x3 real symmetric\n% matrices as:\n% a11 a12 a13\n% [ a12 a22 a13 ]\n% a13 a23 a33\n% These six inputs must have the same size. They can be 2D, 3D or any\n% dimension. The outputs eigenvalue1, eigenvalue2 and eigenvalue3 will\n% follow the size and dimension of these inputs. Owing to the use of \n% trigonometric functions, the inputs must be double to maintain the \n% accuracy.\n%\n% eigenvalue1, eigenvalue2 and eigenvalue3 are the unordered resultant \n% eigenvalues. They are solved using the cubic equation solver, see\n% http://en.wikipedia.org/wiki/Eigenvalue_algorithm\n%\n% The peak memory consumption of the method is about 1.5 times of the total \n% of all inputs, in addition to the original inputs. GPU computation is \n% used automatically if all inputs are matlab GPU arrays. \n%\n% Author: Max W.K. Law\n% Email: max.w.k.law@gmail.com\n% Page: http://www.cse.ust.hk/~maxlawwk/\n%\nfunction [b,j,d] = eigenvaluefield33( a11, a12, a13, a22, a23, a33)\n% multiprocess;\n% b=a11*0;\n% j=a11*0;\n% d=a11*0;\n% parfor i=1:numel(a11)\n% [~,l]=eig([a11(i) a12(i) a13(i); a12(i) a22(i) a23(i); a13(i) a23(i) a33(i)]);\n% b(i)=l(1,1);\n% j(i)=l(2,2);\n% d(i)=l(3,3);\n% end\n% return;\n\n ep=1e-50;\n b=double(a11)+ep;\n d=double(a22)+ep;\n j=double(a33)+ep;\n\n c=-(double(a12).^2 + double(a13).^2 + double(a23).^2 - b.*d - d.*j - j.*b);\n d=-(b.*d.*j - double(a23).^2.*b - double(a12).^2.*j - double(a13).^2.*d + 2*double(a13).*double(a12).*double(a23));\n\n b=-double(a11) - double(a22) - double(a33) - ep - ep -ep;\n\n \n d = d + ((2*b.^3) - (9*b.*c))/27;\n\n% c=c-(b.^2)/3;\n% c=c.^3;\n% c=c/27;\n% c=(d.^2/4-(d.^2/4 + c));\n \n \n%%%% c=(d.^2/4-(d.^2/4 + ((3 * c - (b.^2))/3).^3/27));\n c=(b.^2)/3 - c;\n c=c.^3;\n c=c/27;\n c=max(c,0);\n c=realsqrt(c);\n \n \n j=c.^(1/3);\n c=c+(c==0);\n d=-d/2./c;\n d=min(d, 1);\n d=max(d, -1);\n \n d=real(acos(d)/3); \n% d=real(acos(-(d/2./c))/3);\n c=j.*cos(d);\n d=j.*sqrt(3).*sin(d);\n b=-b/3;\n \n \n j = single(-c-d+b);\n d = single(-c+d+b);\n\n b = single(2*c+b);\n\nend\n\n\n% Old version\n% ep=1e-20;\n% b=double(a11)+ep;\n% d=double(a22)+ep;\n% j=double(a33)+ep;\n% \n% c=-double(double(a12).^2 + double(a13).^2 + double(a23).^2 - b.*d - d.*j - j.*b);\n% d=-(b.*d.*j - double(a23).^2.*b - double(a12).^2.*j - double(a13).^2.*d + 2*double(a13).*double(a12).*double(a23));\n% \n% b=-double(a11) - double(a22) - double(a33) - ep - ep -ep;\n% \n% \n% d = ((2*b.^3) - (9*b.*c) + (27*d))/27;\n% %clear d;\n% %x = (((3*c) - (b.^2))/3);\n% \n% %c = (d^2/4 + (((3*c) - (b.^2))/3).^3/27);\n% \n% %clear x;\n% c=(d.^2/4-(d.^2/4 + (((3*c) - (b.^2))/3).^3/27));\n% c(c<0)=0;\n% c=realsqrt(c);\n% %clear c; \n% \n% \n% j=c.^(1/3);\n% d=real(acos(-(d/2./c))/3);\n% c=j.*cos(d);\n% d=j.*sqrt(3).*sin(d);\n% b=-b/3;\n% \n% \n% j = single(-c-d+b);\n% d = single(-c+d+b);\n% \n% b = single(2*c+b);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/40677-fast-eigenvalue-computation-of-massive-3-by-3-real-symmetric-matrices/eigenvaluefield33.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7182094064313566}} {"text": "function d=v_distchar(ar1,ar2,mode)\n%V_DISTCHAR calculates the cosh spectral distance between AR coefficients D=(AR1,AR2,MODE)\n%\n% Inputs: AR1,AR2 AR coefficient sets to be compared. Each row contains a set of coefficients.\n% AR1 and AR2 must have the same number of columns.\n%\n% MODE Character string selecting the following options:\n% 'x' Calculate the full distance matrix from every row of AR1 to every row of AR2\n% 'd' Calculate only the distance between corresponding rows of AR1 and AR2\n% The default is 'd' if AR1 and AR2 have the same number of rows otherwise 'x'.\n% \n% Output: D If MODE='d' then D is a column vector with the same number of rows as the shorter of AR1 and AR2.\n% If MODE='x' then D is a matrix with the same number of rows as AR1 and the same number of columns as AR2'.\n%\n% The COSH spectral distance is the average over +ve and -ve frequency of \n%\n% cosh(log(p1/p2))-1 = (p1-p2)^2/(2p1*p2) = (p1/p2 + p2/p1)/2 - 1\n%\n% Where p1 and p2 are the power spectra corresponding to the AR coefficient sets AR1 and AR2.\n% The COSH distance is a symmetrical version of the Itakura-Saito distance: v_distchar(x,y)=(v_distisar(x,y)+v_distisar(y,x))/2\n\n% Since the power spectrum is the fourier transform of the autocorrelation, we can calculate\n% the average value of p1/p2 by taking the 0'th order term of the convolution of the autocorrelation\n% functions associated with p1 and 1/p2. Since 1/p2 corresponds to an FIR filter, this convolution is\n% a finite sum even though the autocorrelation function of p1 is infinite in extent.\n\n% The Cosh distance can also be calculated directly from the power spectra; providing np is large\n% enough, the values of d0 and d1 in the following will be very similar:\n%\n% np=255; d0=v_distchar(ar1,ar2); d1=v_distchpf(v_lpcar2pf(ar1,np),v_lpcar2pf(ar2,np))\n%\n\n% Ref: A.H.Gray Jr and J.D.Markel, \"Distance measures for speech processing\", IEEE ASSP-24(5): 380-391, Oct 1976\n% L. Rabiner abd B-H Juang, \"Fundamentals of Speech Recognition\", Section 4.5, Prentice-Hall 1993, ISBN 0-13-015157-2\n\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: v_distchar.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[nf1,p1]=size(ar1);\nnf2=size(ar2,1);\np2=p1+1;\nm1=zeros(nf1,2*p1);\nm2=zeros(nf2,2*p1);\nm1(:,1:p1)=v_lpcar2rr(ar1);\nm1(:,p2:end)=v_lpcar2ra(ar1);\nm1(:,1)=m1(:,1)*0.5;\nm1(:,p2)=m1(:,p1+1)*0.5;\nm2(:,p2:end)=v_lpcar2rr(ar2);\nm2(:,1:p1)=v_lpcar2ra(ar2);\n\nif nargin<3 | isempty(mode) mode='0'; end\nif any(mode=='d') | (mode~='x' & nf1==nf2)\n nx=min(nf1,nf2);\n d=sum(m1(1:nx,:).*m2(1:nx,:),2)-1;\nelse\n d=m1*m2'-1;\nend\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_distchar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587905460027, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7181768435050345}} {"text": "function X = lyapunov_symmetric_eig(V, lambda, C, tol)\n% Solves AX + XA = C when A = A', as a pseudo-inverse, given eig(A).\n%\n% function X = lyapunov_symmetric_eig(V, lambda, C)\n% function X = lyapunov_symmetric_eig(V, lambda, C, tol)\n%\n% Same as lyapunov_symmetric(A, C, [tol]), where A is symmetric, its\n% eigenvalue decomposition [V, lambda] = eig(A, 'vector') is provided as\n% input directly, and C is a single matrix of the same size as A.\n%\n% See also: lyapunov_symmetric sylvester lyap sylvester_nocheck\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Aug. 31, 2018.\n% Contributors: \n% Change log: \n\n % AX + XA = C is equivalent to DY + YD = M with\n % Y = V'XV, M = V'CV and D = diag(lambda).\n M = V'*C*V;\n \n % W(i, j) = lambda(i) + lambda(j)\n W = bsxfun(@plus, lambda, lambda');\n \n % Normally, the solution Y is simply this:\n Y = M ./ W;\n \n % But this may involve divisions by (almost) 0 in certain places.\n % Thus, we go for a pseudo-inverse.\n absW = abs(W);\n if ~exist('tol', 'var') || isempty(tol)\n tol = numel(C)*eps(max(absW(:))); % similar to pinv tolerance\n end\n Y(absW <= tol) = 0;\n \n % Undo the change of variable\n X = V*Y*V';\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/lyapunov_symmetric_eig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.8080672135527631, "lm_q1q2_score": 0.718176837016099}} {"text": "% compare geodesic with euclidean distance inside a 2D shape\n\n\nrep = 'images/';\nname = 'bird';\nname = 'giraffe';\nname = 'camel';\nname = 'chicken';\n\ntest = 'meangeodesic';\ntest = 'eccentricity';\n\n% put s=-1 for Linf eccentricity\ns = -1;\n\nrepsrc = 'data/';\n\nrep = 'results/geodesic-vs-euclidean/';\nif ~exist(rep)\n mkdir(rep);\nend\n\nn = 256;\nM = rescale( load_image([repsrc name],n), 0,1 );\nM = double(M>0.5);\n\n% make sure pixels on the boundary are black\nif M(1)==1\n M = 1-M;\nend\n\n% compare the geodesic ditance to the euclidean distance\nclf;\nimagesc(M); axis image; axis off;\n[y,x] = ginput(1);\nstart_points = round([x y]');\nW = ones(n);\nL = zeros(n)-Inf; L(M==1) = +Inf;\noptions.constraint_map = [];\n[D0,S,Q] = perform_fast_marching(W, start_points, options);\noptions.constraint_map = L;\n[D1,S,Q] = perform_fast_marching(W, start_points, options);\nD0(M==0) = Inf; D1(M==0) = Inf;\n\n% compute a nice color image\nD0a = convert_distance_color(D0);\nD1a = convert_distance_color(D1);\n\n% place a dot at the center\n[Y,X] = meshgrid(1:n,1:n);\nr = 0.02*n;\nI = find( (X-x).^2 + (Y-y).^2 <= r^2 );\nfor i=1:3\n A = D0a(:,:,i); A(I) = i==1;\n D0a(:,:,i) = A;\n A = D1a(:,:,i); A(I) = i==1;\n D1a(:,:,i) = A;\nend\n\n\n% display\nclf;\nsubplot(1,2,1)\nimagesc(D0a); axis image; axis off; title('Euclidean');\nsubplot(1,2,2)\nimagesc(D1a); axis image; axis off; title('Geodesic');\n\nwarning off;\nimwrite(rescale(D0a), [rep name '-euclidean.png' ], 'png');\nimwrite(rescale(D1a), [rep name '-geodesic.png' ], 'png');\nwarning on;\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/external/toolbox_fast_marching/tests/test_geodesic_vs_euclidean.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.718176837016099}} {"text": "function M = fit_metric(fDir)\n\n% fit_metric - fit a 2D Riemannian metric\n%\n% M = fit_metric(fDir);\n%\n% fDir(h) gives the value of the metric in direction h (a 1x2 vector). \n% M is a 2x2 symmetric matrix, that fit the measurements, i.e. such that\n% fDir(h)^2 ~ h*M*h'\n%\n% Copyright (c) 2014 Gabriel Peyre\n\n\n\na = fDir([1 0])^2;\nb = fDir([0 1])^2;\nc = (fDir([1 1])^2-a-b)/2;\nM = [a c; c b];\n\n[U,S] = eig(M); S = diag(S);\nif min(S)<0\n warning('Non positive matrix, clamping singular values');\n M = U*diag(max(S,0))*U';\nend", "meta": {"author": "gpeyre", "repo": "2015-SIGGRAPH-convolutional-ot", "sha": "484b83c5ee396f3d998f67ed35652249b5e29e81", "save_path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot", "path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot/2015-SIGGRAPH-convolutional-ot-484b83c5ee396f3d998f67ed35652249b5e29e81/code/colors_functions/fit_metric.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7181681623739314}} {"text": "function [y,N,algo] = erf_(x,N,algo)\n% error function for a real or complex array\n%\n% Note: The Fresnel integrals C(x) and S(x) can be computed for real x as\n% C(x)+1i*S(x) == ((1+1i)/2)*erf_((sqrt(pi)*(1-1i)/2)*x)\n% (See demo example at the end of this file.)\n%\n% syntax:\n% y = erf_(x);\n% [y,N,algo] = erf_(x,N,algo);\n%\n% inputs:\n%\n% x: numeric array, can be complex\n%\n% optional inputs:\n%\n% N: positive integer - scalar or size-matched to x, or [] (optional; unspecified or\n% [] defaults to 1000)\n% maximum number of terms to use in series or continued-fraction expansion. N can be\n% specified independently for each x element\n%\n% algo: integers 1, 2, or 3 - scalar or size-matched to x, or [] (optional; default\n% is [])\n% Set algo = 1 to force use of Taylor series expansion (good for small arguments).\n% Set algo = 2 to force use of erf continued-fraction expansion (good for arguments\n% with large real part).\n% Set algo = 3 to force use of Dawson's-function continued-fraction expansion (good\n% for arguments with large imaginary part).\n% Leave algo unspecified or [] to make the choice automatically.\n% algo can be specified independently for each x element.\n%\n% outputs:\n%\n% y: numeric array, size-matched to x\n% y = 2/sqrt(pi) * integral from 0 to x of exp(-t^2) dt.\n%\n% optional outputs:\n%\n% N: integer array, size-matched to x\n% number of terms used in series or continued-fraction expansion for each x element\n%\n% algo: integer array of values 1, 2, or 3; size-matched to x\n% This indicates which algorithm was used for each x. 1: Taylor series, 2: erf\n% continued fraction, 3: Dawson's-function continued fraction\n%\n%\n% Author: Kenneth C. Johnson, kjinnovation@earthlink.net, kjinnovation.com\n% Version: November 1, 2011\n%\n%\n% BSD Copyright notice:\n%\n% Copyright 2011 by Kenneth C. Johnson (kjinnovation.com)\n%\n% Redistribution and use in source and binary forms, with or without modification, are\n% permitted provided that this entire copyright notice is duplicated in all such copies.\n%\n% This software is provided \"as is\" and without any express or implied warranties,\n% including, without limitation, the implied warranties of merchantibility and fitness\n% for any particular purpose.\n%\n\nif nargin<3\n algo = [];\n if nargin<2\n N = [];\n end\nend\n\nsize_ = size(x);\n\nif isempty(N)\n N = 1000;\nend\nif isscalar(N)\n N = repmat(N,size_);\nelseif ~isequal(size(N),size_)\n error('erf_:validation','Size mismatch between args N and x.')\nend\n\nif isempty(algo)\n % Algorithm selection for erf_(x):\n % Apply algo 1 (Taylor series) for |real(x)|<=1, |imag(x)|<=6.\n % Apply algo 3 (Dawson's-function continued fraction) for |real(x)|<=1, |imag(x)|>6.\n % Apply algo 2 (erf continued fraction) for |real(x)|>1.\n % See test code at the bottom of this file for checking algorithm continuity across\n % algo boundaries.\n algo = ones(size(x));\n algo(abs(imag(x))>6) = 3;\n algo(abs(real(x))>1) = 2;\nelse\n if isscalar(algo)\n algo = repmat(algo,size_);\n elseif ~isequal(size(algo),size_)\n error('erf_:validation','Size mismatch between args algo and x.')\n end\n if ~all(algo==1 | algo==2 | algo==3)\n error('erf_:validation','Invalid arg: algo values must be 1, 2, or 3.')\n end\nend\n\nx = x(:);\nN = N(:);\nalgo = algo(:);\ny = zeros(size(x));\nsgn = ones(size(x));\nsgn(real(x)<0) = -1;\nx = sgn.*x; % Only apply algorithm with abs(angle(x))<=pi/2; use erf(x)==-erf(-x).\n\nwarn = false; % for possible non-convergence\n\ni = find(algo==1);\nif ~isempty(i)\n % Apply series expansion to x(i) (see http://mathworld.wolfram.com/Erf.html, Eq 6).\n n = 0; % summation index\n Ni = N(i);\n term = x(i);\n xx = term.*term;\n term = (2/sqrt(pi))*term; % n-th summation term\n psum = term; % partial sum up to n-th term\n prec = abs(psum)*eps; % estimated precision of partial sum\n while true\n n = n+1;\n term = (-(2*n-1)/(n*(2*n+1)))*term.*xx;\n psum = psum+term;\n test = (abs(term)<=prec);\n if any(test)\n y(i(test)) = psum(test);\n N(i(test)) = n;\n i(test) = [];\n if isempty(i)\n break\n end\n Ni(test) = [];\n term(test) = [];\n psum(test) = [];\n prec(test) = [];\n xx(test) = [];\n end\n test = (n==Ni);\n if any(test)\n warn = true;\n y(i(test)) = psum(test);\n N(i(test)) = n;\n i(test) = [];\n if isempty(i)\n break\n end\n Ni(test) = [];\n term(test) = [];\n psum(test) = [];\n prec(test) = [];\n xx(test) = [];\n end\n prec = max(prec,abs(psum)*eps);\n end\nend\n\ni = find(algo==2);\nif ~isempty(i)\n % Apply erf continued fraction to x(i). Use Eq 6.9.4 (second form) in Numerical\n % Recipes in C++, 2nd Ed. (2002). Apply Lentz's method (Sec. 5.2) to top-level\n % denominator in Eq 6.9.4.\n n = 0;\n Ni = N(i);\n b = x(i);\n b = 2*b.*b+1;\n f = b;\n C = f;\n D = zeros(size(i));\n while true\n n = n+1;\n a = -(2*n-1)*(2*n);\n b = b+4;\n D = b+a*D;\n D(D==0) = eps^2;\n D = 1./D;\n C = b+a./C;\n C(C==0) = eps^2;\n Delta = C.*D;\n f = f.*Delta;\n test = (abs(Delta-1)<=eps);\n if any(test)\n y(i(test)) = f(test);\n N(i(test)) = n;\n i(test) = [];\n if isempty(i)\n break\n end\n Ni(test) = [];\n b(test) = [];\n f(test) = [];\n C(test) = [];\n D(test) = [];\n end\n test = (n==Ni);\n if any(test)\n warn = true;\n y(i(test)) = f(test);\n N(i(test)) = n;\n i(test) = [];\n if isempty(i)\n break\n end\n Ni(test) = [];\n b(test) = [];\n f(test) = [];\n C(test) = [];\n D(test) = [];\n end\n end\n i = find(algo==2);\n y(i) = 1-exp(-x(i).^2).*((2/sqrt(pi))*x(i)./y(i));\nend\n\ni = find(algo==3);\nif ~isempty(i)\n % Apply Dawson's-function (F) continued fraction to x(i). See\n % http://mathworld.wolfram.com/DawsonsIntegral.html, Eq 14.\n % erf(x) = i*erfi(-i*x) = (2i/sqrt(pi))*exp(-x^2)*F(-i*x)\n % Apply Lentz's method to top-level denominator in Eq 14.\n n = 0;\n Ni = N(i);\n xx = x(i);\n xx = -xx.*xx; % (-1i*x)^2\n b = 1+2*xx;\n f = b;\n C = f;\n D = zeros(size(i));\n while true\n n = n+1;\n a = -4*n*xx;\n b = 2+b;\n D = b+a.*D;\n D(D==0) = eps^2;\n D = 1./D;\n C = b+a./C;\n C(C==0) = eps^2;\n Delta = C.*D;\n f = f.*Delta;\n test = (abs(Delta-1)<=eps);\n if any(test)\n y(i(test)) = f(test);\n N(i(test)) = n;\n i(test) = [];\n if isempty(i)\n break\n end\n Ni(test) = [];\n xx(test) = [];\n b(test) = [];\n f(test) = [];\n C(test) = [];\n D(test) = [];\n end\n test = (n==Ni);\n if any(test)\n warn = true;\n y(i(test)) = f(test);\n N(i(test)) = n;\n i(test) = [];\n if isempty(i)\n break\n end\n Ni(test) = [];\n xx(test) = [];\n b(test) = [];\n f(test) = [];\n C(test) = [];\n D(test) = [];\n end\n end\n i = find(algo==3);\n % Current state: y(i)==(-1i*x(i))./F(-1i*x(i)). Convert F(-1i*x) to erfi(x).\n y(i) = (2/sqrt(pi))*exp(-x(i).^2).*x(i)./y(i);\nend\n\ny = sgn.*y;\ny = reshape(y,size_);\nN = reshape(N,size_);\nalgo = reshape(algo,size_);\n\nif warn\n warning('erf_:convergence','Possible non-convergence in erf_');\nend\n\nreturn\n\n%--------------------------------------------------------------------------------------\n% Demo example: Cornu Spiral (http://en.wikipedia.org/wiki/Cornu_spiral)\nFresnelCS = @(x) ((1+1i)/2)*erf_((sqrt(pi)*(1-1i)/2)*x); % Fresnel integrals\nCS = FresnelCS(-10:.001:10);\nfigure, plot(real(CS),imag(CS)), axis equal\n\n\n%--------------------------------------------------------------------------------------\n% Test code for checking algorithm discontinuity across algo boundaries:\n\n% boundary between algo 1 and algo 2:\nclose all\nx = (0:.02:3).'; y = [0 6]; z = repmat(x,size(y))+1i*repmat(y,size(x));\n[e,N] = erf_(z,[],1); [e_,N_] = erf_(z,[],2); d = log10(abs(2*(e-e_)./(e+e_)));\nfigure, hold on, plot(x,N), plot([1 1],ylim,':k')\nxlabel('x'), ylabel('N, algo 1'), legend('y = 0','y = 6')\nfigure, hold on, plot(x,N_), plot([1 1],ylim,':k')\nxlabel('x'), ylabel('N, algo 2'), legend('y = 0','y = 6')\nfigure, hold on, plot(x,d), plot([1 1],ylim,':k')\nxlabel('x'), ylabel('log10(algo 1-2 diff)'), legend('y = 0','y = 6')\ntitle('erf\\_(x+1i*y), algo 1 vs 2 (boundary at |x|==1, |y|<=6)')\n\n% boundary between algo 3 and algo 2:\nclose all\nx = (0:.02:3).'; y = [6 10]; z = repmat(x,size(y))+1i*repmat(y,size(x));\n[e,N] = erf_(z,[],3); [e_,N_] = erf_(z,[],2); d = log10(abs(2*(e-e_)./(e+e_)));\nfigure, hold on, plot(x,N), plot([1 1],ylim,':k')\nxlabel('x'), ylabel('N, algo 3'), legend('y = 6','y = 10')\nfigure, hold on, plot(x,N_), plot([1 1],ylim,':k')\nxlabel('x'), ylabel('N, algo 2'), legend('y = 6','y = 10')\nfigure, hold on, plot(x,d), plot([1 1],ylim,':k')\nxlabel('x'), ylabel('log10(algo 3-2 diff)'), legend('y = 6','y = 10')\ntitle('erf\\_(x+1i*y), algo 3 vs 2 (boundary at |x|==1, |y|>6)')\n\n% boundary between algo 1 and algo 3:\nclose all\ny = (0:.02:10).'; x = [0 1]; z = repmat(x,size(y))+1i*repmat(y,size(x));\n[e,N] = erf_(z,[],1); [e_,N_] = erf_(z,[],3); d = log10(abs(2*(e-e_)./(e+e_)));\nfigure, hold on, plot(y,N), plot([6 6],ylim,':k')\nxlabel('y'), ylabel('N, algo 1'), legend('x = 0','x = 1')\nfigure, hold on, plot(y,N_), plot([6 6],ylim,':k')\nxlabel('y'), ylabel('N, algo 3'), legend('x = 0','x = 1')\nfigure, hold on, plot(y,d), plot([6 6],ylim,':k')\nxlabel('y'), ylabel('log10(algo 1-3 diff)'), legend('x = 0','x = 1')\ntitle('erf\\_(x+1i*y), algo 1 vs 3 (boundary at |x|<=1, |y|==6)')\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/33577-complex-erf-error-function-fresnel-integrals/erf_.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.7180543885629259}} {"text": "function [ n_data, n, p ] = pi_values ( n_data )\n\n%*****************************************************************************80\n%\n%% PI_VALUES returns values of the Pi function.\n%\n% Discussion:\n%\n% Pi[n] is the number of primes less than or equal to n.\n%\n% In Mathematica, the function can be evaluated by:\n%\n% PrimePi[n]\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 argument.\n%\n% Output, integer P, the value of the function.\n%\n n_max = 17;\n\n n_vec = [ ...\n 10, ...\n 20, ...\n 30, ...\n 40, ...\n 50, ...\n 60, ...\n 70, ...\n 80, ...\n 90, ...\n 100, ...\n 1000, ...\n 10000, ...\n 100000, ...\n 1000000, ...\n 10000000, ...\n 100000000, ...\n 1000000000 ];\n\n p_vec = [ ...\n 4, ...\n 8, ...\n 10, ...\n 12, ...\n 15, ...\n 17, ...\n 19, ...\n 22, ...\n 24, ...\n 25, ...\n 168, ...\n 1229, ...\n 9592, ...\n 78498, ...\n 664579, ...\n 5761455, ...\n 50847534 ];\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 p = 0;\n else\n n = n_vec(n_data);\n p = p_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/pi_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7180519287643568}} {"text": "\n% Copyright (C) 1993-2014, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\n%%begin\n\n% In the field of robotics there are many possible ways of representing \n% orientations of which the most common are: \n% - orthonormal rotation matrices (3x3),\n% - three angles (1x3), and\n% - quaternions.\n\n% A rotation of pi/2 about the x-axis can be represented as an orthonormal rotation\n% matrix\n\nR = rotx(pi/2)\n% which we can see is a 3x3 matrix.\n\n% Such a matrix has the property that it's columns (and rows) are sets of orthogonal\n% unit vectors. The determinant of such a matrix is always 1\n\ndet(R)\n\n% Let's create a more complex rotation\n\nR = rotx(30, 'deg') * roty(50, 'deg') * rotz(10, 'deg')\n% where this time we have specified the rotation angle in degrees.\n\n% Any rotation can be expressed in terms of a single rotation about some axis\n% in space\n\n[theta,vec] = tr2angvec(R)\n% where theta is the angle (in radians) and vec is unit vector representing the\n% direction of the rotation axis.\n\n% Commonly rotations are represented by Euler angles\n\neul = tr2eul(R)\n% which are three angles such that R = rotz(a)*roty(b)*rotz(c), ie. the rotations\n% required about the Z, then then the Y, then the Z axis.\n\n% Rotations are also commonly represented by roll-pitch-yaw angles\n\nrpy = tr2rpy(R)\n% which are three angles such that R = rotx(r)*roty(p)*rotz(y), ie. the rotations\n% required about the X, then then the Y, then the Z axis.\n\n% We can investigate the effects of rotations about different axes\n% using this GUI based demonstration. The menu buttons allow the rotation\n% axes to be varied\n% *** close the window when you are done.\ntripleangle('rpy', 'wait')\n\n% The final useful form is the quaternion which comprises 4 numbers. We can create\n% a quaternion from an orthonormal matrix\n\nq = Quaternion(R)\n% where we can see that it comprises a scalar part and a vector part. To convert back\n\nq.R\n% which is the same of the value of R we determined above.\n\n% Quaternions are a class and the orientations they represent can be compounded, just\n% as we do with rotation matrices by multiplication.\n\n% First we create two quaternions\n\nq1 = Quaternion( rotx(pi/2) )\nq2 = Quaternion( roty(pi/2) )\n\n% then the rotation of q1 followed by q2 is simply\n\nq1 * q2\n\n% We can also take the inverse of a Quaternion\n\nq1 * inv(q1)\n% which results in a null rotation (zero vector part)\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/demos/rotation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964035, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7179409903907955}} {"text": "function value = p14_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P14_F evaluates the integrand for problem 14.\n%\n% Dimension:\n%\n% DIM_NUM arbitrary.\n%\n% Region:\n%\n% 0 <= X(1:DIM_NUM) <= 1\n%\n% Integrand:\n%\n% sum ( 1 <= i <= dim_num ) (-1)**i * product ( 1 <= j <= i ) x(j)\n%\n% Exact Integral:\n%\n% -1/3 ( 1 - (-1/2)**DIM_NUM )\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% Paul Bratley, Bennett Fox, Harald Niederreiter,\n% Implementation and Tests of Low-Discrepancy Sequences,\n% ACM Transactions on Modeling and Computer Simulation,\n% Volume 2, Number 3, July 1992, pages 195-213.\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 value(1:point_num) = 0.0;\n\n for point = 1 : point_num\n\n factor = 1.0;\n\n for dim = 1 : dim_num\n\n factor = - factor * x(dim,point);\n\n value(point) = value(point) + factor;\n\n end\n\n end\n\n p14_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/p14_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7179409815030822}} {"text": "function triangulation_order6_print ( node_num, triangle_num, node_xy, ...\n triangle_node, triangle_neighbor )\n\n%*****************************************************************************80\n%\n%% TRIANGULATION_ORDER6_PRINT prints out information defining a Delaunay triangulation.\n%\n% Discussion:\n%\n% Triangulations created by R8TRIS2 include extra information encoded\n% in the negative values of TRIANGLE_NEIGHBOR.\n%\n% Because some of the nodes counted in NODE_NUM may not actually be\n% used in the triangulation, I needed to compute the true number\n% of vertices. I added this calculation on 13 October 2001.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 June 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NODE_NUM, the number of nodes.\n%\n% Input, integer TRIANGLE_NUM, the number of triangles.\n%\n% Input, real NODE_XY(2,NODE_NUM), the point coordinates.\n%\n% Input, integer TRIANGLE_NODE(6,TRIANGLE_NUM), the nodes that make up the triangles.\n%\n% Input, integer TRIANGLE_NEIGHBOR(3,TRIANGLE_NUM), the triangle neighbors on each side.\n% If there is no triangle neighbor on a particular side, the value of\n% TRIANGLE_NEIGHBOR should be negative. If the triangulation data was created by\n% R8TRIS2, then there is more information encoded in the negative values.\n%\n dim_num = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGULATION_ORDER6_PRINT\\n' );\n fprintf ( 1, ' Information defining a triangulation.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of nodes is %d\\n', node_num );\n\n r8mat_transpose_print ( dim_num, node_num, node_xy, ' Nodes:' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of triangles is %d\\n', triangle_num );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sets of six points are used as vertices of\\n' );\n fprintf ( 1, ' the triangles. For each triangle, the vertices\\n' );\n fprintf ( 1, ' are listed in counterclockwise order, followed by\\n' );\n fprintf ( 1, ' the midside nodes.\\n' );\n\n i4mat_transpose_print ( 6, triangle_num, triangle_node, ' Triangle nodes:' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' On each side of a given triangle, there is either\\n' );\n fprintf ( 1, ' another triangle, or a piece of the convex hull.\\n' );\n fprintf ( 1, ' For each triangle, we list the indices of the three\\n' );\n fprintf ( 1, ' neighbors, or (if negative) the codes of the\\n' );\n fprintf ( 1, ' segments of the convex hull.\\n' );\n\n i4mat_transpose_print ( 3, triangle_num, triangle_neighbor, ...\n ' Triangle neighbors' );\n%\n% Determine the number of vertices. This is not the same as the\n% number of points!\n%\n vertex_list( 1: triangle_num) = ...\n triangle_node(1,1:triangle_num);\n vertex_list( triangle_num+1:2*triangle_num) = ...\n triangle_node(2,1:triangle_num);\n vertex_list(2*triangle_num+1:3*triangle_num) = ...\n triangle_node(3,1:triangle_num);\n\n vertex_list = i4vec_sort_heap_a ( 3*triangle_num, vertex_list );\n\n [ vertex_num, vertex_list ] = i4vec_sorted_unique ( 3*triangle_num, ...\n vertex_list );\n%\n% Determine the number of boundary points.\n%\n boundary_num = 2 * vertex_num - triangle_num - 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of boundary points is %d\\n', boundary_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The segments that make up the convex hull can be\\n' );\n fprintf ( 1, ' determined from the negative entries of the triangle\\n' );\n fprintf ( 1, ' neighbor list.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' # Tri Side N1 N2 N3\\n' );\n fprintf ( 1, '\\n' );\n\n skip = 0;\n\n k = 0;\n\n for i = 1 : triangle_num\n\n for j = 1 : 3\n\n if ( triangle_neighbor(j,i) < 0 )\n \n s = -triangle_neighbor(j,i);\n t = floor ( s / 3 );\n\n if ( t < 1 | triangle_num < t )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Sorry, this data does not use the R8TRIS2\\n' );\n fprintf ( 1, ' convention for convex hull segments.\\n' );\n skip = 1;\n break\n end\n\n s = mod ( s, 3 ) + 1;\n k = k + 1;\n n1 = triangle_node(s,t);\n n2 = triangle_node(s+3,t);\n n3 = triangle_node(i4_wrap(s+1,1,3),t);\n fprintf ( 1, ' %4d %4d %4d %4d %4d %4d\\n', k, t, s, n1, n2, n3 );\n end\n\n end\n\n if ( skip )\n break\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/triangulation/triangulation_order6_print.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7179409779368437}} {"text": "function c=melcepst(s,fs,w,nc,p,n,inc,fl,fh)\n%MELCEPST Calculate the mel cepstrum of a signal C=(S,FS,W,NC,P,N,INC,FL,FH)\n%\n%\n% Simple use: (1) c=melcepst(s,fs) % calculate mel cepstrum with 12 coefs, 256 sample frames\n%\t\t\t (2) c=melcepst(s,fs,'e0dD') % include log energy, 0th cepstral coef, delta and delta-delta coefs\n%\n% Inputs:\n% s\t speech signal\n% fs sample rate in Hz (default 11025)\n% w mode string (see below)\n% nc number of cepstral coefficients excluding 0'th coefficient [default 12]\n% p number of filters in filterbank [default: floor(3*log(fs)) = approx 2.1 per ocatave]\n% n length of frame in samples [default power of 2 < (0.03*fs)]\n% inc frame increment [default n/2]\n% fl low end of the lowest filter as a fraction of fs [default = 0]\n% fh high end of highest filter as a fraction of fs [default = 0.5]\n%\n%\t\tw any sensible combination of the following:\n%\n% 'R' rectangular window in time domain\n%\t\t\t\t'N'\t Hanning window in time domain\n%\t\t\t\t'M'\t Hamming window in time domain (default)\n%\n% 't' triangular shaped filters in mel domain (default)\n% 'n' hanning shaped filters in mel domain\n% 'm' hamming shaped filters in mel domain\n%\n%\t\t\t\t'p'\t filters act in the power domain\n%\t\t\t\t'a'\t filters act in the absolute magnitude domain (default)\n%\n% '0' include 0'th order cepstral coefficient\n%\t\t\t\t'E' include log energy\n%\t\t\t\t'd'\t include delta coefficients (dc/dt)\n%\t\t\t\t'D'\t include delta-delta coefficients (d^2c/dt^2)\n%\n% 'z' highest and lowest filters taper down to zero (default)\n% 'y' lowest filter remains at 1 down to 0 frequency and\n%\t\t\t \t highest filter remains at 1 up to nyquist freqency\n%\n%\t\t If 'ty' or 'ny' is specified, the total power in the fft is preserved.\n%\n% Outputs:\tc mel cepstrum output: one frame per row. Log energy, if requested, is the\n% first element of each row followed by the delta and then the delta-delta\n% coefficients.\n%\n\n% BUGS: (1) should have power limit as 1e-16 rather than 1e-6 (or possibly a better way of choosing this)\n% and put into VOICEBOX\n% (2) get rdct to change the data length (properly) instead of doing it explicitly (wrongly)\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: melcepst.m 3497 2013-09-26 16:10:51Z 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<2 fs=11025; end\nif nargin<3 w='M'; end\nif nargin<4 nc=12; end\nif nargin<5 p=floor(3*log(fs)); end\nif nargin<6 n=pow2(floor(log2(0.03*fs))); end\nif nargin<9\n fh=0.5; \n if nargin<8\n fl=0;\n if nargin<7\n inc=floor(n/2);\n end\n end\nend\n\nif isempty(w)\n w='M';\nend\nif any(w=='R')\n z=enframe(s,n,inc);\nelseif any (w=='N')\n z=enframe(s,hanning(n),inc);\nelse\n z=enframe(s,hamming(n),inc);\nend\nf=rfft(z.');\n[m,a,b]=melbankm(p,n,fs,fl,fh,w);\npw=f(a:b,:).*conj(f(a:b,:));\npth=max(pw(:))*1E-20;\nif any(w=='p')\n y=log(max(m*pw,pth));\nelse\n ath=sqrt(pth);\n y=log(max(m*abs(f(a:b,:)),ath));\nend\nc=rdct(y).';\nnf=size(c,1);\nnc=nc+1;\nif p>nc\n c(:,nc+1:end)=[];\nelseif p.\n\nncircle = npnt-2;\nndhk = 2*ncircle;\n\npnt = zeros(npnt, 3);\ndhk = zeros(ndhk, 3);\n\npnt(1:ncircle, 1) = cos(linspace(0, 2*pi, ncircle)');\t\t% bottom plane\npnt(1:ncircle, 2) = sin(linspace(0, 2*pi, ncircle)');\t\t% bottom plane\npnt(npnt-1, :) = [0 0 0];\t\t\t\t% bottom point\npnt(npnt , :) = [0 0 1];\t\t\t\t% top point\n\n% connect all points on the circle to the bottom point\ndhk(1:ncircle, 1) = npnt-1;\ndhk(1:ncircle, 2) = (1:ncircle)';\ndhk(1:ncircle, 3) = (2:(ncircle+1))';\ndhk( ncircle, 3) = 1;\n\n% connect all points on the circle to the top point\ndhk((ncircle+1):ndhk, 1) = npnt;\ndhk((ncircle+1):ndhk, 2) = dhk(1:ncircle, 3);\ndhk((ncircle+1):ndhk, 3) = dhk(1:ncircle, 2);\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/plotting/private/mesh_cone.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.798186784940666, "lm_q1q2_score": 0.717666794921702}} {"text": "function [u,v,t]=rotro2pl(r)\n%ROTRO2PL find the plane and rotation angle of a rotation matrix [u,v,t]=r\n% Inputs:\n%\n% R(n,n) Rotation matrix\n%\n% Outputs:\n%\n% U(n,1) and V(n,1) are orthonormal vectors defining a plane in n-dimensional space\n% T is the rotation angle in radians from U towards V with 0<=T<=pi. If T\n% is omitted it U and V will be separated by T instead of being orthogonal\n\n%\n% Copyright (C) Mike Brookes 2007\n% Version: $Id: rotro2pl.m,v 1.1 2007/11/24 14:38:29 dmb Exp $\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\nn=size(r,1);\n[q,e]=schur(r);\n[m,i]=max(abs(e(2:n+1:n^2)));\nz=e(i+1,i)<0; % =1 if negative\nuv=q(:,i+z:1-2*z:i+1-z);\nu=uv(:,1);\n% the following code selects unique values of u and v\n% v=uv(:,2);\n% f=u.*v; % maximize inner product of u.^2 and v.^2\n% g=(v+u).*(v-u);\n% t=atan2(sum(f.*g),sum(g.^2/4-f.^2))/4;\n% c=cos(t);\n% s=sin(t);\n% uv=uv*[c s; -s c];\n% a=sum(uv)<0;\n% uv=uv*[1-a(1)-a(2) a(2)-a(1); a(1)-a(2) 1-a(1)-a(2)];\n% u=uv(:,1);\nif nargout>2\n v=uv(:,2);\n t=atan2(abs(e(i+1,i)),e(i,i));\nelse\n [s,c]=atan2sc(abs(e(i+1,i)),e(i,i));\n v=uv*[c;s];\nend\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/rotro2pl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7176667927617021}} {"text": "classdef ZXH_CF9 < PROBLEM\n% \n% Constrained benchmark MOP proposed by Zhou, Xiang, and He\n\n%------------------------------- Reference --------------------------------\n% Y. Zhou, Y. Xiang, and X. He, Constrained multiobjective optimization:\n% Test problem construction and performance evaluations, IEEE Transactions\n% on Evolutionary Computation, 2021, 25(1): 172-186.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n properties\n k; % Number of constrained variables\n end\n\tmethods\n %% Default settings of the problem\n function Setting(obj)\n if isempty(obj.M); obj.M = 3; end\n if isempty(obj.D); obj.D = obj.M+10; end\n obj.lower = zeros(1,obj.D) + 1e-10;\n obj.upper = ones(1,obj.D) - 1e-10;\n obj.encoding = ones(1,obj.D);\n if obj.M <= 3\n obj.k = obj.M - 1;\n elseif obj.M > 3 && obj.M <= 8 \n obj.k = floor(obj.M/2); \n else\n obj.k = 3; \n end\n end\n %% Evaluate multiple solutions\n function Population = Evaluation(obj,varargin)\n PopDec = varargin{1};\n OptX = 0.2;\n [N,D] = size(PopDec);\n M = obj.M;\n % Step 1: Compute cumsum \n Sx = cumsum(PopDec(:,1:M).^2,2,'reverse'); \n % Step 2: Compute theta\n THETA = 2/pi*atan(sqrt(Sx(:,2:end))./PopDec(:,1:M-1));\n % Step 3: Calculate Ackley function\n h = 20 - 20 * exp(-0.2 * sqrt(sum((PopDec(:,M+1:end)-OptX).^2,2)/(D-M))) + exp (1) - exp(sum(cos(2 * pi .*(PopDec(:,M+1:end)-OptX)),2)/(D-M));\n % Step 4: Compute T_\n T = (1 - Sx(:,1)).^2 + h;\n % Step 5: Objectives (mixed)\n A = 2; % number of segments\n G = 1-[ones(N,1) cumprod(sin(pi/2*THETA),2)] .* [cos(pi/2*THETA) ones(N,1)];\n G(:,1) = THETA(:,1) - cos(2*pi*A*THETA(:,1)+pi/2)/2/A/pi;\n PopObj = G .* repmat((1+T),1,M);\n % Step 6: Constraints\n PopCon(:,1) = Sx(:,1) + h - 1; \n for i = 1 : obj.k\n PopCon(:,i+1) = min(THETA(:,i)-1/4,3/4-THETA(:,i));\n end\n Population = SOLUTION(varargin{1},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 = UniformPoint(N,obj.M);\n R = 1 - R./repmat(sqrt(sum(R.^2,2)),1,obj.M);\n V = asin(sqrt(sum((1-R(:,2:end)).^2,2)));\n R(:,1) = (2/pi).*(V+1/8*sin(8*V));\n T = zeros(size(R));\n for i = obj.M-1 : -1 : 2\n T(:,i) = atan((1-R(:,i+1))./(1-R(:,i))./cos(T(:,i+1)));\n end\n T(:,1) = asin((1-R(:,2))./cos(T(:,2)));\n THETA = T(:,1:obj.k)*2/pi;\n Valid = all(THETA<=1/4|THETA>=3/4,2);\n R = R(Valid,:);\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n if obj.M == 2\n R = obj.GetOptimum(100);\n elseif obj.M == 3\n a = linspace(0,pi/2,30)';\n R = {1-sin(a)*cos(a'),1-sin(a)*sin(a'),1-cos(a)*ones(size(a'))};\n V = asin(sqrt((1-R{2}).^2+(1-R{3}).^2));\n R{1} = (2/pi).*(V+1/8*sin(8*V));\n T2 = atan((1-R{3})./(1-R{2}));\n T1 = asin((1-R{2})./cos(T2));\n THETA = cat(3,T1,T2)*2/pi;\n Valid = all(THETA<=1/4|THETA>=3/4,3);\n R{1}(~Valid) = nan;\n else\n R = [];\n end\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/ZXH_CF/ZXH_CF9.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7176667906046947}} {"text": "function [ status, x ] = newton ( n, x0, p, f, fp, tol )\n\n%*****************************************************************************80\n%\n%% NEWTON carries out the Newton iteration for the continuation system.\n%\n% Discussion:\n%\n% We assume that X0 is a point on the curve of solutions.\n%\n% Given a starting point X, this function applies Newton's method \n% to the system of N equations:\n%\n% G(X) = ( F(X) ) <-- N-1 equations in N unknowns\n% ( X(P) - X0(P) ) <-- Hold component P fixed.\n%\n% whose NxN Jacobian matrix is\n%\n% GP(X) = ( FP(X) ) <-- N-1 by N matrix.\n% ( Delta(P,J) ) <-- 1 by N matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 April 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of unknowns.\n% (This should always be 2 for this program!)\n%\n% Input, real X0(n), a starting point.\n%\n% Input, integer P, the index of the current continuation parameter.\n%\n% Input, function fx = F ( n, x ), a pointer to the\n% function that evaluates the N-1 nonlinear equations.\n%\n% Input, function fpx = FP ( n, x ), a pointer to the\n% function that evaluates the N-1 by N Jacobian matrix\n% associated with the nonlinear equations.\n%\n% Input, real TOL, an error tolerance.\n%\n% Output, integer STATUS, the return flag.\n% 0, no errors, the iteration converged.\n% 1, the iteration did not converge in IT_MAX steps.\n%\n% Output, real X(n), the estimated solution.\n%\n verbose = 0;\n\n alpha = x0(p);\n x = x0;\n\n it = 0;\n it_max = 10;\n\n while ( 1 )\n\n if ( it_max < it )\n status = 1;\n return;\n end\n\n fx = f ( n, x );\n fx(n,1) = x(p) - alpha;\n\n fx_norm = max ( abs ( fx ) );\n\n if ( verbose )\n fprintf ( 1, ' %d %g\\n', it, fx_norm );\n end\n\n if ( fx_norm <= tol )\n status = 0;\n return;\n end\n\n it = it + 1;\n\n fpx = fp ( n, x );\n fpx(n,1:n) = 0.0;\n fpx(n,p) = 1.0;\n\n dx = - fpx \\ fx;\n x0 = x;\n x = x0 + dx;\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/continuation/newton.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7176667906034976}} {"text": "%% DEMO_mesh_bifurcation_cut_loft_branch\n% This demo shows how one can use logic operations to cut meshes and to\n% extrude features from meshes. Here a bifurcated vessel is created by\n% cutting a hole in a particular direction and by extruding the side-branch\n% from this hole. The initial surface mesh is then thickened to produce a\n% hexahedral mesh.\n\n%%\n\nclear; close all; clc;\n\n%% \n% Plot Settings\nfontSize=15;\nfaceAlpha=0.8;\nedgeColor=0.*ones(1,3);\nlineWidth1=2;\nmarkerSize1=50; \nmarkerSize2=25; \n\n%% Control parameters\npointSpacing=0.5; \ntrunkRadiusInner=3; %Radius\ntrunkLength=15; %Length\nbranchRadiusInner=2;\nbranchLength=6;\nbranchAngle=50;\ncutDist=0.5; \nbranchBaseOffset=cutDist+pointSpacing;\n\nwallThickness=0.5; \nnumElementsWall=2; \n\nbezierTangency=0.5;\n\nnumSmootIterations=25;\nsmoothMethod='HC'; \nsmoothIncludeSteps=2; \n\n%% Derived parameters\n\n%Get outer radii \ntrunkRadiusOuter=trunkRadiusInner+wallThickness; \nbranchRadiusOuter=branchRadiusInner+wallThickness; \n\n%Have branch exit in middle\nV_branch_origin=[0 0 -trunkRadiusOuter*tand(90-branchAngle)];\n\n%% Create example geometry\n\n%Guide curves and branches\nR=euler2DCM([0 (branchAngle/180)*pi 0]);\nR_90=euler2DCM([0 (90/180)*pi 0]);\n\n%Main trunk\nVm=evenlySpaceCurve([0 0 -trunkLength/2; 0 0 trunkLength/2],pointSpacing);\n\nN_branch_dir=[0 0 1]*R;\nt=linspace(0,2*pi,ceil((2*pi*trunkRadiusOuter)./pointSpacing)+1)'; t=t(1:end-1);\nVc1=trunkRadiusOuter.*[cos(t) sin(t) zeros(size(t))];\n\nVc2_trunk=Vc1+Vm(end,:);\nVc1_trunk=Vc1+Vm(1,:);\n\n%%\n\nn1=vecnormalize(Vm(2,:)-Vm(1,:));\nn2=vecnormalize(Vm(end,:)-Vm(end-1,:));\n[Ft,Vt,Ct]=sweepLoft(Vc1_trunk,Vc2_trunk,n1,n2,Vm,[],0,0);\n\n%% Ray trace branch direction onto trunk to get branch centre point\n\noptionStruct.tolEps = 1e-6;\noptionStruct.triSide = -1;\noptionStruct.rayType = 'ray';\noptionStruct.exclusionType = 'inclusive';\noptionStruct.paired = 0; \nP=triSurfRayTrace(V_branch_origin,N_branch_dir,Ft,Vt,optionStruct);\nP=mean(P,1);\n\n%%\n% Visualization250\n\ncFigure; hold on; \ntitle('Main trunk');\nhp1=gpatch(Ft,Vt,'w','k',faceAlpha);\nhp2=quiverVec(V_branch_origin,N_branch_dir,branchLength*2,'r');\nhp3=plotV(P,'b.','markerSize',markerSize1);\nlegend([hp1 hp2 hp3],{'Main trunk','Branch direction vector','Intersection point'})\naxisGeom(gca,fontSize); camlight headlight; \ngdrawnow; \n\n%% Cut main trunk using side branch ellipse\n\nt=linspace(0,2*pi,2*ceil((2*pi*branchRadiusOuter)./pointSpacing)+1)'; t=t(1:end-1);\nb=branchRadiusOuter./cosd(90-branchAngle);\nV_cut_ellipse=[b*cos(t) branchRadiusOuter.*sin(t) zeros(size(t))];\nV_cut_ellipse=V_cut_ellipse*R_90+P;\n[~,indRemove]=minDist(V_cut_ellipse,Vt);\nindRemove=unique(indRemove); \nlogicFacesSelect=~any(ismember(Ft,indRemove),2);\n\nFt_precut=Ft(logicFacesSelect,:);\n\nclear optionStruct\noptionStruct.outputType='label';\n[G,~,groupSize]=tesgroup(Ft_precut,optionStruct);\n[~,indLargestGroup]=max(groupSize);\nFt_cut=Ft_precut(G==indLargestGroup,:);\n\n\nEt_boundary_cut=patchBoundary(Ft_cut);\nEt_boundary=patchBoundary(Ft);\nEt_cut_boundary=Et_boundary_cut(~any(ismember(Et_boundary_cut,Et_boundary),2),:);\nindCutCurve=edgeListToCurve(Et_cut_boundary);\n\nclear optionStruct\noptionStruct.numSeeds=numel(indCutCurve); %Number of seeds\noptionStruct.waitBarOn=0; %Turn on/off waitbar\nDt_cut=meshDistMarch(Ft_cut,Vt,indCutCurve,optionStruct);\nlogicVerticesFar=Dt_cut>cutDist;\nlogicKeep=all(logicVerticesFar(Ft_cut),2);\nFt_cut=Ft_cut(logicKeep,:);\n\nEt_boundary_cut=patchBoundary(Ft_cut);\nEt_boundary=patchBoundary(Ft);\nEt_cut_boundary=Et_boundary_cut(~any(ismember(Et_boundary_cut,Et_boundary),2),:);\nindCutCurve=edgeListToCurve(Et_cut_boundary);\n\nV_branch_curve_trunk=Vt(indCutCurve(1:end-1),:);\n[~,~,Nt]=patchNormal(Ft_cut,Vt);\n\nN_branch_curve_trunk=Nt(indCutCurve(1:end-1),:);\n\n%%\n% Visualization\n\ncFigure; hold on; \ntitle('Cut main trunk');\nhp1=gpatch(Ft_cut,Vt,Dt_cut,'k',faceAlpha);\nhp2=quiverVec(V_branch_origin,N_branch_dir,branchLength*2,'r');\nhp3=plotV(V_cut_ellipse,'g.-','markerSize',markerSize2,'LineWidth',lineWidth1);\nhp4=plotV(V_branch_curve_trunk,'b.-','markerSize',markerSize2,'LineWidth',lineWidth1);\nlegend([hp1 hp2 hp3 hp4],{'Cut main trunk','Branch direction vector','Branch base ellipse','Cut boundary'})\naxisGeom(gca,fontSize); camlight headlight; \ngdrawnow; \n\n%% Define bezier start and end vector directions\n\n[~,indNearest]=minDist(V_branch_curve_trunk(1,:),V_cut_ellipse);\ndt=linspace(2*pi,0,size(V_branch_curve_trunk,1)+1)'; dt=dt(1:end-1);\ndt=dt+t(indNearest);\nV_cut_ellipse=[b*cos(dt) branchRadiusOuter.*sin(dt) zeros(size(dt))];\nV_branch_curve_ellipse1=V_cut_ellipse*R_90+P+N_branch_dir.*(branchBaseOffset/cosd(90-branchAngle));\n\nd1=sum(sqrt(sum((V_branch_curve_ellipse1-V_branch_curve_trunk).^2,2)));\nd2=sum(sqrt(sum((flipud(V_branch_curve_ellipse1)-V_branch_curve_trunk).^2,2)));\nif d2>\n% \n% _*GIBBON*_ \n% \n% \n% _Kevin Mattheus Moerman_, \n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/DEMO_mesh_bifurcation_cut_loft_branch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7176667862876871}} {"text": "% spline 举例\nclear; clc;\n\nxi=[27.7, 28, 29, 30]; % 插值节点\nyi=[4.1, 4.3, 4.1, 3.0]; % 节点处的函数值\ndf0=3.0; dfn=-4.0; % 边界条件\npp=spline(xi,[df0, yi, dfn]);\n\nxh=27.7:0.1:30; % 需要插值的点\nyh=ppval(pp,xh); % 通过插值求得的近似值 \nplot(xi,yi,'r+',xh,yh,'o-b','LineWidth',1.5,'MarkerSize',12);\n", "meta": {"author": "qxr777", "repo": "NumericalAnalysis", "sha": "145e47521459defdcfd6a929702651abe29ba6de", "save_path": "github-repos/MATLAB/qxr777-NumericalAnalysis", "path": "github-repos/MATLAB/qxr777-NumericalAnalysis/NumericalAnalysis-145e47521459defdcfd6a929702651abe29ba6de/第二章 插值方法/demo_2_9.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.7176213109484464}} {"text": "function K = covMaternard(d, hyp, x, z, i)\n\n% Matern covariance function with nu = d/2 and Automatic Relevance Detemination\n% (ARD) distance measure. For % d=1 the function is also known as the exponential \n% covariance function or the Ornstein-Uhlenbeck covariance. The covariance \n% function is:\n%\n% k(x^p,x^q) = s2f * f( sqrt(d)*r ) * exp(-sqrt(d)*r)\n%\n% with f(t)=1 for d=1, f(t)=1+t for d=3 and f(t)=1+t.*(1+t/3) for d=5.\n% Here r is the distance sqrt((x^p-x^q)'*inv(P)*(x^p-x^q)), P is ell times\n% the unit matrix and sf2 is the signal variance. The hyperparameters are:\n%\n% hyp = [ log(ell_1)\n% log(ell_2)\n% .\n% log(ell_D)\n% log(sqrt(sf2)) ]\n%\n% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2010-09-10.\n% Ali Abusnina, 2014\n%\n% See also COVFUNCTIONS.M.\n\nif nargin<3, K = '(D+1)'; return; end % report number of parameters\nif nargin<4, z = []; end % make sure, z exists\nxeqz = numel(z)==0; dg = strcmp(z,'diag') && numel(z)>0; % determine mode\n\n[n,D] = size(x);\nell = exp(hyp(1:D)); % characteristic length scale\nsf2 = exp(2*hyp(D+1)); \n\nswitch d\n case 1, f = @(t) 1; df = @(t) 1;\n case 3, f = @(t) 1 + t; df = @(t) t;\n case 5, f = @(t) 1 + t.*(1+t/3); df = @(t) t.*(1+t)/3;\nend\n m = @(t,f) f(t).*exp(-t); dm = @(t,f) df(t).*t.*exp(-t);\n\n% precompute distances\nif dg % vector kxx\n K = zeros(size(x,1),1);\nelse\n if xeqz % symmetric matrix Kxx\n K = sqrt( sq_dist(sqrt(d)* (bsxfun(@rdivide, x', ell)) ));\n\n else % cross covariances Kxz\n \n K = sqrt( sq_dist(sqrt(d)* (bsxfun(@rdivide, x', ell)) , sqrt(d) * (bsxfun(@rdivide, z', ell))) );\n \n end\nend\n\nif nargin<5 % covariances\n K = sf2*m(K,f);\nelse % derivatives\n if i<=D \n K = sf2*dm(K,f);\n elseif i<=D+1\n K = 2*sf2*m(K,f);\n else\n error('Unknown hyperparameter')\n end\nend", "meta": {"author": "Dynamic-Systems-and-GP", "repo": "GPdyn", "sha": "343c20a28a0f95f488db4a086c43fafab5423bda", "save_path": "github-repos/MATLAB/Dynamic-Systems-and-GP-GPdyn", "path": "github-repos/MATLAB/Dynamic-Systems-and-GP-GPdyn/GPdyn-343c20a28a0f95f488db4a086c43fafab5423bda/gpdyn-utilities/covMaternard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7176205026456816}} {"text": "classdef MatrixVectorizedInverter_3x3 < MatrixVectorizedInverter_Interface\n \n methods (Access = public)\n \n function B = computeInverse(obj,A)\n d = obj.computeAdjointsTranspose(A);\n \n det = obj.computeDeterminant(A);\n \n B = zeros(size(A));\n for i = 1:3\n for j = 1:3\n B(i,j,:) = squeeze(d(i,j,:))./det;\n end\n end\n end\n \n function detA = computeDeterminant(obj,A)\n d = obj.computeAdjointsTranspose(A);\n d = permute(d,[2 1 3]);\n detA = squeeze(sum(A.*d,[1 2]))/3;\n end\n \n end\n \n methods (Access = private, Static)\n \n function d = computeAdjointsTranspose(A)\n d = zeros(size(A));\n \n A11 = A(1,1,:);\n A12 = A(1,2,:);\n A13 = A(1,3,:);\n A21 = A(2,1,:);\n A22 = A(2,2,:);\n A23 = A(2,3,:);\n A31 = A(3,1,:);\n A32 = A(3,2,:);\n A33 = A(3,3,:);\n \n d(1,1,:) = A22.*A33-A23.*A32;\n d(1,2,:) = A32.*A13-A33.*A12;\n d(1,3,:) = A12.*A23-A13.*A22;\n \n d(2,1,:) = A23.*A31-A21.*A33;\n d(2,2,:) = A33.*A11-A31.*A13;\n d(2,3,:) = A13.*A21-A11.*A23;\n \n d(3,1,:) = A21.*A32-A22.*A31;\n d(3,2,:) = A31.*A12-A32.*A11;\n d(3,3,:) = A11.*A22-A12.*A21;\n end\n \n end\n \nend", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/Topology Optimization/Operators/MatrixVectorizedInverter/MatrixVectorizedInverter_3x3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.717620495915352}} {"text": "function value = epn_lag_monomial_integral ( n, expon )\n\n%*****************************************************************************80\n%\n%% EPN_LAG_MONOMIAL_INTEGRAL: integral of monomial with Laguerre weight on EPN.\n%\n% Discussion:\n%\n% EPN is the N-dimensional positive space [0,+oo)^N with exponential\n% or Laguerre weight function:\n%\n% w(x(1:n)) = exp ( - sum ( x(1:n) ) )\n%\n% value = integral ( EPN )\n% product ( 1 <= i <= n ) x(I)^expon(i) exp ( -x(i) ) dx(i)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n%\n% Input, integer EXPON(N), the exponents.\n%\n% Output, real VALUE, the value of the integral.\n%\n value = 1.0;\n for i = 1 : n\n value2 = ep1_lag_monomial_integral ( expon(i) );\n value = value * value2;\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/epn_lag_monomial_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7176204959153519}} {"text": "function value = epn_glg_monomial_integral ( n, expon, alpha )\n\n%*****************************************************************************80\n%\n%% EPN_GLG_MONOMIAL_INTEGRAL: integral of monomial with GLG weight on EPN.\n%\n% Discussion:\n%\n% EPN_GLG is the N-dimensional positive space [0,+oo)^N with generalized\n% Laguerre weight function:\n%\n% w(alpha;x) = product ( 1 <= i <= n ) x(i)^alpha exp ( - x(i) )\n%\n% value = integral ( EPN )\n% product ( 1 <= i <= n ) x(I)^expon(i) x(i)^alpha exp ( - x(i) ) dx(i)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n%\n% Input, integer EXPON(N), the exponents.\n%\n% Input, real ALPHA, the exponent of X in the weight function.\n% -1.0 < ALPHA.\n%\n% Output, real VALUE, the value of the integral.\n%\n value = 1.0;\n for i = 1 : n\n value2 = ep1_glg_monomial_integral ( expon(i), alpha );\n value = value * value2;\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/epn_glg_monomial_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7176204939052603}} {"text": "function value = r8_binom ( n, m )\n\n%*****************************************************************************80\n%\n%% R8_BINOM evaluates the binomial coefficient using R8 arithmetic.\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, integer N, M, the arguments.\n%\n% Output, real VALUE, the binomial coefficient.\n%\n persistent bilnmx\n persistent fintmx\n persistent sq2pil\n\n sq2pil = 0.91893853320467274178032973640562;\n\n if ( isempty ( bilnmx ) )\n bilnmx = log ( r8_mach ( 2 ) ) - 0.0001;\n fintmx = 0.9 / r8_mach ( 3 );\n end\n\n if ( n < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_BINOM - Fatal error!\\n' );\n fprintf ( 1, ' N < 0.\\n' );\n error ( 'R8_BINOM - Fatal error!' )\n end\n\n if ( m < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_BINOM - Fatal error!\\n' );\n fprintf ( 1, ' M < 0.\\n' );\n error ( 'R8_BINOM - Fatal error!' )\n end\n\n if ( n < m )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_BINOM - Fatal error!\\n' );\n fprintf ( 1, ' N < M.\\n' );\n error ( 'R8_BINOM - Fatal error!' )\n end\n\n k = min ( m, n - m );\n\n if ( k <= 20 && k * log ( max ( n, 1 ) ) <= bilnmx )\n\n value = 1.0;\n\n for i = 1 : k\n value = value * ( n - i + 1 ) / i;\n end\n\n else\n\n if ( k < 9 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_BINOM - Fatal error!\\n' );\n fprintf ( 1, ' Result overflows.\\n' );\n fprintf ( 1, ' N or M is too big.\\n' );\n error ( 'R8_BINOM - Fatal error!' )\n end\n\n xn = n + 1;\n xk = k + 1;\n xnk = n - k + 1;\n\n corr = r8_lgmc ( xn ) - r8_lgmc ( xk ) - r8_lgmc ( xnk );\n\n value = xk * log ( xnk / xk ) ...\n - xn * r8_lnrel ( - ( xk - 1.0 ) / xn ) ...\n - 0.5 * log ( xn * xnk / xk ) + 1.0 - sq2pil + corr;\n\n if ( bilnmx < value )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_BINOM - Fatal error!\\n' );\n fprintf ( 1, ' Result overflows.\\n' );\n fprintf ( 1, ' N or M is too big.\\n' );\n error ( 'R8_BINOM - Fatal error!' )\n end\n\n value = exp ( value );\n\n end\n\n if ( value < fintmx )\n value = r8_aint ( value + 0.5 );\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_binom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384595, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7176204938177536}} {"text": "% Jason Joseph Rebello\n% Carnegie Mellon University (Jan 2012 - May 2013) \n% MS in Electrical & Computer Engineering\n% K Means Algorithm with the application to image compression\n\n% This program uses the K means clustering algorithm to group the pixels \n% in an image in order to provide image compression.\n\nclear all;\nclc;\nclose all;\n\nfprintf('K means clustering algorithm used for image compression\\n\\n');\nt = cputime;\n\n%% Read the image\nfprintf('Reading image');\nI = imread('bird_small.png');\n%imshow(I);\nI = (double(I))/255;\nfprintf('...done\\n\\n');\n\n%% Declare and Initialize Variabels\nfprintf('Initializing variables');\nK = 16; % number of clusters\nimgSize = size(I); % get size of image\niterCentroids = 10; % number of times K means runs to find the best centroid\niterKMeans = 10; % number of times K means runs with different initial centroids\nfprintf('...done\\n\\n');\n\n%% Get input\nfprintf('Formatting input');\nX = reshape(I, imgSize(1) * imgSize(2), 3); % resize into (total pixel x features)\nfprintf('...done\\n\\n');\n\n%% Run K Means\nfor i=1:iterKMeans\n \n fprintf(' ********* Running K means iteration %d ***********\\n\\n',i);\n [centroids cost idx] = runKMeans(X, K, iterCentroids);\n fprintf('Cost after %d iteration : %f\\n\\n',i,cost);\n \n if i==1\n bestCentroids = centroids;\n bestCost = cost;\n bestidx = idx;\n elseif (i>1 && cost 0) and the center of the sphere (xo,yo,zo).\n% If (xo,yo,zo) are not provided, they are assumed (0,0,0).\n%\n% Returned values are the fitted radius 'r' (constant)\n% and the (x,y,z) Cartesian co-ordinates on the projected sphere.\n%\n% Options: estim - echo spherical radius estimates (default),\n% plot - plot the input/projected xyz on a sphere.\n%\n\n% $Revision: 1.1 $ $Date: 2009-04-28 22:13:55 $\n\n% Licence: GNU GPL, no express or implied warranties\n% History: 02/2002, Darren.Weber_at_radiology.ucsf.edu\n% adapted from elec_fit_sph\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% initialise centroid, unless input parameters defined\nif ~exist('xo','var') xo = 0; else, if isempty(xo) xo = 0; end, end\nif ~exist('yo','var') yo = 0; else, if isempty(yo) yo = 0; end, end\nif ~exist('zo','var') zo = 0; else, if isempty(zo) zo = 0; end, end\n\nif (nargin>6), estim = varargin{1};\nelse estim = 1;\nend\nif (nargin>7), plot = varargin{2};\nelse plot = 0;\nend\n\neegversion = '$Revision: 1.1 $';\nfprintf('ELEC_SPHERE_PROJECT [v %s]\\n',eegversion(11:15));\nfprintf('...projecting electrodes to spherical points\\n');\ntic;\n\n% Initialise r0 as a rough guess at the sphere radius\nrX = (max(X) - min(X)) / 2;\nrY = (max(Y) - min(Y)) / 2;\nrZ = max(Z) - zo;\nr0 = mean([ rX rY rZ ]);\n\nif isequal(estim,1),\n fprintf('...initial spherical radius = %f\\n', r0); end\n\n% perform least squares estimate of spherical radius (r)\noptions = optimset('fminsearch');\n[r,fval,exitflag,output] = fminsearch('elec_sphere_fit_optim',...\n r0, options, X, Y, Z, xo, yo, zo);\n%fprintf('\\n%s%f\\n', 'Iterations = ', output.iterations);\n%fprintf('\\n%s%d\\n', 'Exit = ', exitflag);\n\nif isequal(estim,1),\n fprintf('...estimated spherical radius = %f\\n', r); end\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Find the projection point of X,Y,Z to the fitted sphere radius r\n\n% Convert Cartesian X,Y,Z to spherical (radians)\ntheta = atan2( (Y-yo), (X-xo) );\nphi = atan2( sqrt( (X-xo).^2 + (Y-yo).^2 ), (Z-zo) );\n% do not recalc: r = sqrt( (X-xo).^2 + (Y-yo).^2 + (Z-zo).^2);\n\n% Recalculate X,Y,Z for constant r, given theta & phi.\nR = ones(size(phi)) * r; \nx = R .* sin(phi) .* cos(theta);\ny = R .* sin(phi) .* sin(theta);\nz = R .* cos(phi);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Plot the input & projected electrode positions on a sphere\nif isequal(plot,1),\n figure('NumberTitle','off','Name','Electrode Placements');\n set(gca,'Projection','perspective');\n set(gca,'DataAspectRatio',[1 1 1]);\n\n hold on\n\n plot3(x,y,z,'b.');\n plot3(X,Y,Z,'ro');\n legend('input xyz','fitted sphere','Location','BestOutside');\n\n [Xs,Ys,Zs]=sphere;\n Xs = Xs * r;\n Ys = Ys * r;\n Zs = Zs * r;\n\n surf(Xs,Ys,Zs,...\n 'EdgeColor','none',...\n 'FaceColor',[0.7 0.7 0.7],...\n 'FaceAlpha',0.4);\n view(2);\n rotate3d;\n\n axis tight; hold off;\nend\n\nt = toc; fprintf('...done (%6.2f sec).\\n\\n',t);\n\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/external/bioelectromagnetism_ligth/elec_sphere_project.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.7174837360559608}} {"text": "% Calculate statistics of a rate map that depend on probability distribution function (PDF)\n%\n% Calculates information, sparsity and selectivity of a rate map. Calculations are done\n% according to 1993 Skaggs et al. \"An Information-Theoretic Approach to Deciphering the Hippocampal Code\"\n% paper. Another source of information is 1996 Skaggs et al. paper called\n% \"Theta phase precession in hippocampal neuronal populations and the compression of temporal sequences\".\n%\n% USAGE\n% [information, sparsity, selectivity] = analyses.mapStatsPDF(map)\n% map Structure with rate map, output of analyses.map\n% information Structure with fields:\n% rate information rate [bits/sec]\n% content Spatial information content [bits/spike]\n% sparsity Sparsity value\n% selectivity Selectivity value\n%\n% SEE\n% See also analyses.map\n%\nfunction [information, sparsity, selectivity] = mapStatsPDF(map)\n if ~isstruct(map)\n error('BNT:arg', 'Incorrect argument. Map should be a structure. You are probably relying on old code when mapStatsPDF accepted map as matrix.');\n end\n T = nansum(nansum(map.time)); % overall trial duration\n posPDF = map.time / (T+eps); % probability of animal being in bin x:\n % duration of time animal spent in the bin divided by overall trial duration.\n \n meanrate = nansum(nansum(map.z .* posPDF));\n meansquarerate = nansum(nansum( (map.z .^ 2) .* posPDF ));\n if meansquarerate == 0\n sparsity = NaN;\n else\n sparsity = meanrate^2 / meansquarerate;\n end\n\n maxrate = nanmax(nanmax(map.z));\n if meanrate == 0;\n selectivity = NaN;\n information.content = nan;\n information.rate = nan;\n else\n selectivity = maxrate / meanrate;\n logArg = map.z / meanrate;\n logArg(logArg < 1) = 1;\n \n information.rate = nansum(nansum(posPDF .* map.z .* log2(logArg)));\n information.content = information.rate / meanrate;\n end\nend\n", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Analysis/+SpatialTuning_BNT/mapStatsPDF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850110816422, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.7174692621028651}} {"text": "function gauss = get_gaussian_kernel(Nsigmas, sigma_in_pix)\n% generate gaussian kernel with given sigmas\n ndims = numel(sigma_in_pix);\n width = 2 * floor(Nsigmas .* sigma_in_pix) + 1;\n hw = (width - 1)/2;\n \n sigma_in_pix(sigma_in_pix == 0) = 1;\n if ndims == 3\n -hw(1):hw(1)\n hw(2)\n hw(3)\n [n1, n2, n3] = ndgrid(-hw(1):hw(1), -hw(2):hw(2), -hw(3):hw(3));\n size(n1)\n weight = exp(-n1.^2/(2*sigma_in_pix(1)^2) - n2.^2/(2*sigma_in_pix(2)^2) - n3.^2/(2*sigma_in_pix(3)^2) );\n elseif ndims == 2\n [n1, n2] = ndgrid(-hw(1):hw(1), -hw(2):hw(2));\n weight = exp(-n1.^2/(2*sigma_in_pix(1)^2) - n2.^2/(2*sigma_in_pix(2)^2));\n end\n \n gauss = weight / sum(weight(:));\nend", "meta": {"author": "visva89", "repo": "pTVreg", "sha": "c359620e3c8435392db02354274d6c74d682d437", "save_path": "github-repos/MATLAB/visva89-pTVreg", "path": "github-repos/MATLAB/visva89-pTVreg/pTVreg-c359620e3c8435392db02354274d6c74d682d437/mutils/My/image_utils/get_gaussian_kernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037732, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.7174692607404953}} {"text": "% Fig. 6.29 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n%\n\nclear all;\n%close all;\nclf\n\nnum=[1 1];\nden=conv([1 0],[0.1 -1]);\nrlocus(num,den);\n\naxis([-8 12 -10 10]);\naxis equal\ngrid;\ntitle('Fig. 6.29 Root locus for Example 6.10');\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/fig6_29.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7174026177082367}} {"text": "function [A_K_I,A_K_F,A_F_I,A_Rfl_F,A_Rfr_F,A_down_up] = Rotation_Matrices(phi,chi,delta)\n%% Rotation from rear axle fixed coordinate system into vehicle fixed coordinate system\n% Input parameters:\n% phi [rad] Vehicle Rotation Angles [Phi Theta Psi] [3x1]\n% chi [rad] Road Cardan Angles [chi_x chi_y Psi] [3x1]\n% delta [rad] Steering Angles [deltaFL deltaFR 0 0] [1x4]\n% Output parameters:\n% A_K_I [---] Transformation Matrix A_K_I [3x3]\n% A_K_F [---] Transformation Matrix A_K_F [3x3]\n% A_F_I [---] Transformation Matrix A_F_I [3x3]\n% A_Rfl_F [---] Transformation Matrix A_Rfl_F [3x3]\n% A_Rfr_F [---] Transformation Matrix A_Rfr_F [3x3]\n% A_down_up [---] Transformation Matrix W := A_down_up [3x3]\n\n%% Pre-Computation of trigonometric values\ncphi=cos(phi);\nsphi=sin(phi);\ncchi=cos(chi);\nschi=sin(chi);\n\n%% Definition of rotation matrices\n\n% rotation matrix from z-up coordinate system to z-down coordinate system\nA_down_up = reshape([1 0 0,0 -1 0,0 0 -1],[3,3]);\n\n% rotation matrix from inertial coordinate system to vehicle fixed coordinate system\nA_K_I = reshape([cphi(3)*cphi(2),-cphi(1)*sphi(3)+cphi(3)*sphi(2)*sphi(1),sphi(3)*sphi(1)+cphi(3)*cphi(1)*sphi(2),cphi(2)*sphi(3),cphi(3)*cphi(1)+sphi(3)*sphi(2)*sphi(1),-cphi(3)*sphi(1)+cphi(1)*sphi(3)*sphi(2),-sphi(2),cphi(2)*sphi(1),cphi(2)*cphi(1)],[3,3]);\n\n% rotation matrix from rear axle fixed coordinate system to vehicle fixed coordinate system without road inclination\n% A_K_F = reshape([cphi(2),sphi(2)*sphi(1),cphi(1)*sphi(2),0,cphi(1),-sphi(1),-sphi(2),cphi(2)*sphi(1),cphi(2)*cphi(1)],[3,3]);\n\n% rotation matrix from rear axle fixed coordinate system to vehicle fixed coordinate system over inertial coordinate system with road inclination\nA_K_F = reshape([cos(phi(2)-chi(2)),sin(phi(2)-chi(2))*sphi(1),sin(phi(2)-chi(2))*cphi(1),-sin(-chi(2)+phi(2))*schi(1),cchi(1)*cphi(1)+cphi(2)*cchi(2)*schi(1)*sphi(1)+sphi(2)*schi(1)*schi(2)*sphi(1),-cchi(1)*sphi(1)+cphi(2)*cchi(2)*cphi(1)*schi(1)+cphi(1)*sphi(2)*schi(1)*schi(2),-sin(-chi(2)+phi(2))*cchi(1),-cphi(1)*schi(1)+cphi(2)*cchi(1)*cchi(2)*sphi(1)+cchi(1)*sphi(2)*schi(2)*sphi(1),schi(1)*sphi(1)+cphi(2)*cchi(1)*cchi(2)*cphi(1)+cchi(1)*cphi(1)*sphi(2)*schi(2)],[3,3]);\n\n% rotation matrix from inertial coordinate system to rear axle fixed coordinate system\nA_F_I = reshape([cphi(3)*cchi(2),-cchi(1)*sphi(3)+cphi(3)*schi(1)*schi(2),sphi(3)*schi(1)+cphi(3)*cchi(1)*schi(2),cchi(2)*sphi(3),cphi(3)*cchi(1)+sphi(3)*schi(1)*schi(2),-cphi(3)*schi(1)+cchi(1)*sphi(3)*schi(2),-schi(2),cchi(2)*schi(1),cchi(1)*cchi(2)],[3,3]);\n\n% rotation matrix from rear axle fixed coordinate system to wheel fixed coordinate systems of front axle\nA_Rfl_F = reshape([cos(delta(1)),-sin(delta(1)),0,sin(delta(1)),cos(delta(1)),0,0,0,1],[3,3]);\nA_Rfr_F = reshape([cos(delta(2)),-sin(delta(2)),0,sin(delta(2)),cos(delta(2)),0,0,0,1],[3,3]);\n\nend\n\n", "meta": {"author": "TUMFTM", "repo": "sim_vehicle_dynamics", "sha": "df2ae95dbeb6f8e4591f31ee378acac8e812f358", "save_path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics", "path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics/sim_vehicle_dynamics-df2ae95dbeb6f8e4591f31ee378acac8e812f358/vehicle_model/vehicledynamics/src/Rotation_Matrices.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660989095221, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.717394501320543}} {"text": "function [sigma,bnd] = bdsqr(alpha,beta)\n\n% BDSQR: Compute the singular values and bottom element of\n% the left singular vectors of a (k+1) x k lower bidiagonal \n% matrix with diagonal alpha(1:k) and lower bidiagonal beta(1:k),\n% where length(alpha) = length(beta) = k.\n%\n% [sigma,bnd] = bdsqr(alpha,beta)\n%\n% Input parameters:\n% alpha(1:k) : Diagonal elements.\n% beta(1:k) : Sub-diagonal elements.\n% Output parameters:\n% sigma(1:k) : Computed eigenvalues.\n% bnd(1:k) : Bottom elements in left singular vectors.\n\n% Below is a very slow replacement for the BDSQR MEX-file.\n\n% warning('PROPACK:NotUsingMex','Using slow matlab code for bdsqr.')\nk = length(alpha);\nif min(size(alpha)') ~= 1 | min(size(beta)') ~= 1\n error('alpha and beta must be vectors')\nelseif length(beta) ~= k\n error('alpha and beta must have the same lenght')\nend \nB = spdiags([alpha(:),beta(:)],[0,-1],k+1,k);\n[U,S,V] = svd(full(B),0);\nsigma = diag(S);\nbnd = U(end,1:k)';\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/IALM-MC/utils/bdsqr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7173825341725903}} {"text": "function [B,EV,ED] = biharmonic_embedding(V,F,dim,p);\n % [B,EV,ED] = biharmonic_embedding(V,F);\n %\n % Takes a mesh (V,F) and returns an embedding using the spectrum of the\n % biharmonic operator. Then the biharmonic distance between two points i and\n % j can be computed as the euclidean distance between B(i,:) and B(j,:),\n % namely: \n % dist_ij = sqrt(sum((B(i,:)-B(j,:)).^2,2));\n % \n % Input:\n % V vertex list\n % F face list\n % dim requested dimension of the embedding\n % Optional:\n % p exponent above eigen values\n % 0.5 \"semi-harmonic\" embedding\n % 1 commute time embedding, \"harmonic\"\n % 2 biharmonic {default}\n % 3 \"triharmonic\" embedding\n % Output:\n % B biharmonic embedding\n % EV eigenvectors used in embedding\n % ED eigenvalues used in embedding\n % \n\n % if dimension is not specfied use 4\n if(~exist('dim','var'))\n dim = 4;\n end\n\n if(~exist('p','var'))\n p = 2;\n end\n\n % get cotangent matrix\n L = cotmatrix(V,F);\n % This should be better, but yaron seemed to use barycentric\n %M = massmatrix(V,F);\n M = massmatrix(V,F,'barycentric');\n\n % get dim+1 smallest magnitude eigenvalues and corresponding vectors\n [EV,ED] = eigs(L,M,dim+1,'sm');\n EV = EV(:, 2:end);\n ED = ED(2:end, 2:end);\n\n % This is not exactly the same, essentially it removes the mass matrix and\n % multiplies everything by a factos of -2\n % % This also works, because of the sign change in the eigenvalues matlab\n % % reverses the output order so 0.0 is the last eigenvalue\n % [EV,ED] = eigs(-2*L,M./sum(M(:)),dim+1,'sm');\n % EV = EV(:, 1:end-1);\n % ED = ED(1:end-1, 1:end-1);\n\n % divide each eigenvector by corresponding eigenvalue \n % divide the power by 2 first because it will appear in the denominator of\n % distance computation *outside* the squared difference see (4) and (11)\n B = EV * (inv(abs(ED))^(p/2));\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/biharmonic_embedding.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7173146446400677}} {"text": " function f = nufft_diric(k, N, K, use_true_diric)\n%function f = nufft_diric(k, N, K, use_true_diric)\n% \"regular fourier\" Dirichlet-function WITHOUT phase\n% diric(t) = sin(pi N t / K) / ( N * sin(pi t / K) )\n%\t\\approx sinc(t / (K/N))\n% in:\n%\tk [...]\t\tsample locations (unitless real numbers)\n%\tN\t\tsignal length\n%\tK\t\tDFT length\n%\tuse_true_diric\t1 = use true Diric function.\n%\t\t\t(default is to use sinc approximation)\n% out:\n%\tf [...]\t\tcorresponding function values\n%\n% Copyright 2001-12-8, Jeff Fessler, The University of Michigan\n\n% default is to plot\nif nargin < 3\n\thelp(mfilename)\n\tkmax = 2 * (10 + 1 * 4);\n\tk = linspace(-kmax,kmax,201);\n\tki = [-kmax:kmax];\n\tN = 32;\n\tK = 2*N;\n\tg = nufft_diric(k, N, K, 1);\n\tgi = nufft_diric(ki, N, K, 1);\n\ts = nufft_diric(k, N, K);\n\tdm = diric((2*pi/K)*k,N);\n\tplot(k, g, 'y-', k, s, 'c-', k, dm, 'r-', ki, gi, '.'), axis tight\n\tlegend('nufft diric', 'sinc', 'matlab diric')\n\txlabel k, ylabel diric(k)\n\tprintf('max %% difference = %g', max_percent_diff(g,s))\n\treturn\nend\n\nif nargin < 4\n\tuse_true_diric = logical(0);\nend\n\n% diric version\nif use_true_diric\n\tt = (pi/K) * k;\n\tf = sin(t);\n\ti = abs(t) > 1e-12;\t% nonzero argument\n\tf(i) = sin(N*t(i)) ./ (N * f(i));\n\tf(~i) = 1;\n\n% sinc version\nelse\n%\tf = sinc(k / (K/N));\n\tf = nufft_sinc(k / (K/N));\nend\n\n% this is faster than matlab's sinc because it does not use \"find\"\nfunction y = nufft_sinc(x)\ny = ones(size(x));\n%i = abs(x) > 1e-12; \ni = x ~= 0;\nx = x(i);\ny(i) = sin(pi*x) ./ (pi*x);\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/@NUFFT/private/nufft_diric.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7172865274016172}} {"text": "function a = r8gd_indicator ( n, ndiag, offset )\n\n%*****************************************************************************80\n%\n%% R8GD_INDICATOR sets up a R8GD indicator matrix.\n%\n% Discussion:\n%\n% The R8GD storage format is suitable for matrices whose only nonzero entries\n% occur along a few diagonals, but for which these diagonals are not all\n% close enough to the main diagonal for band storage to be efficient.\n%\n% In that case, we assign the main diagonal the offset value 0.\n% Each successive superdiagonal gets an offset value 1 higher, until\n% the highest superdiagonal (the A(1,N) entry) is assigned the offset N-1.\n% Similarly, the subdiagonals are assigned offsets of -1 through -(N-1).\n%\n% Now, assuming that only a few of these diagonals contain nonzeros,\n% then for the I-th diagonal to be saved, we stored its offset in\n% OFFSET(I), and its entries in column I of the matrix. \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 must be positive.\n%\n% Input, integer NDIAG, the number of diagonals of the matrix\n% that are stored in the array.\n% NDIAG must be at least 1, and no more than 2 * N - 1.\n%\n% Input, integer OFFSET(NDIAG), the offsets for the diagonal storage.\n%\n% Output, real A(N,NDIAG), the R8GD matrix.\n%\n fac = 10^( i4_log_10 ( n ) + 1 );\n\n for i = 1 : n\n for diag = 1 : ndiag\n j = i + offset(diag);\n if ( 1 <= j & j <= n )\n a(i,diag) = fac * i + j;\n else\n a(i,diag) = 0.0;\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r8gd_indicator.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.8499711737573762, "lm_q1q2_score": 0.7172865108463861}} {"text": "function coeffs = alias(coeffs, m)\n%ALIAS Alias Fourier coefficients on equally spaced grid.\n% ALIAS(C, M) aliases the Fourier coefficients stored in the column vector C\n% to have length M. If M > LENGTH(C), the coefficients are padded with zeros.\n% If C is a matrix of coefficients, each of the columns is aliased to length\n% M.\n%\n% See also PROLONG.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Get the number of coefficients.\nn = size(coeffs, 1);\n\n% Pad with zeros:\nif ( m > n )\n \n k = ceil((m-n)/2);\n z = zeros(k, size(coeffs, 2));\n \n % Need to handle the odd vs. even case separately.\n if ( ~mod(n, 2) ) % n even.\n \n % First, account for the asymmetry in the coefficients when n is even.\n % This will account for the cos(N/2) coefficient, which is stored\n % in the coeffs(n,:) entry, using properties of the complex\n % exponential.\n coeffs = [ coeffs(1,:)/2; coeffs(2:n,:); coeffs(1,:)/2 ];\n coeffs = [ z; coeffs; z(1:end-1,:) ];\n \n % Next, check if m is odd. If it is, then coeffs is too long and we\n % need to remove the first row (the lowest degree\n % coefficients).\n if ( mod(m, 2) ) % m odd.\n coeffs = coeffs(2:end,:);\n end\n \n else % n odd.\n \n % There is no asymmetry in the coefficients, just pad them.\n coeffs = [ z; coeffs; z ];\n \n % Only need to check if m is even, in which case coeffs is too \n % long and we need to remove the last row (the highest degree\n % coefficients).\n if ( ~mod(m, 2) ) % m even.\n coeffs = coeffs(1:end-1,:);\n end\n end\n \n return\n \nend\n\n% If the number of coefficients is even then we extend them by one so they\n% are odd by exploiting the symmetry property. This makes the code below a\n% little cleaner since fewer cases need to be handled.\nif ( ~mod(n, 2) ) % n even.\n coeffs(1,:) = 0.5*coeffs(1,:);\n coeffs = [ coeffs; coeffs(1,:) ];\n n = n + 1;\nend\n\n% Need to handle the odd and even case (for m) differently.\nif ( mod(m, 2) ) % m is odd.\n\n if ( m == 1 )\n\n % Reduce to a single point:\n constCoeffs = coeffs((n-1)/2+1,:);\n posCoeffs = coeffs((n-1)/2:-1:1,:);\n negCoeffs = coeffs((n-1)/2+2:n,:);\n e = ones(1, ceil((n-1)/2));\n e(1:2:end) = -1;\n coeffs = constCoeffs + (e*posCoeffs + e*negCoeffs);\n\n else\n \n m2 = (m-1)/2;\n n2 = (n-1)/2;\n % Extract coefficients:\n aliasedCoeffs = coeffs(n2-m2+1:n2+m2+1,:);\n \n % The code below aliases the coefficients from the higher modes\n % onto the lower modes. The principle behind the formula is figure\n % out which of the higher Fourier modes are indistinguishable from\n % the lower Fouirer modes on the grid consisting of m equally\n % spaced points from [-1,1). In general, when m and n are odd the\n % following will be equal for j=-(n-1)/2 to -(m+1)/2\n % exp(1i*pi*j*x) = sgn*exp(1i*pi*k*x) where\n % k = mod(j+(m+1)/2, -m) + (m-1)/2 and sgn = (-1)^mod(j+k, 2);\n for j = -n2:-m2-1\n k = mod(j+m2+1, -m) + m2;\n coeffIndexK = k + m2 + 1; % Index into aliasedCoeffs for mode k.\n coeffIndexJ = j + n2 + 1; % Index into coeffs for mode j.\n sgn = (-1)^mod(j+k, 2);\n aliasedCoeffs(coeffIndexK,:) = aliasedCoeffs(coeffIndexK,:) + sgn*coeffs(coeffIndexJ,:);\n coeffIndexK = -k + m2 + 1;\n coeffIndexJ = -j + n2 + 1;\n aliasedCoeffs(coeffIndexK,:) = aliasedCoeffs(coeffIndexK,:) + sgn*coeffs(coeffIndexJ,:);\n end\n coeffs = aliasedCoeffs;\n\n end\n \nelse % m is even.\n \n m2 = m/2;\n n2 = (n-1)/2;\n \n % Put the coefficient for the cos(m/2*pi*x) in the first entry of the\n % coefficient vector. This corresopnds to the exp(-1i*pi*m/2*x). \n aliasedCoeffs = coeffs(n2+1-m2:n2+m2,:);\n % Extend the aliased cofficient vector so it is symmetric. This allows\n % us to easily account for aliasing on the exp(-1i*pi*m/2*x) and \n % exp(1i*pi*m/2*x) term in the code below without the need for a \n % special if check. The negative allows contribution for sin(m/2*pi*x)\n % to be removed. \n aliasedCoeffs = [ aliasedCoeffs; -aliasedCoeffs(1,:) ];\n \n % Follow a similar structure to the odd m case above. The main\n % difference is that the higher order modes do not change sign when\n % aliased onto an even point grid.\n for j = -n2:-m2\n k = mod(j+m2,-m) + m2;\n coeffIndexK = k + m2 + 1; % Index into aliasedCoeffs for mode k.\n coeffIndexJ = j + n2 + 1; % Index into coeffs for mode j.\n aliasedCoeffs(coeffIndexK,:) = aliasedCoeffs(coeffIndexK,:) + coeffs(coeffIndexJ,:);\n coeffIndexK = -k + m2 + 1;\n coeffIndexJ = -j + n2 + 1;\n aliasedCoeffs(coeffIndexK,:) = aliasedCoeffs(coeffIndexK,:) + coeffs(coeffIndexJ,:);\n end\n % Collapse the aliased coefficient vector down to an even number of\n % terms by adding in the aliasing of the exp(1i*pi*m/2*x) terms to the\n % exp(-1i*pi*m/2*x).\n aliasedCoeffs(1,:) = aliasedCoeffs(1,:) + aliasedCoeffs(end,:);\n aliasedCoeffs(end,:) = [];\n\n coeffs = aliasedCoeffs;\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/@trigtech/alias.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.717286506295454}} {"text": "function [r,s,t,w] = threed_gauss(rule)\n%-----------------------------------------------------------------------\n% threed_gauss.m - calculate Gauss integration points for tetrahedral\n% elements\n%\n% Copyright (c) 2002, Jeff Borggaard, Virginia Tech\n% Version: 1.0\n%\n% Usage: [r,s,t,w] = threed_gauss(rule)\n%\n% Variables: rule\n% Number of Gauss points:\n% r\n% xi coordinate of Gauss points\n% s\n% eta coordinate of Gauss points\n% t\n% zeta coordinate of Gauss points\n% w\n% Gauss weights corresponding to (r,s,t)\n%-----------------------------------------------------------------------\n\n if (rule == 1)\n % The following points correspond to a 1 point rule\n % Polynomials of degree 1 are integrated exactly\n r(1) = 0.25000000; s(1) = 0.25000000; t(1) = 0.25000000;\n\n w(1) = 0.16666666; % (the volume of a regular tet is 1/6)\n\n elseif (rule == 4)\n % The following points correspond to a 4 point rule\n % Polynomials of degree 2 are integrated exactly\n r = zeros(4,1); s = zeros(4,1); t = zeros(4,1);\n r(1) = 0.13819660; s(1) = 0.13819660; t(1) = 0.13819660;\n r(2) = 0.58541020; s(2) = 0.13819660; t(2) = 0.13819660;\n r(3) = 0.13819660; s(3) = 0.58541020; t(3) = 0.13819660;\n r(4) = 0.13819660; s(4) = 0.13819660; t(4) = 0.58541020;\n\n w = 0.041666666667*ones(4,1);\n\n elseif (rule == 5)\n % The following points correspond to a 5 point rule\n % Polynomials of degree 3 are integrated exactly\n r = zeros(5,1); s = zeros(5,1); t = zeros(5,1);\n r(1) = 0.25000000000; s(1) = 0.25000000000; t(1) = 0.25000000000;\n r(2) = 0.16666666666; s(2) = 0.16666666666; t(2) = 0.16666666666;\n r(3) = 0.50000000000; s(3) = 0.16666666666; t(3) = 0.16666666666;\n r(4) = 0.16666666666; s(4) = 0.50000000000; t(4) = 0.16666666666;\n r(5) = 0.16666666666; s(5) = 0.16666666666; t(5) = 0.50000000000;\n\n w = zeros(5,1);\n w(1) =-0.13333333333;\n w(2) = 0.07500000000;\n w(3) = 0.07500000000;\n w(4) = 0.07500000000;\n w(5) = 0.07500000000;\n\n else\n error('quadrature rules other than 1, 4 or 5 are not supported\\n');\n keyboard\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/threed/threed_gauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.7172578157800432}} {"text": "function value = r8_gamr ( x )\n\n%*****************************************************************************80\n%\n%% R8_GAMR evaluates the reciprocal gamma function 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 value of the reciprocal gamma\n% function at X.\n%\n if ( x <= 0.0 && r8_aint ( x ) == x )\n\n value = 0.0;\n\n elseif ( abs ( x ) <= 10.0 )\n\n value = 1.0 / r8_gamma ( x );\n\n else\n\n [ alngx, sgngx ] = r8_lgams ( x );\n value = sgngx * exp ( - alngx );\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_gamr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7172496956082164}} {"text": "function a = dif2_llt ( n )\n\n%*****************************************************************************80\n%\n%% DIF2_LLT returns the Cholesky factor of the DIF2 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n a(i,i) = sqrt ( i + 1 ) / sqrt ( i );\n end\n\n for i = 2 : n\n a(i,i-1) = - sqrt ( i - 1 ) / sqrt ( 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/test_mat/dif2_llt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.822189134878876, "lm_q1q2_score": 0.7172345442149648}} {"text": "function [ x, seed ] = gompertz_sample ( a, b, seed )\n\n%*****************************************************************************80\n%\n%% GOMPERTZ_SAMPLE samples the Gompertz PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the parameters of the PDF.\n% 1 < A, 0 < B.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X, a sample of the PDF.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n [ cdf, seed ] = r8_uniform_01 ( seed );\n\n x = gompertz_cdf_inv ( cdf, a, b );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/gompertz_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8221891305219504, "lm_q1q2_score": 0.7172345349569976}} {"text": "function [TKenergy]=TKEO(x)\n%\n%% Utility function to calculate measures based on the nonlinear energy operator\n%\n% Function to estimate the TKEO of input data, follows the classical rule\n% of Teager and Kaiser\n%\n% Inputs: x -> any time-series signal (vector)\n%\n% =========================================================================\n% Output: TKenergy -> (nonlinear) Teager-Kaiser Energy Operator (TKEO)\n% =========================================================================\n%\n% Part of the \"Speech Disorders\" Toolbox\n%\n% -----------------------------------------------------------------------\n% Useful references:\n% \n% 1) J. Kaiser: On a simple algorithm to calculate the 'energy' of a\n% signal, Proc. IEEE International Conference on Acoustics, Speech, and \n% Signal Processing (ICASSP '90), pp. 381-384, Albuquerque, NM, USA, \n% April 1990\n%\n% -----------------------------------------------------------------------\n%\n% Last modified on 24 August 2014\n%\n% Copyright (c) Athanasios Tsanas, 2014\n%\n% ********************************************************************\n% If you use this program please cite:\n%\n% 1) A. Tsanas: \"Accurate telemonitoring of Parkinson's disease symptom\n% severity using nonlinear speech signal processing and statistical\n% machine learning\", D.Phil. thesis, University of Oxford, 2012\n% ********************************************************************\n%\n% For any question, to report bugs, or just to say this was useful, email\n% tsanasthanasis@gmail.com\n\n%% Algorithm computation\n\n% The algorithm is computed using the instantaneous value squared minus the\n% previous step value times the next step value:[x_n]^2-[x_(n-1)]*(x_(n+1)]\n%\n%\n% This program 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 of the License, or (at your\n% option) any later version.\n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n% Public License for more details.\n\n% This program 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 of the License, or (at your\n% option) any later version.\n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n% Public License for more details.\n%\n\ndata_length=length(x);\nTKenergy=zeros(data_length,1);\n\nTKenergy(1)=(x(1))^2; % first sample\n\nfor n=2:data_length-1\n TKenergy(n)=(x(n))^2-x(n-1)*x(n+1);\nend\n\n% TKenergy(2:data_length-1) = x(2:data_length-1).^2 - x(1:data_length-2).*x(3:data_length); % alternative, vectorized version\n\nTKenergy(data_length)=(x(data_length))^2; % last sample\n", "meta": {"author": "fernandoandreotti", "repo": "cinc-challenge2017", "sha": "78cfc8e6194857cee0cd731f41ba5b2dd589aed2", "save_path": "github-repos/MATLAB/fernandoandreotti-cinc-challenge2017", "path": "github-repos/MATLAB/fernandoandreotti-cinc-challenge2017/cinc-challenge2017-78cfc8e6194857cee0cd731f41ba5b2dd589aed2/featurebased-approach/subfunctions/lib/Teager-Kaiser/TKEO.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.7172345166849767}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n%\n%\n% Unit step sequence\n\n% u[n]\n n1=-3:-1;\n n2=0:5;\n n=[n1 n2];\n u1=zeros(size(n1));\n u2=ones(size(n2));\n u=[u1 u2];\n stem(n,u)\n\n% second way\n figure\n n=-3:5\n n0=0;\n u=(n>=n0)\n stem(n,u)\n\n \n %u[n-n0]\n figure\n n1=-3:1;\n n2=2:5;\n n=[n1 n2];\n u1=zeros(size(n1));\n u2=ones(size(n2));\n u2=ones(size(n2));\n u=[u1 u2];\n stem(n,u)\n\n% second way\n figure\n n=-3:5\n n0=2;\n u=((n-n0)>=0)\n stem(n,u)\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/c232.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.7172178126296215}} {"text": "function S = randskew(n, N)\n% Generates random skew symmetric matrices with normal entries.\n% \n% function S = randskew(n)\n% function S = randskew(n, N)\n%\n% S is an n-by-n-by-N array where each slice S(:, :, i) for i = 1..N is a\n% random skew-symmetric matrix with upper triangular entries distributed\n% independently following a normal distribution (Gaussian, zero mean, unit\n% variance).\n%\n% By default, N = 1.\n%\n% See also: randrot randsym randskewh\n\n% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Sept. 25, 2012.\n% Contributors: \n% Change log: \n% June 19, 2019 (NB):\n% Now handles the case n = 1 properly.\n\n if nargin < 2\n N = 1;\n end\n \n if n == 1\n S = zeros(1, 1, N);\n return;\n end\n\n % Subindices of the (strictly) upper triangular entries of an n-by-n\n % matrix\n [I, J] = find(triu(ones(n), 1));\n \n K = repmat(1:N, n*(n-1)/2, 1);\n \n % Indices of the strictly upper triangular entries of all N slices of\n % an n-by-n-by-N matrix\n L = sub2ind([n n N], repmat(I, N, 1), repmat(J, N, 1), K(:));\n \n % Allocate memory for N random skew matrices of size n-by-n and\n % populate each upper triangular entry with a random number following a\n % normal distribution and copy them with opposite sign on the\n % corresponding lower triangular side.\n S = zeros(n, n, N);\n S(L) = randn(size(L));\n S = S - multitransp(S);\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/rotations/randskew.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7171957205269479}} {"text": "function value = box_01_contains_point_nd ( dim_num, p )\n\n%*****************************************************************************80\n%\n%% BOX_01_CONTAINS_POINT_ND determines if a point is inside a unit box in ND.\n%\n% Discussion:\n%\n% A unit box is assumed to be a rectangle with sides aligned on coordinate\n% axes. It can be described by its low and high corner, P1 and P2:\n%\n% 0 <= P(1:DIM_NUM) <= 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 June 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, real P(DIM_NUM), the point to be checked.\n%\n% Output, logical VALUE, is TRUE if P is inside the box.\n%\n value = 0;\n\n for i = 1 : dim_num\n if ( p(i) < 0.0 | 1.0 < p(i) )\n return\n end\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/geometry/box_01_contains_point_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7171957062872584}} {"text": "function [mu,P,w,cost]=kMeanspp(z,K,maxIter)\n%%KMEANSPP Run the k-means++ algorithm for clustering a set of more than K\n% data points into k clusters. The k-means++ algorithm is the\n% same as the general k-means algorithm, except a different\n% initialization routine is used.\n%\n%INPUTS: z A zDim X numPoints set of vectors that are to be clustered.\n% K The number of clusters to form. K>=numPoints.\n% maxIter The maximum number of iterations to perform for clustering. If\n% omitted, maxIter=1000;\n%\n%OUTPUTS: mu A zDim X K set of the cluster means. \n% P A zDim X zDim X K set of sample covariance matrices for each\n% of the k clusters, where mu(:,n) is the mean of the nth\n% cluster.\n% w A KX1 vector of weights such that w(n) is the fraction of the\n% total original points assigned to the nth cluster.\n% cost The cost of the k-means assignment. This is the sum of the\n% squared distances between the points assigned to a cluster and\n% the cluster mean.\n%\n%The k-means algorithm is a suboptimal algorithm that tries to find a set\n%of k-means such that the sum of the squared distances from the points to\n%the closest means is minimized. The implementation here uses a better\n%initialization the k-means++ initialization from [1], which improves the\n%probability that the algorithm will converge to a good solution.\n%\n%Note that the k-means algorithm used a randomized initialization, so one\n%will not always get the same results when the function is run twice on the\n%same data.\n%\n%REFERENCES:\n%[1] D. Arthur and S. Vassilvitskii, \"k-means++: The advantages of careful\n% seeding,\" in Proceedings of the Eighteenth Annual ACM-SIAM Symposium\n% on Discrete Algorithms, New Orleans, LA, Jan. 2007, pp. 1027-1035.\n%\n%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<3)\n maxIter=1000; \nend\n\n%This uses the k-mean++ initalization algorithm on the given data.\n%K is the number of clusters to form.\n\nzDim=size(z,1);\nnumPoints=size(z,2);\n\nmu=zeros(zDim,K);\n\n%Use k-mean++ initialization.\n%The first center is chosen randomly.\nmu(:,1)=z(:,randi([1;numPoints]));\ndiff=mu(:,1)*ones(1,numPoints)-z;\nnearestMuDist=sum(diff.*diff,1);%The squared distances from this point.\n\nfor k=2:K\n %The points are chosen with a probability equal to the ratio of the\n %squared distance to the sum of all distances.\n PMF=nearestMuDist/sum(nearestMuDist);%The PMF from which we will draw.\n CMF=cumsum(PMF);\n \n %We have to find the first element in the CMF that is greater than a\n %random draw; that will be the next center.\n idx=sum(CMF1)\n w=zeros(K,1);\n P=zeros(zDim,zDim,K);\n for k=1:K\n sel=selClust==k;\n w(k)=sum(sel);\n\n zSel=z(:,sel);\n\n diff=bsxfun(@minus,zSel,mu(:,k)); \n P(:,:,k)=diff*diff'/w(k);\n end\n w=w/sum(w);\n\n cost=sum(minCosts)/numPoints;\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/Clustering_and_Mixture_Reduction/kMeanspp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533088603708, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7171314217062369}} {"text": "function [R_ned_2_inert, ned_x, ned_y, ned_z] = computeNedFrame(ut, rVectECI, bodyInfo)\n %Source: https://en.wikipedia.org/wiki/North_east_down\n \n [phi, lambda, ~, ~, ~, ~, ~, ~, REci2Ecef] = getLatLongAltFromInertialVect(ut, rVectECI, bodyInfo);\n \n REcef2Ned = [-sin(phi)*cos(lambda), -sin(lambda), -cos(phi)*cos(lambda);\n -sin(phi)*sin(lambda), cos(lambda), -cos(phi)*sin(lambda);\n cos(phi), 0, -sin(phi)]';\n \n R_ned_2_inert = (REcef2Ned * REci2Ecef)';\n ned_x = R_ned_2_inert(:,1);\n ned_y = R_ned_2_inert(:,2);\n ned_z = R_ned_2_inert(:,3);\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/ksptot_lvd/steering/computeNedFrame.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572777975782054, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.7170845522022588}} {"text": "function a = stripe ( n )\n\n%*****************************************************************************80\n%\n%% STRIPE returns the STRIPE matrix.\n%\n% Example:\n%\n% N = 7\n%\n% 5 2 1 1 . . .\n% 2 6 3 1 1 . .\n% 1 3 6 3 1 1 .\n% 1 1 3 6 3 1 1\n% . 1 1 3 6 3 1\n% . . 1 1 3 6 2\n% . . . 1 1 2 5\n%\n% Properties:\n%\n% A is integral, therefore det ( A ) is integral, and \n% det ( A ) * inverse ( A ) is integral.\n%\n% A is symmetric: A' = A.\n%\n% A is banded, with bandwidth 7.\n%\n% A is centrosymmetric: A(I,J) = A(N+1-I,N+1-J).\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% 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% Input, integer N, the order of A.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n for i = 1 : n\n for j = 1 : n\n\n if ( j == i - 3 )\n a(i,j) = 1.0;\n elseif ( j == i - 2 )\n a(i,j) = 1.0;\n elseif ( j == i - 1 )\n if ( j == 1 | j == n - 1 )\n a(i,j) = 2.0;\n else\n a(i,j) = 3.0;\n end\n elseif ( j == i )\n if ( i == 1 | i == n )\n a(i,j) = 5.0;\n else\n a(i,j) = 6.0;\n end\n elseif ( j == i + 1 )\n if ( j == 2 | j == n )\n a(i,j) = 2.0;\n else\n a(i,j) = 3.0;\n end\n elseif ( j == i + 2 )\n a(i,j) = 1.0;\n elseif ( j == i + 3 )\n a(i,j) = 1.0;\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/stripe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7170595419151116}} {"text": "clear; clc;\n% P2.5\nn = 0:10;\nx = 10*exp(-j*0.4*pi*n);\n[xe, xo, m] = evenoddcomplex(x,n);\nsubplot(3,2,1); stem(n,real(x),'ko'); title('Real Original Sequence')\nxlabel('n'); ylabel('x(n)');\nsubplot(3,2,3); stem(m,real(xe),'ko'); title('Real Even Part')\nxlabel('n'); ylabel('xe(n)');\nsubplot(3,2,5); stem(m,real(xo),'ko'); title('Real Odd Part')\nxlabel('n'); ylabel('xo(n)');\nsubplot(3,2,2); stem(n,imag(x),'ko'); title('Imaginary Original Sequence')\nxlabel('n'); ylabel('x(n)');\nsubplot(3,2,4); stem(m,imag(xe),'ko'); title('Imaginary Even Part')\nxlabel('n'); ylabel('xe(n)');\nsubplot(3,2,6); stem(m,imag(xo),'ko'); title('Imaginary Odd Part')\nxlabel('n'); ylabel('xo(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/16323-ingle-proakis-chapter-2-solutions/P205.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7170046247497203}} {"text": "function [xp,dxpdom,dxpdT,dxpdf,dxpdc,dxpdk,dxpdalpha] = project_points_fisheye(X,om,T,f,c,k,alpha)\n\n%project_points2.m\n%\n%[xp,dxpdom,dxpdT,dxpdf,dxpdc,dxpdk] = project_points_fisheye(X,om,T,f,c,k,alpha)\n%\n%Projects a 3D structure onto the image plane of a fisheye camera.\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 fisheye coefficients (5x1 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)x5 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%call theta = atan(r),\n%Fisheye distortion -> theta_d = theta * (1 + k(1)*theta^2 + k(2)*theta^4 + k(3)*theta^6 + k(4)*theta^8)\n%\n%The distorted point coordinates are: xd = [xx;yy] where:\n%\n%xx = (theta_d / r) * x\n%yy = (theta_d / r) * y\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\nif nargin < 7,\n alpha = 0;\n if nargin < 6,\n k = zeros(4,1);\n if nargin < 5,\n c = zeros(2,1);\n if nargin < 4,\n f = ones(2,1);\n if nargin < 3,\n T = zeros(3,1);\n if nargin < 2,\n om = zeros(3,1);\n if nargin < 1,\n error('Need at least a 3D structure to project (in project_points.m)');\n return;\n end;\n end;\n end;\n end;\n end;\n end;\nend;\n\n[m,n] = size(X);\n\nif nargout > 1,\n [Y,dYdom,dYdT] = rigid_motion(X,om,T);\nelse\n Y = rigid_motion(X,om,T);\nend;\n\ninv_Z = 1./Y(3,:);\n\nx = (Y(1:2,:) .* (ones(2,1) * inv_Z)) ;\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% Add fisheye 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% Radial distance:\nr = sqrt(r2);\nif nargout > 1,\n drdr2 = ones(1,length(r));\n drdr2(r>1e-8) = 1 ./ (2*r(r>1e-8));\n\n drdom = [ (drdr2').*dr2dom(:,1) (drdr2').*dr2dom(:,2) (drdr2').*dr2dom(:,3) ];\n drdT = [ (drdr2').*dr2dT(:,1) (drdr2').*dr2dT(:,2) (drdr2').*dr2dT(:,3) ];\nend;\n\n% Angle of the incoming ray:\ntheta = atan(r);\nif nargout > 1,\n dthetadr = 1 ./ (1 + r2);\n\n dthetadom = [ (dthetadr').*drdom(:,1) (dthetadr').*drdom(:,2) (dthetadr').*drdom(:,3) ];\n dthetadT = [ (dthetadr').*drdT(:,1) (dthetadr').*drdT(:,2) (dthetadr').*drdT(:,3) ];\nend;\n\n% Add the fisheye distortion:\n\ntheta2 = theta.^2;\ntheta3 = theta2.*theta;\ntheta4 = theta2.^2;\ntheta5 = theta4.*theta;\ntheta6 = theta3.^2;\ntheta7 = theta6.*theta;\ntheta8 = theta4.*theta4;\ntheta9 = theta8.*theta;\n\n% Fisheye distortion -> theta_d = theta * (1 + k(1)*theta2 + k(2)*theta4 + k(3)*theta6 + k(4)*theta8)\n\ntheta_d = theta + k(1)*theta3 + k(2)*theta5 + k(3)*theta7 + k(4)*theta9;\n\nif nargout > 1,\n dtheta_ddtheta = 1 + 3*k(1)*theta2 + 5*k(2)*theta4 + 7*k(3)*theta6 + 9*k(4)*theta8;\n dtheta_ddom = [ (dtheta_ddtheta').*dthetadom(:,1) (dtheta_ddtheta').*dthetadom(:,2) (dtheta_ddtheta').*dthetadom(:,3) ];\n dtheta_ddT = [ (dtheta_ddtheta').*dthetadT(:,1) (dtheta_ddtheta').*dthetadT(:,2) (dtheta_ddtheta').*dthetadT(:,3) ];\n dtheta_ddk = [theta3' theta5' theta7' theta9'];\nend;\n\n% ratio:\ninv_r = ones(1,length(r));\ninv_r(r>1e-8) = 1./r(r>1e-8);\n\ncdist = ones(1,length(r));\ncdist(r > 1e-8) = theta_d(r > 1e-8) ./ r(r > 1e-8);\n\nif nargout > 1,\n dcdistdom = [ ((inv_r').*(dtheta_ddom(:,1) - (cdist').*drdom(:,1))) ((inv_r').*(dtheta_ddom(:,2) - (cdist').*drdom(:,2))) ((inv_r').*(dtheta_ddom(:,3) - (cdist').*drdom(:,3))) ];\n dcdistdT = [ ((inv_r').*(dtheta_ddT(:,1) - (cdist').*drdT(:,1))) ((inv_r').*(dtheta_ddT(:,2) - (cdist').*drdT(:,2))) ((inv_r').*(dtheta_ddT(:,3) - (cdist').*drdT(:,3))) ];\n dcdistdk = [ (inv_r'.*dtheta_ddk(:,1)) (inv_r'.*dtheta_ddk(:,2)) (inv_r'.*dtheta_ddk(:,3)) (inv_r'.*dtheta_ddk(:,4)) ];\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,4);\n dxd1dk(1:2:end,:) = (x(1,:)'*ones(1,4)) .* dcdistdk;\n dxd1dk(2:2:end,:) = (x(2,:)'*ones(1,4)) .* dcdistdk;\nend;\n\n% No tangential distortion:\nxd2 = xd1;\nif nargout > 1,\n dxd2dom = dxd1dom;\n dxd2dT = dxd1dT;\n dxd2dk = dxd1dk;\nend;\n\n% Add Skew:\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,4);\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% 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,4)) .* 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\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(4,1);\nalpha = 0.01*randn(1,1);\n\n[x,dxdom,dxdT,dxdf,dxdc,dxdk,dxdalpha] = project_points_fisheye(X,om,T,f,c,k,alpha);\n\n\n% Test on om: not OK\n\ndom = 0.00000000001 * norm(om)*randn(3,1);\nom2 = om + dom;\n\n[x2] = project_points_fisheye(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: not OK\n\ndT = 0.0001 * norm(T)*randn(3,1);\nT2 = T + dT;\n\n[x2] = project_points_fisheye(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_points_fisheye(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_points_fisheye(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.00001 * norm(k)*randn(4,1);\nk2 = k + dk;\n\n[x2] = project_points_fisheye(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_points_fisheye(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": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/toolbox_calib/project_points_fisheye.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7170046129351503}} {"text": "function [phi, theta, psi] = rotMatXYZ2Eul(rotMat)\n % Function to convert rotation matrix to Euler angles (extrinsic x-y-z convention).\n % Used in yaw to convert between global and local reference frames.\n %\n % Parameters\n % ------------\n % rotMat : float array [3,3]\n % Rotational matrix to transform vectors to the new frame\n %\n % Returns\n % ------------\n % phi : float [rad]\n % Angle of rotation about the x-axis\n % theta : float [rad]\n % Angle of rotation about the y-axis\n % psi : float [rad]\n % Angle of rotation about the z-axis\n \n phi = atan2(-rotMat(2,3), rotMat(3,3));\n theta = asin(rotMat(1,3));\n psi = atan2(-rotMat(1,2), rotMat(1,1));\nend\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/functions/coordTransformation/rotMatXYZ2Eul.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7169441151914058}} {"text": "%% Equation: Poisson Equation Discretized by $BDM_1$ Element in 2D\n% We explain the assembling of the matrix equation for the lowest order BDM element\n% discretization of Poisson equation. \n%\n% [u,sigma] = PoissonBDM1(node,elem,bdEdge,f,g_D,varargin)\n%\n% Created by Ming Wang at Jan 2. 2011.\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details. \n\n%% Data Structure\n% [elem2dof,dofSign,edge] = dofRT0(elem);\n%\n% will construct local to global index map; see ifem dofBDM1doc for\n% details.\n%\n%% Local Bases\n% Suppose [i,j] is the k-th edge. The hierarchic basis along with\n% their div are given by\n% \n% $$ \\phi_k = \\lambda_i rot \\lambda_j - \\lambda_j rot \\lambda_i,\\quad\n% \\psi_k = \\lambda_i rot \\lambda_j + \\lambda_j rot \\lambda_i. $$\n%\n% $$ div \\phi_k = 2 \\nabla \\lambda_i \\cdot rot \\lambda_j, \\quad div \\psi_k = 0.$$\n%\n% Inside one triangular, the 6 bases functions along with their div\n% corresponding to 3 local edges [2 3; 3 1; 1 2] are:\n%\n% $$ \\phi_1 = \\lambda_2 rot \\lambda_3 - \\lambda_3 rot \\lambda_2,\\quad\n% \\psi_1 = \\lambda_2 rot \\lambda_3 + \\lambda_3 rot \\lambda_2,\\quad\n% div\\phi_1 = 2 \\nabla \\lambda_2 \\cdot rot \\lambda_3, \\quad div \\psi_1 = 0. $$\n%\n% $$ \\phi_2 = \\lambda_3 rot \\lambda_1 - \\lambda_1 rot \\lambda_3,\\quad\n% \\psi_2 = \\lambda_3 rot \\lambda_1 + \\lambda_1 rot \\lambda_3,\\quad\n% div\\phi_2 = 2 \\nabla \\lambda_3 \\cdot rot \\lambda_1, \\quad div \\psi_2 = 0. $$\n%\n% $$ \\phi_3 = \\lambda_1 rot \\lambda_2 - \\lambda_2 rot \\lambda_1,\\quad\n% \\psi_3 = \\lambda_1 rot \\lambda_2 + \\lambda_2 rot \\lambda_1,\\quad\n% div\\phi_3 = 2 \\nabla \\lambda_1 \\cdot rot \\lambda_2, \\quad div \\psi_3 = 0. $$\n%\n% Locally, we order the local bases in the following way: \n% \n% $$\\{\\phi_1,~\\,\\phi_2,~\\,\\phi_3,~\\,\\psi_1,~\\,\\psi_2,~\\, \\psi_3.\\}$$\n%\n% Note that $RT_0 \\subset BDM_1$, and $\\{ \\phi_1,~\\,\\phi_2,~\\,\\phi_3 \\}$ is the \n% local bases for $RT_0$.\n%\n% Because of the different oritentation of local and global faces, from\n% local bases to the global one, the direction should be corrected. That is\n%\n% phiGlobal(elem2dof(t,1),:) = phi(t,1)*dofSign(t,1);\n\n%% Mass Matrix\n% We use the integral formula \n% \n% $$ \\int_T\n% \\lambda_1^{\\alpha_1}\\lambda_2^{\\alpha_2}\\lambda_3^{\\alpha_3}\n% dx = \\frac{\\alpha_1!\\alpha_2!\\alpha_3!2!}{(\\sum _{i=1}^3\\alpha_i\n% + 2)!}\\;|T|,$$\n%\n% to get \n%\n% $$ \\int _T\\lambda_i\\lambda_j dx = (1+(i==j))|T|/12. $$\n%\n% For two local bases $\\phi_i$ and $\\phi_j$ corresponding to the ith and\n% jth local edges, suppose i = [i1 i2], j = [j1 j2].\n% $$\\int_T \\phi_i \\phi_j dx = \\int_T (\n% \\lambda_{i1} rot \\lambda_{i2}\\cdot\\lambda_{j1} rot \\lambda_{j2}\n% -\\lambda_{i2} rot \\lambda_{i1}\\cdot\\lambda_{j1} rot \\lambda_{j2}\n% -\\lambda_{i1} rot \\lambda_{i2}\\cdot\\lambda_{j2} rot \\lambda_{j1}\n% +\\lambda_{i2} rot \\lambda_{i1}\\cdot\\lambda_{j2} rot \\lambda_{j1})dx\n% $$\n%\n% $\\int_T \\psi_i \\psi_j dx$ and $\\int_T \\psi_i \\phi_j dx$ can be computed similarly.\n%\n%% Matrix for Differential Operator\n% Note that $\\nabla \\cdot \\psi = 0$, We only need to record $\\nabla \\cdot \\phi_i$ and \n% then the computation $\\int _T \\nabla\n% \\cdot \\phi_i dx$ is straightforward. Just remember to correct the direction.\n\n%% Right hand side\n% We use 5-points quadrature which is exact for cubic polynomials. In the\n% barycentric coordinate, the 5-points are\n%\n% $$ p_1 = [2/3, 1/6, 1/6], \\quad w_1 = 1/3 $$\n%\n% $$ p_2 = [1/6, 2/3, 1/6], \\quad w_2 = 1/3 $$\n%\n% $$ p_3 = [1/6, 1/6, 2/3], \\quad w_3 = 1/3 $$\n%\n%%\n% Note that the two for loops are nested in such a way that the point pxy\n% and the evulation Jp is just computed once.\n%\n% The local to global assembling is computed using accumarray\n%\n% b = accumarray(elem2dof(:),bt(:),[Ndof 1]);\n\n\n\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/iFEM/doc/PoissonBDM1doc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7169441145101783}} {"text": "function [x C d] = project_affine(v, A, b, C, d)\n% PROJECT_AFFINE Project a point into an affine set.\n%\n% project_affine(v,A,b) is the projection of v onto\n% the affine set { x | Ax = b }.\n%\n% You can also call the function as\n%\n% [x C d] = project_affine(v,A,b);\n%\n% and then call it again with different argument v2 via\n%\n% x2 = project_affine(v2,A,b,C,d);\n%\n% If calling the function repeatedly with the same A and b,\n% all evaluations after the initial one will be much faster\n% when passing in the cached values C and d.\n\n if exist('C','var') && ~isempty(C) && exist('d','var') && ~isempty(d)\n x = C*v + d;\n else\n % x = v - pinv(A)*(A*v - b);\n pA = pinv(A);\n C = eye(length(v)) - pA*A;\n d = pA*b;\n x = C*v + d;\n end\nend\n", "meta": {"author": "cvxgrp", "repo": "proximal", "sha": "736f2c48bdb1d8ac4fc325d529ea85be2a3d7f8b", "save_path": "github-repos/MATLAB/cvxgrp-proximal", "path": "github-repos/MATLAB/cvxgrp-proximal/proximal-736f2c48bdb1d8ac4fc325d529ea85be2a3d7f8b/matlab/project_affine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.716930205431941}} {"text": "function x_opt = coordinate_search ( x, function_handle, flag )\n\n%*****************************************************************************80\n%\n%% COORDINATE_SEARCH carries out a direct search minimization algorithm.\n%\n% Discussion:\n%\n% This function implements a direct search algorithm, to seek a \n% multidimensional point X_OPT which minimizes a scalar function F(X).\n%\n% The function is currently set up for coordinate search by\n% using a default stencil along coordinate axes. The stencil and the\n% initial size of the stencil (delta) should probably be input parameters.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 January 2009\n%\n% Author:\n%\n% Jeff Borggaard\n%\n% Parameters:\n%\n% Input, real X(N_VAR), a starting estimate for the minimizer.\n%\n% Input, function handle FUNCTION_HANDLE ( X ), ...\n%\n% Optional input, integer FLAG, selects features of the algorithm.\n% If FLAG is not input, it defaults to the value 0.\n% 0, do not include graphical displays.\n% nonzero, display the status of the search graphically.\n% 3, use the water stick stencil.\n%\n% Output, real X_OPT(N_VAR), the estimated minimizer.\n%\n% Local Parameters:\n%\n% Local, real DELTA, the initial size of the stencil.\n%\n% Local, real TOLERANCE, a tolerance for the variation between the maximum\n% and minimum values of F in the stencil.\n%\n% Local, integer MAX_FEVAL, the maximum number of function evaluations.\n%\n delta = 1.0;\n tolerance = 1.0E-06;\n max_feval = 250;\n verbose = 0;\n%\n% The default value of FLAG is 0.\n%\n if ( nargin <= 2 )\n flag = 0;\n end\n\n x = x(:)';\n n_var = length(x);\n%\n% Define the search stencil\n%\n if ( flag ~= 3 )\n\n for i = 1 : n_var\n stencil(2*i-1).v = zeros(size(x));\n stencil(2*i-1).v(i) = 1;\n stencil(2*i ).v = zeros(size(x));\n stencil(2*i ).v(i) =-1;\n end\n\n else\n\n stencil(1).v = [ 1 0 ];\n stencil(2).v = [ -1/2 sqrt(3)/2 ];\n stencil(3).v = [ -1/2 -sqrt(3)/2 ];\n\n end\n \n n_sten = length ( stencil );\n%\n% Compute the function value at the initial point.\n%\n f = feval ( function_handle, x );\n n_feval = 1;\n \n if ( flag )\n xp = linspace ( -5.0, 5.0, 101 );\n yp = xp;\n for i=1:101\n for j=1:101\n fp(j,i) = feval(function_handle,[xp(i),yp(j)]);\n end\n end\n \n figure(27)\n hold on\n contour(xp,yp,fp,linspace(0,200,25))\n end\n%\n% Begin the Direct Search iteration.\n% \n while ( 1 )\n \n x_s = compute_points ( x, stencil, delta );\n%\n% Plot the current search pattern.\n%\n if ( flag )\n for i=1:n_sten\n plot([x(1) x_s(i,1)],[x(2) x_s(i,2)],'r')\n plot(x_s(i,1),x_s(i,2),'r*')\n end\n end\n\n f_s = evaluate ( x_s, function_handle );\n n_feval = n_feval + n_sten;\n%\n% \"erase\" the current search pattern after it has been considered\n%\n if ( flag ) \n \n for i = 1 : n_sten\n plot ( [x(1) x_s(i,1)],[x(2) x_s(i,2)],'b')\n plot ( x_s(i,1),x_s(i,2),'b*')\n end\n end\n% \n% Find the element in the pattern with the lowest function value.\n%\n [ fc_min, i_min ] = min ( f_s );\n [ fc_max ] = max ( f_s ); \n%\n% If we found a lower value, move to that location.\n%\n if ( fc_min < f )\n\n xb = x_s(i_min,:);\n shift = xb - x;\n \n x = xb;\n f = fc_min;\n \n for i = 1 : n_sten\n x_s(i,:) = x_s(i,:) + shift;\n end\n%\n% Otherwise, shrink the pattern about the center and recalculate the stencil.\n%\n else\n delta = delta / 2.0;\n x_s = compute_points ( x, stencil, delta );\n end\n%\n% Test whether we should continue.\n% \n converged = ( fc_max - fc_min < tolerance ) || ( delta < tolerance );\n\n if ( converged )\n break\n end\n \n diverged = ( max_feval < n_feval );\n \n if ( diverged )\n break\n end\n\n end\n\n if ( verbose )\n fprintf ( 'The best point x^* was: %d %d\\n', x(1,:) );\n fprintf ( 'f(x^*) = %d\\n', f(1) );\n end\n\n x_opt = x(1,:);\n\n if ( verbose )\n fprintf ( 'The algorithm terminated after %d function evaluations\\n',...\n n_feval);\n end\n\n if ( diverged )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Convergence was not achieved.\\n' );\n fprintf ( 1, ' The iteration limit of %d was exceeded.\\n', max_feval );\n end\n\n return\nend\nfunction f = evaluate ( x, function_handle )\n\n%*****************************************************************************80\n%\n%% EVALUATE evaluates the function at the stencil points.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 January 2009\n%\n% Author:\n%\n% Jeff Borggaard\n%\n% Parameters:\n%\n% Input, real X(N_STEN,N_VAR), a set of N_STEN points, each of\n% dimension N_VAR.\n%\n% Input, f = FUNCTION_HANDLE ( x ), the handle of a function which\n% accepts as input a vector X and returns the scalar function value F.\n%\n% Output, real F(N_STEN), the function evaluated at each of the points.\n%\n [ n_sten, n_var ] = size ( x );\n\n f = zeros ( 1, n_sten );\n \n for i = 1 : n_sten\n f(i) = feval ( function_handle, x(i,:) );\n end\n\n return\nend\nfunction x_s = compute_points ( x, stencil, delta )\n\n%*****************************************************************************80\n%\n%% COMPUTE_POINTS computes all of the points in the stencil.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 January 2009\n%\n% Author:\n%\n% Jeff Borggaard\n%\n% Parameters:\n%\n% Input, real X(N_VAR), the center of the stencil.\n%\n% Input, real STENCIL, a structure describing the stencil.\n%\n% Input, real DELTA, determines the geometric size of the stencil.\n%\n% Output, real X_S(N_STEN,N_VAR), the stencil points.\n%\n n_var = length(x);\n n_sten = length(stencil);\n\n x_s = zeros ( n_sten, n_var );\n \n for i = 1 : n_sten\n x_s(i,:) = x + delta * stencil(i).v;\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/coordinate_search/coordinate_search.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7169209500474215}} {"text": "function pts = cuboid_prm2pts(prm, vp)\n% converts five parameters of cuboid to eight 2D points\n%\n% prm: [x, y, w, h, d]\n% x,y: 2D coordinates of corner1 (top,left,front corner)\n% w: length (in pixels) from corner1 to corner2\n% h: length (in pixels) from corner1 to corner3\n% d: length (in pixels) from corner1 to corner5\n%\n% pts: [8 x 2] 2D coordinates of eight points on cuboid\n% 5---6 1------2\n% / /| | |\n% 1---2 8 3------4 ....\n% | |/ \\ /\n% 3---4 7--8\n%\n% 1: front,top,left\n% 2: front,top,right\n% ...\n% 8: back,bottom,right\n\npts = zeros(8,2);\n\npts(1,:) = [prm(1) prm(2)];\npts(2,:) = towardsright(pts(1,:), vp, prm(3));\npts(3,:) = towardsdown(pts(1,:), vp, prm(4));\npts(5,:) = towardsback(pts(1,:), vp, prm(5));\npts(4,:) = line_intersect(pts(2,:), vp{1}, pts(3,:), vp{2});\npts(6,:) = line_intersect(pts(2,:), vp{3}, pts(5,:), vp{2});\npts(7,:) = line_intersect(pts(3,:), vp{3}, pts(5,:), vp{1});\npts(8,:) = mean(...\n [line_intersect(pts(4,:), vp{3}, pts(6,:), vp{1}); ...\n line_intersect(pts(7,:), vp{2}, pts(6,:), vp{1}); ...\n line_intersect(pts(4,:), vp{3}, pts(7,:), vp{2})], 1);\n\n", "meta": {"author": "zouchuhang", "repo": "LayoutNet", "sha": "95293bfb8ff787dd3b02c8a52a147a703024980f", "save_path": "github-repos/MATLAB/zouchuhang-LayoutNet", "path": "github-repos/MATLAB/zouchuhang-LayoutNet/LayoutNet-95293bfb8ff787dd3b02c8a52a147a703024980f/matlab/panoContext_code/Toolbox/VP/genobjhyp/cuboid_prm2pts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9496693702514737, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7169196349355255}} {"text": "function [U S V info] = truncated_svd(A, p)\n% Returns an SVD decomposition of A truncated to rank p.\n%\n% function [U S V] = truncated_svd(A, p)\n%\n% Input: A real matrix A of size mxn and an integer p <= min(m, n).\n% Output: An orthonormal matrix U of size mxp, an orthonormal matrix Y of\n% size nxp and a diagonal matrix S of size pxp with nonnegative and\n% decreasing diagonal entries such that USV.' is the best rank p\n% approximation of A according to the Frobenius norm. All real.\n% This function produces an output akin to svds.\n% \n% The decomposition is obtained by maximizing\n% f(U, V) = .5*norm(U'*A*V, 'fro')^2\n% where U, V are orthonormal. Notice that f(U*Q, V*R) = f(U, V) for all\n% Q, R orthogonal pxp matrices. Hence, only the column spaces of U and V\n% matter and we may perform the optimization over a product of two\n% Grassmannian manifolds.\n%\n% It is easy to show that maximizing f is equivalent to minimizing g with\n% g(U, V) = min_S norm(U*S*V' - A, 'fro')^2,\n% which confirms that we are going for a best low-rank approximation of A.\n% \n% The inner workings of the Grassmann manifold use the built-in svd\n% function of Matlab but only for matrices of size mxp and nxp to\n% re-orthonormalize them.\n% \n% Notice that we are actually chasing a best fixed-rank approximation of a\n% matrix, which is best obtained by working directly over a manifold of\n% fixed-rank matrices. This is simply an example script to demonstrate some\n% functionalities of the toolbox.\n% \n% The code can be modified to accept a function handle for A(x) = A*x\n% instead of a matrix A, which is often useful. This would further require\n% a function handle At for the transpose of A, such that At(x) = A.'*x.\n\n% This file is part of Manopt and is copyrighted. See the license file.\n% \n% Main author: Nicolas Boumal, July 5, 2013\n% Contributors:\n% \n% Change log:\n% \n\n \n % Generate some random data to test the function if none is given.\n if ~exist('A', 'var') || isempty(A)\n A = randn(42, 60);\n end\n if ~exist('p', 'var') || isempty(p)\n p = 5;\n end\n \n % Retrieve the size of the problem and make sure the requested\n % approximation rank is at most the maximum possible rank.\n [m n] = size(A);\n assert(p <= min(m, n), 'p must be smaller than the smallest dimension of A.');\n \n % Define the cost and its derivatives on the Grassmann manifold\n tuple.U = grassmannfactory(m, p);\n tuple.V = grassmannfactory(n, p);\n % All of the code will work just as well if we ignore the invariance\n % property of the cost function indicated above and thus place U and V\n % on the Stiefel manifold (orthonormal matrices) instead of the\n % Grassmann manifold. Working on Stiefel is expected to be slower\n % though, partly because de search space is higher dimensional and\n % partly because the optimizers are not isolated.\n % tuple.U = stiefelfactory(m, p);\n % tuple.V = stiefelfactory(n, p);\n M = productmanifold(tuple);\n \n % Define a problem structure, specifying the manifold M, the cost\n % function and its derivatives. Here, to demonstrate the rapid\n % prototyping capabilities of Manopt, we directly define the Euclidean\n % gradient and the Euclidean Hessian egrad and ehess instead of the\n % Riemannian gradient and Hessian grad and hess. Manopt will take care\n % of the conversion. This automatic conversion is usually not\n % computationally optimal though, because much of the computations\n % involved in obtaining the gradient could be reused to obtain the\n % Hessian. After the prototyping stage, when efficiency becomes\n % important, it makes sense to define grad and hess rather than egrad\n % an ehess, and to use the caching system (the store structure).\n problem.M = M;\n problem.cost = @cost;\n problem.egrad = @egrad;\n problem.ehess = @ehess;\n \n % The functions below make many redundant computations. This\n % performance hit can be alleviated by using the caching system.\n \n % Cost function\n function f = cost(X)\n U = X.U;\n V = X.V;\n f = -.5*norm(U'*A*V, 'fro')^2;\n end\n % Euclidean gradient of the cost function\n function g = egrad(X)\n U = X.U;\n V = X.V;\n AV = A*V;\n AtU = A'*U;\n g.U = -AV*(AV'*U);\n g.V = -AtU*(AtU'*V);\n end\n % Euclidean Hessian of the cost function\n function h = ehess(X, H)\n U = X.U;\n V = X.V;\n Udot = H.U;\n Vdot = H.V;\n AV = A*V;\n AtU = A'*U;\n AVdot = A*Vdot;\n AtUdot = A'*Udot;\n h.U = -(AVdot*AV'*U + AV*AVdot'*U + AV*AV'*Udot);\n h.V = -(AtUdot*AtU'*V + AtU*AtUdot'*V + AtU*AtU'*Vdot);\n end\n \n \n % Execute some checks on the derivatives for early debugging.\n % These things can be commented out of course.\n checkgradient(problem);\n pause;\n checkhessian(problem);\n pause;\n \n % Issue a call to a solver. A random initial guess will be chosen and\n % default options are selected. Here, we specify a maximum trust\n % region radius (which in turn induces an initial trust region radius).\n % Note that this is not required: default values are used if we omit\n % this. The diameter of the manifold scales like sqrt(2*p), hence the\n % form of our (empirical) choice.\n options.Delta_bar = 4*sqrt(2*p);\n [X Xcost info] = trustregions(problem, [], options); %#ok\n U = X.U;\n V = X.V;\n \n % Finish the job by rotating U and V such that the middle matrix S can\n % be diagonal with nonnegative, decreasing entries. This requires a\n % small svd of size pxp.\n Spp = U'*A*V;\n [Upp Spp Vpp] = svd(Spp);\n U = U*Upp;\n S = Spp;\n V = V*Vpp;\n \n % For our information, Manopt can also compute the spectrum of the\n % Riemannian Hessian on the tangent space at (any) X. Computing the\n % spectrum at the solution gives us some idea of the conditioning of\n % the problem. If we were to implement a preconditioner for the\n % Hessian, this would also inform us on its performance.\n %\n % Notice that if the optimization is performed on a product of Stiefel\n % manifolds instead of a product of Grassmannians, the double\n % invariance under the orthogonal group O(p) will appear as twice\n % p*(p-1)/2, thus p*(p-1) zero eigenvalues in the spectrum of the\n % Hessian. This means that the minimizers are not isolated, which\n % typically hinders convergence of second order algorithms.\n if M.dim() < 512\n evs = hessianspectrum(problem, X);\n stairs(sort(evs));\n title(['Eigenvalues of the Hessian of the cost function ' ...\n 'at the solution']);\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/examples/truncated_svd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7167886903603705}} {"text": "function variance = chi_square_noncentral_variance ( a, b )\n\n%*****************************************************************************80\n%\n%% CHI_SQUARE_NONCENTRAL_VARIANCE returns the variance of the noncentral Chi squared PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, the parameter of the PDF.\n% 1 <= A.\n%\n% Input, real B, the noncentrality parameter of the PDF.\n% 0.0 <= B.\n%\n% Output, real VARIANCE, the variance value.\n%\n variance = 2.0 * ( a + 2.0 * b );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/chi_square_noncentral_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7167886883813918}} {"text": "% DIAGPROD - Computes the diagonal elements of a matrix product.\n%\n% D = DIAGPROD(A,B)\n%\n% Evaluates diag(A*B') efficiently. A and B must have the same size.\n%\n% D = DIAGPROD(A)\n%\n% Evaluates diag(A*A') efficiently.\n\n% Last modified 2010-06-24\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)\n\nfunction d = diagprod(A,B)\n\nif nargin < 2\n d = dot(A,A,2);\nelse\n d = dot(A,B,2);\nend\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/matrix_computations/diagprod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8152324983301567, "lm_q1q2_score": 0.7167090208384266}} {"text": "function variance = gumbel_variance ( )\n\n%*****************************************************************************80\n%\n%% GUMBEL_VARIANCE returns the variance of the Gumbel PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real VARIANCE, the variance of the PDF.\n%\n variance = pi * pi / 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/prob/gumbel_variance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.716709016134781}} {"text": "function [v,g] = ctransform(x, u, y, p, epsilon)\n\n% ctransform - c-transform and gradient of semi-discrete energy\n%\n% [v,g] = ctransform(x,u, y, epsilon);\n%\n% u is sampled at points x. \n% v is u^c sampled at points y. \n%\n% x must be of size (dim,n)\n% y must be of size (dim,m)\n%\n% If epsilon==0\n% u^c(y) = min_x |x-y|^p-u(x)\n% else\n% u^c(y) = - epsilon * log( sum_x exp( (-|x-y|^p + u(x))/epsilon )\n%\n% The semi discrete energy between continuous measure a and discrete\n% measure b is\n% E(u) = int u^c(y) da(y) - \n% g(:,j) is the gradient of u -> u^c(y_j).\n%\n% Copyright (c) 2017 Gabriel Peyre\n\nif nargin<5\n epsilon = 0;\nend\n\nn = size(x,2);\nm = size(y,2);\n\nc = distmat(x,y).^p; % cost\nS = c - repmat(u(:), [1 m]);\n[v,I] = min(S);\nif epsilon>0\n % use soft-min, stabilized\n if 1\n S = S - repmat(v, [size(S,1) 1]);\n v = - epsilon * log( sum( exp( -S/epsilon ) ) ) + v;\n else\n v = - epsilon * log( sum( exp( -S/epsilon ) ) ); \n end\nend\nv = v(:);\n\nif nargout>1\n % compute also the gradient\n if epsilon==0\n % simply indicator function of the Laguerre cells, indicated by the index I\n g = sparse( I, 1:m, ones(m,1),n, m );\n else\n % smoothed-indicator\n g = exp( -S/epsilon );\n g = g ./ repmat( sum(g), [n 1] );\n end\n \nend\n\nend\n", "meta": {"author": "optimaltransport", "repo": "optimaltransport.github.io", "sha": "2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203", "save_path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io", "path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io/optimaltransport.github.io-2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203/code/semi-discrete-sgd/ctransform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303292, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.716667759327212}} {"text": "function h = p41_h ( n, x )\n\n%*****************************************************************************80\n%\n%% P41_H evaluates the Hessian for problem 41.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 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 h = zeros ( n, n );\n\n h(1,1) = 1200.0 * x(1)^2 - 400.0 * x(2) + 2.0;\n h(1,2) = - 400.0 * x(1);\n\n h(2,1) = -400.0 * x(1);\n h(2,2) = 220.2;\n h(2,4) = 19.8;\n\n h(3,3) = -360.0 * x(4) + 1080.0 * x(3)^2 + 2.0;\n h(3,4) = - 360.0 * x(3);\n\n h(4,2) = 19.8;\n h(4,3) = - 360.0 * x(3);\n h(4,4) = 200.2;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_opt/p41_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686199, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7166677577302462}} {"text": "function [mse, rmse] = RMSE2(signal1, signal2)\n\noriginalRowSize = size(signal1,1);\noriginalColSize = size(signal1,2);\n\nsignal1 = signal1(:);\nsignal2 = signal2(:);\n\nmse = sum((signal1 - signal2).^2)./(originalRowSize*originalColSize);\nrmse = sqrt(mse);\n\nend\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/29671-importance-of-image-phase-information-demo/RMSE2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.7166677416660578}} {"text": "function rms_x=rms(x)\n\n%Calculates RMS for x, NaN's are ignored\nx=x(~isnan(x)); %Removing nans\nrms_x=sqrt( sum(x.^2)./numel(x) );\n\n\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/rms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7166511399609048}} {"text": "function [beta_gibbs,sigma_gibbs]=ndgibbs(It,Bu,beta0,omega0,X,Y,y,Bhat,n,T,q)\n\n\n\n% function [beta_gibbs sigma_gibbs]=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\ninvomega0=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=invomega0+kron(invsigma,X'*X);\nC=chol(bear.nspd(invomegabar));\ninvC=C\\speye(q);\nomegabar=invC*invC';\n\n% following, obtain betabar\nbetabar=omegabar*(invomega0*beta0+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\nB=reshape(beta,size(B));\n\n% update progress by one iteration\nhbar.iterate(1); \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% 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/ndgibbs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7166097173353847}} {"text": "function [mWalkout, fR95, fProbR95, PHI, R] = calc_Schusterwalk(mCatalog)\n% function [mWalkout, fR95, fProbR95, PHI, R] = calc_Schusterwalk(mCatalog)\n% ------------------------------------------------------------------------\n% Calculate random walkout (Schuster's method). See Rydelek & Sacks, Nature\n% 1989. Shows phazor plot for one catalog.\n%\n% Incoming variables:\n% mCatalog : EQ catalog\n%\n% Outgoing variables:\n% mWalkout : Random walkout phases\n% fR95 : Critical radius at 95% level\n% fProbR95 : Probability to obtain vector of length >= R\n% PHI : Sum of phase angles\n% R : Possible sum of vector length\n%\n% J. Woessner, woessner@seismo.ifg.ethz.ch\n% last update: 12.02.03\n\n% Get hours and minutes, calculate minutes\nvH = mCatalog(:,8);\nvMin = mCatalog(:,9);\nvTime = vH*60+vMin;\n\n% Calculate degrees and radians\nvThetaDegree = vTime*180/720;\nvThetaRad = deg2rad(vThetaDegree);\n\nmWalkout(1,1)=0;\nmWalkout(1,2)=0;\nfor i=1:length(mCatalog(:,8))\n mWalkout(i+1,1)=mWalkout(i,1)+sin(vThetaRad(i));\n mWalkout(i+1,2)=mWalkout(i,2)+cos(vThetaRad(i));\nend\n\nA=sum(sin(vThetaRad));\nB=sum(cos(vThetaRad));\nR=sqrt(A^2+B^2);\nPHI=atan(B/A);\nif mWalkout(length(mCatalog(:,8)),2)<0\n PHI=PHI+pi;\nend\n\nN=length(mCatalog(:,8));\n% Critical radius at 95% level\nfR95=1.37*sqrt(N); %Nature 1989\n% Probability to obtain vector of length >= R\nfProbR95=exp(-R^2/N);\n\n\nfigure_w_normalized_uicontrolunits('tag','schuster')\n% Plot Schuster walkout\nplot(mWalkout(:,1),mWalkout(:,2));\nhold on;\npolar([0:360]*pi/180,ones(1,361)*fR95,'r');\n[x, y] =pol2cart(PHI,R);\nplot([0,x],[0 y],'g');\nplot ([0 0],[-1/5*fR95,1/5*fR95],'k');\nplot ([-1/5*fR95,1/5*fR95],[0 0],'k');\nhold off\ntext (0,2/5*fR95,'0:00','HorizontalAlignment','center');\ntext (2/5*fR95,0,'6:00','HorizontalAlignment','left');\ntext (0,-2/5*fR95,'12:00','HorizontalAlignment','center');\ntext (-2/5*fR95,0,'18:00','HorizontalAlignment','right');\ntext (0,fR95 ,'95KI','VerticalAlignment','bottom','HorizontalAlignment','center');\naxis equal;\n%xlim([-15 15])\n%ylim([-15 15])\ntext (-fR95,-fR95,num2str(length(mCatalog(:,8))));\n\nfigure_w_normalized_uicontrolunits('tag','schuster2')\n% Plot hourly histogram\nsubplot(2,1,1);\nvTime = (mCatalog(:,8)*60+mCatalog(:,9))/60; % Calculate decimal hour\nhistogram(vTime,0:1:24)\n% Plot FMD\nsubplot(2,1,2);\n[mFMDC, mFMD] = calc_FMD(mCatalog);\nplot(mFMDC(1,:),mFMDC(2,:),'ks',mFMD(1,:),mFMD(2,:),'k^');\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/jochen/plot/plot_Schusterwalk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.7166097097369556}} {"text": "% Data File DTXY3\n% Motion of a particle on a horizontal\n% plane under action of elastic and\n% resistance forces and force of \n% dry friction\n m = 'm'; % mass of the particle\n % Projections of forces on axis x and y\n Fx = '-c*x-k*xt - mu*m*9.81*xt/sqrt(xt^2+yt^2)';\n Fy = '-c*y-k*yt - mu*m*9.81*yt/sqrt(xt^2+yt^2)';\n x0 = '1'; % Initial\n y0 = '0'; % coordinates\n v0 = 'v0'; % Initial velocity\n alfa = 'alfa'; % angle between v0 and axis x\n Tend = 7; % upper bound of integration\n eps = 1e-10; % desirable accuracy\n np = 4; % number of parameters\n P{1} = 'm'; % mass of the particle\n P{2} = 'c'; % spring stiffness\n P{3} = 'k'; % coefficient of resistance\n P{4} = 'mu'; % coefficient of dry friction", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/6363-matlab-in-dynamics/Dinp_2004/DATA Files/DTXY3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566341975270266, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.7166024449957641}} {"text": "function d = sine_taper_scaled(n, k)\n\n% Compute Riedel & Sidorenko sine tapers.\n% sine_taper_scaled(n, k) produces the first 2*k tapers of length n,\n% returned as the columns of d. The norm of the tapers will not be 1. The\n% norm is a function of the number of the taper in the sequence. This is to\n% mimick behavior of the scaling of the resulting powerspectra prior to\n% april 29, 2011. Before april 29, 2011, equivalent scaling was applied to\n% the powerspectra of the tapered data segments, prior to averaging.\n\n% Copyright (C) 2006, Tom Holroyd\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%\n% $Id$\n\nif nargin < 2\n ft_error('usage: sine_taper_scaled(n, k)');\nend\n\nk = round(k * 2);\nif k <= 0 || k > n\n ft_error('sine_taper_scaled: k is %g, must be in (1:n)/2', k)\nend\n\nx = (1:k) .* (pi / (n + 1));\nd = sqrt(2 / (n + 1)) .* sin((1:n)' * x);\n\nscale = zeros(k);\nfor i = 1:k\n scale(i,i) = sqrt(1 - ((i-1)./(k-1)).^2);\nend\nd = d * scale;\n\nreturn\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/specest/private/sine_taper_scaled.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7165863009177921}} {"text": "function qUnNormalised = unnormaliseImagePoints(qNormalised,K,kc)\n%function to unnormalise a set of image points according to the perspective\n%intrinsic calibration matrix K and distortion parameters kc. This is the model\n%from Oulu university and described clearly in Bouguet's Matlab camera calibration toolbox\n% (http://www.vision.caltech.edu/bouguetj/calib_doc/). This is done using\n% code from Bouguet's toolbox.\n%\n%inputs:\n%q: a 2*N matrix of normalised points in an image.\n%\n%K: a 3x3 perspective intrinsic calibration matrix\n%\n%kc: a 5x1 vector of radial and tangential distortion coefficients.\n%\n%outputs:\n%qUnNormalised: the un-normalised points\n\n%first compensate for radial and tangential distortion:\nxn = qNormalised;\nx = xn(1,:);\ny = xn(2,:);\n\nr = sqrt(xn(1,:).^2 + xn(2,:).^2);\n\ndx(1,:) = 2*kc(3)*x.*y + kc(4)*(r.^2 + 2*x.^2);\ndx(2,:) = kc(3)*(r.^2 + 2*y.^2) + 2*kc(4)*x.*y;\n\n\ns = (1+kc(1)*r.^2 + kc(2)*r.^4 + kc(5)*r.^6);\nxd = [s;s].*xn + dx;\nxd(3,:) = 1;\n\n%now apply the intrinsic matrix\nqUnNormalised = K*xd;\nqUnNormalised(1,:) = qUnNormalised(1,:)./qUnNormalised(3,:);\nqUnNormalised(2,:) = qUnNormalised(2,:)./qUnNormalised(3,:);\nqUnNormalised = qUnNormalised(1:2,:);\n", "meta": {"author": "tobycollins", "repo": "IPPE", "sha": "3304dfa40c7cbd046ba0d540b8b1143283c83f4e", "save_path": "github-repos/MATLAB/tobycollins-IPPE", "path": "github-repos/MATLAB/tobycollins-IPPE/IPPE-3304dfa40c7cbd046ba0d540b8b1143283c83f4e/matlab/IPPE_utils/unnormaliseImagePoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361628580401, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.716543957374049}} {"text": "function [z phi]=sim_rbf(Xc,X,W,k_i,basisfunction)\n%simulates a radial basis function\n%Xc is a N_r by N_dim matrix of rbf centres\n%X is a N_p by N_dim matrix of the points to simulate\n%W is the weight vector\n%basisfunction may be 'gaussian' or 'polyharmonicspline'\n%k_i is a prescaler for 'gaussian' rbf and function order for\n%'polyharmonicspline'. See k_i(i)=0 for constant bias\n\n% Copyright Travis Wiens 2008\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% If you would like to request that this software be licensed under a less\n% restrictive license (i.e. for commercial closed-source use) please\n% contact Travis at travis.mlfx@nutaksas.com\n\nif nargin<4\n k_i=1;\nend\n\nif nargin<5\n basisfunction='gaussian';\nend\n\nN_r=size(Xc,1);%number of rbf centres\nN_p=size(X,1);%number of points\n\nif numel(k_i)==1\n k_i=k_i*ones(N_r);\nend\n\nphi=zeros(N_p,N_r);%rbf outputs\n\nfor i=1:N_r\n if k_i(i)==0\n phi(:,i)=1;\n else\n r=sqrt(sum((repmat(Xc(i,:),N_p,1)-X(:,:)).^2,2));%distance from point Xc to X\n\n switch basisfunction\n case {'gaussian','Gaussian'}\n phi(:,i)=exp(-k_i(i).*r.^2);\n case {'phs','polyharmonicspline'}\n if r==0\n phi(:,i)=0;\n else\n if round(k_i(i)/2)==k_i(i)/2%even\n phi(:,i)=r.^k_i(i).*log(r);\n phi(r==0,i)=0;%avoid log(0)\n else\n phi(:,i)=r.^k_i(i);\n end\n end\n otherwise\n error('unknown basis function')\n end\n end\nend\n\nz=phi*W;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22174-rbf-acoustic-tomography/rbf_tomo_1_01/sim_rbf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7165439417501562}} {"text": "function [mappedX, mapping] = landmark_isomap(X, no_dims, k, percentage)\n%ISOMAP Runs the Isomap algorithm\n%\n% [mappedX, mapping] = landmark_isomap(X, no_dims, k, percentage); \n%\n% The functions runs the Landmark Isomap algorithm on dataset X to reduce the\n% dimensionality of the dataset to no_dims. The number of neighbors used in\n% the compuations is set by k (default = 12). The variable percentage has to be\n% between 0 and 1, and determines the number of landmarks that is used (default = 0.1).\n%\n% If the neighborhood graph that is constructed is not completely\n% connected, only the largest connected component is embedded. The indices\n% of this component are returned in mapping.conn_comp.\n%\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n\n if ~exist('no_dims', 'var')\n no_dims = 2;\n end\n if ~exist('k', 'var')\n k = 12;\n end\n\tif ~exist('percentage', 'var')\n\t\tpercentage = 0.2;\n end\n\n % Construct neighborhood graph\n disp('Constructing neighborhood graph...'); \n D = find_nn(X, k);\n \n % Select largest connected component\n blocks = components(D)';\n count = zeros(1, max(blocks));\n for i=1:max(blocks)\n count(i) = length(find(blocks == i));\n end\n [count, block_no] = max(count);\n conn_comp = find(blocks == block_no); \n D = D(conn_comp, conn_comp);\n mapping.D = D;\n n = size(D, 1);\n\n % Compute shortest paths\n disp('Computing shortest paths...');\n landmarks = randperm(n);\n\tlandmarks = landmarks(1:round(percentage * n));\n nl = length(landmarks); \n D = dijkstra(D, landmarks);\n\tD = full(D)';\n mapping.DD = D;\n mapping.landmarks = landmarks;\n\n\t% Do not embed in more dimensions than (nl - 1)\n\tif no_dims > nl - 1\n\t\tno_dims = nl - 1;\n\t\twarning(['Target dimensionality reduced to ' num2str(no_dims) '...']);\n\tend\n \n % Performing MDS using eigenvector implementation\n disp('Constructing low-dimensional embedding...'); \n D = D .^ 2;\n subB = -.5 .* (bsxfun(@minus, bsxfun(@minus, D, sum(D, 2) ./ nl), sum(D, 1) ./ n) + sum(D(:)) ./ (n * nl));\n subB2 = subB' * subB;\n\tsubB2(isnan(subB2)) = 0;\n\tsubB2(isinf(subB2)) = 0;\n [alpha, beta] = eig(subB2);\n val = beta .^ (1 / 2);\n mapping.invVal = inv(val);\n vec = subB * alpha * mapping.invVal;\n\tif size(vec, 2) < no_dims\n\t\tno_dims = size(vec, 2);\n\t\twarning(['Target dimensionality reduced to ' num2str(no_dims) '...']);\n\tend\n\t\n % Computing final embedding\n [val, ind] = sort(real(diag(val)), 'descend'); \n vec = vec(:,ind(1:no_dims));\n val = val(1:no_dims);\n mappedX = real(bsxfun(@times, vec, sqrt(val)'));\n \n % Store data for out-of-sample extension\n mapping.conn_comp = conn_comp;\n mapping.k = k;\n mapping.X = X(conn_comp,:);\n mapping.alpha = alpha;\n mapping.beta = beta;\n mapping.no_dims = no_dims;\n \n ", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/landmark_isomap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7165285147539725}} {"text": "function [p,f,p1,f1]=optimitaestep(n)\n%OPTIMITAESTEP Calculate the optimal ITAE trasnfer function coefficient for a step input\n%\n% Usage:\n% [p,itae,p0,itae0] = optimitaestep(n) returns the optimal coefficients of a \n% nth-order transfer function based on the ITAE criterion for a step input.\n% Input: n - the order of transfer function\n% Output: p - the optimal coefficients of the nth-order transfer function\n% itae - the optimal ITAE criterion.\n% p0 - original coefficients derivided by Graham and Lathrop.\n% itae0 - the ITAE citerion correcponding to p0.\n%\n% Background:\n% The original ITAE (stands for Integral of Time multiplied by Absolute\n% Error) coefficient table was drived by D. Graham and R.C. Lathrop through \n% an analog computer. The table has been widely adopted as a standard in \n% most undergraduate level control engineering text books. However, the \n% optimality of these coefficients has been questioned by several researchers.\n% This code provides a means to re-calculate these coefficient using more\n% advanced numerical optimization techniques in digital computers.\n%\n% References:\n% 1. D. Graham and R.C. Lathrop, \"The Synthesis of Optimum Response: Criteria\n% ans Standard Forms, Part 2\", Transactions of the AIEE 72, Nov. 1953, pp. 273-288\n% 2. Y. Cao, \"Correcting the minimum ITAE standard forms of \n% zero-displaceemnt-error systems\", Journal of Zhejiang University \n% (Natural Science) Vol. 23, N0o.4, pp. 550-559, 1989.\n%\n% Example, the 7th-order optimal and original ITAE coefficients \n%{\nformat compact\nformat short g\n[p,f,p1,f1] = optimitaestep(7)\n%}\n% p =\n% 1 2.2172 6.7447 9.3493 11.58 8.6799 4.3233 1\n% f =\n% 10.585\n% p1 =\n% 1 4.475 10.42 15.08 15.54 10.64 4.58 1\n% f1 =\n% 14.953\n%\n\n%Input check\nerror(nargchk(1,2,nargin));\nif n<2 || n>8\n error('n must be within range of [2 8].')\nend\nitaeOrg={ 1.4, [1.75 2.15], [2.1 3.4 2.7],...\n [2.8 5.0 5.5 3.4], [3.25 6.60 8.60 7.45 3.95],...\n [4.475 10.42 15.08 15.54 10.64 4.58],...\n [5.2 12.8 21.6 25.75 22.2 13.3 5.15]};\np1=itaeOrg{n-1};\np0=fliplr(p1);\nopt=optimset('display','off','TolX',1e-9,'TolFun',1e-9,'LargeScale','off');\ndt=0.01;\ntf=50;\nflag=0;\nwhile ~flag\n cost=@(x)itaecost(x,dt,tf);\n [p0,f,flag]=fminunc(cost,p0,opt);\n p=[1 fliplr(p0) 1];\n if any(real(roots(p))>0)\n tf=tf*2;\n flag=0;\n p0=fliplr(itaeOrg{n-1});\n end\nend\nif nargout>2\n f1=cost(fliplr(p1));\n p1=[1 p1 1];\nend\n \nfunction E=itaecost(p,dt,tf)\nn=numel(p);\nA=[zeros(n,1) eye(n);-1 -p];\nB=[zeros(n,1);1];\nA=expm([A B;zeros(1,n+2)]*dt);\nx=[zeros(n+1,1);1];\nE=0;\nfor t=0:dt:tf\n tdt=t*dt;\n x=A*x;\n e=1-x(1);\n E=E+abs(e)*tdt;\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/18547-the-optimal-itae-transfer-function-for-step-input/itae/optimitaestep.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.8104789086703225, "lm_q1q2_score": 0.716495189815086}} {"text": "function [fTmax, mRes] = calc_ChTime(mCatalog, fTimeWindow)\n% [fTmax, mRes] = calc_ChTime(mCatalog, fTimeWindow)\n% -------------------------------------------------------\n% Function to identify times of maximum changes of seismicity in time using\n% the absolute difference of the non-cumulative FMD in successive time windows\n%\n% Incoming:\n% mCatalog : EQ catalog\n% fTimeWindow : Length of moving time window in dec. years\n%\n% Outgoing variable:\n% fTmax : Time of maximum change\n% mRes : Matrix containing time and absoulte changes\n%\n% J. Woessner\n% last update: 21.01.2004\n\nmRes = [];\n\n% Initialize\nfMinTime = min(mCatalog(:,3));\nfMaxTime = max(mCatalog(:,3));\nfTimePeriod = fMaxTime-fMinTime;\n\n% Minimum bin\nfMinBin = roundn(min(mCatalog(:,6)),-1);\nfMaxBin = roundn(max(mCatalog(:,6)),-1);\n\n% Seismicity of catalog normalized to time period\nnNumevents = max(length(mCatalog(:,1)));\nfNum = nNumevents/fTimePeriod;\n\n% Starttime\nfTime = fMinTime;\n\nwhile fTime < fMaxTime-2*fTimeWindow\n vSel = (mCatalog(:,3) >= fTime & mCatalog(:,3) < fTime+fTimeWindow);\n nNumper = max(length(mCatalog(vSel,1)));\n fNumper = nNumper/fTimeWindow;\n fChTime = fNumper/fNum; % Relative change of entire data\n\n % Change in FMD\n [vFMD1, vBin1] = hist(mCatalog(vSel,6),fMinBin:0.1:fMaxBin);\n vSel2 = (mCatalog(:,3) >= fTime+fTimeWindow & mCatalog(:,3) < fTime+2*fTimeWindow);\n [vFMD2, vBin2] = hist(mCatalog(vSel2,6),fMinBin:0.1:fMaxBin);\n fChFMD = max(cumsum(abs(vFMD2-vFMD1)));\n\n\n mRes = [mRes; fTime fNumper fChTime fChFMD];\n\n % Shift time by half window width\n fTime = fTime+0.1; %fTimeWindow/10;\nend\n\n% Maximum positive change\nvSel = (mRes(:,4) == max(mRes(:,4)));\nmMax = mRes(vSel,:);\nfTmax = mRes(vSel,1);\n\nfigure\nhPlot1=plot(mRes(:,1),mRes(:,4)/mean(mRes(:,4)),'Color',[0 0 0],'Linewidth',2)\n% sTitle = ['Time of maximum change: ' num2str(fTmax)]\n% hTit=title(sTitle)\nxlabel('Time [dec. year]','FontSize',12,'Fontweight','bold')\nylabel('Normalized \\Delta_{FMD}','FontSize',12,'Fontweight','bold')\nset(gca,'FontSize',12,'Fontweight','bold','Linewidth',2)\n%set(hTit,'FontSize',12,'Fontweight','bold')\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/jochen/seisvar/calc/calc_ChTime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912849, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7164507709585314}} {"text": "\nfunction [LS,LD,I] = isolines(V,F,S,iso)\n % ISOLINES compute a list of isolines for a scalar field S defined on the\n % mesh (V,F)\n %\n % [LS,LD,I] = isolines(V,F,S,iso)\n %\n % Inputs:\n % V #V by dim list of vertex positions\n % F #F by 3 list of triangle indices\n % S #V list of scalar values defined on V\n % iso #iso list of iso values\n % Outputs:\n % LS #L by dim list of isoline start positions\n % LD #L by dim list of isoline destination positions\n % I #L list of indices into iso revealing corresponding iso value\n %\n % alternative: tracing isolines should result in smaller plot data (every\n % vertex only appears once\n %\n\n % make sure iso is a ROW vector\n iso = iso(:)';\n % number of isolines\n niso = numel(iso);\n\n % number of domain positions\n n = size(V,1);\n % number of dimensions\n dim = size(V,2);\n\n % number of faces\n m = size(F,1);\n\n % Rename for convenience\n S1 = S(F(:,1),:);\n S2 = S(F(:,2),:);\n S3 = S(F(:,3),:);\n\n % t12(i,j) reveals parameter t where isovalue j falls on the line from\n % corner 1 to corner 2 of face i\n t12 = bsxfun(@rdivide,bsxfun(@minus,iso,S1),S2-S1);\n t23 = bsxfun(@rdivide,bsxfun(@minus,iso,S2),S3-S2);\n t31 = bsxfun(@rdivide,bsxfun(@minus,iso,S3),S1-S3);\n\n % replace values outside [0,1] with NaNs\n t12( (t12<-eps)|(t12>(1+eps)) ) = NaN;\n t23( (t23<-eps)|(t23>(1+eps)) ) = NaN;\n t31( (t31<-eps)|(t31>(1+eps)) ) = NaN;\n\n % masks for line \"parallel\" to 12\n l12 = ~isnan(t23) & ~isnan(t31);\n l23 = ~isnan(t31) & ~isnan(t12);\n l31 = ~isnan(t12) & ~isnan(t23);\n\n % find non-zeros (lines) from t23 to t31\n [F12,I12,~] = find(l12);\n [F23,I23,~] = find(l23);\n [F31,I31,~] = find(l31);\n % indices directly into t23 and t31 corresponding to F12 and I12\n %ti12 = sub2ind(size(l12),F12,I12);\n %ti23 = sub2ind(size(l23),F23,I23);\n %ti31 = sub2ind(size(l31),F31,I31);\n % faster sub2ind\n ti12 = F12+(I12-1)*size(l12,1);\n ti23 = F23+(I23-1)*size(l23,1);\n ti31 = F31+(I31-1)*size(l31,1);\n\n % compute actual position values\n LS = [ ...\n ... % average of vertex positions between 2 and 3\n bsxfun(@times,1-t23(ti12), V(F(F12,2),:)) + ...\n bsxfun(@times, t23(ti12), V(F(F12,3),:)) ...\n ; ... % average of vertex positions between 2 and 3\n bsxfun(@times,1-t31(ti23), V(F(F23,3),:)) + ...\n bsxfun(@times, t31(ti23), V(F(F23,1),:)) ...\n ;... % average of vertex positions between 2 and 3\n bsxfun(@times,1-t12(ti31), V(F(F31,1),:)) + ...\n bsxfun(@times, t12(ti31), V(F(F31,2),:)) ...\n ];\n LD = [...\n ... % hcat with average of vertex positions between 3 and 1\n bsxfun(@times,1-t31(ti12), V(F(F12,3),:)) + ...\n bsxfun(@times, t31(ti12), V(F(F12,1),:)) ...\n ;... % hcat with average of vertex positions between 3 and 1\n bsxfun(@times,1-t12(ti23), V(F(F23,1),:)) + ...\n bsxfun(@times, t12(ti23), V(F(F23,2),:)) ...\n ;... % hcat with average of vertex positions between 3 and 1\n bsxfun(@times,1-t23(ti31), V(F(F31,2),:)) + ...\n bsxfun(@times, t23(ti31), V(F(F31,3),:)) ...\n ];\n\n % I is just concatenation of each I12\n I = [I12;I23;I31];\n\nend", "meta": {"author": "gpeyre", "repo": "2015-SIGGRAPH-convolutional-ot", "sha": "484b83c5ee396f3d998f67ed35652249b5e29e81", "save_path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot", "path": "github-repos/MATLAB/gpeyre-2015-SIGGRAPH-convolutional-ot/2015-SIGGRAPH-convolutional-ot-484b83c5ee396f3d998f67ed35652249b5e29e81/code/mesh_functions/isolines.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7164080723201699}} {"text": "function [sbc, fpe, logdp, np] = arord(R, m, mcor, ne, pmin, pmax)\n%ARORD\tEvaluates criteria for selecting the order of an AR model.\n%\n% [SBC,FPE]=ARORD(R,m,mcor,ne,pmin,pmax) returns approximate values\n% of the order selection criteria SBC and FPE for models of order\n% pmin:pmax. The input matrix R is the upper triangular factor in the\n% QR factorization of the AR model; m is the dimension of the state\n% vectors; the flag mcor indicates whether or not an intercept vector\n% is being fitted; and ne is the number of block equations of size m\n% used in the estimation. The returned values of the order selection\n% criteria are approximate in that in evaluating a selection\n% criterion for an AR model of order p < pmax, pmax-p initial values\n% of the given time series are ignored.\n%\n% ARORD is called by ARFIT. \n%\t\n% See also ARFIT, ARQR.\n\n% For testing purposes, ARORD also returns the vectors logdp and np,\n% containing the logarithms of the determinants of the (scaled)\n% covariance matrix estimates and the number of parameter vectors at\n% each order pmin:pmax.\n\n% Modified 17-Dec-99\n% Author: Tapio Schneider\n% tapio@gps.caltech.edu\n \n imax \t = pmax-pmin+1; % maximum index of output vectors\n \n % initialize output vectors\n sbc = zeros(1, imax); % Schwarz's Bayesian Criterion\n fpe = zeros(1, imax); % log of Akaike's Final Prediction Error\n logdp = zeros(1, imax); % determinant of (scaled) covariance matrix\n np = zeros(1, imax); % number of parameter vectors of length m\n np(imax)= m*pmax+mcor;\n\n % Get lower right triangle R22 of R: \n %\n % | R11 R12 |\n % R=| |\n % | 0 R22 |\n %\n R22 = R(np(imax)+1 : np(imax)+m, np(imax)+1 : np(imax)+m);\n\n % From R22, get inverse of residual cross-product matrix for model\n % of order pmax\n invR22 = inv(R22);\n Mp = invR22*invR22';\n \n % For order selection, get determinant of residual cross-product matrix\n % logdp = log det(residual cross-product matrix)\n logdp(imax) = 2.*log(abs(prod(diag(R22))));\n\n % Compute approximate order selection criteria for models of \n % order pmin:pmax\n i = imax;\n for p = pmax:-1:pmin\n np(i) = m*p + mcor;\t% number of parameter vectors of length m\n if p < pmax\n % Downdate determinant of residual cross-product matrix\n % Rp: Part of R to be added to Cholesky factor of covariance matrix\n Rp = R(np(i)+1:np(i)+m, np(imax)+1:np(imax)+m);\n\n % Get Mp, the downdated inverse of the residual cross-product\n % matrix, using the Woodbury formula\n L = chol(eye(m) + Rp*Mp*Rp')';\n N = L \\ Rp*Mp;\n Mp = Mp - N'*N;\n\n % Get downdated logarithm of determinant\n logdp(i) = logdp(i+1) + 2.* log(abs(prod(diag(L))));\n end\n\n % Schwarz's Bayesian Criterion\n sbc(i) = logdp(i)/m - log(ne) * (ne-np(i))/ne;\n\n % logarithm of Akaike's Final Prediction Error\n fpe(i) = logdp(i)/m - log(ne*(ne-np(i))/(ne+np(i)));\n\n % Modified Schwarz criterion (MSC):\n % msc(i) = logdp(i)/m - (log(ne) - 2.5) * (1 - 2.5*np(i)/(ne-np(i)));\n\n i = i-1; % go to next lower order\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/174-arfit/arord.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802529509909, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7164080716280801}} {"text": "function cor_n = coriolis(lat, vel, h)\n% coriolis: calculates Coriolis forces in the navigation frame.\n%\n% INPUT\n% lat, Mx1 latitude (radians).\n% vel, Mx3 NED velocities (m/s).\n% h, Mx1 altitude (m).\n%\n% OUTPUT\n%\t\tcor_n, Mx3 Coriolis forces vector in the nav-frame (m/s^2).\n%\n% Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved. \n% \n% This file is part of NaveGo, an open-source MATLAB toolbox for \n% simulation of integrated navigation systems.\n% \n% NaveGo is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License (LGPL) \n% version 3 as published by the Free Software Foundation.\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 Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Lesser General Public \n% License along with this program. If not, see \n% .\n%\n% Reference: \n%\n%\tR. Gonzalez, J. Giribet, and H. Patiño. NaveGo: a \n% simulation framework for low-cost integrated navigation systems, \n% Journal of Control Engineering and Applied Informatics}, vol. 17, \n% issue 2, pp. 110-120, 2015. Eq. 11.\n%\n% Version: 002\n% Date: 2022/01/25\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego \n\nM = max(size(lat)); \n\ncor_n = zeros(M, 3);\n\nfor i = 1:M\n \n omega_en_n = transport_rate(lat(i), vel(i,1), vel(i,2), h(i));\n omega_ie_n = earth_rate(lat(i));\n\n cor_n(i,:) = (omega_en_n + 2*omega_ie_n) * vel(i,:)'; \nend\n", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/simulation/coriolis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7164080214745508}} {"text": "function [ v, lambda ] = l1nd_eigen ( n, h )\n\n%*****************************************************************************80\n%\n%% L1ND_EIGEN returns eigeninformation for the 1D ND Laplacian.\n%\n% Discussion:\n%\n% The grid points are assumed to be evenly spaced by H.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 October 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n%\n% Input, real H, the spacing between points.\n%\n% Output, real V(N,N), the eigenvectors.\n%\n% Output, real LAMBDA(N), the eigenvalues.\n%\n v = zeros ( n, n );\n lambda = zeros ( n, 1 );\n\n for j = 1 : n\n theta = pi * ( j - 0.5 ) / ( 2.0 * n + 1.0 );\n lambda(j) = 4.0 * ( sin ( theta ) / h ) ^ 2;\n for i = 1 : n\n theta = pi * ( i - 0.5 ) * ( 2.0 * j - 1.0 ) / ( 2.0 * n + 1.0 );\n v(i,j) = sqrt ( 2.0 / ( n + 0.5 ) ) * cos ( theta );\n end\n end\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/laplacian/l1nd_eigen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.7164080104312587}} {"text": "function btv_test01 ( )\n\n%*****************************************************************************80\n%\n%% BTV_TEST01 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_TEST01\\n' );\n fprintf ( 1, ' Test BURGERS_TIME_VISCOUS with the gaussian initial condition.\\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: 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 ( 1 )\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_test01.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_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7163789455000202}} {"text": "function a = givens_llt ( n )\n\n%*****************************************************************************80\n%\n%% GIVENS_LLT returns the Cholesky factor of the GIVENS matrix.\n%\n% Example:\n%\n% N = 5\n%\n% 1 0 0 0 0\n% 1 sqrt(2) 0 0 0\n% 1 sqrt(2) sqrt(2) 0 0\n% 1 sqrt(2) sqrt(2) sqrt(2) 0\n% 1 sqrt(2) sqrt(2) sqrt(2) sqrt(2)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Output, real A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n a(1:n,1) = 1.0;\n\n for i = 1 : n\n a(i,2:i) = sqrt ( 2.0 );\n end\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/test_mat/givens_llt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7163146088259379}} {"text": "function [MATreordered,MATindices,MATcost] = reorderMAT(MAT,H,cost)\n%REORDERMAT Reorder matrix for visualization\n%\n% [MATreordered,MATindices,MATcost] = reorderMAT(MAT,H,cost);\n%\n% This function reorders the connectivity matrix in order to place more\n% edges closer to the diagonal. This often helps in displaying community\n% structure, clusters, etc.\n%\n% Inputs: MAT, connection matrix\n% H, number of reordering attempts\n% cost, 'line' or 'circ', for shape of lattice\n% (linear or ring lattice)\n%\n% MATreordered reordered connection matrix\n% MATindices reordered indices\n% MATcost cost of reordered matrix\n% \n%\n% Olaf Sporns, Indiana University\n\n\nN = length(MAT);\ndiagMAT = diag(diag(MAT));\nMAT = MAT-diagMAT;\n\n% generate cost function\nif strcmp(cost,'line')\n profil = fliplr(normpdf(1:N,0,N/2));\nend;\nif strcmp(cost,'circ')\n profil = fliplr(normpdf(1:N,N/2,N/4));\nend;\nCOST = toeplitz(profil,profil);\n\n% initialize lowCOST\nlowMATcost = sum(sum(COST.*MAT));\n\n% keep track of starting configuration\nMATstart = MAT;\nstarta = 1:N;\n \n% reorder\nfor h=1:H\n a = 1:N;\n % choose two positions at random and flip them\n r = randperm(N);\n a(r(1)) = r(2);\n a(r(2)) = r(1);\n MATcostnew = sum(sum(MAT(a,a).*COST));\n if (MATcostnew < lowMATcost)\n MAT = MAT(a,a);\n r2 = starta(r(2));\n r1 = starta(r(1));\n starta(r(1)) = r2;\n starta(r(2)) = r1;\n lowMATcost = MATcostnew;\n end;\nend;\t% h\n\nMATreordered = MATstart(starta,starta) + diagMAT(starta,starta);\nMATindices = starta;\nMATcost = lowMATcost;\n\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/External/2019_03_03_BCT/reorderMAT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8244619350028205, "lm_q1q2_score": 0.716314605119596}} {"text": "function [RMAOV1MS] = RMAOV1MS(X,alpha)\n%RMAOV1MS Repeated measures single-factor analysis of variance multiple samples\n% test. \n% This m-file deals with repeated measurements at t time points obtained from\n% s groups of subjects or multiple samples. With or without same size. The\n% simplest model is:\n%\n% x_hij = m + g_h +t_j + (gt)_hj + p_i(h) + e_hij\n%\n% where: x_hij = response at time j from the ith subject in group h; m = \n% overall mean; g_h = fixed effect of group h; t_j = fixed effect of\n% time j; (gt)_hj = fixed effect for the interaction of the hth group\n% with the jth time; p_i(h) = random effects for the ith subject in\n% the hth group, and e_hij = independent random error terms.\n%\n% For we are interested test for differences among groups, test differences\n% among time points, and test the significance of the group x time interaction.\n% The first test requires the assumption that the within-group covariance\n% matrices are equal. The two last-ones tests require this same assumption\n% and that the sphericity condition is satisfied. In general, these assumtions\n% are required for all tests of within-subjects effects (repeated measures).\n% \n% Syntax: RMAOV1MS(X,alpha) \n% \n% Inputs:\n% X - data matrix (Size of matrix must be n-by-4;dependent variable=\n% column 1;group=column 2;independent variable=column 3;subject=\n% column 4). \n% alpha - significance level (default = 0.05).\n%\n% Outputs:\n% - Complete Analysis of Variance Table.\n%\n% Example: From the example 5.4.2 of Charles S. Davis (2002). from an experiment\n% comparing dissolution times of pills. We use the logarithms of the\n% times, in seconds, for each pill to reach fractions remaining of\n% 0.9,0.7,0.5,0.3,0.25, and 0.10. The four groups correspond to\n% different storage conditions. Under the assumption thet the \n% logarithms of the times are normally distributed, repeated measures\n% ANOVA can be used to test for effects due to group, fraction\n% remaining, and interaction effect between group and fraction\n% remaining. Tha data are shown on the below table.\n%\n% -----------------------------------------------------------\n% Fraction remainig\n% ------------------------------------------\n% Group Tablet 0.90 0.70 0.50 0.30 0.25 0.10\n% -----------------------------------------------------------\n% 1 1 2.56 2.77 2.94 3.14 3.18 3.33\n% 2 2.64 2.89 3.09 3.26 3.33 3.47\n% 3 2.94 3.18 3.33 3.50 3.50 3.66\n% 4 2.56 2.83 3.04 3.22 3.26 3.37\n% 5 2.64 2.77 2.94 3.14 3.22 3.30\n% 6 2.56 2.77 2.94 3.14 3.18 3.26\n% 2 1 2.56 2.83 3.07 3.26 3.33 3.51\n% 2 2.44 2.74 3.02 3.20 3.28 3.44\n% 3 2.34 2.67 2.91 3.16 3.22 3.39\n% 4 2.41 2.71 2.94 3.16 3.21 3.36\n% 3 1 2.46 2.83 3.09 3.32 3.37 3.54\n% 2 2.60 2.93 3.21 3.40 3.46 3.62\n% 3 2.48 2.84 3.12 3.35 3.41 3.58\n% 4 2.49 2.82 3.05 3.29 3.37 3.52\n% 4 1 2.40 2.67 2.94 3.20 3.26 3.47\n% 2 2.64 2.94 3.18 3.40 3.45 3.66\n% 3 2.40 2.64 2.86 3.09 3.16 3.38\n% -----------------------------------------------------------\n% \n% Data matrix must be:\n% X=[2.56 1 1 1;2.77 1 1 2;2.94 1 1 3;3.14 1 1 4;3.18 1 1 5;3.33 1 1 6;2.64 1 2 1;2.89 1 2 2;3.09 1 2 3;3.26 1 2 4;3.33 1 2 5;3.47 1 2 6;\n% 2.94 1 3 1;3.18 1 3 2;3.33 1 3 3;3.50 1 3 4;3.50 1 3 5;3.66 1 3 6;2.56 1 4 1;2.83 1 4 2;3.04 1 4 3;3.22 1 4 4;3.26 1 4 5;3.37 1 4 6;\n% 2.64 1 5 1;2.77 1 5 2;2.94 1 5 3;3.14 1 5 4;3.22 1 5 5;3.30 1 5 6;2.56 1 6 1;2.77 1 6 2;2.94 1 6 3;3.14 1 6 4;3.18 1 6 5;3.26 1 6 6;\n% 2.56 2 1 1;2.83 2 1 2;3.07 2 1 3;3.26 2 1 4;3.33 2 1 5;3.51 2 1 6;2.44 2 2 1;2.74 2 2 2;3.02 2 2 3;3.20 2 2 4;3.28 2 2 5;3.44 2 2 6;\n% 2.34 2 3 1;2.67 2 3 2;2.91 2 3 3;3.16 2 3 4;3.22 2 3 5;3.39 2 3 6;2.41 2 4 1;2.71 2 4 2;2.94 2 4 3;3.16 2 4 4;3.21 2 4 5;3.36 2 4 6;\n% 2.46 3 1 1;2.83 3 1 2;3.09 3 1 3;3.32 3 1 4;3.37 3 1 5;3.54 3 1 6;2.60 3 2 1;2.93 3 2 2;3.21 3 2 3;3.40 3 2 4;3.46 3 2 5;3.62 3 2 6;\n% 2.48 3 3 1;2.84 3 3 2;3.12 3 3 3;3.35 3 3 4;3.41 3 3 5;3.58 3 3 6;2.49 3 4 1;2.82 3 4 2;3.05 3 4 3;3.29 3 4 4;3.37 3 4 5;3.52 3 4 6;\n% 2.40 4 1 1;2.67 4 1 2;2.94 4 1 3;3.20 4 1 4;3.26 4 1 5;3.47 4 1 6;2.64 4 2 1;2.94 4 2 2;3.18 4 2 3;3.40 4 2 4;3.45 4 2 5;3.66 4 2 6;\n% 2.40 4 3 1;2.64 4 3 2;2.86 4 3 3;3.09 4 3 4;3.16 4 3 5;3.38 4 3 6];\n%\n% Calling on Matlab the function: \n% RMAOV1MS(X)\n%\n% Answer is:\n%\n% The number of groups are: 4\n% The maximum number of subjects in a group are: 6\n% The minimum number of subjects in a group are: 3\n% The number of IV levels are: 6\n%\n% ANOVA table for repeated measures single-factor multiple samples.\n% ------------------------------------------------------------------------------\n% SOV SS df MS F P \n% ------------------------------------------------------------------------------\n% Groups 0.2038 3 0.0679 0.87 0.4798\n% Subjts(Gps.) 1.0108 13 0.0778\n% IV 10.0745 5 2.0149 3198.78 0.0000\n% Group x IV 0.2045 15 0.0136 21.64 0.0000\n% Residual 0.0409 65 0.0006\n% ------------------------------------------------------------------------------\n% Total 11.5344 101\n% ------------------------------------------------------------------------------\n% If the P results are smaller than 0.05\n% the corresponding Ho's tested result statistically significant. Otherwise,\n% are not significative.\n%\n% Created by A. Trujillo-Ortiz, R. Hernandez-Walls, K. Barba-Rojo and \n% A. Castro-Perez\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.December 13, 2006.\n%\n% To cite this file, this would be an appropriate format:\n% Trujillo-Ortiz, A., R. Hernandez-Walls, K. Barba-Rojo and A. Castro-Perez. (2006).\n% RMAOV1MS:Repeated measures single-factor analysis of variance multiple samples test.\n% A MATLAB file. [WWW document]. URL http://www.mathworks.com/matlabcentral/\n% fileexchange/loadFile.do?objectId=13380\n%\n% Reference:\n% Davis, S. Ch. (2002), Statistical Methods for the Analysis of Repeated\n% Measurements. Springer-Verlag:New York. Chapter 5.\n%\n\nif nargin < 2,\n alpha = 0.05; %(default)\nend; \n\nif (alpha <= 0 | alpha >= 1)\n fprintf('Warning: significance level must be between 0 and 1\\n');\n return;\nend;\n\nif nargin < 1, \n error('Requires at least one input argument.');\n return;\nend;\n\na = max(X(:,2)); %Number of groups.\nb = max(X(:,3)); %Maximum number of subjects in a group.\nt = max(X(:,4)); %Number of levels of independent variable.\n \nindice = X(:,2);\nfor i = 1:a\n Xe = find(indice==i);\n eval(['G' num2str(i) ' = X(Xe,1);']);\nend\nindice = X(:,4);\nfor k = 1:t\n Xe = find(indice==k);\n eval(['IV' num2str(k) '=X(Xe,1);']);\nend\n\nC = (sum(X(:,1)))^2/length(X(:,1)); %Correction term.\nSSTO = sum(X(:,1).^2)-C; %Total sum of squares.\ndfTO = length(X(:,1))-1; %Total degrees of freedom.\n\nfor i = 1:a\n for j = 1:b\n Xe = find((X(:,2)==i) & (X(:,3)==j));\n eval(['T' num2str(i) num2str(j) ' = X(Xe,1);']);\n end\nend\n\nfor i = 1:a\n for k = 1:t\n Xe = find((X(:,2)==i) & (X(:,4)==k));\n eval(['GI' num2str(i) num2str(k) '=X(Xe,1);']);\n end\nend\n \n%Procedure related to the subjects in groups.\nNSG = [];\nfor i = 1:a\n for j = 1:b\n eval(['n' num2str(i) num2str(j) ' = length(T' num2str(i) num2str(j) ');'])\n eval(['x = n' num2str(i) num2str(j) ';'])\n NSG = [NSG,x]; \n end\nend\n\n%Due it is an unequal sample sizes design, some subgroups arithmetic operations \n%could been not-a-number (like 0.0/0.0). So it is necessary to make the estimations\n%ignoring NaNs.\nwarning off;\nSG = [];\nfor i = 1:a\n for j = 1:b\n eval(['x = ((sum(T' num2str(i) num2str(j) ').^2)/length(T' num2str(i) num2str(j) '));'])\n SG = [SG,x];\n nans = isnan(SG);\n r = find(nans);\n SG(r) = zeros(size(r));\n end\nend\nwarning on;\nSSSG = sum(SG)-C;\ndfSG = (a*b)-1;\n\n%Procedure related to the groups.\nG = [];\nfor i = 1:a\n eval(['x = ((sum(G' num2str(i) ').^2)/length(G' num2str(i) '));'])\n G = [G,x];\nend\nSSG = sum(G)-C;\ndfG = a-1;\nMSG = SSG/dfG;\n\n%Procedure related to the IV (independent variable). \nIV = [];\nfor k = 1:t\n eval(['x =((sum(IV' num2str(k) ').^2)/length(IV' num2str(k) '));']);\n IV = [IV,x];\n end\nSSIV = sum(IV)-C; %sum of squares for the IV\ndfIV = t-1; %degrees of freedom for the IV\nMSIV = SSIV/dfIV; %mean square for the IV\n\n%Procedure related to the interaction group-independent variable.\nGI = [];\nfor i = 1:a\n for k = 1:t\n eval(['x =((sum(GI' num2str(i) num2str(k) ').^2)/length(GI' num2str(i) num2str(k) '));']);\n GI = [GI,x];\n end\n end\nSSGI = sum(GI)-sum(G)-sum(IV)+C; %sum of squares of the Group x IV\ndfGI = dfG*dfIV; %degrees of freedom of the Group x IV\nMSGI = SSGI/dfGI; %mean square for the Group x IV\n\n%Procedure for estimation of sample size for unequal sample sizes.\nno1 = []; no2 = []; \nfor i = 1:a\n for j = 1:b\n eval(['x = length(T' num2str(i) num2str(j) ');']);\n no1 = [no1,x];\n eval(['x = length(T' num2str(i) num2str(j) ').^2;']);\n no2 = [no2,x];\n end\nend\n\n%Procedure related to the within subgroups (error).\nSSE = SSTO-SSSG;\nnneg = length(find((no1-1)<0));\ndfE = sum(no1-1)+nneg;\nMSE = SSE/dfE;\n\n%Procedure related to the among subgroups within groups.\nSSSGG = SSTO-SSG-SSE;\ndfSGG = dfTO-dfG-dfE;\nMSSGG = SSSGG/dfSGG;\n\n%Procedure related to the residual.\nSSR = SSTO-SSG-SSSGG-SSIV-SSGI; \ndfR = dfTO-dfG-dfSGG-dfIV-dfGI;\nMSR = SSR/dfR;\n\nfprintf('The number of groups are:%2i\\n', a);\nfprintf('The maximum number of subjects in a group are:%2i\\n', b);\nc = min(full(sum(spones(reshape(no2,b,a))))); %Minimum number of subjects in a group.\nfprintf('The minimum number of subjects in a group are:%2i\\n', c);\nfprintf('The number of IV levels are:%2i\\n\\n', t);\nFG = MSG/MSSGG;\nFIV = MSIV/MSR;\nFGI = MSGI/MSR;\nPrG = 1 - fcdf(FG,dfG,dfSGG); %Probability associated to the groups F statistic.\nPrIV = 1 - fcdf(FIV,dfIV,dfR); %Probability associated to the IV F statistic.\nPrGI = 1 - fcdf(FGI,dfGI,dfR); %Probability associated to the interaction group-IV F statistic.\ndisp('ANOVA table for repeated measures single-factor multiple samples.')\nfprintf('------------------------------------------------------------------------------\\n');\ndisp('SOV SS df MS F P ')\nfprintf('------------------------------------------------------------------------------\\n');\nfprintf('Groups %18.4f%10i%14.4f%13.2f%9.4f\\n',SSG,dfG,MSG,FG,PrG);\nfprintf('Subjts(Gps.)%19.4f%10i%14.4f\\n',SSSGG,dfSGG,MSSGG);\nfprintf('IV %25.4f%10i%14.4f%13.2f%9.4f\\n',SSIV,dfIV,MSIV,FIV,PrIV);\nfprintf('Group x IV %20.4f%10i%14.4f%13.2f%9.4f\\n',SSGI,dfGI,MSGI,FGI,PrGI);\nfprintf('Residual %22.4f%10i%14.4f\\n',SSR,dfR,MSR);\nfprintf('------------------------------------------------------------------------------\\n');\nfprintf('Total %25.4f%10i\\n',SSTO,dfTO);\nfprintf('------------------------------------------------------------------------------\\n');\nfprintf('If the P results are smaller than% 3.2f\\n', alpha );\ndisp('the corresponding Ho''s tested result statistically significant. Otherwise,');\ndisp('are not significative.');\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/13380-rmaov1ms/RMAOV1MS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7163146022988232}} {"text": "function stateVec=orbEls2State(orbEls,deltaT,elType,GM,epsVal)\n%%ORBELS2STATE Obtain a velocity and position from a set of orbital\n% elements at a desired time in seconds since the epoch time.\n%\n%INPUTS: orbEls A 6XnumVec vector of orbital numVec elements to convert.\n% The elements are either Gooding's universal orbital\n% elements or equinoctial orbital elements, as specified by\n% the parameter elType. The components of the elements\n% depends on the type and are explained below.\n% deltaT The time in seconds forward that the trajectory should be\n% propagated from the epoch time of the orbital elements. If\n% this parameter is omitted, a value of 0 is used. For\n% example, if one wishes to propagate the state forward an\n% hour from the time associated with the elements, one can\n% use deltaT=60*60.\n% elType A value indicating the type of orbital elements. Possible\n% values are:\n% 0 (The default if omitted) The elements are Gooding's\n% universal orbital elements.\n% 1 The elements are direct equinoctial orbital elements.\n% 2 The elements are retrograde equnoctial orbital\n% elements.\n% GM An optional value of the universal gravitational constant\n% times the mass of the Earth. If omitted, the value\n% Constants.WGS84GMWithAtmosphere is used. The units are\n% m^3/sec^2.\n% epsVal If universal orbital elements are chosen, this is a\n% precision bound used on the alpha term (GM divided by the\n% semi-major axis) for determining whether the trajectory is\n% parabolic. If omitted, a default value of eps is used.\n%\n%OUTPUTS: stateVec A 6XnumVec matrix of numVec state vectors consisting of\n% position and velocity in a Cartesian inertial coordinate\n% system where the gravitating body is at the origin. Units\n% are meters, and then meters per second.\n%\n%Gooding's universal orbital elements are consist of (in order)\n%alpha=GM/a where a is the semi-major axis in meters\n%q=a*(1-e) where e is the eccentricity (unitless). This is the perifocal\n% distance.\n%i inclination in radians\n%Omega longitude of the ascending node in radians\n%omega argument of periapsis in radians\n%tau the time at pericenter (seconds)\n%\n%The equinoctial orbital elements (for both direct and retrograde elements)\n%are\n%a semi-major axis in meters\n%h first eccentricity vector component (unitless)\n%k second eccentricity vector component (unitless)\n%p first ascending node vector component (unitless)\n%q second ascending node vector component (unitless)\n%lambda mean longitude in radians.\n%\n%The algorithm using Gooding's universal orbital elements is very robust to\n%numerical errors. It is implemented using the algorithm of [1], where the\n%elements are also described.\n%\n%Equinoctial orbital elements are discussed in Section 2 of [2] and in [3].\n%The diffference between direct and retrograde elements is essentially a\n%matter of handedness.\n%\n%Orbital elements are discussed in general in Chapter 2.2 of [4].\n%\n%REFERENCES:\n%[1] R. H. Gooding, \"On universal elements, and conversion procedures to\n% and from position and velocity,\" Celestial mechanics, vol. 44, no. 3,\n% pp. 283-298, 1988.\n%[2] D. A. Danielson, C. P. Sagovac, B. Neta, and L. W. Early, \n% \"Semianalytic satellite theory,\" Mathematics Department, Naval\n% Postgraduate School, Monterey, CA, Tech. Rep., 1995. [Online].\n% Available: http://oai.dtic.mil/oai/oai?verb=getRecord&metadataPrefix= html&identifier=ADA531136\n%[3] R. A. Broucke and P. J. Cefola, \"On the equinoctial orbit elements,\"\n% Celestial Mechanics, vol. 5, no. 3, pp. 303-310, 1972.\n%[4] O. Montenbruck and E. Gill, Satellite Orbits: Models, Methods\n% Applications. Berlin: Springer, 2000.\n%\n%January 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<5)\n epsVal=eps;\nend\n\nif(nargin<4)\n GM=Constants.WGS84GMWithAtmosphere; \nend\n\nif(nargin<3)\n elType=0;\nend\n\nif(nargin<2)\n deltaT=0;\nend\n\nnumVecs=size(orbEls,2);\nstateVec=zeros(6,numVecs);\n\nswitch(elType)\n case 0\n for curVec=1:numVecs\n stateVec(:,curVec)=orbEls2StateUniv(orbEls(:,curVec),deltaT,GM,epsVal);\n end\n case 1\n for curVec=1:numVecs\n stateVec(:,curVec)=orbEls2StateEquinoctial(orbEls(:,curVec),deltaT,1,GM);\n end\n case 2\n for curVec=1:numVecs\n stateVec(:,curVec)=orbEls2StateEquinoctial(orbEls(:,curVec),deltaT,-1,GM);\n end\n otherwise\n error('Invalid element type provided.')\nend\nend\n\n\nfunction state=orbEls2StateUniv(theEls,deltaT,GM,epsVal)\n%%ORBELS2STATEUNIV An implementation of Gooding's conversion from\n% universal orbital elements to state vectors. This\n% implements the ELS3PV function.\n%\n%The implementation is taken from Appendix B of\n%R. H. Gooding, \"On universal elements, and conversion procedures to\n%and from position and velocity,\" Celestial mechanics, vol. 44, no. 3,\n%pp. 283-298, 1988.\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\n%If we are given classical elements...\nalpha=theEls(1);%alpha=GM/a where a is the semi-major axis in meters\nq=theEls(2);%q=a*(1-e), where e=eccentricity. q is the perifocal distance\ni=theEls(3);%Inclination\nOmega=theEls(4);%Longitude of the ascending node\nomega=theEls(5);%Argument of periapsis\ntau=theEls(6)+deltaT;%The time at pericenter.\n\n[r,u,VR,VT]=ELS2PV(alpha,q,omega,tau,GM,epsVal);\n\nc=cos(u);\ns=sin(u);\nx1=r*c;\ny1=r*s;\nx2=VR*c-VT*s;\ny2=VR*s+VT*c;\n\nc=cos(i);\ns=sin(i);\nz=y1*s;\ny1=y1*c;\nzDot=y2*s;\ny2=y2*c;\nc=cos(Omega);\ns=sin(Omega);\nx=x1*c-y1*s;\ny=x1*s+y1*c;\nxDot=x2*c-y2*s;\nyDot=x2*s+y2*c;\n\nstate=[x;y;z;xDot;yDot;zDot];\nend\n\nfunction state=orbEls2StateEquinoctial(theEls,deltaT,I,GM)\n%%ORBELS2STATEEQUINOCTIAL An algorithm to convert from equinoctial orbital\n% elements to a target state vector.\n%\n%The input I is the retrograde factor ond is +1 for direct equinoctial\n%elements and -1 for retrograde equinoctial elements.\n%\n%The algorithm is taken from Section 2.1.4 of\n%D. A. Danielson, C. P. Sagovac, B. Neta, and L. W. Early, \"Semianalytic\n%satellite theory,\" Mathematics Department, Naval Postgraduate School,\n%Monterey, CA, Tech. Rep., 1995. [Online]. Available:\n%http://oai.dtic.mil/oai/oai?verb=getRecord&metadataPrefix= html&identifier=ADA531136\n%\n%The equation for propagating the elements forward in time is taken from\n%R. A. Broucke and P. J. Cefola, \"On the equinoctial orbit elements,\"\n%Celestial Mechanics, vol. 5, no. 3, pp. 303-310, 1972.\n%\n%January 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\na=theEls(1);%Semi-major axis\nh=theEls(2);%First eccentricity vector component\nk=theEls(3);%Second eccentricity vector component\np=theEls(4);%First ascending node vector component\nq=theEls(5);%Second ascending node vector component\nlambda=theEls(6);%Mean longitude (at epoch)\n\nn=sqrt(GM/a^3);%The mean motion\n%The propagation of the mean longitude is from Equation 15 in Brouke and\n%Cefola.\nlambda=lambda+n*deltaT;\n\n%Section 2.1.4 conversion from equinoctial elements to position and\n%velocity.\ncoeff=(1/(1+p^2+q^2));\nf=coeff*[1-p^2+q^2;\n 2*p*q;\n -2*I*p];\ng=coeff*[2*I*p*q;\n (1+p^2-q^2)*I;\n 2*q];\n\n%Solve the Equinoctial form of Kepler's Equation. to get F.\nF=solveEquinoctialKeplersEq(lambda,h,k);\n\nn=sqrt(GM/a^3);\nb=1/(1+sqrt(1-h^2-k^2));\ndenom=1-h*sin(F)-k*cos(F);\nsinL=((1-k^2*b)*sin(F)+h*k*b*cos(F)-h)/denom;\ncosL=((1-h^2*b)*cos(F)+h*k*b*sin(F)-k)/denom;\n\nr=a*(1-h^2-k^2)/(1+h*sinL+k*cosL);\nX=r*cosL;\nY=r*sinL;\nXDot=-n*a*(h+sinL)/sqrt(1-h^2-k^2);\nYDot=n*a*(k+cosL)/sqrt(1-h^2-k^2);\n\nr=X*f+Y*g;\nrDot=XDot*f+YDot*g;\n\nstate=[r;rDot];\n\nend\n\n\nfunction [r,u,VR,VT]=ELS2PV(alpha,q,omega,tau,GM,epsVal)\n%%ELS2PV An implementation of the ELS2PV subroutine of Gooding's algorithm\n% for universal orbital element conversion. This is a\n% two-dimensional conversion suroutine.\n%\n%The algorithm is taken from Appendix A of\n%R. H. Gooding, \"On universal elements, and conversion procedures to\n%and from position and velocity,\" Celestial mechanics, vol. 44, no. 3,\n%pp. 283-298, 1988.\n%with minor changes so that alpha is compared to an epsilon value rather\n%than zero for determining the parabolic case.\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nif(abs(alpha)<=epsVal) %Parabolic case, GM cannot be zero.\n d=solveCubicEqGoodin(0.5/GM,q,1.5*GM*tau);\n r=q+(1/2)*d^2/GM;\n h=sqrt(2*GM*q);\n v=2*atan2(d,h);\nelse%Ellipse or hyperbola\n e1=alpha*q;\n e=GM-e1;\n ep1=GM+e;\n h=sqrt(q*ep1);\n \n em=tau*abs(alpha)^(3/2);\n if(alpha>0)%ellipse, GM cannot be zero\n ee2=(1/2)*solveKeplersEq(em/GM,e1/GM,2);\n s2=sin(ee2);\n c2=cos(ee2);\n r=q+2*e*s2^2/alpha;\n d=2*e*s2*c2/sqrt(abs(alpha));\n v=2*atan2(ep1*s2,h*sqrt(abs(alpha))*c2);\n emv=em/GM-v;\n v=v+4*pi*fix(abs(emv/(4*pi))+(1/2))*sign(emv);\n else%hyperbola\n s=solveKeplersEq(em/e,-e1/e,3);\n c=sqrt(1+s^2);\n s2=s^2/(c+1);\n r=q-e*s2/alpha;\n d=e*s/sqrt(abs(alpha));\n v=atan2(s*h*sqrt(abs(alpha)),-GM*s2-e1);\n end\nend\n\n%All orbits\nu=omega+v;\nVR=d/r;\nVT=h/r;\nend\n\nfunction x=solveCubicEqGoodin(a,b,c)\n%SOLVECUBICEQGOODING This solves the equation a*x^3+3*b*x-2*c=0, where\n% a>=0 and b^3+a*c^2>=0 for the real root of x.\n% Additionally, if a and b are both zero, then zero is\n% generated in lieu of an indeterminate solution.\n%\n%INPUTS: a,b,c The coefficients in the equation a*x^3+3*b*x-2*c=0 where\n% a>=0 and b^3+a*c^2>=0.\n%\n%OUTPUTS: x The one real solution to a*x^3+3*b*x-2*c=0.\n%\n%In the report\n%R. H. Gooding and A. W. Odell, \"The hyperbolic Kepler's equation,\n%and the elliptic equations revisited,\" Royal Aerospace Executive,\n%Procurement Executive, Ministry of Defence, Farnborough, Hants, United\n%Kingdom, Tech. Rep. 369, Jul. 1989.\n%the source of the algorithm is listed as being in \n%R. H. Gooding, \"Solution of the hyperbolic Kepler's equation,\" Royal\n%Aerospace Executive, Procurement Executive, Ministry of Defence,\n%Farnborough, Hants, United Kingdom, Tech. Rep. 87042, 1987.\n%However, the 1987 report appears to be unobtainable. Nonetheless, the\n%solution is given in Equation 4.47 in\n%G. Beutler, Methods of Celestial Mechanics: Physical, Mathematical and\n%Numerical Principles. Berlin: Springer, 2005, vol. 1.\n%The modification to return zero instead of infinity is consistent with how\n%Gooding used the algorithm.\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n\nif(a==0&&b==0||c==0)\n x=0;\nelse\n d=nthroot(sqrt(a)*abs(c)+sqrt(b^3+a*c^2),3)^2;\n x=2*c/(d+b+b^2/d);\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/Astronomical_Code/orbEls2State.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.7162792629973991}} {"text": "function [uv, out] = surface_param(x, param)\n% surface_param 2D parametrization of a scattered set of 3D points or of\n% the vertices of a triangular mesh, for open and closed surfaces.\n%\n% surface_param takes a scattered data set X in 3D that is supposed to\n% represent a sampling of a surface, and finds a 2D parameterisation U, V\n% for them. The surface can be open or closed, in which case the\n% parametrization domain will be the R^2 plane or the unit sphere,\n% respectively.\n%\n% surface_param provides several parametrization methods, some\n% implemented by us, some by other authors.\n%\n% [UV, OUT] = surface_param(X, PARAM)\n%\n% X is a 3-column matrix. Each row has the coordinates of a point that\n% belongs to the surface we want to interpolate.\n%\n% UV is a 2-column matrix with the parameterisation of X, (U, V)->X. In\n% planar parameterisations, UV has units of meters. In spherical\n% parameterisations, UV=[LAT, LON], in units of radians.\n%\n% OUT is a struct with the extra output from some of the parametrization\n% methods.\n%\n% PARAM is a string or struct that selects the parametrization method\n% and possibly arguments for the method.\n%\n% Parametrization methods summary (PARAM.type):\n%\n% XY plane:\n% 'xy': Simple projection on XY.\n% 'pca': Projection on main PCA plane.\n% 'isomap': Isomap (with Dijkstra's shortest path).\n% 'cmdsmap': MDS mapping, global neighbourhood, classical\n% MDS.\n% 'lmdscale': MDS mapping, local neighbourhood, local MDS.\n%\n% Unit sphere:\n% 'sphproj': Simple projection on sphere around centroid.\n% 'cald': CALD method by Shen & Makedon 2006.\n% 'smdscale': Spherical extension of lmdscale.\n%\n%=========================== OPEN SURFACES ================================\n%\n% * 'xy': Projection on the xy-plane, i.e. xy-coordinates of the points\n% in X.\n%\n%--------------------------------------------------------------------------\n%\n% * 'pca': Projection on the plane defined by the two eigenvectors with\n% the largest eigenvalues.\n%\n%--------------------------------------------------------------------------\n%\n% * 'isomap': Isometric mapping (Tenenbaum et al. [1][2]). This is a\n% non-linear method that can be applied to complex open surfaces that\n% bend on themselves or are rolled-up. This option uses the\n% third-party function IsomapII. Because isomap uses Dijkstra's\n% shortest-path algorithm internally, it suffers strongly from\n% metrication errors in regular meshes. On the other hand, it can be\n% applied to any adjacency graph, not only meshes.\n%\n% Small neighbourhoods capture higher curvature in the surface, but\n% too small neighbourhoods create several connected components and\n% will produce an error.\n%\n% PARAM.d: [Opt] Distance matrix between points. The parameter can have\n% the following formats:\n% (1) a full N x N matrix with distances between all pairs of points.\n% In this case, you can define the local neighbourhoods using\n% PARAM.neigh and PARAM.size, so that some of the connections in the\n% full matrix will be deleted and replaced by Disjkstra's\n% shortest-path lengths.\n% (2) a sparse N x N matrix (missing entries are treated as Inf). In\n% this case, you usually want to make PARAM.size=Inf, because the\n% local neighbourhood is already given by the sparse matrix. The\n% missing connections will be replaced internally by Disjkstra's\n% shortest-path lengths.\n% (3) the name of a function (e.g. 'd_fun') that takes one argument,\n% i, and returns a row vector containing the distances from all N\n% points to point i.\n%\n% If not provided, PARAM.d is the full Euclidean matrix of distances\n% between every pair of points.\n%\n% As a particular case, note that in case of a triangular mesh, the\n% sparse local distance that corresponds to the mesh can be computed\n% using dmatrix_mesh().\n%\n% PARAM.neigh: [Opt] Type of neighbourhood ('epsilon' or 'k'). \n% PARAM.size: [Opt] Size of neighbourhood.\n%\n% Each point in X is directly connected only to neighbours within a\n% distance PARAM.size (for 'epsilon'), or the PARAM.size closest\n% neighbours (for 'k'), according to the distances in PARAM.d. This\n% allows to further restrict the neighbourhoods in PARAM.d.\n%\n% PARAM.options: [Opt] Extra arguments passed to IsomapII. Most users\n% won't need to change this. For details, see help to IsomapII().\n%\n%--------------------------------------------------------------------------\n%\n% * 'cmdsmap': Open surface classical MDS mapping improved with a Fast\n% Marching method (Zigelman et al. [3]). The fast marching algorithm\n% doesn't suffer from metrication errors on regular meshes as badly as\n% Dijkstra's. On the other hand, the current implementation is limited\n% to triangular meshes, while Dijkstra's will work with any adjacency\n% graph. This option uses classical MDS on a full distance matrix, so\n% it's not valid for local neighbourhoods or closed surfaces. For local\n% neighbourhoods, see 'lmdscale' below.\n%\n% PARAM.d or PARAM.tri must be provided. If PARAM.d is provided,\n% PARAM.tri and PARAM.options are ignored. Otherwise, PARAM.d is\n% computed from PARAM.tri and PARAM.options.\n%\n% PARAM.d: [Req/Opt] This is expected to be the full distance matrix\n% between mesh vertices that can be computed with\n% [~, param.d] = dmatrix_mesh(param.tri, x, 'fastmarching');\n% Note that for comparison purposes, Dijkstra's algorithm can be used\n% instead of Fast Marching\n% [~, param.d] = dmatrix_mesh(param.tri, x, 'dijkstra');\n% The latter is equivalent to the 'isomap' method above.\n%\n% If PARAM.d is not provided:\n%\n% PARAM.tri: [Req/Opt] 3-column matrix. Each row contains the 3 nodes\n% that form one triangular facet in the mesh.\n%\n% PARAM.dmethod: [Opt] String with the method to compute distances\n% between non-neighbours: 'fastmarching' (default) or 'dijkstra'. The\n% latter is faster, but suffers much more from metrication errors.\n%\n% PARAM.options: [Opt] Extra arguments passed to the fast marching\n% method. From the help to perform_fast_marching_mesh():\n% - options.W: non-uniform speed.\n% - options.heuristic: heuristic that tries to guess the distance\n% that remains from a given node to a given target. This is an\n% array of same size as W.\n% - parameters that create a local neighbourhood are ignored with a\n% warning.\n%\n%--------------------------------------------------------------------------\n%\n% * 'lmdscale': Open surface local neighbourhood MDS mapping (Schwartz,\n% Wolfson and Shaw [4, 5]), improved with a Fast Marching method\n% (Zigelman et al. [3]). This is like 'cmdsmap' above, but with local\n% neighbourhoods. Local neighbourhoods were already proposed in the\n% first publications [4, 5] on what we are calling MDS mapping. We use\n% our own implementation of this idea, lmdscale().\n%\n% PARAM.d or PARAM.tri must be provided. If PARAM.d is provided,\n% PARAM.tri and PARAM.options are ignored. Otherwise, PARAM.d is\n% computed from PARAM.tri and PARAM.options.\n%\n% PARAM.d: [Req/Opt] Can be a sparse or full distance matrix. Distances\n% greater than 0 reflect that two vertices are within a common local\n% neighbourhood.\n% [~, param.d] = dmatrix_mesh(param.tri, x, 'fastmarching');\n%\n% If PARAM.d is not provided:\n%\n% PARAM.tri: [Req/Opt] 3-column matrix. Each row contains the 3 nodes\n% that form one triangular facet in the mesh.\n%\n% PARAM.dmethod: [Opt] String with the method to compute distances\n% between non-neighbours: 'fastmarching' (default) or 'dijkstra'. The\n% latter is faster, but suffers much more from metrication errors,\n% and produces only full matrices in the current implementation, so\n% it's not valid for local neighbourhoods.\n%\n% PARAM.options: [Opt] Extra arguments passed to the fast marching\n% method. From the help to perform_fast_marching_mesh():\n% - options.constraint_map: Exploration radius to reduce the set of\n% explored points. Only points with current distance smaller than L\n% will be expanded. Set some entries of L to -Inf to avoid any\n% exploration of these points.\n% - options.W: non-uniform speed.\n% - options.end_points: stop when these points are reached.\n% - options.nb_iter_max: stop when a given number of iterations is\n% reached.\n% - options.heuristic: heuristic that tries to guess the distance\n% that remains from a given node to a given target. This is an\n% array of same size as W.\n%\n% PARAM.options2: [Opt] Extra arguments passed to the local\n% neighbourhood MDS algorithm. See help to lmdscale().\n% - opt.MaxIter: (default = 20) maximum number of iterations we allow\n% the optimisation algorithm. Each iteration consists of an entire\n% sweep of all points on the sphere.\n% - opt.MaxInc: inc is the Euclidean distance that each output point\n% is moved in an iteration. The algorithm will stop if no point has\n% been moved more than MaxInc.\n%\n% OUT.stopCondition: cell-array with the condition/s that made the\n% algorithm stop, in string form.\n%\n% OUT.err: struct with several error measures at each algorithm\n% iteration. See help to lmdscale() for details.\n%\n%\n%========================== CLOSED SURFACES ===============================\n%\n% * 'sphproj': Direct projection on unit sphere centered on point set\n% centroid.\n%\n% OUT.medrad: Median value of the radii of all points in the point\n% set.\n%\n%--------------------------------------------------------------------------\n%\n% * 'smdscale': Local neighbourhood Multidimensional scaling on a sphere.\n% Our extension to lmdscale() based on method by Agarwal et al. 2010\n% [6].\n%\n% PARAM.d or PARAM.tri must be provided. If PARAM.d is provided,\n% PARAM.tri and PARAM.options are ignored. Otherwise, PARAM.d is\n% computed from PARAM.tri and PARAM.options.\n%\n% PARAM.d: [Req/Opt] Can be a sparse or full distance matrix. Distances\n% greater than 0 reflect that two vertices are within a common local\n% neighbourhood.\n% [~, param.d] = dmatrix_mesh(param.tri, x, 'fastmarching');\n%\n% If PARAM.d is not provided:\n%\n% PARAM.tri: [Req/Opt] 3-column matrix. Each row contains the 3 nodes\n% that form one triangular facet in the mesh.\n%\n% PARAM.dmethod: [Opt] String with the method to compute distances\n% between non-neighbours: 'fastmarching' (default) or 'dijkstra'. The\n% latter is faster, but suffers much more from metrication errors,\n% and produces only full matrices in the current implementation, so\n% it's not valid for local neighbourhoods.\n%\n% PARAM.options: [Opt] Extra arguments passed to the fast marching\n% method. From the help to perform_fast_marching_mesh():\n% - options.constraint_map: Exploration radius to reduce the set of\n% explored points. Only points with current distance smaller than L\n% will be expanded. Set some entries of L to -Inf to avoid any\n% exploration of these points.\n% - options.W: non-uniform speed.\n% - options.end_points: stop when these points are reached.\n% - options.nb_iter_max: stop when a given number of iterations is\n% reached.\n% - options.heuristic: heuristic that tries to guess the distance\n% that remains from a given node to a given target. This is an\n% array of same size as W.\n%\n% PARAM.init: [Opt] Parameterization initialisation:\n% - 'sphproj' (default): Direct projection on unit sphere centered on\n% point set centroid, as the option above.\n% - 'random': Random distribution of points on the sphere. This is\n% useful if 'sphproj' produces a fold-over of points that\n% corresponds to a local minimum.\n% - [lat lon]: A 2-column matrix with the initial latitude and\n% longitude coordinates of the parameterization.\n%\n% PARAM.sphrad: [Opt] Parameterization sphere's radius. If not\n% provided, it is computed as the median of the distance of the\n% points in X to their centroid.\n%\n% PARAM.options2: [Opt] Extra arguments passed to the spherical local\n% neighbourhood MDS algorithm. See help to smdscale().\n% - opt.MaxIter: (default = 20) maximum number of iterations we allow\n% the optimisation algorithm. Each iteration consists of an entire\n% sweep of all points on the sphere.\n% - opt.MaxAlpha: inc is the angular distance in radians that each\n% output point is moved in an iteration. The algorithm will stop if\n% no point has been moved more than MaxAlpha.\n%\n% OUT.stopCondition: cell-array with the condition/s that made the\n% algorithm stop, in string form.\n%\n% OUT.err: Error measures vs. iterations:\n% - err.rawstress: Raw stress (sigma_r), as defined above.\n% - err.stress1: Stress-1 (sigma_1).\n% sigma_1 = sqrt(sigma_r / sum_{i,j} (d_ij)^2)\n% - err.maxalpha: Maximum angular displacement of any point in each\n% iteration.\n% - err.medalpha: Median angular displacement of all points in each\n% iteration.\n%\n%--------------------------------------------------------------------------\n%\n% * 'cald': Li Shen's Control Area and Length Distortions (CALD)\n% spherical parametrization [7, 8].\n%\n% PARAM.tri: [Req] 3-column matrix. Each row contains the 3 nodes that\n% form one triangular facet in the mesh.\n%\n% PARAM.options: [Opt] Extra arguments passed to CALD:\n% - options.MeshGridSize: The interpolation mesh used to smooth the\n% spherical parametrization has length 2*PARAM.MeshGridSize+1. By\n% default, MeshGridSize = 50.\n% - options.MaxSPHARMDegree: Degree of the spherical harmonics used\n% for interpolation to smooth the spherical parametrization. By\n% default, MaxSPHARMDegree = 6.\n% - options.Tolerance: Scalar. In the interpolation smoothing, grid\n% points with a height larger than PARAM.Tolerance*gmin, where gmin\n% is the lowest point in the grid, will be truncated. By default,\n% Tolerance = 2.\n% - options.Smoothing: Scalar. Before parametrization smoothing,\n% parametrization triangle areas relative to triangular mesh areas\n% are smoothed by elevating to (1/PARAM.Smoothing). By default,\n% Smoothing = 2.\n% - options.Iteration: Maximum number of smoothing iterations.\n% Smoothing will stop before reaching Iteration if the algorithm\n% converges to a solution. By default, Iteration = 100.\n% - options.LocalIteration: Number of smoothing iteration in the\n% local smoothing algorithm. By default, LocalIteration = 10.\n%\n%--------------------------------------------------------------------------\n%\n% [1] J.B. Tenenbaum, V. de Silva and J.C. Langford, \"A Global Geometric\n% Framework for Nonlinear Dimensionality Reduction\", Science 290(5500):\n% 2319-2323, 2000.\n%\n% [2] Isomap Homepage, http://isomap.stanford.edu/\n%\n% [3] G. Zigelman, R. Kimmel, and N. Kiryati, \"Texture mapping using\n% surface flattening via multidimensional scaling,” Visualization and\n% Computer Graphics, IEEE Transactions on, vol. 8, no. 2, pp. 198–207,\n% 2002.\n%\n% [4] E. Wolfson and E.L. Schwartz, \"Computing minimal distances on\n% polyhedral surfaces\", IEEE Pattern Analysis and Machine Intelligence,\n% 11(9):1001-1005, 1989.\n%\n% [5] E.L. Schwartz, A. Shaw, E. Wolfson, \"A numerical solution to the\n% generalized mapmaker’s problem: flattening nonconvex polyhedral\", IEEE\n% Pattern Analysis and Machine Intelligence, 11(9):1005-1008, 1989.\n%\n% [6] A. Agarwal et al., \"Universal Multi-Dimensional Scaling\", Procs. of\n% the 16th ACM SIGKDD international conference on Knowledge discovery and\n% data mining (KDD '10), p. 1149-1158.\n%\n% [7] Shen and Makedon, \"Spherical mapping for processing of 3D closed\n% surfaces\", Image and Vision Computing, 24(7):743–761, 2006.\n% http://www.sciencedirect.com/science/article/pii/S0262885606000485\n%\n% [8] CALD and SPHARM-MAT homepage,\n% http://www.iupui.edu/~shenlab/software.html\n%\n% See also: surface_tridomain, surface_interp, scimat_surface2seg.\n\n% Author: Ramon Casero \n% Copyright © 2013-2014 University of Oxford\n% Version: 0.6.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(2, 2);\n\nif (size(x, 2) ~= 3)\n error('X must be a 3-column matrix')\nend\n\nif ischar(param)\n aux = param; param = [];\n param.type = aux;\nend\n\nout = [];\n\n% defaults\nif (isempty(param) || ~isfield(param, 'type') ...\n || isempty(param.type))\n error('No PARAM.type provided');\nend\n\n% obtain a 2D parameterisation for the input 3D points\nswitch param.type\n \n%--------------------------------------------------------------------------\n% Open surface\n%--------------------------------------------------------------------------\n\n case 'xy'\n \n % check arguments\n nargoutchk(0, 1);\n \n % (u,v) is simply (x,y)\n uv = x(:, 1:2);\n \n%--------------------------------------------------------------------------\n\n case 'pca'\n \n % this function doesn't provide the \"out\" output\n nargoutchk(0, 1);\n \n % rotate valve points to make the valve surface as horizontal as\n % possible\n m = mean(x, 1);\n uv = x - m(ones(1, size(x, 1)), :);\n eigv = pts_pca(uv');\n uv = uv * eigv;\n uv = uv(:, 1:2);\n \n%--------------------------------------------------------------------------\n\n case 'isomap'\n \n % check arguments\n nargoutchk(0, 1);\n\n % IsomapII takes the following distance matrices:\n % (1) a full N x N matrix (as in isomap.m) \n % (2) a sparse N x N matrix (missing entries are treated as INF)\n % (3) the name of a function (e.g. 'd_fun') that takes\n % one argument, i, and returns a row vector containing the \n % distances from all N points to point i. \n \n % default parameters\n if (~isfield(param, 'neigh') || isempty(param.neigh))\n param.neigh = 'epsilon';\n end\n if (~isfield(param, 'size') || isempty(param.size))\n param.size = Inf;\n end\n\n % if distance matrix is not provided by the user, it is computed\n % internally as the full Euclidean distance matrix\n if (~isfield(param, 'd') || isempty(param.d))\n param.d = dmatrix(x', x', 'euclidean');\n end\n \n % compute 2-d projection of the 3-d data\n if (~isfield(param, 'options') || isempty(param.options))\n param.options.dims = 2;\n param.options.display = 0;\n param.options.overlay = 0;\n param.options.verbose = 0;\n param.options.dijkstra = 1;\n end\n uv = IsomapII(param.d, param.neigh, param.size, param.options);\n uv = uv.coords{1}';\n if (size(uv, 1) ~= size(x, 1))\n error('The neighbourhood size (param.size) is too small to connect all points')\n end\n \n%--------------------------------------------------------------------------\n\n case 'cmdsmap'\n \n % check arguments\n nargoutchk(0, 1);\n\n % if distance matrix is not provided we need to compute it from the\n % mesh description\n if (~isfield(param, 'd') || isempty(param.d))\n \n % but if the user hasn't provided the mesh triangulation\n % either, we cannot, so we give an error\n if (~isfield(param, 'tri') || isempty(param.tri))\n error('Either PARAM.d or PARAM.tri must be provided')\n end\n \n % default for fast marching method options\n if (~isfield(param, 'dmethod') || isempty(param.dmethod))\n param.dmethod = 'fastmarching';\n end\n if (~isfield(param, 'options') || isempty(param.options))\n param.options = [];\n end\n \n % remove fast marching options that don't apply to this method\n if (isfield(param.options, 'constraint_map'))\n warning('Gerardus:InvalidInputArg', 'PARAM.options.constraint_map ignored, this method only works with a full distance matrix')\n param.options = rmfield(param.options, 'constraint_map');\n end\n if (isfield(param.options, 'end_points'))\n warning('Gerardus:InvalidInputArg', 'PARAM.options.end_points ignored, this method only works with a full distance matrix')\n param.options = rmfield(param.options, 'end_points');\n end\n if (isfield(param.options, 'nb_iter_max'))\n warning('Gerardus:InvalidInputArg', 'PARAM.options.nb_iter_max ignored, this method only works with a full distance matrix')\n param.options = rmfield(param.options, 'nb_iter_max');\n end\n \n % compute full distance matrix from the mesh\n [~, param.d] ...\n = dmatrix_mesh(param.tri, x, param.dmethod, param.options);\n \n if (issparse(param.d))\n error('Assertion fail: param.d should be a ');\n end\n \n end\n \n % if the user provided a sparse distance matrix, we assume that\n % it's a mistake\n if (issparse(param.d))\n error('PARAM.d must be a full distance matrix, not a sparse mesh adjacency-distance matrix');\n end\n \n % use classic MDS for the optimization\n uv = cmdscale(param.d, 2);\n \n%--------------------------------------------------------------------------\n\n case 'lmdscale'\n \n % check arguments\n nargoutchk(0, 2);\n\n % if distance matrix is not provided we need to compute it from the\n % mesh description\n if (~isfield(param, 'd') || isempty(param.d))\n \n % but if the user hasn't provided the mesh triangulation\n % either, we cannot, so we give an error\n if (~isfield(param, 'tri') || isempty(param.tri))\n error('Either PARAM.d or PARAM.tri must be provided')\n end\n \n % default for distance method\n if (~isfield(param, 'options') || isempty(param.options))\n param.options = [];\n end\n \n % default for fast marching method options\n if (~isfield(param, 'dmethod') || isempty(param.dmethod))\n param.dmethod = 'fastmarching';\n end\n if (~isfield(param, 'options') || isempty(param.options))\n param.options = [];\n end\n \n % compute neighbourhood distance matrix from the mesh\n [~, param.d] ...\n = dmatrix_mesh(param.tri, x, param.dmethod, param.options);\n \n end\n \n % at this point, the distance matrix can be full or sparse, both\n % are valid, unlike in the cases above, where it had to be full\n \n % compute parameterization using local neighbourhood method\n [u, v, out.stopCondition, out.err] ...\n = lmdscale(param.d, [], [], param.options2);\n uv = [u, v];\n \n%--------------------------------------------------------------------------\n% Closed surface\n%--------------------------------------------------------------------------\n\n case 'sphproj'\n \n % check arguments\n nargoutchk(0, 2);\n\n % init output\n uv = zeros(size(x, 1), 1);\n \n % project 3D Cartesian coordinates onto the surface of a sphere\n % lon, lat given in radians, centered around 0\n [uv(:, 2), uv(:, 1), r] = cart2sph(...\n x(:, 1) - mean(x(:, 1)), ...\n x(:, 2) - mean(x(:, 2)), ...\n x(:, 3) - mean(x(:, 3)));\n \n % we use the median radius of the points in the configuration as the radius\n % of the sphere that best can contains their projections\n out.medrad = median(r);\n \n%--------------------------------------------------------------------------\n\n case 'smdscale'\n\n % check arguments\n nargoutchk(0, 2);\n\n % number of points to embed\n N = size(x, 1);\n \n % if distance matrix is not provided we need to compute it from the\n % mesh description\n if (~isfield(param, 'd') || isempty(param.d))\n \n % but if the user hasn't provided the mesh triangulation\n % either, we cannot, so we give an error\n if (~isfield(param, 'tri') || isempty(param.tri))\n error('Either PARAM.d or PARAM.tri must be provided')\n end\n \n % if no options are provided for fastmarching, we need to have\n % at least an empty field\n if (~isfield(param, 'options') || isempty(param.options))\n param.options = [];\n end\n \n % default for fast marching method options\n if (~isfield(param, 'dmethod') || isempty(param.dmethod))\n param.dmethod = 'fastmarching';\n end\n if (~isfield(param, 'options') || isempty(param.options))\n param.options = [];\n end\n \n % compute neighbourhood distance matrix from the mesh\n [~, param.d] ...\n = dmatrix_mesh(param.tri, x, param.dmethod, param.options);\n \n end\n \n % defaults\n if (~isfield(param, 'init') || isempty(param.init))\n param.init = 'sphproj';\n end\n\n % sMDS initialisation\n if ischar(param.init) % initial parametrization as a string\n \n switch param.init\n case 'sphproj'\n \n % initial guess for the sphere embedding by simply\n % projecting each point along the radius to the\n % centroid\n [lat, lon, sphrad] = proj_on_sphere(x);\n \n % if the user didn't provide an estimate for the\n % parameterization sphere's radius, we can use sphrad\n if (~isfield(param, 'sphrad') || isempty(param.sphrad))\n param.sphrad = sphrad;\n end\n \n case 'random'\n \n % counter-intuitively, starting from a completely\n % random distribution usually gives good results\n lat = (rand(N, 1) - .5) * pi;\n lon = 2 * (rand(N, 1) - .5) * pi;\n \n otherwise\n error('Not valid initialisation for spherical Isomap parameterisation')\n end\n \n else % initial parametrization as a point set\n \n if (size(param.init, 1) ~= N || size(param.init, 1) ~= 2)\n error('Initial parametrization provided, but it is not a 2-column matrix with the same number of points as X')\n end\n \n lat = param.init(:, 1);\n lon = param.init(:, 2);\n \n end\n \n % if the user has not provided an estimate for the parameterization\n % sphere's radius, we have to compute it internally\n if (~isfield(param, 'sphrad') || isempty(param.sphrad))\n [~, ~, param.sphrad] = proj_on_sphere(x);\n end\n \n % if no options are provided for the MDS algorithm, we need to have\n % at least an empty field\n if (~isfield(param, 'options2') || isempty(param.options2))\n param.options = [];\n end\n \n % compute the parametrization that optimises isometry\n [lat, lon, out.stopCondition, out.err] = ...\n smdscale(param.d, param.sphrad, lat, lon, param.options2);\n \n % create output with the parameterisation values for each point\n % lat = em(1, :)\n % lon = em(2, :)\n uv = [lat lon];\n \n%--------------------------------------------------------------------------\n\n case 'cald'\n \n % check arguments\n nargoutchk(0, 1);\n\n % required parameters\n if (~isfield(param, 'tri') || isempty(param.tri))\n error('PARAM.tri must be provided')\n end\n\n % set up parameters for the CALD algorithm. We have to create a\n % structure with the right format. We can then replace default\n % values by values provided by the user\n param.options.vars = {'MeshGridSize', 'MaxSPHARMDegree', 'Tolerance', ...\n 'Smoothing', 'Iteration', 'LocalIteration', 't_major', ...\n 'SelectDiagonal', 'OutDirectory'};\n param.options.args = [1 1 1 1 1 1 10 10 200];\n param.options.inFilter = {\n '*_bim.mat;*_fix.mat;*_obj.mat' 'Binary and Mesh Objects (*_bim.mat;*_fix.mat;*_obj.mat)'\n '*_obj.mat' 'Mesh Objects (*_obj.mat)'\n '*_bim.mat;*_fix.mat' 'Binary Objects (*_bim.mat, *_fix.mat)'\n '*.mat' 'All Objects (*.mat)'\n };\n param.options.default = {'50' '6' '2' '2' '100' '10' '' '' './'};\n if (~isfield(param.options, 'MeshGridSize') || isempty(param.options.MeshGridSize))\n param.options.MeshGridSize = 50;\n end\n if (~isfield(param.options, 'MaxSPHARMDegree') || isempty(param.options.MaxSPHARMDegree))\n param.options.MaxSPHARMDegree = 6;\n end\n if (~isfield(param.options, 'Tolerance') || isempty(param.options.Tolerance))\n param.options.Tolerance = 2;\n end\n if (~isfield(param.options, 'Smoothing') || isempty(param.options.Smoothing))\n param.options.Smoothing = 2;\n end\n if (~isfield(param.options, 'Iteration') || isempty(param.options.Iteration))\n param.options.Iteration = 100;\n end\n if (~isfield(param.options, 'LocalIteration') || isempty(param.options.LocalIteration))\n param.options.LocalIteration = 10;\n end\n param.options.t_major = 'x';\n param.options.SelectDiagonal = 'ShortDiag';\n param.options.OutDirectory = '.';\n param.options = orderfields(param.options, ...\n {'vars', 'args', 'inFilter', 'default', ...\n 'MeshGridSize', 'MaxSPHARMDegree', 'Tolerance', ...\n 'Smoothing', 'Iteration', 'LocalIteration', 't_major', ...\n 'SelectDiagonal', 'OutDirectory'});\n \n % initial parametrization\n [sph_verts, name3] ...\n = initParamCALD(x, param.tri, '', param.options);\n \n if (any(isnan(sph_verts)))\n error('Initial parameterization produced NaN values')\n end\n \n % smooth the parameterization\n [~, ~, sph_verts, new_name] ...\n = smootheCALD(x, param.tri, sph_verts, name3, param.options);\n \n % convert xyz coordinates to spherical coordinates\n [lon, lat] ...\n = cart2sph(sph_verts(:, 1), sph_verts(:, 2), sph_verts(:, 3));\n \n % delete files created by the SPHARM functions\n if exist(new_name, 'file')\n delete(new_name) % CALD_smo.mat\n end\n if exist('initParamCALD', 'file')\n rmdir('initParamCALD', 's')\n end\n \n % create output\n uv = [lat lon];\n \n%--------------------------------------------------------------------------\n\n otherwise\n \n error('Parametrization method not implemented')\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/ManifoldToolbox/surface_param.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7162792541768195}} {"text": "function [acre] = m22acre(m2)\n% Convert area from square meters to acres.\n% Chad A. Greene 2012\nacre = m2*0.0002471053814672;", "meta": {"author": "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/m22acre.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.8031737940012417, "lm_q1q2_score": 0.7162792516586496}} {"text": "function M = rotmat(deg)\n% M = rotmat(deg)\n\nrads = radians(deg) ;\n\nM = eye(3) ;\nM(1,1) = cos(rads) ;\nM(1,2) = sin(rads) ;\nM(2,1) = -sin(rads) ;\nM(2,2) = cos(rads) ;\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/freesurfer/rotmat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7162424583835157}} {"text": "% Fig. 5.9 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n% Script to generate Figure 5.9\n\nclf\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.9 Locus for L=1/[s(s+4)^2+16)]')\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/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig5_09.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7162124187258173}} {"text": "function [center,radius] = minboundcircle(x,y,hullflag)\n% minboundcircle: Compute the minimum radius enclosing circle of a set of (x,y) pairs\n% usage: [center,radius] = minboundcircle(x,y,hullflag)\n%\n% arguments: (input)\n% x,y - vectors of points, describing points in the plane as\n% (x,y) pairs. x and y must be the same size. If x and y\n% are arrays, they will be unrolled to vectors.\n%\n% hullflag - boolean flag - allows the user to disable the\n% call to convhulln. This will allow older releases of\n% matlab to use this code, with a possible time penalty.\n% It also allows minboundellipse to call this code\n% efficiently.\n% \n% hullflag = false --> do not use the convex hull\n% hullflag = true --> use the convex hull for speed\n%\n% default: true\n%\n%\n% arguments: (output)\n% center - 1x2 vector, contains the (x,y) coordinates of the\n% center of the minimum radius enclosing circle\n%\n% radius - scalar - denotes the radius of the minimum\n% enclosing circle\n%\n%\n% Example usage:\n% x = randn(50000,1);\n% y = randn(50000,1);\n% tic,[c,r] = minboundcircle(x,y);toc\n%\n% Elapsed time is 0.171178 seconds.\n%\n% c: [-0.2223 0.070526]\n% r: 4.6358\n%\n%\n% See also: minboundrect\n%\n%\n% Author: John D'Errico\n% E-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 1/10/07\n\n% default for hullflag\nif (nargin<3) || isempty(hullflag)\n hullflag = true;\nelseif ~islogical(hullflag) && ~ismember(hullflag,[0 1])\n error 'hullflag must be true or false if provided'\nend\n\n% preprocess data\nx=x(:);\ny=y(:);\n\n% not many error checks to worry about\nn = length(x);\nif n~=length(y)\n error 'x and y must be the same sizes'\nend\n\n% start out with the convex hull of the points to\n% reduce the problem dramatically. Note that any\n% points in the interior of the convex hull are\n% never needed.\nif hullflag && (n>3)\n edges = convhulln([x,y],{'QJ' 'Pp'});\n\n % list of the unique points on the convex hull itself\n % convhulln returns them as edges\n edges = unique(edges(:));\n\n % exclude those points inside the hull as not relevant\n x = x(edges);\n y = y(edges);\n \nend\n\n% now we must find the enclosing circle of those that\n% remain.\nn = length(x);\n\n% special case small numbers of points. If we trip any\n% of these cases, then we are done, so return.\nswitch n\n case 0\n % empty begets empty\n center = [];\n radius = [];\n return\n case 1\n % with one point, the center has radius zero\n center = [x,y];\n radius = 0;\n return\n case 2\n % only two points. center is at the midpoint\n center = [mean(x),mean(y)];\n radius = norm([x(1),y(1)] - center);\n return\n case 3\n % exactly 3 points\n [center,radius] = enc3(x,y);\n return\nend\n\n% more than 3 points.\n\n% Use an active set strategy.\naset = 1:3; % arbitrary, but quite adequate\niset = 4:n;\n\n% pick a tolerance\ntol = 10*eps*(max(abs(mean(x) - x)) + max(abs(mean(y) - y)));\n\nflag = true;\nwhile flag\n % get the enclosing circle for the current set\n [center,radius] = enc3(x(aset),y(aset));\n \n % are all the inactive set points inside the circle?\n r = sqrt((x(iset) - center(1)).^2 + (y(iset) - center(2)).^2);\n [rmax,k] = max(r);\n if (rmax - radius) <= tol\n % the active set enclosing circle also enclosed\n % all of the inactive points.\n flag = false;\n else\n % it must be true that we can replace one member of aset\n % with iset(k). Which one?\n s1 = [aset([2 3]),iset(k)];\n [c1,r1] = enc3(x(s1),y(s1));\n if (norm(c1 - [x(aset(1)),y(aset(1))]) <= r1)\n center = c1;\n radius = r1;\n \n % update the active/inactive sets\n swap = aset(1);\n aset = [iset(k),aset([2 3])];\n iset(k) = swap;\n \n % bounce out to the while loop\n continue\n end\n s1 = [aset([1 3]),iset(k)];\n [c1,r1] = enc3(x(s1),y(s1));\n if (norm(c1 - [x(aset(2)),y(aset(2))]) <= r1)\n center = c1;\n radius = r1;\n \n % update the active/inactive sets\n swap = aset(2);\n aset = [iset(k),aset([1 3])];\n iset(k) = swap;\n \n % bounce out to the while loop\n continue\n end\n s1 = [aset([1 2]),iset(k)];\n [c1,r1] = enc3(x(s1),y(s1));\n if (norm(c1 - [x(aset(3)),y(aset(3))]) <= r1)\n center = c1;\n radius = r1;\n \n % update the active/inactive sets\n swap = aset(3);\n aset = [iset(k),aset([1 2])];\n iset(k) = swap;\n \n % bounce out to the while loop\n continue\n end\n \n % if we get through to this point, then something went wrong.\n % Active set problem. Increase tol, then try again.\n tol = 2*tol;\n \n end\n \nend\n\n% =======================================\n% begin subfunction\n% =======================================\nfunction [center,radius] = enc3(X,Y)\n% minimum radius enclosing circle for exactly 3 points\n%\n% x, y are 3x1 vectors\n\n% convert to complex\nxy = X + sqrt(-1)*Y;\n\n% just in case the points are collinear or nearly so, get\n% the interpoint distances, and test the farthest pair\n% to see if they work.\nDij = @(XY,i,j) abs(XY(i) - XY(j));\nD12 = Dij(xy,1,2);\nD13 = Dij(xy,1,3);\nD23 = Dij(xy,2,3);\n\n% Find the most distant pair. Test if their circumcircle\n% also encloses the third point.\nif (D12>=D13) && (D12>=D23)\n center = (xy(1) + xy(2))/2;\n radius = D12/2;\n if abs(center - xy(3)) <= radius\n center = [real(center),imag(center)];\n return\n end\nelseif (D13>=D12) && (D13>=D23)\n center = (xy(1) + xy(3))/2;\n radius = D13/2;\n if abs(center - xy(2)) <= radius\n center = [real(center),imag(center)];\n return\n end\nelseif (D23>=D12) && (D23>=D13)\n center = (xy(2) + xy(3))/2;\n radius = D23/2;\n if abs(center - xy(1)) <= radius\n center = [real(center),imag(center)];\n return\n end\nend\n\n% if we drop down to here, then the points cannot\n% be collinear, so the resulting 2x2 linear system\n% of equations will not be singular.\nA = 2*[X(2)-X(1), Y(2)-Y(1); X(3)-X(1), Y(3)-Y(1)];\nrhs = [X(2)^2 - X(1)^2 + Y(2)^2 - Y(1)^2; ...\n X(3)^2 - X(1)^2 + Y(3)^2 - Y(1)^2];\n \ncenter = (A\\rhs)';\nradius = norm(center - [X(1),Y(1)]);\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/34767-a-suite-of-minimal-bounding-objects/MinBoundSuite/minboundcircle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684336, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7162124109282217}} {"text": "\n\nV = (max(newt2.Latitude) - min(newt2.Latitude)) * (max(newt2.Longitude) - min(newt2.Longitude)) * 111*111 *1000*1000 *100 *100*30*1000*100;\ndt = max(newt2.Date) - min(newt2.Date);\nc = sum( 10.^(1.5*newt2.Magnitude + 16.1));\nMsum = 2/3*( log10(c) - 16.1 )\nstrain = 1/(2*3*10^11*V*dt) * c\n% annual deformation in mm\ndef = strain*(max(newt2.Latitude) - min(newt2.Latitude))*111*1000*100*10\n\n\n%bdiff2\nplotfmdsA1A2\nc = 0; RE = [];\ndt = 1;\nfor m = 2:0.1:9\n N = 10^(aw-bw*m);\n c = c + N*( 10.^(1.5*m + 16.1));\n Msum = 2/3*( log10(c) - 16.1 );\n strain = 1/(2*3*10^11*V*dt) * c;\n def = strain*(max(newt2.Latitude) - min(newt2.Latitude))*111*1000*100*10;\n RE = [RE ; m Msum strain def];\nend\n\nfigure\npl = plot(RE(:,1),RE(:,4),'sk');\nset(gca,'Yscale','log')\nset(pl,'markerfacecolor','b');\nxlabel('Mw')\nylabel('annual deformation (mm)');\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/strainrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947148047777, "lm_q2_score": 0.7577943712746407, "lm_q1q2_score": 0.7161116757633449}} {"text": "function coeff = calc_energy_coeff(dim,N,s,energy)\n%CALC_ENERGY_COEFF Coefficient of second term in expansion of energy\n%\n%Syntax\n% coeff = calc_energy_coeff(d,N,s,energy);\n%\n%Description\n% COEFF = CALC_ENERGY_COEFF(dim,N,s,ENERGY) sets COEFF to be the coefficient of\n% the second term of an expansion of ENERGY with the same form as the expansion \n% of E(dim,N,s), the minimum r^(-s) energy of a set of N points on S^dim.\n%\n% Specifically, for s not equal to 0, COEFF is the solution to\n%\n% ENERGY == (SPHERE_INT_ENERGY(dim,s)/2) N^2 + COEFF N^(1+s/dim),\n%\n% and for s == 0 (the logarithmic potential), COEFF is the solution to\n%\n% ENERGY == (SPHERE_INT_ENERGY(dim,0)/2) N^2 + COEFF N LOG(N).\n%\n% The argument dim must be a positive integer.\n% The argument N must be a positive integer or an array of positive integers. \n% The argument ENERGY must an array of real numbers of the same array size as N.\n% The result COEFF will be an array of the same size as N.\n%\n%Notes\n% 1) The energy expansion is not valid for N == 1, and in particular,\n%\n% EQ_ENERGY_COEFF(dim,N,0,energy) := 0.\n%\n% 2) For s > 0, [KuiS98 (1.6) p524] has\n%\n% E(dim,N,s) == (SPHERE_INT_ENERGY(dim,s)/2) N^2 + COEFF N^(1+s/dim) + ...\n% \n% where SPHERE_INT_ENERGY(dim,s) is the energy integral of the r^(-s) potential\n% on S^dim.\n%\n% The case s == 0 (logarithmic potential) can be split into subcases.\n% For s == 0 and dim == 1, E(1,N,0) is obtained by equally spaced points on S^1,\n% and the formula for the log potential for N equally spaced points on a circle\n% gives\n%\n% E(1,N,0) == (-1/2) N LOG(N) exactly.\n%\n% For s == 0 and dim == 2, [SafK97 (4) p7] has\n%\n% E(2,N,0) == (SPHERE_INT_ENERGY(2,0)/2) N^2 + COEFF N LOG(N) + o(N LOG(N)).\n%\n% In general, for s == 0,\n%\n% E(dim,N,0) == (SPHERE_INT_ENERGY(dim,0)/2) N^2 + COEFF N LOG(N) + ... \n%\n% with sphere_int_energy(1,0) == 0.\n%\n% CALC_ENERGY_COEFF just uses this general formula for s == 0, so for s == 0 and\n% dim == 1, the coefficient returned is actually the coefficient of the first\n% non-zero term.\n%\n%Examples\n% > N=2:6\n% N =\n% 2 3 4 5 6\n% \n% > energy=eq_energy_dist(2,N,0)\n% energy =\n% -0.6931 -1.3863 -2.7726 -4.4205 -6.2383\n% \n% > calc_energy_coeff(2,N,0,energy)\n% ans =\n% -0.2213 -0.1569 -0.2213 -0.2493 -0.2569\n%\n%See also\n% EQ_ENERGY_DIST, EQ_ENERGY_COEFF\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-12 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\n%\n% Compute the energy coefficient: subtract the first term in the expansion of\n% the minimum energy and divide by the power of N in the second term.\n%\nif s > 0\n %\n % The first term in the expansion of the minimum energy.\n % Ref: [KuiS98 (1.6) p524]\n %\n first_term = (sphere_int_energy(dim,s)/2) * N.^2;\n coeff = (energy-first_term) ./ (N.^(1+s/dim));\nelse\n %\n % Flatten N into a row vector.\n %\n shape = size(N);\n n_partitions = prod(shape);\n N = reshape(N,1,n_partitions);\n %\n % Refs for s==0, dim == 2: \n % [SafK97 (4) p. 7] [Zho95 (5.6) p. 68, 3.11 - corrected) p. 42]\n %\n first_term = (sphere_int_energy(dim,s)/2) * N.^2;\n %\n % Avoid division by zero.\n %\n coeff = zeros(size(N));\n neq1 = (N ~= 1);\n coeff(neq1) = (energy(neq1)-first_term(neq1)) ./ (N(neq1) .* log(N(neq1)));\n %\n % Reshape output to same array size as original N.\n %\n coeff = reshape(coeff,shape);\n %\nend\n%\n% end function\n\nfunction energy = sphere_int_energy(dim,s)\n%SPHERE_INT_ENERGY Energy integral of r^(-s) potential\n%\n%Syntax\n% energy = sphere_int_energy(d,s);\n%\n%Description\n% ENERGY = SPHERE_INT_ENERGY(dim,s) sets ENERGY to be the energy integral \n% on S^dim of the r^(-s) potential, defined using normalized Lebesgue measure.\n%\n% Ref for s > 0: [KuiS98 (1.6) p524]\n% Ref for s == 0 and dim == 2: SafK97 (4) p. 7] \n% For s == 0 and dim >= 2, integral was obtained using Maple:\n% energy = (1/2)*(omega(dim)/omega(dim+1)* ...\n% int(-log(2*sin(theta/2)*(sin(theta))^(dim-1),theta=0..Pi),\n% where omega(dim+1) == area_of_sphere(dim).\n\nif s ~= 0\n energy = (gamma((dim+1)/2)*gamma(dim-s)/(gamma((dim-s+1)/2)*gamma(dim-s/2)));\nelseif dim ~= 1\n energy = (psi(dim)-psi(dim/2)-log(4))/2;\nelse\n energy = 0; \nend\n%\n% end function\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/eq_sphere_partitions/eq_point_set_props/calc_energy_coeff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7160614879719182}} {"text": "% \n% Usage: V=mexSparseProject(U,param);\n%\n% Name: mexSparseProject\n%\n% Description: mexSparseProject solves various optimization \n% problems, including projections on a few convex sets.\n% It aims at addressing the following problems\n% for all columns u of U in parallel\n% 1) when param.mode=1 (projection on the l1-ball)\n% min_v ||u-v||_2^2 s.t. ||v||_1 <= thrs\n% 2) when param.mode=2\n% min_v ||u-v||_2^2 s.t. ||v||_2^2 + lamuda1||v||_1 <= thrs\n% 3) when param.mode=3\n% min_v ||u-v||_2^2 s.t ||v||_1 + 0.5lamuda1||v||_2^2 <= thrs \n% 4) when param.mode=4\n% min_v 0.5||u-v||_2^2 + lamuda1||v||_1 s.t ||v||_2^2 <= thrs\n% 5) when param.mode=5\n% min_v 0.5||u-v||_2^2 + lamuda1||v||_1 +lamuda2 FL(v) + ... \n% 0.5lamuda_3 ||v||_2^2\n% where FL denotes a \"fused lasso\" regularization term.\n% 6) when param.mode=6\n% min_v ||u-v||_2^2 s.t lamuda1||v||_1 +lamuda2 FL(v) + ...\n% 0.5lamuda3||v||_2^2 <= thrs\n% \n% When param.pos=true and param.mode <= 4,\n% it solves the previous problems with positivity constraints \n%\n% Inputs: U: double m x n matrix (input signals)\n% m is the signal size\n% n is the number of signals to project\n% param: struct\n% param.thrs (parameter)\n% param.lambda1 (parameter)\n% param.lambda2 (parameter)\n% param.lambda3 (parameter)\n% param.mode (see above)\n% param.pos (optional, false by default)\n% param.numThreads (optional, number of threads for exploiting\n% multi-core / multi-cpus. By default, it takes the value -1,\n% which automatically selects all the available CPUs/cores).\n%\n% Output: V: double m x n matrix (output matrix)\n%\n% Note: this function admits a few experimental usages, which have not\n% been extensively tested:\n% - single precision setting \n%\n% Author: Julien Mairal, 2009\n\n\n", "meta": {"author": "tiepvupsu", "repo": "DICTOL", "sha": "1a0361aa35c32d70525d06910d0e9b87997ff246", "save_path": "github-repos/MATLAB/tiepvupsu-DICTOL", "path": "github-repos/MATLAB/tiepvupsu-DICTOL/DICTOL-1a0361aa35c32d70525d06910d0e9b87997ff246/build_spams/mexSparseProject.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900945711678, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7160586375290603}} {"text": "function value = r4_asin ( x )\n\n%*****************************************************************************80\n%\n%% R4_ASIN evaluates the arc-sine of 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 arc-sine of X.\n%\n persistent asincs\n persistent nterms\n persistent sqeps\n\n if ( isempty ( nterms ) )\n asincs = [ ...\n 0.10246391753227159, ...\n 0.054946487221245833, ...\n 0.004080630392544969, ...\n 0.000407890068546044, ...\n 0.000046985367432203, ...\n 0.000005880975813970, ...\n 0.000000777323124627, ...\n 0.000000106774233400, ...\n 0.000000015092399536, ...\n 0.000000002180972408, ...\n 0.000000000320759842, ...\n 0.000000000047855369, ...\n 0.000000000007225128, ...\n 0.000000000001101833, ...\n 0.000000000000169476, ...\n 0.000000000000026261, ...\n 0.000000000000004095, ...\n 0.000000000000000642, ...\n 0.000000000000000101, ...\n 0.000000000000000016 ]';\n nterms = r4_inits ( asincs, 20, 0.1 * r4_mach ( 3 ) );\n sqeps = sqrt ( 6.0 * r4_mach ( 3 ) );\n end\n\n y = abs ( x );\n\n if ( x < - 1.0 - sqeps )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_ASIN - Fatal error!\\n' );\n fprintf ( 1, ' X < - 1.0\\n' );\n error ( 'R4_ASIN - Fatal error!' )\n\n elseif ( x < - 1.0 )\n\n value = - 0.5 * pi;\n\n elseif ( x < 1.0 )\n\n z = 0.0;\n if ( sqeps < y )\n z = y * y;\n end\n\n if ( z <= 0.5 )\n value = x * ( 1.0 + r4_csevl ( 4.0 * z - 1.0, asincs, nterms ) );\n else\n value = 0.5 * pi - sqrt ( 1.0 - z ) * ( 1.0 + ...\n r4_csevl ( 3.0 - 4.0 * z, asincs, nterms ) );\n end\n\n if ( x < 0.0 )\n value = - abs ( value );\n elseif ( 0.0 < x )\n value = + abs ( value );\n end\n\n elseif ( x < 1.0 + sqeps )\n\n value = 0.5 * pi;\n\n else\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R4_ASIN - Fatal error!\\n' );\n fprintf ( 1, ' 1.0 < X\\n' );\n error ( 'R4_ASIN - Fatal 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/fn/r4_asin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7160210875989887}} {"text": "function alt = triaxial(rsc)\n\n% geodetic altitude relative\n% to a triaxial ellipsoid\n\n% input\n\n% rsc = geocentric position vector (kilometers)\n\n% output\n\n% alt = geodetic altitude (kilometers)\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal flat cx cy cz vcon ucon caxis\n\n% semi-axes\n\naaxis = 6378.138;\nbaxis = 6367.0;\ncaxis = aaxis * (1 - flat);\n\nucon = aaxis * aaxis - caxis * caxis;\n\nvcon = baxis * baxis - caxis * caxis;\n\ncx = (aaxis * caxis * rsc(1)) ^ 2;\ncy = (baxis * caxis * rsc(2)) ^ 2;\ncz = caxis ^ 2 * rsc(3);\n\ng = sqrt((rsc(1) / aaxis) ^ 2 + (rsc(2) / baxis) ^ 2 + ...\n (rsc(3) / caxis) ^ 2);\n\nzp0 = rsc(3) / g;\n\n% bracketing interval\n\nzp1 = zp0 - 10;\n\nzp2 = zp0 + 10;\n\nrtol = 1.0e-8;\n\nzp = brent('trifunc', zp1, zp2, rtol);\n\nxp = (aaxis ^ 2 * rsc(1) * zp) / (caxis ^ 2 * rsc(3) + ucon * zp);\n\nyp = (baxis ^ 2 * rsc(2) * zp) / (caxis ^ 2 * rsc(3) + vcon * zp);\n\ndx = rsc(1) - xp;\ndy = rsc(2) - yp;\ndz = rsc(3) - zp;\n\nalt = sqrt(dx ^ 2 + dy ^ 2 + dz ^ 2);\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/triaxial.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395157060208, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7160210739726255}} {"text": "function Jb = JacobianBody_sym(Blist, thetalist)\n% *** CHAPTER 5: VELOCITY KINEMATICS AND STATICS ***\n% Takes Blist: The joint screw axes in the end-effector frame when the\n% manipulator is at the home position, in the format of a \n% matrix with the screw axes as the columns,\n% thetalist: A list of joint coordinates.\n% Returns the corresponding body Jacobian (6xn real numbers).\n% Example Input:\n% \n% clear; clc;\n% Blist = [[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% Jb = JacobianBody(Blist, thetalist)\n% \n% Output:\n% Jb =\n% -0.0453 0.9950 0 1.0000\n% 0.7436 0.0930 0.3624 0\n% -0.6671 0.0362 -0.9320 0\n% 2.3259 1.6681 0.5641 0.2000\n% -1.4432 2.9456 1.4331 0.3000\n% -2.0664 1.8288 -1.5887 0.4000\n\nJb = sym(Blist);\nT = eye(4);\nfor i = length(thetalist) - 1: -1: 1 \n T = T * simplify(MatrixExp6_sym(VecTose3(Blist(:, i + 1)),-1*thetalist(i + 1)));\n\tJb(:, i) = Adjoint(T) * Blist(:, 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/JacobianBody_sym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.7159711688644838}} {"text": "function lagrange_nd_test10 ( )\n\n%*****************************************************************************80\n%\n%% LAGRANGE_ND_TEST10 tests LAGRANGE_PARTIAL2 in 2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 January 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LAGRANGE_ND_TEST10\\n' );\n fprintf ( 1, ' LAGRANGE_PARTIAL2 determines\\n' );\n fprintf ( 1, ' the Lagrange interpolating polynomials L(x)\\n' );\n fprintf ( 1, ' for ND points in D dimensions, assuming that\\n' );\n fprintf ( 1, ' the number of points is less than or equal to\\n' );\n fprintf ( 1, ' R = Pi(D,N), the number of monomials of degree N or less\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For this example, the data points are the same as those\\n' );\n fprintf ( 1, ' used by the level 2 Clenshaw Curtis sparse grid in 2D.\\n' );\n\n d = 2;\n n = 4;\n r = mono_upto_enum ( d, n );\n nd = 13;\n xd = [ 0.0, 0.0;\n -1.0, 0.0;\n 1.0, 0.0,\n 0.0, -1.0,\n 0.0, 1.0,\n -1.0, 1.0,\n 1.0, 1.0,\n -1.0, -1.0,\n 1.0, -1.0,\n -0.5, 0.0,\n 0.0, -0.5,\n 0.0, +0.5,\n 0.5, 0.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension D = %d\\n', d );\n fprintf ( 1, ' Maximum degree N = %d\\n', n );\n fprintf ( 1, ' Number of monomials R = %d\\n', r );\n fprintf ( 1, ' Number of data points ND = %d\\n', nd );\n\n r8mat_transpose_print ( d, nd, xd, ' Data points XD:' );\n\n [ po, pc, pe ] = lagrange_partial2 ( d, n, r, nd, xd );\n%\n% Print the polynomials.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Lagrange polynomials for XD data points:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : nd\n o = po(i);\n label = sprintf ( ' P(%d)(x) =', i );\n polynomial_print ( d, o, pc(i,1:o), pe(i,1:o), label );\n end\n%\n% Evaluate the polynomials at XD.\n%\n value = zeros ( nd, nd );\n\n for j = 1 : nd\n o = po(j);\n label = sprintf ( ' P(%d)(x) =', j );\n value(1:nd,j) = polynomial_value ( d, o, pc(j,1:o), pe(j,1:o), nd, xd ); \n end\n\n err = r8mat_is_identity ( nd, value );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Frobenius norm of Lagrange matrix error = %g\\n', err );\n%\n% Now evaluate a function at the data points.\n%\n pd = zeros ( nd, 1 );\n for i = 1 : nd\n pd(i) = sin ( xd(1,i) ) * cos ( xd(2,i) );\n end\n%\n% Compare exact function and interpolant at a grid of points.\n%\n ni = 11 * 11;\n xyi = zeros ( 2, ni );\n\n k = 0;\n for j = 1 : 11\n for i = 1 : 11\n k = k + 1;\n xyi(1,k) = ( ( 11 - i ) * ( - 1.0 ) ...\n + ( i - 1 ) * ( + 1.0 ) ) ...\n / ( 11 - 1 );\n xyi(2,k) = ( ( 11 - j ) * ( - 1.0 ) ...\n + ( j - 1 ) * ( + 1.0 ) ) ...\n / ( 11 - 1 );\n end\n end\n\n pn = nd;\n zi = interpolant_value ( d, r, pn, po, pc, pe, pd, ni, xyi );\n\n err = 0.0;\n for k = 1 : ni\n f = sin ( xyi(1,k) ) * cos ( xyi(2,k) );\n err = max ( err, abs ( zi(k) - f ) );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Maximum absolute interpolant error on 11x11 grid = %g\\n', err );\n\n%\n% Plot the interpolant at a grid of points.\n%\n% Reshuffling the shapes of MATLAB vectors is my definition of hell.\n%\n x1 = linspace ( -1, +1, 11 );\n y1 = linspace ( -1, +1, 11 );\n [ x2, y2 ] = meshgrid ( x1, y1 );\n x3 = reshape ( x2, 1, 11 * 11 );\n y3 = reshape ( y2, 1, 11 * 11 );\n xyi = [ x3; y3 ];\n ni = 11 * 11;\n zi = interpolant_value ( d, r, pn, po, pc, pe, pd, ni, xyi );\n z2 = reshape ( zi, 11, 11 );\n\n surf ( x2, y2, z2 );\n title ( 'Lagrange interpolant to sin(x)*cos(y)', 'FontSize', 16 )\n xlabel ( '<---X--->', 'FontSize', 16 )\n ylabel ( '<---Y--->', 'FontSize', 16 )\n zlabel ( '<---F(X,Y)--->', 'FontSize', 16 )\n\n filename = 'test10_interpolant.png';\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Saving plot file in \"%s\"\\n', filename );\n\n return\nend\n\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/lagrange_nd/lagrange_nd_test10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7159711674150254}} {"text": "function [sY] = smooth2(Y,va)\n% smooth 2D image with gaussian kernel\n% function [sY] = smooth2(Y,va)\n% IN:\n% - Y: the input image\n% - va: the smoothing value\n\nif ~exist('va','var') || isempty(va)\n va = 0;\nend\n\nif va > 0\n nv = 4;\n w = zeros(2*nv+1);\n for i=-nv:nv\n for j=-nv:nv\n w(i+nv+1,j+nv+1) = exp(-0.5.*(i.^2+j.^2)/va);\n end\n end\n w = w./sum(w(:));\n sY = conv2(Y,w,'same');\nelse\n sY = Y;\nend\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/legacy/trashbin/smooth2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.7159711623280162}} {"text": "function theta = polyhedronNormalAngle(varargin)\n%POLYHEDRONNORMALANGLE Compute normal angle at a vertex of a 3D polyhedron.\n%\n% THETA = polyhedraNormalAngle(NODES, EDGES, FACES, IND);\n% THETA = polyhedraNormalAngle(NODES, FACES, IND);\n% where NODES is a set of 3D points, and FACES a set of faces, whose\n% elements are indices to NODES array, compute the normal angle at the\n% vertex whose index is given by IND.\n%\n% THETA = polyhedraNormalAngle(GRAPH, IND);\n% Uses a graph structure. GRAPH should contain at least fields : 'nodes'\n% and 'faces'.\n%\n% Example :\n% % create a simple (irregular) tetrahedra\n% nodes = [0 0 0;1 0 0;0 1 0;0 0 1];\n% faces = [1 2 3;1 2 4;1 3 4;2 3 4];\n% % compute normal angle at each vertex\n% theta = polyhedronNormalAngle(nodes, faces, 1:size(nodes, 1));\n% % sum of normal angles should be equal to 4*pi :\n% sum(theta)\n%\n% To-do\n% Works only for polyhedra with convex faces!!!\n%\n% See also \n% polyhedra, polygon3dNormalAngle\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2005-11-30\n% Copyright 2005-2022 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas)\n\nif length(varargin)==4\n nodes = varargin{1};\n faces = varargin{3};\n ind = varargin{4};\n \nelseif length(varargin)==3\n nodes = varargin{1};\n faces = varargin{2};\n ind = varargin{3};\n \nelseif length(varargin)==2\n graph = varargin{1};\n nodes = graph.nodes;\n faces = graph.faces;\n ind = varargin{2};\nelse\n error('wrong number of arguments');\nend\n\n\n% number of angles to compute\nna = length(ind);\n\ntheta = zeros(na, 1);\nfor i=1:na\n \n thetaf = [];\n \n % find faces containing given vertex,\n % and compute normal angle at each face containing vertex\n if iscell(faces)\n for j=1:length(faces)\n if ismember(ind(i), faces{j})\n % create 3D polygon\n face = nodes(faces{j}, :);\n \n % index of point in polygon\n indp = find(faces{j}==i);\n \n % compute normal angle of vertex\n thetaf = [thetaf polygon3dNormalAngle(face, indp)]; %#ok\n end\n end\n else\n indf = find(sum(ismember(faces, ind(i)), 2));\n \n thetaf = zeros(length(indf), 1);\n for j=1:length(indf)\n ind2 = faces(indf(j), :);\n face = nodes(ind2, :);\n indp = find(ind2==ind(i));\n thetaf(j) = pi - polygon3dNormalAngle(face, indp);\n end\n end\n \n\n % compute normal angle of polyhedron, by use of angle defect formula\n theta(i) = 2*pi - sum(thetaf);\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/polyhedronNormalAngle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7159711583350533}} {"text": "function [pos, tri] = octahedron(varargin)\n\n% OCTAHEDRON\n%\n% Use as\n% [pos tri] = octahedron;\n%\n% See also TETRAHEDRON ICOSAHEDRON\n\n\npos = [\n 0 0 +1\n +1 0 0\n 0 +1 0\n -1 0 0\n 0 -1 0\n 0 0 -1\n ];\n\ntri = [\n 1 2 3\n 1 3 4\n 1 4 5\n 1 5 2\n 6 3 2\n 6 4 3\n 6 5 4\n 6 2 5\n ];\n\nif nargin>0\n n = varargin{1};\n % perform an n-fold refinement\n for i=1:n\n [pos, tri] = refine(pos, tri, 'banks');\n end\n % scale all vertices to the unit sphere\n pos = pos ./ repmat(sqrt(sum(pos.^2,2)), 1,3);\nend", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/plotting/private/octahedron.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7159283852875633}} {"text": "function mse = eval_MTL_mse (Y, X, W)\n%% FUNCTION eval_MTL_mse\n% computation of mean squared error given a specific model.\n% the value is the lower the better.\n% \n%% FORMULATION\n%\n% multi-task mse = sum_t (mse(t) * N_t) / sum_t N_t\n%\n% where \n% mse(t) = sum((Yt_pred - Y{t})^2))/ N_t\n% Yt_pred = X{t} * W(:, t)\n% N_t = length(Y{t})\n%\n% which can be simplified as:\n% \n% multi-task mse = sum_t sum((Yt_pred - Y{t})^2)) / sum_t N_t\n% \n%\n%% INPUT\n% X: {n * d} * t - input matrix\n% Y: {n * 1} * t - output matrix\n% percent: percentage of the splitting range (0, 1)\n%\n%% OUTPUT\n% X_sel: the split of X that has the specifid percent of samples \n% Y_sel: the split of Y that has the specifid percent of samples \n% X_res: the split of X that has the 1-percent of samples \n% Y_res: the split of Y that has the 1-percent of samples \n% selIdx: the selection index of for X_sel and Y_sel for each task\n%\n%% LICENSE\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% Copyright (C) 2011 - 2012 Jiayu Zhou and Jieping Ye \n%\n% You are suggested to first read the Manual.\n% For any problem, please contact with Jiayu Zhou via jiayu.zhou@asu.edu\n%\n% Last modified on Jan 6, 2016.\n%\n task_num = length(X);\n mse = 0;\n \n total_sample = 0;\n for t = 1: task_num\n y_pred = X{t} * W(:, t);\n %mse = mse + (sum((y_pred - Y{t}).^2)/length(y_pred)) * length(y_pred);\n mse = mse + sum((y_pred - Y{t}).^2); % length of y cancelled. \n total_sample = total_sample + length(y_pred);\n end\n mse = mse/total_sample;\nend\n", "meta": {"author": "jiayuzhou", "repo": "MALSAR", "sha": "fb9751594983df020ddc4f7e4a40520ee7c37989", "save_path": "github-repos/MATLAB/jiayuzhou-MALSAR", "path": "github-repos/MATLAB/jiayuzhou-MALSAR/MALSAR-fb9751594983df020ddc4f7e4a40520ee7c37989/examples/train_and_test/eval_MTL_mse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7159283827125521}} {"text": "function pass = test_rhs( pref )\n% Check that non-zero righthand forcing terms are being dealt with\n% correctly. \n% Alex Townsend, March 2013. \n\nif ( nargin < 1 ) \n pref = chebfunpref(); \nend \ntol = 100*pref.cheb2Prefs.chebfun2eps;\n\nd = [0 pi 0 pi]; \nN = chebop2(@(u) laplacian(u), d); \nN.lbc = 0; \nN.rbc = @(y) pi*y.^3./6; \nN.dbc = 0; \nN.ubc = @(x) x*pi^3/6 + sin(x).*sinh(pi); \n\nrhs = chebfun2(@(x,y) x.*y, d); \n\nu = N \\ rhs;\n\nexact = chebfun2(@(x,y) x.*y.^3/6 + sin(x).*sinh(y), d);\n\npass(1) = ( norm(u - exact) < 10*tol ); \n\n\n\nd = [0 pi 0 pi]; \nN = chebop2(@(u) laplacian(u), d); \nN.lbc = 0; \nN.rbc = @(y) pi^4*y./12 + sinh(pi)*(cos(y) + sin(y)); \nN.dbc = @(x) sinh(x); \nN.ubc = @(x) pi*x.^4/12 - sinh(x); \n\nrhs = chebfun2(@(x,y) x.^2.*y, d); \n\nu = N \\ rhs;\n\nexact = chebfun2(@(x,y) x.^4.*y./12 + sinh(x).*(cos(y) + sin(y)), d);\n\npass(2) = ( norm(u - exact) < 10*tol );\n\n\n% right hand side when we are on a rectangular domain. \n% real part of analytic plus forcing term\nd = [0 pi 0 1];\nexact = chebfun2(@(x,y) real(exp(x+1i*y)) + x.^3.*y.^3, d);\nN = chebop2(@(u) laplacian(u), d); \nN.lbc = exact(d(1),:); \nN.rbc = exact(d(2),:); \nN.dbc = exact(:,d(3)); \nN.ubc = exact(:,d(4)); \n\nu = N \\ chebfun2(@(x,y) 6*x.*y.^3 + 6*y.*x.^3, d); \n\npass(3) = ( norm(u - exact) < 10*tol );\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebop2/test_rhs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7157956185649532}} {"text": "function [MATreordered,MATindices,MATcost] = reorderMAT(MAT,H,cost)\n%REORDERMAT Reorder matrix for visualization\n%\n% [MATreordered,MATindices,MATcost] = reorderMAT(MAT,H,cost);\n%\n% This function reorders the connectivity matrix in order to place more\n% edges closer to the diagonal. This often helps in displaying community\n% structure, clusters, etc.\n%\n% Inputs: MAT, connection matrix\n% H, number of reordering attempts\n% cost, 'line' or 'circ', for shape of lattice\n% (linear or ring lattice)\n%\n% MATreordered reordered connection matrix\n% MATindices reordered indices\n% MATcost cost of reordered matrix\n% \n%\n% Olaf Sporns, Indiana University\n\n\nN = length(MAT);\ndiagMAT = diag(diag(MAT));\nMAT = MAT-diagMAT;\n\n% generate cost function\nif strcmp(cost,'line');\n profil = fliplr(normpdf(1:N,0,N/2));\nend;\nif strcmp(cost,'circ');\n profil = fliplr(normpdf(1:N,N/2,N/4));\nend;\nCOST = toeplitz(profil,profil);\n\n% initialize lowCOST\nlowMATcost = sum(sum(COST.*MAT));\n\n% keep track of starting configuration\nMATstart = MAT;\nstarta = 1:N;\n \n% reorder\nfor h=1:H\n a = 1:N;\n % choose two positions at random and flip them\n r = randperm(N);\n a(r(1)) = r(2);\n a(r(2)) = r(1);\n MATcostnew = sum(sum(MAT(a,a).*COST));\n if (MATcostnew < lowMATcost)\n MAT = MAT(a,a);\n r2 = starta(r(2));\n r1 = starta(r(1));\n starta(r(1)) = r2;\n starta(r(2)) = r1;\n lowMATcost = MATcostnew;\n end;\nend;\t% h\n\nMATreordered = MATstart(starta,starta) + diagMAT(starta,starta);\nMATindices = starta;\nMATcost = lowMATcost;\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/reorderMAT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7157956054577639}} {"text": "function output = linear_transform_animation(data,A)\n% data = N x 2 matrix\n% A = 2 x 2 matrix\n% output = N x 2 matrix\n\ndot_colors = jet(size(data,1));\n\noutput = transpose(A*data');\n\nminmin = min(min(data));\nmaxmax = max(max(data));\n\nxy_min = -max(abs(minmin),abs(maxmax));\nxy_max = max(abs(minmin),abs(maxmax));\n\nfigure;\nset(gcf,'position',[316.2000 215.4000 904.8000 420.0000]);\nsubplot(1,2,1);\nscatter(data(:,1),data(:,2),30,dot_colors,'filled')\ngrid on;\nxlim([xy_min, xy_max]); ylim([xy_min, xy_max]);\nset(gcf,'color','white');\n\nsubplot(1,2,2);\nscatter(data(:,1),data(:,2),30,dot_colors,'filled')\ngrid on;\nxlim([xy_min, xy_max]); ylim([xy_min, xy_max]);\nset(gcf,'color','white');\n\nn_steps = 100;\nfor i_steps = 1:n_steps\n step_mtx = (A-eye(2))/n_steps*i_steps;\n new_xy = (eye(2)+step_mtx)*[data(:,1), data(:,2)]';\n scatter(new_xy(1,:), new_xy(2,:),30,dot_colors,'filled')\n grid on;\n xlim([xy_min, xy_max]); ylim([xy_min, xy_max]);\n set(gcf,'color','white')\n pause(0.001);\nend\n\n\n\n", "meta": {"author": "angeloyeo", "repo": "gongdols", "sha": "7be9fbd988dec6edab1dc881cb22d63e6f69398d", "save_path": "github-repos/MATLAB/angeloyeo-gongdols", "path": "github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/선형대수/PCA/linear_transform_animation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646393, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7157296889307327}} {"text": "function [ cx, cy ] = csrot ( n, cx, incx, cy, incy, c, s )\n\n%*****************************************************************************80\n%\n%% CSROT applies a complex plane rotation.\n%\n% Discussion:\n%\n% The cosine C and sine S are real and the vectors CX and CY are complex.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 April 2006\n%\n% Author:\n%\n% MATLAB version by 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% LC: QA214.L56.\n%\n% Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,\n% Basic Linear Algebra Subprograms for Fortran Usage,\n% Algorithm 539,\n% ACM Transactions on Mathematical Software,\n% Volume 5, Number 3, September 1979, pages 308-323.\n%\n% Parameters:\n%\n% Input, integer N, the number of entries in the vectors.\n%\n% Input, complex CX(*), one of the vectors to be rotated.\n%\n% Input, integer INCX, the increment between successive entries of CX.\n%\n% Input, complex CY(*), one of the vectors to be rotated.\n%\n% Input, integer INCY, the increment between successive elements of CY.\n%\n% Input, real C, S, parameters (presumably the cosine and sine of\n% some angle) that define a plane rotation.\n%\n% Output, complex CX(*), one of the vectors to be rotated.\n%\n% Output, complex CY(*), one of the vectors to be rotated.\n%\n temp(1:n) = c * cx(1:incx:1+(n-1)*incx) ...\n + s * cy(1:incy:1+(n-1)*incy);\n\n cy(1:incy:1+(n-1)*incy) = - s * cx(1:incx:1+(n-1)*incx) ...\n + c * cy(1:incy:1+(n-1)*incy);\n\n cx(1:incx:1+(n-1)*incx) = temp(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/linpack_c/csrot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8289388167733099, "lm_q1q2_score": 0.7156988166698819}} {"text": "% Mathematics Q2706108\n% https://math.stackexchange.com/questions/2706108\n% Lasso ADMM with Positive Constraint\n% References:\n% 1. aa\n% Remarks:\n% 1. sa\n% TODO:\n% \t1. ds\n% Release Notes\n% - 1.0.000 25/03/2018\n% * First release.\n\n\n%% General Parameters\n\nrun('InitScript.m');\n\nfigureIdx = 0;\nfigureCounterSpec = '%04d';\n\ngenerateFigures = ON;\n\n\n%% Simulation Parameters\n\nparamLambda = 0.5;\n\nnumRows = 12;\nnumCols = 8;\n\nnumIterations = 250;\nstepSize = 0.0075;\n\n\n%% Generate Data\n\nmA = randn([numRows, numCols]);\nvB = 10 * randn([numRows, 1]);\n\nhObjFun = @(vX) (0.5 * sum(((mA * vX) - vB) .^ 2)) + (paramLambda * norm(vX, 1));\nhL2SubGrad = @(vX) vX ./ max(norm(vX, 2), 1e-9);\n\nhSoftThresholdL1 = @(vX, paramLambda) sign(vX) .* max(abs(vX) - paramLambda, 0);\nhProjectRPlus = @(vX, paramLambda) max(vX, 0);\n\n\n%% Solution by CVX\n\ncvx_begin('quiet')\n cvx_precision('best');\n variable vX(numCols)\n minimize( (0.5 * square_pos(norm((mA * vX) - vB, 2))) + (paramLambda * norm(vX, 1)) );\n subject to\n vX >= 0;\ncvx_end\n\ndisp([' ']);\ndisp(['CVX Solution Summary']);\ndisp(['The CVX Solver Status - ', cvx_status]);\ndisp(['The Optimal Value Is Given By - ', num2str(cvx_optval)]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(vX.'), ' ]']);\ndisp([' ']);\n\n\n%% Solution by Sub Gradient Method\n\nvObjValSgm = zeros([numIterations, 1]);\n\nvX = zeros([numCols, 1]);\nvObjValSgm(1) = hObjFun(vX);\n\nmAA = mA.' * mA;\nvAb = mA.' * vB;\n\nfor ii = 2:numIterations\n vG = (mAA * vX) - vAb + (paramLambda * sign(vX));\n vX = vX - (stepSize * vG);\n vX = max(vX, 0); %=v);\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction y = perform_hard_thresholding(x,t)\n\nt = t(1);\ny = x .* (abs(x) > t);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction y = perform_soft_thresholding(x,t)\n\nif not(isreal(x))\n % complex threshold\n d = abs(x);\n d(d=t(1) & abs(x)\n% Copyright © 2012, 2015 University of Oxford\n% Version: 0.3.3\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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Basic Dijkstra\n\n% distance matrix to describe the graph in \n% http://en.wikipedia.org/wiki/Dijkstra's_algorithm\n% (saved to matlab/test/Dijkstra_Animation_wikipedia.gif)\n\nd = [...\n % 1 2 3 4 5 6\n 0 7 9 0 0 14; ...\n 7 0 10 15 0 0; ...\n 9 10 0 11 0 2; ...\n 0 15 11 0 6 0; ...\n 0 0 0 6 0 9; ...\n 14 0 2 0 9 0];\n \n% run disjkstra's algorithm on first node\n[dd, p] = dijkstra(sparse(d'), 1)\n\n% dd' =\n% \n% 0 7 9 20 20 11\n% \n% p' =\n% \n% 0 1 1 3 6 3\n\n% query several source nodes at the same time\n[dd, p] = dijkstra(sparse(d'), [1 3 6])\n\n% dd' =\n% \n% 0 7 9 20 20 11\n% 9 10 0 11 11 2\n% 11 12 2 13 9 0\n% \n% p' =\n% \n% 0 1 1 3 6 3\n% 3 3 0 3 6 3\n% 3 3 6 3 6 0\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Dijkstra with limited number of targets\n\n% query a source node, but we are only interested in the path to a single\n% target node\n[dd, p] = dijkstra(sparse(d'), 1, 3)\n\n% dd' =\n% \n% 0 7 9 20 Inf 11\n% \n% p' =\n% \n% 0 1 1 3 NaN 3\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Dijkstra with piggyback\n\n% secondary distance matrix. The algorithm will ignore this distances in\n% terms of searching for shortest-paths, but will create another distance\n% output adding the values in D2 while following the path given by D\n\nd2 = [...\n % 1 2 3 4 5 6\n 0 10 7 0 0 6; ...\n 10 0 2 11 0 0; ...\n 7 2 0 9 0 9; ...\n 0 11 9 0 14 0; ...\n 0 0 0 14 0 15; ...\n 6 0 9 0 15 0];\n\n[dd, p, dd2] = dijkstra(sparse(d'), 1:6, 1:6, sparse(d2))\n\n% dd2 =\n% \n% 0 10 7 16 31 16\n% 10 0 2 11 25 11\n% 7 2 0 9 24 9\n% 16 11 9 0 14 18\n% 31 26 24 14 0 15\n% 16 11 9 18 15 0\n \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Dijkstra with non-symmetric input matrix\n\n% we start with a symmetric matrix\nd = [...\n % 1 2 3 4 5 6\n 0 7 9 0 0 14; ...\n 7 0 10 15 0 0; ...\n 9 10 0 11 0 2; ...\n 0 15 11 0 6 0; ...\n 0 0 0 6 0 9; ...\n 14 0 2 0 9 0];\n\n% the path from 1 to 5 is 1, 3, 6, 5, and has cost 20\n[dd, p] = dijkstra(sparse(d'), 1);\ndd(5)\ngraphpred2path(p', 5)\n\n% in the opposite direction, same path, 5, 6, 3, 1\n[dd, p] = dijkstra(sparse(d'), 5);\ndd(1)\ngraphpred2path(p', 1)\n\n% change the distance from 6 to 5 to be very expensive, so that the best\n% path now is 1, 3, 4, 5, with cost 26\nd(6, 5) = 20;\n[dd, p] = dijkstra(sparse(d'), 1);\ndd(5)\ngraphpred2path(p', 5)\n \n% note that in the opposite direction nothing has changed, because the\n% matrix is asymmetric\n[dd, p] = dijkstra(sparse(d'), 5);\ndd(1)\ngraphpred2path(p', 1)\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/test/test_dijkstra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7155958333820357}} {"text": "function ydata = tsne_d(D, labels, no_dims, perplexity)\n%TSNE_D Performs symmetric t-SNE on the pairwise Euclidean distance matrix D\n%\n% mappedX = tsne_d(D, labels, no_dims, perplexity)\n% mappedX = tsne_d(D, labels, initial_solution, perplexity)\n%\n% The function performs symmetric t-SNE on the NxN pairwise Euclidean \n% distance matrix D to construct an embedding with no_dims dimensions \n% (default = 2). An initial solution obtained from an other dimensionality \n% reduction technique may be specified in initial_solution. \n% The perplexity of the Gaussian kernel that is employed can be specified \n% through perplexity (default = 30). The labels of the data are not used \n% by t-SNE itself, however, they are used to color intermediate plots. \n% Please provide an empty labels matrix [] if you don't want to plot \n% results during the optimization.\n% The data embedding is returned in mappedX.\n%\n%\n% (C) Laurens van der Maaten, 2010\n% University of California, San Diego\n\n\n if ~exist('labels', 'var')\n labels = [];\n end\n if ~exist('no_dims', 'var') || isempty(no_dims)\n no_dims = 2;\n end\n if ~exist('perplexity', 'var') || isempty(perplexity)\n perplexity = 30;\n end\n \n % First check whether we already have an initial solution\n if numel(no_dims) > 1\n initial_solution = true;\n ydata = no_dims;\n no_dims = size(ydata, 2);\n else\n initial_solution = false;\n end\n \n % Compute joint probabilities\n D = D / max(D(:)); % normalize distances\n P = d2p(D .^ 2, perplexity, 1e-5); % compute affinities using fixed perplexity\n \n % Run t-SNE\n if initial_solution\n ydata = tsne_p(P, labels, ydata);\n else\n ydata = tsne_p(P, labels, no_dims);\n end\n ", "meta": {"author": "liuziwei7", "repo": "mobile-id", "sha": "ba7548349829481d330e9787815d3ef6cfc57e41", "save_path": "github-repos/MATLAB/liuziwei7-mobile-id", "path": "github-repos/MATLAB/liuziwei7-mobile-id/mobile-id-ba7548349829481d330e9787815d3ef6cfc57e41/utils/tSNE_matlab/tsne_d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.7155572465833399}} {"text": "% composit.m September 2, 2013\n\n% sun-synchronous, repeating ground track,\n% frozen orbit design - Kozai J2 perturbations\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclear all;\n\nglobal j2 j3 mu req omega argper fi xldot xqp\n\n% astrodynamic and utility constants\n\nj2 = 0.00108263;\nj3 = -0.00000254;\nmu = 398600.4415;\nreq = 6378.14;\nomega = 0.000072921151467;\n\npi2 = 2.0 * pi;\ndtr = pi / 180.0;\nrtd = 180.0 / pi;\n\nx = zeros(3, 1);\n\nclc; home;\n\nfprintf('\\n program composit');\n\nfprintf('\\n\\n < sun-synchronous, repeating ground track, frozen orbits >\\n\\n');\n\n% request initial guesses\n\nwhile(1)\n\n fprintf('\\nplease input an initial guess for the semimajor axis (kilometers)\\n');\n\n x(1) = input('? ');\n\n if (x(1) > 0.0)\n break;\n end\n \nend\n\nwhile(1)\n\n fprintf('\\nplease input an initial guess for the eccentricity (non-dimensional)');\n fprintf('\\n(0 <= eccentricity < 1)\\n');\n\n x(2) = input('? ');\n\n if (x(2) >= 0.0 && x(2) < 1.0)\n break;\n end\n \nend\n\nwhile(1)\n\n fprintf('\\nplease input an initial guess for the inclination (degrees)');\n fprintf('\\n(90 < inclination <= 180)\\n');\n\n x(3) = input('? ');\n\n if (x(3) > 90.0 && x(3) <= 180.0)\n break;\n end\n \nend\n\nx(3) = x(3) * dtr;\n\nwhile(1)\n\n fprintf('\\nplease input the number of integer orbits in the repeat cycle\\n');\n\n norbits = input('? ');\n\n if (norbits > 1)\n break;\n end\n \nend\n\nwhile(1)\n\n fprintf('\\nplease input the number of integer days in the repeat cycle\\n');\n\n ndays = input('? ');\n\n if (ndays > 0)\n break;\n end\n \nend\n\n% compute repetition factor\n\nxqp = norbits / ndays;\n\n% fundamental interval\n\nfi = pi2 / xqp;\n\n% required nodal regression rate\n\nxldot = (360.0 / 365.25) * dtr / 86400.0;\n\nargper = 90.0 * dtr;\n\n% solve system of nonlinear equations\n\nn = 3;\n\nmaxiter = 200;\n\n[xf, niter, icheck] = snle ('compfunc', x, n, maxiter);\n\nsma = xf(1);\n\necc = xf(2);\n\ninc = rtd * xf(3);\n\n% keplerian period\n\ntkepler = pi2 * sqrt(sma ^ 3 / mu);\n\ntnode = pi2 * (1.0 / xqp) / (omega - xldot);\n\n% print results\n\nclc; home;\n\nfprintf('\\n program composit');\n\nfprintf('\\n\\n < sun-synchronous, repeating ground track, frozen orbits >\\n\\n');\n\nfprintf('mean semimajor axis %12.4f kilometers \\n\\n', sma);\n\nfprintf('mean eccentricity %12.10f \\n\\n', ecc);\n\nfprintf('mean orbital inclination %12.4f degrees \\n\\n', inc);\n\nfprintf('mean argument of perigee %12.4f degrees \\n\\n', argper*rtd);\n\nfprintf('keplerian period %12.4f minutes \\n\\n', tkepler/60);\n\nfprintf('nodal period %12.4f minutes \\n\\n', tnode/60);\n\nfprintf('number of orbits in repeat cycle %12.4f \\n\\n', norbits);\n\nfprintf('number of days in repeat cycle %12.4f \\n\\n', ndays);\n\nfprintf('ground trace repetition factor %12.4f \\n\\n', xqp);\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/39123-composite-orbit-design/composit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7155452232907846}} {"text": "function f = f01_f0 ( n, x, y )\n\n%*****************************************************************************80\n%\n%% F01_F0 returns the value of function 1.\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 F(N,1), the function values.\n%\n f(1:n,1) = ...\n 0.75 * exp ( - ( ( 9.0 * x(1:n,1) - 2.0 ).^2 ...\n + ( 9.0 * y(1:n,1) - 2.0 ).^2 ) / 4.0 ) ...\n + 0.75 * exp ( - ( ( 9.0 * x(1:n,1) + 1.0 ).^2 ) / 49.0 ...\n - ( 9.0 * y(1:n,1) + 1.0 ) / 10.0 ) ...\n + 0.5 * exp ( - ( ( 9.0 * x(1:n,1) - 7.0 ).^2 ...\n + ( 9.0 * y(1:n,1) - 3.0 ).^2 ) / 4.0 ) ...\n - 0.2 * exp ( - ( 9.0 * x(1:n,1) - 4.0 ).^2 ...\n - ( 9.0 * y(1:n,1) - 7.0 ).^2 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_interp_2d/f01_f0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7154895612622095}} {"text": "%solve the inverse of matrix M,and MOut is the outcome Matrix.\nfunction [MOut] = InverseM(M)\n[nRow,nCol] = size(M);\nis = zeros(nRow,1);\njs = zeros(nRow,1);\nfDet = 1.0;\nf = 1;\nfor k = 1:nRow\n fMax = 0;\n for i = k:nRow\n for j = k:nRow\n f1 = abs(M(i,j));\n if f1 > fMax\n fMax = f1;\n is(k,1) = i;\n js(k,1) = j;\n end\n end\n end\n if abs(fMax) < 0.0001\n disp('Error happen 0.0001');\n end\n if is(k,1) ~= k\n f = -f;\n for i = 1:nRow\n [M(k,i),M(is(k,1),i)] = swap(M(k,i),M(is(k,1),i));\n end\n end\n if js(k,1) ~= k\n f = -f;\n for i = 1:nRow\n [M(i,k),M(i,js(k,1))] = swap(M(i,k),M(i,js(k,1)));\n end\n end\n fDet = fDet*M(k,k);\n M(k,k) = 1/M(k,k);\n for j = 1:nRow\n if j ~= k\n M(k,j) = M(k,j)*M(k,k);\n end\n end\n for i = 1:nRow\n if i ~= k\n for j = 1:nRow\n if j ~= k\n M(i,j) = M(i,j) - M(i,k)*M(k,j);\n end\n end\n end\n end\n for i = 1:nRow\n if i ~= k\n M(i,k) = M(i,k)*(-M(k,k)); \n end\n end \nend\nfor k = nRow:-1:1\n if js(k,1) ~= k\n for i = 1:nRow\n [M(k,i),M(js(k,1),i)] = swap(M(k,i),M(js(k,1),i));\n end\n end\n if is(k,1) ~= k\n for i = 1:nRow\n [M(i,k),M(i,is(k,1))] = swap(M(i,k),M(i,is(k,1)));\n end\n end\nend\nMOut = M;\nclear M;\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/logreg/InverseM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7154895565709432}} {"text": "function [out] = interflow_10(S,p1,p2,p3)\n%interflow_10 \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: Scaled linear interflow if storage exceeds a threshold\n% Constraints: f = 0, for S < p2\n% @(Inputs): p1 - time coefficient [d-1]\n% p2 - threshold for flow generation [mm]\n% p3 - linear scaling parameter [-]\n% S - current storage [mm]\n\nout = p1*max(0,S-p2)/(p3);\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/interflow_10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.715489555406429}} {"text": "function value = i4_divp ( i, j )\n\n%*****************************************************************************80\n%\n%% I4_DIVP returns the smallest multiple of J greater than or equal to I.\n%\n% Example:\n%\n% I J VALUE\n%\n% 0 4 0\n% 1 4 1\n% 2 4 1\n% 3 4 1\n% 4 4 1\n% 5 4 2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, the number to be analyzed.\n%\n% Input, integer J, the number, multiples of which will\n% be compared against I. J may not be zero.\n%\n% Output, integer VALUE, the smallest multiple of J that\n% is greater than or equal to I.\n%\n if ( j ~= 0 )\n value = 1 + floor ( ( i - 1 ) / j );\n else\n value = 0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_DIVP - Fatal error!\\n' );\n fprintf ( 1, ' The input value of J was zero!\\n' );\n error ( 'I4_DIVP - Fatal 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/i4lib/i4_divp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7154137198134173}} {"text": "%% 1D Heat Transfer LBM D1Q2\n% by Manuel Diaz\nclc; clear; %close all;\n\n%% Domain Grid\nL = 30; % Length\nn = 30; % Nodes\ndx = L/n; dt = 1;\nx = 1:dx:L;\n\n%% Initial Condition\nf1 = zeros(1,n);\nf2 = zeros(1,n);\nrho= zeros(1,n); % initial value of the dependent variable rho = T(x,t)\nfeq1= zeros(1,n);\nfeq2= zeros(1,n);\n\n%% Constants\ncsq = (dx^2)/(dt^2);\nalpha = 0.25;\nomega = 1/(alpha/(dt*csq)+0.5);\nw = [1/2,1/2];\ncx = [ 1, -1];\ncy = [ 0, 0];\nlinks = [ 1, 2];\ntEnd = 200; % time steps\ntPlot = 10;\nframes= tEnd/tPlot;\ncount = 0;\n\n%% Movie Parameters\ntPlot = 10; frames= tEnd/tPlot; count = 0;\nfigure(1) \ncolordef white\n\n%% Boundary Conditions\ntwall = 1; \n\n%% Main Loop\nfor cycle = 1:tEnd;\n % Collision process\n rho = f1+f2;\n \n % even that for this case k1=k2=1/2m then feq1=feq2=feq\n feq1 = 0.5*rho;\n feq2 = 0.5*rho;\n \n f1 = (1-omega) * f1 + omega * feq1;\n f2 = (1-omega) * f2 + omega * feq2;\n % Streaming process\n f1 = stream2d( f1 , [cy(1),cx(1)]);\n f2 = stream2d( f2 , [cy(2),cx(2)]);\n\n% % Original streaming process in A.A.Mohamad \n% for i = 2:n-1; % Double streaming in one loop\n% f1(n-i+1) = f1(n-i); % Streaming\n% f2( i-1 ) = f2( i ); % Streaming\n% end\n \n % Boundary condition\n f1(1) = twall-f2(1); %Dirichlet BC\n f1(n) = f1(n-1); %Neumann BC\n f2(n) = f2(n-1); %Neumann BC\n \n % Visualization every tPlot\n if mod(cycle,tPlot) == 1\n count = count + 1;\n plot(x,rho,'.');\n title '1D Heat Equation using LBM D1Q2'\n xlabel 'x cell'\n ylabel 'Temperature'\n M(count)=getframe;\n end\n \n % Animated gif file\n if mod(cycle,tPlot) == 1\n F = getframe;\n if count == 1\n [im,map] = rgb2ind(F.cdata,256,'nodither');\n im(1,1,1,tEnd/tPlot) = 0;\n end\n im(:,:,1,count) = rgb2ind(F.cdata,map,'nodither');\n end\nend\n\n%% Make pretty figures\n%plot(x,rho,'.');\n\n%% Make Movie\nmovie(M,3,10); % movie(M,n,fps)\n\n%% Export to Gif\nimwrite(im,map,'heat_eq_d1q2.gif','DelayTime',0,'LoopCount',3)", "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/LBM/heat_eq_d1q2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7153932154229572}} {"text": "function [RHSdiv, RHSdivx, RHSdivy] = divergenceTerm2D(F)\n% This function calculates the divergence of a field using its face\n% average flux vector facevariable, which is a face vector\n%\n% SYNOPSIS:\n% [RHSdiv, RHSdivx, RHSdivy] = divergenceTerm2D(F)\n%\n% PARAMETERS:\n%\n%\n% RETURNS:\n%\n%\n% EXAMPLE:\n%\n% SEE ALSO:\n%\n\n% extract data from the mesh structure\nNx = F.domain.dims(1);\nNy = F.domain.dims(2);\nG=reshape(1:(Nx+2)*(Ny+2), Nx+2, Ny+2);\nDX = repmat(F.domain.cellsize.x(2:end-1), 1, Ny);\nDY = repmat(F.domain.cellsize.y(2:end-1)', Nx, 1);\n\n% define the vector of cell index\nrow_index = reshape(G(2:Nx+1,2:Ny+1),Nx*Ny,1); % main diagonal (only internal cells)\n\n\n% reassign the east, west, north, and south flux vectors for the\n% code readability\nFe = F.xvalue(2:Nx+1,:);\t\tFw = F.xvalue(1:Nx,:);\nFn = F.yvalue(:,2:Ny+1); Fs = F.yvalue(:,1:Ny);\n\n% compute the divergence\ndiv_x = (Fe - Fw)./DX;\ndiv_y = (Fn - Fs)./DY;\n\n% define the RHS Vector\nRHSdiv = zeros((Nx+2)*(Ny+2),1);\nRHSdivx = zeros((Nx+2)*(Ny+2),1);\nRHSdivy = zeros((Nx+2)*(Ny+2),1);\n\n% assign the values of the RHS vector\nRHSdiv(row_index) = reshape(div_x+div_y,Nx*Ny,1);\nRHSdivx(row_index) = reshape(div_x,Nx*Ny,1);\nRHSdivy(row_index) = reshape(div_y,Nx*Ny,1);\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Calculus/divergenceTerm2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7153932110112042}} {"text": "function [loc_assort_pos,loc_assort_neg] = local_assortativity_wu_sign(W)\n%LOCAL_ASSORTATIVITY_WU_SIGN Local Assortativity\n%\n% [loc_assort_pos,loc_assort_neg] = local_assortativity_wu_sign(W);\n%\n% Local Assortativity measures the extent to which nodes are connected to\n% nodes of similar strength (vs. higher or lower strength). Adapted from\n% Thedchanamoorthy et al. (2014)'s formula to allow weighted/signed \n% networks (node degree replaced with node strength). Note, output values \n% sum to total assortativity. \n%\n% Inputs: W, undirected connection matrix with positive and\n% negative weights\n%\n% Output: loc_assort_pos, local assortativity from positive weights\n%\n% loc_assort_neg, local assortativity from negative weights\n%\n% Reference: Thedchanamoorthy G, Piraveenan M, Kasthuriratna D, \n% Senanayake U. Proc Comp Sci (2014) 29:2449-2461.\n%\n%\n% Jeff Spielberg, Boston University\n\n% Modification History:\n% May 2015: Original\n\nW(1:(size(W,1)+1):end) = 0;\nr_pos = assortativity_wei(W.*(W>0),0);\nr_neg = assortativity_wei(-W.*(W<0),0);\n[str_pos,str_neg] = strengths_und_sign(W);\nloc_assort_pos = nan(size(W,1),1);\nloc_assort_neg = nan(size(W,1),1);\n\nfor curr_node = 1:size(W,1)\n [~,j_pos] = find(W(curr_node,:)>0);\n loc_assort_pos(curr_node,1) = sum(abs(str_pos(j_pos)-str_pos(curr_node)))/str_pos(curr_node);\n \n [~,j_neg] = find(W(curr_node,:)<0);\n loc_assort_neg(curr_node,1) = sum(abs(str_neg(j_neg)-str_neg(curr_node)))/str_neg(curr_node);\nend\n\nloc_assort_pos = ((r_pos+1)/size(W,1))-(loc_assort_pos/sum(loc_assort_pos));\nloc_assort_neg = ((r_neg+1)/size(W,1))-(loc_assort_neg/sum(loc_assort_neg));\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/local_assortativity_wu_sign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7153932067096638}} {"text": "function [R, tau] = CholeskyMultIdentity(H)\n% Implements Cholesky with added multiple of the identity. This attempts to\n% to find a scalar tau > 0 such that H + tau * I is sufficiently positive\n% definite, where I is the identity matrix.\n\nglobal numFact % Number of Cholesky factorizations attempted.\n\n% First, we intially try a Cholesky factorization.\n[R, fail] = chol(H);\nnumFact = numFact + 1;\n% If it does not fail, we're done.\nif fail == 0\n tau = 0;\n return;\nend\n\n% If the initial Cholesky factorization fails, we attempt to find a scalar\n% tau > 0 such that H + tau * I is sufficiently positive definite.\nbeta = 0.001; % Heuristic for increasing tau.\nmin_H_diag = min(diag(H)); % Smallest diagonal of H.\n\n% If smallest diagonal of H is positive, set tau to 0; otherwise, set to\n% nonnegative version of the smallest diagonal plus the beta heuristic.\nif min_H_diag > 0\n tau = 0;\nelse\n tau = -min_H_diag + beta;\nend\n\nI = eye(size(H,1)); % Identity matrix.\n\n% Repeatedly add a tau-multiple of the identity to H until the Cholesky\n% factorization succeeds. Upon each failure, double tau.\nwhile 1\n [R, fail] = chol(H + tau * I);\n numFact = numFact + 1;\n if fail == 0\n return;\n else\n % NOTE: In order to decrease number of factorizations, we may want to\n % increase tau by a factor of 10 instead of 2.\n tau = max(2*tau, beta);\n end\nend\nend\n ", "meta": {"author": "clarkzinzow", "repo": "Nonlinear-Optimization-Algorithms", "sha": "bc89cb4b3e51c56cf4040d5cf3ddecd7a33f0b00", "save_path": "github-repos/MATLAB/clarkzinzow-Nonlinear-Optimization-Algorithms", "path": "github-repos/MATLAB/clarkzinzow-Nonlinear-Optimization-Algorithms/Nonlinear-Optimization-Algorithms-bc89cb4b3e51c56cf4040d5cf3ddecd7a33f0b00/src/CholeskyMultIdentity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.715393202518334}} {"text": "function x = r8sp_cg ( n, nz_num, row, col, a, b, x )\n\n%*****************************************************************************80\n%\n%% R8SP_CG uses the conjugate gradient method on an R8SP system.\n%\n% Discussion:\n%\n% The R8SP storage format stores the row, column and value of each nonzero\n% entry of a sparse matrix.\n%\n% It is possible that a pair of indices (I,J) may occur more than\n% once. Presumably, in this case, the intent is that the actual value\n% of A(I,J) is the sum of all such entries. This is not a good thing\n% to do, but I seem to have come across this in MATLAB.\n%\n% The R8SP format is used by CSPARSE (\"sparse triplet\"), DLAP/SLAP \n% (\"nonsymmetric SLAP triad\"), by MATLAB, and by SPARSEKIT (\"COO\" format).\n%\n% The matrix A must be a positive definite symmetric matrix.\n%\n% The method is designed to reach the solution after N computational\n% steps. However, roundoff may introduce unacceptably large errors for\n% some problems. In such a case, calling the routine again, using\n% the computed solution as the new starting estimate, should improve\n% the results.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 02 June 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Frank Beckman,\n% The Solution of Linear Equations by the Conjugate Gradient Method,\n% in Mathematical Methods for Digital Computers,\n% edited by John Ralston, Herbert Wilf,\n% Wiley, 1967,\n% ISBN: 0471706892,\n% LC: QA76.5.R3.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, integer NZ_NUM, the number of nonzero elements in\n% the matrix.\n%\n% Input, integer ROW(NZ_NUM), COL(NZ_NUM), the row and \n% column indices of the nonzero elements.\n%\n% Input, real A(NZ_NUM), the nonzero elements of the matrix.\n%\n% Input, real B(N), the right hand side vector.\n%\n% Input/output, real X(N).\n% On input, an estimate for the solution, which may be 0.\n% On output, the approximate solution vector.\n%\n b = b(:);\n x = x(:);\n%\n% Initialize\n% AP = A * x,\n% R = b - A * x,\n% P = b - A * x.\n%\n ap = r8sp_mv ( n, n, nz_num, row, col, a, x );\n\n r(1:n,1) = b(1:n,1) - ap(1:n,1);\n p(1:n,1) = b(1:n,1) - ap(1:n,1);\n%\n% Do the N steps of the conjugate gradient method.\n%\n for it = 1 : n\n%\n% Compute the matrix*vector product AP=A*P.\n%\n ap = r8sp_mv ( n, n, nz_num, row, col, a, p );\n%\n% Compute the dot products\n% PAP = P*AP,\n% PR = P*R\n% Set\n% ALPHA = PR / PAP.\n%\n pap = p' * ap;\n pr = p' * r;\n\n if ( pap == 0.0 )\n return\n end\n\n alpha = pr / pap;\n%\n% Set\n% X = X + ALPHA * P\n% R = R - ALPHA * AP.\n%\n x(1:n,1) = x(1:n,1) + alpha * p(1:n,1);\n r(1:n,1) = r(1:n,1) - alpha * ap(1:n,1);\n%\n% Compute the vector dot product\n% RAP = R*AP\n% Set\n% BETA = - RAP / PAP.\n%\n rap = r' * ap;\n\n beta = - rap / pap;\n%\n% Update the perturbation vector\n% P = R + BETA * P.\n%\n p(1:n,1) = r(1:n,1) + beta * p(1:n,1);\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/cg/r8sp_cg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7153760022625467}} {"text": "function [Q,J,F,T,I,V,E] = spinv(A,varargin)\n % SPINV Compute a sparse factorization of the Moore-Penrose pseudoinverse A⁺\n % of a sparse matrix A. This is useful for solving\n % under-and-over-constrained systems Ax = b: where A is m by n with\n % rank r < min(m,n). Then to solve the system:\n %\n % x = E*(V*(I'*(T'\\(F'*(J'*(Q'*b))))))\n % \n % Note: Store these sparse factors and sovle using the routine above **with\n % parentheses**. Do not precompute A⁺ as it will be dense.\n %\n % Inputs:\n % A m by n sparse\n % Optional:\n % 'Epsilon' followed by epsilon used to determine rank from qr {1e-15}\n % Outputs:\n % Q m by m sparse orthogonal matrix\n % J m by r sparse rectangular identity matrix\n % F r by r sparse permutation matrix\n % T r by r sparse triangular matrix (diagonal?)\n % I r by n sparse rectangular identity matrix\n % V n by n sparse orthogonal matrix\n % E n by n sparse permutation matrix\n % \n % Example:\n % % over and under determined system of 3 variables\n % A = [1 0 0;1 0 0;0 1 1;0 1 1];\n % b = [4;5;6;7];\n % % Compute facotrization of sparse pseudo inverse\n % [Q,J,F,T,I,V,E] = spinv(A);\n % % Compute minimum norm best fit\n % xs = E*(V*(I'*(T'\\(F'*(J'*(Q'*b))))));\n % % Compare to Tikhonov regularization\n % xt = (A'*A+1e-10*speye(3,3))\\(A'*b);\n % \n\n % default values\n epsilon = 1e-15;\n % Map of parameter names to variable names\n params_to_variables = containers.Map( {'Epsilon'}, {'epsilon'});\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 % http://www.irisa.fr/sage/wg-statlin/WORKSHOPS/LEMASSOL05/SLIDES/QR/Guyomarch.pdf\n\n % dimensions of A\n m = size(A,1);\n n = size(A,2);\n % QR factorization of AE\n [Q,R,E] = qr(A);\n % We have that:\n % AE = QR\n % rank\n r = find(any(abs(R)>epsilon,2),1,'last');\n % Only keep upper, non-zero block\n R1R2 = R(1:r,:);\n J = speye(m,r);\n % We have that:\n % AE = Q*J*R1R2\n % QR factorization of R1R2'\n [V,Tfull,F] = qr(R1R2');\n % This means:\n % R1R2'F = V*Tfull\n % only keep upper, non-zero block\n T = Tfull(1:r,:);\n I = speye(r,n);\n % and now:\n % R1R2'F = V*I'*T\n % R1R2' = V*I'*T*F'\n % Now we have that\n % AE = Q*J*F*T'*I*V'\n % We want to solve:\n % Ax = b\n % AEE'x = b\n % E'x = (Q*J*F*T'*I*V')⁺b\n % x = E*(Q*J*F*T'*I*V')⁺b\n % x = E*(V*(I'*(T'\\(F'*(J'*(Q'*b))))))\n % \nend\n", "meta": {"author": "alecjacobson", "repo": "gptoolbox", "sha": "a0cb37d8edbcfb1e3587f793df8f24c76a2d7305", "save_path": "github-repos/MATLAB/alecjacobson-gptoolbox", "path": "github-repos/MATLAB/alecjacobson-gptoolbox/gptoolbox-a0cb37d8edbcfb1e3587f793df8f24c76a2d7305/matrix/spinv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.7153759935361024}} {"text": "function varargout = trigonometric(X)\n% Trigonometric function\n%\n% TRIGONOMETRIC([x1, x2, ..., xn]) returns the value of the \n% trigonometric fnuction at the specified points. All [xi] may be\n% vectors. \n%\n% The global minimum is \n%\n% f(x1, x2, ..., xn) = f(0, 0, ..., 0) = 0.\n\n% Author: Rody P.S. Oldenhuis\n% Delft University of Technology\n% E-mail: oldenhuis@dds.nl\n% Last edited 28/Feb/2009\n\n % if no input is given, return dimensions, bounds and minimum\n if (nargin == 0)\n varargout{1} = inf; % # dims\n varargout{2} = -inf; % LB\n varargout{3} = +inf; % LB\n varargout{4} = 0; % solution\n varargout{5} = 0; % function value at solution\n\n % otherwise, output function value\n else\n\n % create basevectors\n n = size(X, 2);\n i = repmat(1:n, size(X, 1), 1);\n\n % compute cosine only once\n cosX = cos(X);\n\n % compute intermediate sum\n sumcosX = repmat(sum(cosX, 2), 1, n);\n\n % output rowsum\n varargout{1} = sum( (n + i.*(1 - cosX) - sin(X) - sumcosX).^2, 2);\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/23147-many-testfunctions-for-global-optimizers/single-objective/trigonometric.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7153759912636044}} {"text": "function [fr,th_val,phi_val] = tess_parametrize(vert, th_val, phi_val, p)\n% TESS_PARAMETRIZE_NEW: Get a parametric representation of a closed and non-overlapping surface.\n%\n% USAGE: tess_parametrize(vert, th_val, phi_val, p)\n% tess_parametrize(vert, th_val, phi_val)\n% \n% INPUTS: \n% - vert : x,y,z coordinates of the surface to parametrize\n% - th_val : Row array of theta values\n% - phi_val : Row array of phi values\n% - p : Pad the function of p values in both direction with circular values\n\n% @=============================================================================\n% This function is part of the Brainstorm software:\n% https://neuroimage.usc.edu/brainstorm\n% \n% Copyright (c) University of Southern California & McGill University\n% This software is distributed under the terms of the GNU General Public License\n% as published by the Free Software Foundation. Further details on the GPLv3\n% license can be found at http://www.gnu.org/copyleft/gpl.html.\n% \n% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED \"AS IS,\" AND THE\n% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY\n% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF\n% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY\n% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.\n%\n% For more information type \"brainstorm license\" at command prompt.\n% =============================================================================@\n%\n% Authors: Francois Tadel, 2011\n\n% Parse inputs\nif (nargin < 4) || isempty(p)\n p = 0;\nend\n\n% Convert surface to spherical coordinates\n[th,phi,r] = cart2sph(vert(:,1), vert(:,2), vert(:,3));\n% Replicate the values to get a full coverage at the edges\nth = [th; th; th; th+2*pi; th+2*pi; th+2*pi; th-2*pi; th-2*pi; th-2*pi ];\nphi = [phi; phi+2*pi; phi-2*pi; phi; phi+2*pi; phi-2*pi; phi; phi+2*pi; phi-2*pi ];\nr = [r; r; r; r; r; r; r; r; r ];\n\n% Build grid of (theta,phi) values\n[fth, fphi] = meshgrid(th_val, phi_val);\n% Estimate radius values for all those points\nfr = griddata(th, phi, r, fth, fphi);\n\n% Pad function with circular values, to avoid edge irregularities\nif (p > 0)\n fr_pad = bst_pad(fr, [0 p], 'circular');\n fr_pad = bst_pad(fr_pad, [p 0], 'mirror');\n fr = fr_pad;\n th_val = [th_val(end-p+1:end)-2*pi, th_val, th_val(1:p)+2*pi];\n phi_val = [phi_val(end-p+1:end)-2*pi, phi_val, phi_val(1:p)+2*pi];\nend\n\n\n", "meta": {"author": "brainstorm-tools", "repo": "brainstorm3", "sha": "a892cfaabde1eaa2f9a3ac015c05b73f3739433a", "save_path": "github-repos/MATLAB/brainstorm-tools-brainstorm3", "path": "github-repos/MATLAB/brainstorm-tools-brainstorm3/brainstorm3-a892cfaabde1eaa2f9a3ac015c05b73f3739433a/toolbox/anatomy/tess_parametrize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.7153475766442051}} {"text": "function value = r8_lgic ( a, x, alx )\n\n%*****************************************************************************80\n%\n%% R8_LGIC evaluates the log complementary incomplete gamma function for large X.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 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 ALX, the logarithm of X.\n%\n% Output, real VALUE, the log complementary incomplete\n% gamma function.\n%\n persistent eps\n\n if ( isempty ( eps ) )\n eps = 0.5 * r8_mach ( 3 );\n end\n\n xpa = x + 1.0 - a;\n xma = x - 1.0 - a;\n\n r = 0.0;\n p = 1.0;\n s = p;\n for k = 1 : 300\n fk = k;\n t = fk * ( a - fk ) * ( 1.0 + r );\n r = - t / ( ( xma + 2.0 * fk ) * ( xpa + 2.0 * fk ) + t );\n p = r * p;\n s = s + p;\n if ( abs ( p ) < eps * s )\n value = a * alx - x + log ( s / xpa );\n return\n end\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_LGIC - Fatal error!\\n' );\n fprintf ( 1, ' No convergence in 300 iterations.\\n' );\n\n error ( 'R8_LGIC - Fatal error!' )\nend\n", "meta": {"author": "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_lgic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7153186562804373}} {"text": "function determ = r8mat_gedet ( a, n, pivot )\n\n%*****************************************************************************80\n%\n%% R8MAT_GEDET computes the determinant of a matrix factored by R8MAT_GEFA.\n%\n% Discussion:\n%\n% This is a modified version of the LINPACK routine DGEDI.\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% Reference:\n%\n% Jack Dongarra, Cleve Moler, Jim Bunch, Pete Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, real A(N,N), the LU factors computed by R8MAT_GEFA.\n%\n% Input, integer N, the order of the matrix.\n% N must be positive.\n%\n% Input, integer PIVOT(N), as computed by R8MAT_GEFA.\n%\n% Output, real DETERM, the determinant of the matrix.\n%\n diag = r8mat_diag_get_vector ( n, a );\n\n determ = prod ( diag(1:n) );\n\n for i = 1 : n\n if ( pivot(i) ~= i )\n determ = - determ;\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/r8mat_gedet.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.7152656898519724}} {"text": "function [ n_data, x, fx ] = sin_values ( n_data )\n\n%*****************************************************************************80\n%\n%% SIN_VALUES returns some values of the sine function.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Sin[x]\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% 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 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 X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 13;\n\n fx_vec = [ ...\n 0.00000000000000000000, ...\n 0.25881904510252076235, ...\n 0.47942553860420300027, ...\n 0.50000000000000000000, ...\n 0.70710678118654752440, ...\n 0.84147098480789650665, ...\n 0.86602540378443864676, ...\n 1.00000000000000000000, ...\n 0.90929742682568169540, ...\n 0.14112000805986722210, ...\n 0.00000000000000000000, ...\n -0.75680249530792825137, ...\n -0.95892427466313846889 ];\n\n x_vec = [ ...\n 0.0000000000000000000, ...\n 0.26179938779914943654, ...\n 0.50000000000000000000, ...\n 0.52359877559829887308, ...\n 0.78539816339744830962, ...\n 1.0000000000000000000, ...\n 1.0471975511965977462, ...\n 1.5707963267948966192, ...\n 2.0000000000000000000, ...\n 3.0000000000000000000, ...\n 3.1415926535897932385, ...\n 4.0000000000000000000, ...\n 5.0000000000000000000 ];\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\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_values/sin_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262968, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7152543572235239}} {"text": "function varargout = gallery2(name)\n%CHEB.GALLERY2 Chebfun2 example functions.\n% F = CHEB.GALLERY2(NAME) returns a chebfun2 corresponding to NAME. See the\n% listing below for available names.\n%\n% For example, plot(cheb.gallery2('peaks')) plots the classic MATLAB peaks\n% function represented as a chebfun2. For details of how each function is\n% constructed, try type +cheb/gallery2 or edit cheb.gallery2.\n%\n% [F,FA] = CHEB.GALLERY2(NAME) also returns the anonymous function FA used to\n% define the function.\n%\n% CHEB.GALLERY2 with no input argument returns a function selected at\n% random from the gallery.\n%\n% CHEB.GALLERY2 with no output argument creates a plot of the selected\n% function.\n%\n% airyreal Real part of Airy Ai function\n% airycomplex Imaginary part of Airy Ai function\n% bump 2D C-infinity function with compact support\n% challenge Function from SIAM 100-digit challenge\n% peaks Classic MATLAB peaks function\n% rosenbrock Challenging test function in optimization\n% roundpeg Approx characteristic function of a disk, rank 45\n% smokering A halo, hoop, or hole\n% squarepeg Approx characteristic function of a square, rank 1\n% tiltedpeg A tilted variant of squarepeg, rank 100\n% waffle Function with horizontal and vertical ridges\n%\n% Gallery functions are subject to change in future releases of Chebfun.\n%\n% See also CHEB.GALLERY, CHEB.GALLERYTRIG, CHEB.GALLERY3, CHEB.GALLERYDISK, CHEB.GALLERYSPHERE.\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 user did not supply an input, return a function selected at\n% random from the gallery.\nif ( nargin == 0 )\n names = {'airyreal', 'airycomplex', 'challenge', 'bump', 'peaks', ...\n 'rosenbrock', 'roundpeg', 'smokering', 'squarepeg', 'tiltedpeg', ...\n 'waffle'};\n name = names{randi(length(names))};\nend\n\n% The main switch statement.\nswitch lower(name)\n\n % Real part of Airy Ai function:\n case 'airyreal'\n fa = @(z) real(airy(z));\n f = chebfun2(fa, [-10 10 0 1]);\n\n % Imaginary part of Airy Ai function:\n case 'airycomplex'\n fa = @(z) airy(z);\n f = chebfun2(fa, [-10 10 -5 5]);\n\n % Two-dimensional bump function:\n case 'bump'\n fa = @(x,y) (x.^2 + y.^2 < 1).*exp(-(x.^2 + y.^2 < 1)./ ...\n (1 - x.^2 - y.^2));\n f = chebfun2(fa, [-1 1 -1 1]*2);\n\n % Function from SIAM 100-digit challenge:\n case 'challenge'\n fa = @(x,y) exp(sin(50*x)) + sin(60*exp(y)) + sin(70*sin(x)) + ...\n sin(sin(80*y)) - sin(10*(x+y)) + (x.^2+y.^2)./4;\n f = chebfun2(fa);\n\n % The classic MATLAB peaks function:\n case 'peaks'\n fa = @(x,y) 3*(1-x).^2.*exp(-x.^2 - (y+1).^2) ...\n - 10*(x/5 - x.^3 - y.^5).*exp(-x.^2 - y.^2) ...\n - 1/3*exp(-(x+1).^2 - y.^2);\n f = chebfun2(fa, [-3 3 -3 3]);\n\n % A challenging test function in optimization:\n case 'rosenbrock'\n fa = @(x,y) (1-x).^2 + 100*(y-x.^2).^2;\n f = chebfun2(fa, [-2 2 -1 3]);\n\n % Approximately the characteristic function of a disk:\n case 'roundpeg'\n fa = @(x,y) 1./(1+((2*x).^2+(2*y).^2).^10);\n f = chebfun2(fa);\n \n % A halo, hoop, or hole:\n case 'smokering'\n fa = @(x,y) exp(-100*(x.^2 - x.*y + 2*y.^2 - 1/2).^2);\n f = chebfun2(fa);\n\n % Approximately the characteristic function of a square:\n case 'squarepeg'\n fa = @(x,y) 1./((1+(2*x).^20).*(1+(2*y).^20));\n f = chebfun2(fa);\n\n % A tilted version of squarepeg:\n case 'tiltedpeg'\n fa = @(x,y) 1./((1+(2*x+.4*y).^20).*(1+(2*y-.4*x).^20));\n f = chebfun2(fa);\n\n % A function with horizontal and vertical ridges:\n case 'waffle'\n fa = @(x,y) 1./(1 + 1e3*((x.^2-.25).^2.*(y.^2-.25).^2));\n f = chebfun2(fa);\n\n % Raise an error if the input is unknown.\n otherwise\n error('CHEB:GALLERY2:unknown:unknownFunction', ...\n 'Unknown function.')\nend\n\n% Only return something if there is an output argument.\nif ( nargout > 0 )\n varargout = {f, fa};\nelse\n % Otherwise, plot the function.\n plot(f)\n title([name ', rank = ' num2str(length(f))])\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/+cheb/gallery2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.819893340314393, "lm_q1q2_score": 0.7152318029394084}} {"text": "function [lp,dlp] = priorT(mu,s2,nu,x)\n\n% Univariate Student's t 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) = ( 1 + (x-mu)^2/(s2*(nu-2)) )^(-(nu+1)/2) / Z, where\n% Z = gamma(nu/2) * sqrt(pi*(nu-2)*s2) / gamma((nu+1)/2),\n%\n% mu(1x1) is the mean parameter, s2(1x1) is the variance parameter,\n% nu(1x1) > 2 is the degrees of freedom parameter and x(1xN) contains query\n% 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-10-16.\n%\n% See also PRIORDISTRIBUTIONS.M.\n\nif nargin<3, error('mu, s2 and nu parameters need to be provided'), end\nif ~(isscalar(mu)&&isscalar(s2)&&isscalar(nu))\n error('mu, s2 and nu parameters need to be scalars')\nend\nif nargin<4, lp = mu + sqrt(s2*(nu-2)/priorGamma(nu/2,2))*randn; return, end\n\nlZ = gammaln((nu+1)/2)-gammaln(nu/2)-log(pi*(nu-2)*s2)/2;\nlp = -(nu+1)/2*log(1+(x-mu).^2/(s2*(nu-2))) + lZ;\ndlp = (nu+1)*(mu-x)./(mu^2-2*mu*x+s2*(nu-2)+x.^2);", "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/priorT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809826, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7151921429252321}} {"text": "function cvx_optval = norm_largest( x, k )\n\n%NORM_LARGEST Sum of the k largest magnitudes of a vector.\n% NORM_LARGEST( X, k ) computes the 'largest-k' norm; that is, it computes\n% the sum of the magnitudes of the k largest elements in X. X must\n% be a vector, and k must be a real scalar.\n%\n% Disciplined convex programming information:\n% NORM_LARGEST is convex and nonmonotonic of X, though it is monotonic for\n% positive values of X. So when used in CVX expressions, X must be affine,\n% monomial, or posynomial. k must be a real scalar constant.\n\nif ~any( size( x ) ~= 1 ),\n cvx_throw( 'The first argument must be a vector.' );\nelseif ~isnumeric( k ) || ~isreal( k ) || length( k ) ~= 1,\n cvx_throw( 'Third argument must be a scalar.' );\nelse\n cvx_optval = sum_largest( abs( x ), k );\nend\n\n% Copyright 2005-2014 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\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/functions/norm_largest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.8104789063814616, "lm_q1q2_score": 0.7151891821884321}} {"text": "function value = diaedg ( x0, y0, x1, y1, x2, y2, x3, y3 )\n\n%*****************************************************************************80\n%\n%% DIAEDG chooses a diagonal edge.\n%\n% Discussion:\n%\n% The routine determines whether 0--2 or 1--3 is the diagonal edge\n% that should be chosen, based on the circumcircle criterion, where\n% (X0,Y0), (X1,Y1), (X2,Y2), (X3,Y3) are the vertices of a simple\n% quadrilateral in counterclockwise order.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2005\n%\n% Author:\n%\n% Original FORTRAN77 version by Barry Joe,\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Barry Joe,\n% GEOMPACK - a software package for the generation of meshes\n% using geometric algorithms,\n% Advances in Engineering Software,\n% Volume 13, pages 325-331, 1991.\n%\n% Parameters:\n%\n% Input, real X0, Y0, X1, Y1, X2, Y2, X3, Y3, the\n% coordinates of the vertices of a quadrilateral, given in\n% counter clockwise order.\n%\n% Output, integer VALUE, chooses a diagonal:\n% +1, if diagonal edge 02 is chosen;\n% -1, if diagonal edge 13 is chosen;\n% 0, if the four vertices are cocircular.\n%\n tol = 100.0 * eps;\n\n dx10 = x1 - x0;\n dy10 = y1 - y0;\n dx12 = x1 - x2;\n dy12 = y1 - y2;\n dx30 = x3 - x0;\n dy30 = y3 - y0;\n dx32 = x3 - x2;\n dy32 = y3 - y2;\n\n tola = tol * max ( abs ( dx10 ), ...\n max ( abs ( dy10 ), ...\n max ( abs ( dx30 ), abs ( dy30 ) )));\n \n tolb = tol * max ( abs ( dx12 ), ...\n max ( abs ( dy12 ), ...\n max ( abs ( dx32 ), abs ( dy32 ) )));\n\n ca = dx10 * dx30 + dy10 * dy30;\n cb = dx12 * dx32 + dy12 * dy32;\n\n if ( tola < ca & tolb < cb )\n\n value = -1;\n\n elseif ( ca < -tola & cb < -tolb )\n\n value = 1;\n\n else\n\n tola = max ( tola, tolb );\n s = ( dx10 * dy30 - dx30 * dy10 ) * cb ...\n + ( dx32 * dy12 - dx12 * dy32 ) * ca;\n\n if ( tola < s )\n value = -1;\n elseif ( s < -tola )\n value = 1;\n else\n value = 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/triangulation/diaedg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7151891681999554}} {"text": "function Test_fixedrankembeddedfactory()\n% Given partial observation of a low rank matrix, attempts to complete it.\n%\n% function low_rank_matrix_completion()\n%\n% This example demonstrates how to use the geometry factory for the\n% embedded submanifold of fixed-rank matrices, fixedrankembeddedfactory.\n% This geometry is described in the paper\n% \"Low-rank matrix completion by Riemannian optimization\"\n% Bart Vandereycken - SIAM Journal on Optimization, 2013.\n%\n% This can be a starting point for many optimization problems of the form\n%\n% minimize f(X) such that rank(X) = k, size(X) = [m, n].\n%\n% Input: None. This example file generate random data.\n% \n% Output: None.\n\n% This file is part of Manopt and is copyrighted. See the license file.\n% \n% Main author: Nicolas Boumal, July 15, 2014\n% Contributors:\n% \n% Change log:\n% \n \n % Choose the size of the problem:\n % We will complete a matrix of size mxn of rank k.\n m = 2000;\n n = 5000;\n k = 10;\n % Generate a random mxn matrix A of rank k\n L = randn(m, k);\n R = randn(n, k);\n A = L*R';\n % Generate a random mask for observed entries: P(i, j) = 1 if the entry\n % (i, j) of A is observed, and 0 otherwise.\n fraction = 4 * k*(m+n-k)/(m*n);\n P = sparse(rand(m, n) <= fraction);\n % Hence, we know the nonzero entries in PA:\n PA = P.*A;\n \n % Pick the manifold of matrices of size mxn of fixed rank k.\n problem.M = fixedrankembeddedfactory(m, n, k);\n\n % Define the problem cost function. The input X is a structure with\n % fields U, S, V representing a rank k matrix as U*S*V'.\n % f(X) = 1/2 * || P.*(X-A) ||^2\n problem.cost = @cost;\n function f = cost(X)\n % Note that it is very much inefficient to explicitly construct the\n % matrix X in this way. Seen as we only need to know the entries\n % of Xmat corresponding to the mask P, it would be far more\n % efficient to compute those only.\n Xmat = X.U*X.S*X.V';\n f = .5*norm( P.*Xmat - PA , 'fro')^2;\n end\n\n % Define the Euclidean gradient of the cost function, that is, the\n % gradient of f(X) seen as a standard function of X.\n % nabla f(X) = P.*(X-A)\n problem.egrad = @egrad;\n function G = egrad(X)\n % Same comment here about Xmat.\n Xmat = X.U*X.S*X.V';\n G = P.*Xmat - PA;\n end\n\n % Define the Euclidean Hessian of the cost at X, along H, where H is\n % represented as a tangent vector.\n % nabla^2 f(X)[Xdot] = P.*Xdot\n % (This is the directional derivative of nabla f(X) at X along Xdot.)\n problem.ehess = @euclidean_hessian;\n function ehess = euclidean_hessian(X, H)\n % The function tangent2ambient transforms H (a tangent vector) into\n % its equivalent ambient vector representation. The output is a\n % structure with fields U, S, V such that U*S*V' is an mxn matrix\n % corresponding to the tangent vector H. Note that there are no\n % additional guarantees about U, S and V. In particular, U and V\n % are not orthonormal.\n ambient_H = problem.M.tangent2ambient(X, H);\n Xdot = ambient_H.U*ambient_H.S*ambient_H.V';\n % Same comment here about explicitly constructing the ambient\n % vector as an mxn matrix Xdot: we only need its entries\n % corresponding to the mask P, and this could be computed\n % efficiently.\n ehess = P.*Xdot;\n end\n \n\n % Check consistency of the gradient and the Hessian. Useful if you\n % adapt this example for a now cost function and you would like to make\n % sure there is no mistake.\n % warning('off', 'manopt:fixedrankembeddedfactory:exp');\n % checkgradient(problem); pause;\n % checkhessian(problem); pause;\n \n % Compute an initial guess. Points on the manifold are represented as\n % structures with three fields: U, S and V. U and V need to be\n % orthonormal, S needs to be diagonal.\n [U, S, V] = svds(PA, k);\n X0.U = U;\n X0.S = S;\n X0.V = V;\n \n % Minimize the cost function using Riemannian trust-regions, starting\n % from the initial guess X0.\n options.stopfun = @stopifclosedfigure;\n X = trustregions(problem, X0, options);\n \n % The reconstructed matrix is X, represented as a structure with fields\n % U, S and V.\n Xmat = X.U*X.S*X.V';\n fprintf('||X-A||_F = %g\\n', norm(Xmat - A, 'fro'));\n\n % If the problem has a small enough dimension, we may (for analysis\n % purposes) compute the spectrum of the Hessian at a point X. This may\n % help in studying the conditioning of a problem.\n if problem.M.dim() < 100\n fprintf('Computing the spectrum of the Hessian...');\n s = hessianspectrum(problem, X);\n hist(s);\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/tests/Test_fixedrankembeddedfactory.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7151891601209374}} {"text": "% Figure 6.2: Penalty function approximation\n% Section 6.1.2\n% Boyd & Vandenberghe \"Convex Optimization\"\n% Original by Lieven Vandenberghe\n% Adapted for CVX Argyris Zymnis - 10/2005\n%\n% Comparison of the ell1, ell2, deadzone-linear and log-barrier\n% penalty functions for the approximation problem:\n% minimize phi(A*x-b),\n%\n% where phi(x) is the penalty function\n% Log-barrier will be implemented in the future version of CVX\n\n% Generate input data\nrandn('state',0);\nm=100; n=30;\nA = randn(m,n);\nb = randn(m,1);\n\n% ell_1 approximation\n% minimize ||Ax+b||_1\ndisp('ell-one approximation');\ncvx_begin\n variable x1(n)\n minimize(norm(A*x1+b,1))\ncvx_end\n\n% ell_2 approximation\n% minimize ||Ax+b||_2\ndisp('ell-2');\nx2=-A\\b;\n\n% deadzone penalty approximation\n% minimize sum(deadzone(Ax+b,0.5))\n% deadzone(y,z) = max(abs(y)-z,0)\ndz = 0.5;\ndisp('deadzone penalty');\ncvx_begin\n variable xdz(n)\n minimize(sum(max(abs(A*xdz+b)-dz,0)))\ncvx_end\n\n\n% log-barrier penalty approximation\n%\n% minimize -sum log(1-(ai'*x+bi)^2)\n\ndisp('log-barrier')\n\n% parameters for Newton Method & line search\nalpha=.01; beta=.5;\n\n% minimize linfty norm to get starting point\ncvx_begin\n variable xlb(n)\n minimize norm(A*xlb+b,Inf)\ncvx_end\nlinf = cvx_optval;\nA = A/(1.1*linf);\nb = b/(1.1*linf);\n\nfor iters = 1:50\n\n yp = 1 - (A*xlb+b); ym = (A*xlb+b) + 1;\n f = -sum(log(yp)) - sum(log(ym));\n g = A'*(1./yp) - A'*(1./ym);\n H = A'*diag(1./(yp.^2) + 1./(ym.^2))*A;\n v = -H\\g;\n fprime = g'*v;\n ntdecr = sqrt(-fprime);\n if (ntdecr < 1e-5), break; end;\n\n t = 1;\n newx = xlb + t*v;\n while ((min(1-(A*newx +b)) < 0) || (min((A*newx +b)+1) < 0))\n t = beta*t;\n newx = xlb + t*v;\n end;\n newf = -sum(log(1 - (A*newx+b))) - sum(log(1+(A*newx+b)));\n while (newf > f + alpha*t*fprime)\n t = beta*t;\n newx = xlb + t*v;\n newf = -sum(log(1-(A*newx+b))) - sum(log(1+(A*newx+b)));\n end;\n xlb = xlb+t*v;\nend\n\n\n% Plot histogram of residuals\n\nss = max(abs([A*x1+b; A*x2+b; A*xdz+b; A*xlb+b]));\ntt = -ceil(ss):0.05:ceil(ss); % sets center for each bin\n[N1,hist1] = hist(A*x1+b,tt);\n[N2,hist2] = hist(A*x2+b,tt);\n[N3,hist3] = hist(A*xdz+b,tt);\n[N4,hist4] = hist(A*xlb+b,tt);\n\n\nrange_max=2.0; rr=-range_max:1e-2:range_max;\n\nfigure(1), clf, hold off\nsubplot(4,1,1),\nbar(hist1,N1);\nhold on\nplot(rr, abs(rr)*40/3, '-');\nylabel('p=1')\naxis([-range_max range_max 0 40]);\nhold off\n\nsubplot(4,1,2),\nbar(hist2,N2);\nhold on;\nplot(rr,2*rr.^2),\nylabel('p=2')\naxis([-range_max range_max 0 11]);\nhold off\n\nsubplot(4,1,3),\nbar(hist3,N3);\nhold on\nplot(rr,30/3*max(0,abs(rr)-dz))\nylabel('Deadzone')\naxis([-range_max range_max 0 25]);\nhold off\n\nsubplot(4,1,4),\nbar(hist4,N4);\nrr_lb=linspace(-1+(1e-6),1-(1e-6),600);\nhold on\nplot(rr_lb, -3*log(1-rr_lb.^2),rr,2*rr.^2,'--')\naxis([-range_max range_max 0 11]);\nylabel('Log barrier'),\nxlabel('r')\nhold off\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/Ch06_approx_fitting/penalty_comp_cvx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7151536802624764}} {"text": "function [x, c, funVal, ValueL]=LogisticC(A, y, z, opts)\n%\n%%\n% Function LogisticC\n% Logistic Loss with the L1 ball constraint\n%\n%% Problem\n%\n% min f(x,c) = \\sum_i - weight_i * log (p_i) + 1/2 rsL2 * ||x||_2^2\n% s.alpha. \\|x\\|_1 <=z\n%\n% a_i denotes a training sample,\n% and a_i' corresponds to the i-th row of the data matrix A\n%\n% y_i (either 1 or -1) is the response\n%\n% p_i= 1/ (1+ exp(-y_i (x' * a_i + c) ) ) denotes the probability\n%\n% weight_i denotes the weight for the i-th sample\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 - Radius of the L1 ball\n% opts- Optional inputs (default value: opts=[])\n%\n%% Output parameters:\n% x- The obtained weight of size n x 1\n% c- The obtained intercept (scalar)\n% funVal- Function value during iterations\n%\n%% Copyright (C) 2009-2010 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%% Related papers\n%\n% [1] Jun Liu, Jianhui Chen, and Jieping Ye, Large-Scale Sparse Logistic\n% Regression, KDD 2009\n%\n% [2] Jun Liu and Jieping Ye, Efficient Euclidean Projections\n% in Linear Time, ICML 2009.\n%\n%% Related functions\n%\n% sll_opts, initFactor, pathSolutionLeast,\n% LogisticR, nnLogisticR, nnLogisticC,\n% eplb\n%\n%%\n\n%% Verify and initialize the parameters\n%%\nif (nargin <3)\n error('\\n Inputs: A, y and z 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<=0)\n error('\\n z should be positive!\\n');\nend\n\nopts=sll_opts(opts); % run sll_opts to set default values (flags)\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% The parameter 'weight' contains the weight for each training sample.\n% See the definition of the problem above.\n% The summation of the weights for all the samples equals to 1.\nif (isfield(opts,'sWeight'))\n sWeight=opts.sWeight;\n\n if ( length(sWeight)~=2 || sWeight(1) <=0 || sWeight(2) <= 0)\n error('\\n Check opts.sWeight, which contains two positive values');\n end\n\n % we process the weight, so that the summation of the weights for all\n % the samples is 1.\n\n p_flag=(y==1); % the indices of the postive samples\n m1=sum(p_flag) * sWeight(1); % the total weight for the positive samples\n m2=sum(~p_flag) * sWeight(2); % the total weight for the positive samples\n\n weight(p_flag,1)=sWeight(1)/(m1+m2);\n weight(~p_flag,1)=sWeight(2)/(m1+m2);\nelse\n weight=ones(m,1)/m; % if not specified, we apply equal weight\nend\n\n%% Starting point initialization\n\n% L2 norm regularization\nif isfield(opts,'rsL2')\n rsL2=opts.rsL2;\n if (rsL2<0)\n error('\\n opts.rsL2 should be nonnegative!');\n end\nelse\n rsL2=0;\nend\n\n% initialize a starting point\nif opts.init==2\n x=zeros(n,1); c=0;\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=zeros(n,1);\n end\n\n if isfield(opts,'c0')\n c=opts.c0;\n else\n c=0;\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\n%% The main program\n\n%% Nemirovski's line search\n\nif (opts.lFlag==0)\n\n lambda0=0;\n % a guess of the root\n\n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1/m + rsL2; % the intial guess of the Lipschitz continuous gradient\n\n weighty=weight.*y;\n % the product between weight and y\n\n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,1);\n cp=c; ccp=0;\n\n %% The Armijo Goldstein line search schemes + accelearted gradient descent\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; sc=c + beta* ccp;\n\n % --------------------------- step 2 ---------------------------\n % line search for L and compute the new approximate solution x\n\n % compute As=A*s\n As=Ax + beta* (Ax-Axp);\n\n % aa= - diag(y) * (A * s + sc)\n aa=- y.*(As+ sc);\n\n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_s= weight' * ( log( exp(-bb) + exp(aa-bb) ) + bb )+...\n rsL2/2 * s'*s;\n\n % compute prob=[p_1;p_2;...;p_m]\n prob=1./( 1+ exp(aa) );\n\n % b= - diag(y.* weight) * (1 - prob)\n b= -weighty.*(1-prob);\n\n gc=sum(b); % the gradient of c\n\n % compute g= AT b, the gradient of x\n if (opts.nFlag==0)\n g=A'*b;\n elseif (opts.nFlag==1)\n g=A'*b - sum(b) * mu'; g=g./nu;\n else\n invNu=b./nu; g=A'*invNu-sum(invNu)*mu';\n end\n\n g=g+ rsL2 * s; % add the squared L2 norm regularization term\n\n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n cp=c;\n\n while (1)\n % let s walk in a step in the antigradient of s to get v\n % and then do the Lq/L1-norm regularized projection\n v=s-g/L; c= sc- gc/L;\n\n % projection\n [x, lambda, zf_step]=eplb(v, n, z, lambda0);\n lambda0=lambda;\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 % aa= - diag(y) * (A * x + c)\n aa=- y.*(Ax+ c);\n\n % fun_x is the logistic loss at the new approximate solution\n bb=max(aa,0);\n fun_x= weight'* ( log( exp(-bb) + exp(aa-bb) ) + bb )+...\n rsL2/2 * x'*x;\n\n r_sum= (v'*v + (c-sc)^2) / 2;\n l_sum=fun_x - fun_s - v'* g - (c-sc)* gc;\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 fun_x <= fun_s + v'* g + c * gc\n % + L/2 * (v'*v + (c-sc)^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=%e, r_sum=%e',L, r_sum);\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 ValueL(iterStep)=L;\n % store values for L\n \n xxp=x-xp; ccp=c-cp;\n funVal(iterStep)=fun_x;\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 end\nend\n\n%% adaptive line search\n\nif (opts.lFlag==1)\n\n lambda0=0;\n % a guess of the root\n\n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1/m + rsL2; % the intial guess of the Lipschitz continuous gradient\n \n gamma=1;\n % we shall set the value of gamma = L,\n % and L is appropriate for the starting point\n\n weighty=weight.*y;\n % the product between weight and y\n\n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,1);\n cp=c; ccp=0;\n\n for iterStep=1:opts.maxIter\n while (1)\n if (iterStep~=1)\n alpha= (-gamma+ sqrt(gamma*gamma + 4* L * gamma)) / (2*L);\n beta= (gamma - gamma* alphap) / (alphap * gamma + alphap* L * alpha);\n % beta is the coefficient for generating search point s\n\n s=x + beta* xxp; sc=c + beta* ccp;\n As=Ax + beta* (Ax-Axp);\n else\n alpha= (-1+ sqrt(5)) / 2; beta=0;\n s=x; sc= c;\n As=Ax;\n end\n\n % aa= - diag(y) * (A * s + sc)\n aa=- y.*(As+ sc);\n\n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_s= weight' * ( log( exp(-bb) + exp(aa-bb) ) + bb )+...\n rsL2/2 * s'*s;\n\n % compute prob=[p_1;p_2;...;p_m]\n prob=1./( 1+ exp(aa) );\n\n % b= - diag(y.* weight) * (1 - prob)\n b= -weighty.*(1-prob);\n\n gc=sum(b); % the gradient of c\n\n % compute g= AT b, the gradient of x\n if (opts.nFlag==0)\n g=A'*b;\n elseif (opts.nFlag==1)\n g=A'*b - sum(b) * mu'; g=g./nu;\n else\n invNu=b./nu; g=A'*invNu-sum(invNu)*mu';\n end\n\n g=g+ rsL2 * s; % add the squared L2 norm regularization term\n\n % let s walk in a step in the antigradient of s to get v\n % and then do the Lq/L1-norm regularized projection\n v=s-g/L; cnew= sc- gc/L;\n\n % projection\n [xnew, lambda, zf_step]=eplb(v, n, z, lambda0);\n lambda0=lambda;\n\n v=xnew-s; % the difference between the new approximate solution x\n % and the search point s\n\n % compute A xnew\n if (opts.nFlag==0)\n Axnew=A* xnew;\n elseif (opts.nFlag==1)\n invNu=xnew./nu; mu_invNu=mu * invNu;\n Axnew=A*invNu -repmat(mu_invNu, m, 1);\n else\n Axnew=A*xnew-repmat(mu*xnew, m, 1); Axnew=Axnew./nu;\n end\n\n % aa= - diag(y) * (A * x + c)\n aa=- y.*(Axnew+ cnew);\n\n % fun_x is the logistic loss at the new approximate solution\n bb=max(aa,0);\n fun_x= weight'* ( log( exp(-bb) + exp(aa-bb) ) + bb )+...\n rsL2/2 * xnew'*xnew;\n\n r_sum= (v'*v + (cnew-sc)^2) / 2;\n l_sum=fun_x - fun_s - v'* g - (cnew-sc)* gc;\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 fun_x <= fun_s + v'* g + c * gc\n % + L/2 * (v'*v + (c-sc)^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=%e, r_sum=%e',L, r_sum);\n end\n end\n\n gamma=L* alpha* alpha; alphap=alpha;\n % update gamma, and alphap\n\n ValueL(iterStep)=L;\n % store values for L\n\n tao=L * r_sum / l_sum;\n if (tao >=5)\n L=L*0.8;\n end\n % decrease the value of L\n \n xp=x; x=xnew; xxp=x-xp;\n Axp=Ax; Ax=Axnew; \n cp=c; c=cnew; ccp=c-cp;\n % update x and Ax with xnew and Axnew\n \n funVal(iterStep)=fun_x;\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 end\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/L1/L1C/LogisticC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7151536753979331}} {"text": "%P2.9a\n%T1[x(n)]=2^x(n)\nn=[0:200];x=cos(0.2*pi*n)+0.5*cos(0.6*pi*n);\nt1=2.^x\n[x1,n1]=sigshift(t1,n,50); %x(n-k) -> k=50\n[x2,n2]=sigfold(t1,n); %x(-n)\n[x3,n3]=sigfold(x1,n1); %x(k-n)\n[rxx,nrxx]=conv_m(t1,n,x2,n2);\n[rxk,nrkx]=conv_m(x1,n1,x3,n3);\n[y,m]=sigadd(rxx,nrxx,0.1*rxk,nrkx);\nfigure(1);\nsubplot(3,1,1); stem(m,y,'k');title('Autocorrelation ryy');xlabel('m');\n\n\n%T2[x(n)]=3x(n)+4\nn=[0:200];x=cos(0.2*pi*n)+0.5*cos(0.6*pi*n);\nt2=3*x+4\n[x1,n1]=sigshift(t2,n,50); %x(n-k) -> k=50\n[x2,n2]=sigfold(t2,n); %x(-n)\n[x3,n3]=sigfold(x1,n1); %x(k-n)\n[rxx,nrxx]=conv_m(t2,n,x2,n2);\n[rxk,nrkx]=conv_m(x1,n1,x3,n3);\n[y,m]=sigadd(rxx,nrxx,0.1*rxk,nrkx);\nsubplot(3,1,2); stem(m,y,'k');title('Autocorrelation ryy');xlabel('m');\n\n\n%T3[x(n)]=x(n)+2x(n-1)-x(n-2)\nn=[0:200];x=cos(0.2*pi*n)+0.5*cos(0.6*pi*n);\n[xa,nxa]=sigshift(x,n,1);\n[xb,nxb]=sigshift(x,n,2);\n[xa,nxa]=sigadd(2*xa,nxa,-1*xb,nxb);\n[t3,n]=sigadd(x,n,xa,nxa)\n[x1,n1]=sigshift(t3,n,50); %x(n-k) -> k=50\n[x2,n2]=sigfold(t3,n); %x(-n)\n[x3,n3]=sigfold(x1,n1); %x(k-n)\n[rxx,nrxx]=conv_m(t3,n,x2,n2);\n[rxk,nrkx]=conv_m(x1,n1,x3,n3);\n[y,m]=sigadd(rxx,nrxx,0.1*rxk,nrkx);\nsubplot(3,1,3); stem(m,y,'k');title('Autocorrelation ryy');xlabel('m');\n\n%P2.9b\n%T1[x(n)]=2^x(n)\n%x(n)=random sequence\nnrand=[0:100];xrand=rand(size(nrand));\nt1=2.^xrand\n[x1,n1]=sigshift(t1,n,50); %x(n-k) k=50\n[x2,n2]=sigfold(t1,n); %x(-n)\n[x3,n3]=sigfold(x1,n1); %x(k-n)\n[rxx,nrxx]=conv_m(t1,n,x2,n2);\n[rxk,nrkx]=conv_m(x1,n1,x3,n3);\n[y,m]=sigadd(rxx,nrxx,0.1*rxk,nrkx);\nfigure(2);\nsubplot(3,1,1); stem(m,y,'k');title('Autocorrelation ryy');xlabel('m');\n\n\n%T2[x(n)]=3x(n)+4\n%x(n)=random sequence\nnrand=[0:100];xrand=rand(size(nrand));\nt2=3*xrand+4\n[x1,n1]=sigshift(t2,n,50); %x(n-k) -> k=50\n[x2,n2]=sigfold(t2,n); %x(-n)\n[x3,n3]=sigfold(x1,n1); %x(k-n)\n[rxx,nrxx]=conv_m(t2,n,x2,n2);\n[rxk,nrkx]=conv_m(x1,n1,x3,n3);\n[y,m]=sigadd(rxx,nrxx,0.1*rxk,nrkx);\nsubplot(3,1,2); stem(m,y,'k');title('Autocorrelation ryy');xlabel('m');\n\n\n%T3[x(n)]=x(n)+2x(n-1)-x(n-2)\n%x(n)=Random Sequence\nnrand=[0:100];xrand=rand(size(nrand));\n[xa,nxa]=sigshift(xrand,nrand,1);\n[xb,nxb]=sigshift(xrand,nrand,2);\n[xa,nxa]=sigadd(2*xa,nxa,-1*xb,nxb);\n[t3,n]=sigadd(xrand,nrand,xa,nxa);\n[x1,n1]=sigshift(t3,n,50); %x(n-k) -> k=50\n[x2,n2]=sigfold(t3,n); %x(-n)\n[x3,n3]=sigfold(x1,n1); %x(k-n)\n[rxx,nrxx]=conv_m(t3,n,x2,n2);\n[rxk,nrkx]=conv_m(x1,n1,x3,n3);\n[y,m]=sigadd(rxx,nrxx,0.1*rxk,nrkx);\nsubplot(3,1,3); stem(m,y,'k');title('Autocorrelation ryy');xlabel('m');\n\n%P2.9c\n%T1[x(n)]=2^x(n)\n%x(n)=Gaussian random sequence\nnrand=[0:100];xrand=randn(size(nrand))\nt1=2.^xrand\n[x1,n1]=sigshift(t1,n,50); %x(n-k) k=50\n[x2,n2]=sigfold(t1,n); %x(-n)\n[x3,n3]=sigfold(x1,n1); %x(k-n)\n[rxx,nrxx]=conv_m(t1,n,x2,n2);\n[rxk,nrkx]=conv_m(x1,n1,x3,n3);\n[y,m]=sigadd(rxx,nrxx,0.1*rxk,nrkx);\nfigure(3);\nsubplot(3,1,1); stem(m,y,'k');title('Autocorrelation ryy');xlabel('m');\n\n\n%T2[x(n)]=3x(n)+4\n%x(n)=Gaussian random sequence\nnrand=[0:100];xrand=randn(size(nrand))\nt2=3*xrand+4\n[x1,n1]=sigshift(t2,n,50); %x(n-k) -> k=50\n[x2,n2]=sigfold(t2,n); %x(-n)\n[x3,n3]=sigfold(x1,n1); %x(k-n)\n[rxx,nrxx]=conv_m(t2,n,x2,n2);\n[rxk,nrkx]=conv_m(x1,n1,x3,n3);\n[y,m]=sigadd(rxx,nrxx,0.1*rxk,nrkx);\nsubplot(3,1,2); stem(m,y,'k');title('Autocorrelation ryy');xlabel('m');\n\n%T3[x(n)]=x(n)+2x(n-1)-x(n-2)\n%x(n)=Gaussian Random Sequence\nnrand=[0:100];xrand=randn(size(nrand));\n[xa,nxa]=sigshift(xrand,nrand,1);\n[xb,nxb]=sigshift(xrand,nrand,2);\n[xa,nxa]=sigadd(2*xa,nxa,-1*xb,nxb);\n[t3,n]=sigadd(xrand,nrand,xa,nxa);\n[x1,n1]=sigshift(t3,n,50); %x(n-k) -> k=50\n[x2,n2]=sigfold(t3,n); %x(-n)\n[x3,n3]=sigfold(x1,n1); %x(k-n)\n[rxx,nrxx]=conv_m(t3,n,x2,n2);\n[rxk,nrkx]=conv_m(x1,n1,x3,n3);\n[y,m]=sigadd(rxx,nrxx,0.1*rxk,nrkx);\nsubplot(3,1,3); stem(m,y,'k');title('Autocorrelation ryy');xlabel('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/16323-ingle-proakis-chapter-2-solutions/P209.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.715100331888825}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [Eigen_Vector,Eigen_Value]=Find_K_Max_Gen_Eigen(Matrix1,Matrix2,Eigen_NUM)\n\n[NN,NN]=size(Matrix1);\n[V,S]=eig(Matrix1,Matrix2); %Note this is equivalent to; [V,S]=eig(St,SL); also equivalent to [V,S]=eig(Sn,St); %\n\nS=diag(S);\n[S,index]=sort(S);\n\nEigen_Vector=zeros(NN,Eigen_NUM);\nEigen_Value=zeros(1,Eigen_NUM);\n\np=NN;\nfor t=1:Eigen_NUM\n Eigen_Vector(:,t)=V(:,index(p));\n Eigen_Value(t)=S(p);\n p=p-1;\nend", "meta": {"author": "hiroyuki-kasai", "repo": "ClassifierToolbox", "sha": "63aa78304a8ac10c432840c45d63170ea2bbabb0", "save_path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox", "path": "github-repos/MATLAB/hiroyuki-kasai-ClassifierToolbox/ClassifierToolbox-63aa78304a8ac10c432840c45d63170ea2bbabb0/lib/JDDLDR_PR/utilities/Find_K_Max_Gen_Eigen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7151003300491291}} {"text": "% ZCA & l1-norm operation\nfunction output = whitening_norm(features)\n features = im2double(features);\n% output = features;\n output = zca(features);\n output = l1_norm(output);\n% output = l2_norm(output);\n% output = nuclear(output);\nend\n\n% l1-norm\nfunction output = l1_norm(features)\n [h,w,c] = size(features);\n output = zeros(h, w);\n unit = 5;\n % padding\n pad = (unit-1)/2;\n feature_temp = zeros(h+unit-1, w+unit-1, c);\n feature_temp(1+pad:h+pad, 1+pad:w+pad, :) = features;\n for i=1+pad:h+pad\n for j=1+pad:w+pad\n temp = feature_temp(i-pad:i+pad, j-pad:j+pad, :);\n norm = sum(sum(sum(abs(temp),3)))/(unit*unit);\n output(i-pad, j-pad) = norm;\n end\n end\nend\n\n% l2-norm\nfunction output = l2_norm(features)\n [h,w,c] = size(features);\n output = zeros(h, w);\n unit = 5;\n % padding\n pad = (unit-1)/2;\n feature_temp = zeros(h+unit-1, w+unit-1, c);\n feature_temp(1+pad:h+pad, 1+pad:w+pad, :) = features;\n for i=1+pad:h+pad\n for j=1+pad:w+pad\n temp = feature_temp(i-pad:i+pad, j-pad:j+pad, :);\n temp = temp.*temp;\n norm = sum(sum(sqrt(sum(temp,3))))/(unit*unit);\n output(i-pad, j-pad) = norm;\n end\n end\nend\n\n% nuclear-norm\nfunction output = nuclear(features)\n [h,w,c] = size(features);\n output = zeros(h, w);\n unit = 5;\n % padding\n pad = (unit-1)/2;\n feature_temp = zeros(h+unit-1, w+unit-1, c);\n feature_temp(1+pad:h+pad, 1+pad:w+pad, :) = features;\n for i=1+pad:h+pad\n for j=1+pad:w+pad\n temp = reshape(feature_temp(i-pad:i+pad, j-pad:j+pad, :), [unit*unit c]);\n [U, S, V] = svd(temp, 'econ');\n nu_norm = sum(diag(S));\n output(i-pad, j-pad) = nu_norm;\n end\n end\n\nend\n\n\n\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/ResNet/whitening_norm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.71510032814427}} {"text": "function fem1d_heat_explicit_test01 ( )\n\n%*****************************************************************************80\n%\n%% FEM1D_HEAT_EXPLICIT_TEST01 runs a simple test.\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 fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM1D_HEAT_EXPLICIT_TEST01:\\n' );\n fprintf ( 1, ' The time dependent 1D heat equation is\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Ut - k * Uxx = f(x,t)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' for space interval A <= X <= B with boundary conditions\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' U(A,t) = UA(t)\\n' );\n fprintf ( 1, ' U(B,t) = UB(t)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' and time interval T0 <= T <= T1 with initial condition\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' U(X,T0) = U0(X).\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' To compute an approximate solution:\\n' );\n fprintf ( 1, ' the interval [A,B] is replace by a discretized mesh Xi;\\n' );\n fprintf ( 1, ' a set of finite element functions PSI(X) are determined,\\n' );\n fprintf ( 1, ' the solution U is written as a weighted sum of the basis functions,\\n' );\n fprintf ( 1, ' the weak form of the differential equation is written,\\n' );\n fprintf ( 1, ' a time grid Tj is imposed, and time derivatives replaced by\\n' );\n fprintf ( 1, ' an explicit forward Euler first difference,\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The continuous PDE has now been transformed into a set of algebraic\\n' );\n fprintf ( 1, ' equations for the coefficients C(Xi,Tj).\\n' );\n%\n% Set the nodes.\n%\n x_num = 21;\n x_min = 0.0;\n x_max = 1.0;\n dx = ( x_max - x_min ) / ( x_num - 1 );\n x = ( linspace ( x_min, x_max, x_num ) )';\n%\n% Set the times.\n%\n t_num = 401;\n t_min = 0.0;\n t_max = 80.0;\n dt = ( t_max - t_min ) / ( t_num - 1 );\n t = ( linspace ( t_min, t_max, t_num ) )';\n%\n% Set finite element information.\n%\n element_num = x_num - 1;\n element_node(1,1:element_num) = 1 : x_num - 1;\n element_node(2,1:element_num) = 2 : x_num;\n quad_num = 3;\n mass = assemble_mass ( x_num, x, element_num, element_node, quad_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of X nodes = %d\\n', x_num );\n fprintf ( 1, ' X interval = [ %f, %f ]\\n', x_min, x_max );\n fprintf ( 1, ' X step size = %f\\n', dx );\n fprintf ( 1, ' Number of T steps = %d\\n', t_num );\n fprintf ( 1, ' T interval = [ %f, %f ]\\n', t_min, t_max );\n fprintf ( 1, ' T step size = %f\\n', dt );\n fprintf ( 1, ' Number of elements = %d\\n', element_num );\n fprintf ( 1, ' Number of quadrature points = %d\\n', quad_num );\n\n u_mat = zeros ( x_num, t_num );\n\n for j = 1 : t_num\n\n if ( j == 1 )\n\n u(1:x_num,1) = ic_test01 ( x_num, x, t(j) );\n u(1:x_num,1) = bc_test01 ( x_num, x, t(j), u(1:x_num,1) );\n\n else\n\n u(1:x_num,1) = fem1d_heat_explicit ( x_num, x, t(j-1), dt, @k_test01, ...\n @rhs_test01, @bc_test01, element_num, element_node, quad_num, mass, u );\n\n end\n\n u_mat(1:x_num,j) = u(1:x_num,1);\n\n end\n%\n% Make a product grid of T and X for plotting.\n%\n [ t_mat, x_mat ] = meshgrid ( t, x );\n%\n% Make a mesh plot of the solution.\n%\n mesh ( t_mat, x_mat, u_mat )\n xlabel ( '<--Time-->' )\n ylabel ( '<--X-->' )\n zlabel ( '<--H(X,T)-->' )\n title ( 'H(X,T) for TEST01, by FEM1D\\_HEAT\\_EXPLICIT' )\n%\n% Write the data to files.\n%\n r8mat_write ( 'h_test01.txt', x_num, t_num, u_mat );\n r8vec_write ( 't_test01.txt', t_num, t );\n r8vec_write ( 'x_test01.txt', x_num, x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' H(X,T) written to \"h_test01.txt\"\\n' );\n fprintf ( 1, ' T values written to \"t_test01.txt\"\\n' );\n fprintf ( 1, ' X values written to \"x_test01.txt\"\\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/fem1d_heat_explicit/fem1d_heat_explicit_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7150609976635204}} {"text": "function [X, info] = dominant_invariant_subspace(A, p)\n% Returns an orthonormal basis of the dominant invariant p-subspace of A.\n%\n% function X = dominant_invariant_subspace(A, p)\n%\n% Input: A real, symmetric matrix A of size nxn and an integer p < n.\n% Output: A real, orthonormal matrix X of size nxp such that trace(X'*A*X)\n% is maximized. That is, the columns of X form an orthonormal basis\n% of a dominant subspace of dimension p of A. These are thus\n% eigenvectors associated with the largest eigenvalues of A (in no\n% particular order). Sign is important: 2 is deemed a larger\n% eigenvalue than -5.\n%\n% The optimization is performed on the Grassmann manifold, since only the\n% space spanned by the columns of X matters. The implementation is short to\n% show how Manopt can be used to quickly obtain a prototype. To make the\n% implementation more efficient, one might first try to use the caching\n% system, that is, use the optional 'store' arguments in the cost, grad and\n% hess functions. Furthermore, using egrad2rgrad and ehess2rhess is quick\n% and easy, but not always efficient. Having a look at the formulas\n% implemented in these functions can help rewrite the code without them,\n% possibly more efficiently.\n%\n% See also: dominant_invariant_subspace_complex\n\n% This file is part of Manopt and is copyrighted. See the license file.\n%\n% Main author: Nicolas Boumal, July 5, 2013\n% Contributors:\n%\n% Change log:\n%\n% NB Dec. 6, 2013:\n% We specify a max and initial trust region radius in the options.\n \n % Generate some random data to test the function\n if ~exist('A', 'var') || isempty(A)\n A = randn(128);\n A = (A+A')/2;\n end\n if ~exist('p', 'var') || isempty(p)\n p = 3;\n end\n \n % Make sure the input matrix is square and symmetric\n n = size(A, 1);\n\tassert(isreal(A), 'A must be real.')\n assert(size(A, 2) == n, 'A must be square.');\n assert(norm(A-A', 'fro') < n*eps, 'A must be symmetric.');\n\tassert(p<=n, 'p must be smaller than n.');\n \n % Define the cost and its derivatives on the Grassmann manifold\n Gr = grassmannfactory(n, p);\n problem.M = Gr;\n problem.cost = @(X) -trace(X'*A*X);\n problem.grad = @(X) -2*Gr.egrad2rgrad(X, A*X);\n problem.hess = @(X, H) -2*Gr.ehess2rhess(X, A*X, A*H, H);\n \n % Execute some checks on the derivatives for early debugging.\n % These can be commented out.\n % checkgradient(problem);\n % pause;\n % checkhessian(problem);\n % pause;\n \n % Issue a call to a solver. A random initial guess will be chosen and\n % default options are selected except for the ones we specify here.\n options.Delta_bar = 8*sqrt(p);\n [X, costX, info, options] = trustregions(problem, [], options); %#ok\n \n fprintf('Options used:\\n');\n disp(options);\n \n % For our information, Manopt can also compute the spectrum of the\n % Riemannian Hessian on the tangent space at (any) X. Computing the\n % spectrum at the solution gives us some idea of the conditioning of\n % the problem. If we were to implement a preconditioner for the\n % Hessian, this would also inform us on its performance.\n %\n % Notice that (typically) all eigenvalues of the Hessian at the\n % solution are positive, i.e., we find an isolated minimizer. If we\n % replace the Grassmann manifold by the Stiefel manifold, hence still\n % optimizing over orthonormal matrices but ignoring the invariance\n % cost(XQ) = cost(X) for all Q orthogonal, then we see\n % dim O(p) = p(p-1)/2 zero eigenvalues in the Hessian spectrum, making\n % the optimizer not isolated anymore.\n if Gr.dim() < 512\n evs = hessianspectrum(problem, X);\n stairs(sort(evs));\n title(['Eigenvalues of the Hessian of the cost function ' ...\n 'at the solution']);\n xlabel('Eigenvalue number (sorted)');\n ylabel('Value of the eigenvalue');\n end\n\nend\n", "meta": {"author": "MIT-SPARK", "repo": "GlobalOptimizationTutorial", "sha": "ae1e947a846ca9199d9a3579409d73f4f7fa4ccf", "save_path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial", "path": "github-repos/MATLAB/MIT-SPARK-GlobalOptimizationTutorial/GlobalOptimizationTutorial-ae1e947a846ca9199d9a3579409d73f4f7fa4ccf/SE-Sync/manopt/examples/dominant_invariant_subspace.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.715049542617378}} {"text": "function [ n_data, n, c ] = mertens_values ( n_data )\n\n%*****************************************************************************80\n%\n%% MERTENS_VALUES returns some values of the Mertens function.\n%\n% Discussion:\n%\n% The Mertens function M(N) is the sum from 1 to N of the Moebius\n% function MU.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% M Deleglise, J Rivat,\n% Computing the Summation of the Moebius Function,\n% Experimental Mathematics,\n% Volume 5, 1996, pages 291-295.\n%\n% Eric Weisstein,\n% CRC Concise Encyclopedia of Mathematics,\n% CRC Press, 2002,\n% Second edition,\n% ISBN: 1584883472,\n% LC: QA5.W45.\n%\n% Parameters:\n%\n% Input, integer N_DATA, indicates the index of the previous test data\n% returned, or is 0 if this is the first call. For repeated calls,\n% set the input value of N_DATA to the output value of N_DATA\n% from the previous call.\n%\n% Output, integer N_DATA, the index of the test data.\n%\n% Output, integer N, the argument of the Mertens function.\n%\n% Output, integer C, the value of the Mertens function.\n%\n n_max = 15;\n c_vec = [ ...\n 1, 0, -1, -1, -2, -1, -2, -2, -2, -1, ...\n -2, -2, 1, 2, -23 ];\n n_vec = [ ...\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...\n 11, 12, 100, 1000, 10000 ];\n\n if ( n_data < 0 )\n n_data = 0;\n end\n\n n_data = n_data + 1;\n\n if ( n_max < n_data )\n n_data = 0;\n n = 0;\n c = 0;\n else\n n = n_vec(n_data);\n c = c_vec(n_data);\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/polpak/mertens_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.7150495248710175}} {"text": "function X=get_X_from_xP_lin(xn,Pcomp)\n%get_X_from_xP_lin Estimation of 3D point from image matches and camera matrices, linear.\n% return a 3D point X (column 4-vector, homogeneous, last element 1)\n% from its projections in K images xn (2-by-K matrix) and camera matrices\n% P (K-cell of 3-by-4 matrices) by minimizing algebraic distance.\n% xn 3 x K matrix, homogeneous normalized image coordinates,\n% last rows of 1, the other values usu. falls between -0.5 to 0.5\nK=size(xn,2);\nA = zeros(2*K, 4);\nfor k = 1:K\n A(2*k+(-1:0),:)=[xn(1,k)*Pcomp(3,:,k)-Pcomp(1,:,k); xn(2,k)*Pcomp(3,:,k)-Pcomp(2,:,k)];\nend\n% A = normx(A')';\n[dummy,dummy,X] = svd(A,0);\nX = X(:,end);\nX=X/X(4);", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/ekfmonoslam/imageproc/get_X_from_xP_lin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9621075744568837, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.7150075701801066}} {"text": "function xy = perform_classical_mds(D,ndims)\n\n\nN = size(D,1);\nopt.disp = 0; opt.isreal = 1; opt.issym = 1; \nM = -.5*(D.^2 - sum(D.^2)'*ones(1,N)/N - ones(N,1)*sum(D.^2)/N + sum(sum(D.^2))/(N^2));\n[xy, val] = eigs(M, ndims, 'LR', opt); \n\nfor i=1:ndims\n xy(:,i) = xy(:,i)*sqrt(val(i,i));\nend", "meta": {"author": "gpeyre", "repo": "matlab-toolboxes", "sha": "0cd622c988cda6f63f64d35cd7bd096fa578e5c6", "save_path": "github-repos/MATLAB/gpeyre-matlab-toolboxes", "path": "github-repos/MATLAB/gpeyre-matlab-toolboxes/matlab-toolboxes-0cd622c988cda6f63f64d35cd7bd096fa578e5c6/toolbox_signal/perform_classical_mds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391685381605, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7149708124893251}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n\n\n%problem 2 - Fourier Transform of sinc(t)\n\nsyms t w\nx=sin(pi*t)/(pi*t);\nX=fourier(x,w);\nezplot(X, [-10 10])\nlegend('X(\\Omega)');\nxlabel('\\Omega');\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/6/c69b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.71497080604633}} {"text": "function [ H, Lh ] = homographyHarker( DataA, DataB, LA, LB)\n%\n% Purpose : Computes the general projective transformation between two sets\n% of 2D data using a linear algorithm (the homography).\n%\n% Uses (syntax) :\n% H = homography( DataA, DataB ) \n%\n% Input Parameters :\n% DataA, DataB := 2D homogeneous data sets in matrix form (3xn)\n%\n% Return Parameters :\n% H := the 3x3 homography\n%\n% Description and algorithms:\n% The algorithm is based on the Direct Linear Transform (DLT) method\n% outlined in Hartley et al. The method uses orthogonal projections of\n% matrices, such that the vanishing line is treated as the principal\n% component of the reduction. In this manner, the statistical behaviour\n% of the errors in variables are treated uniformly, see Harker and\n% O'Leary 2005.\n%\n% References :\n% Harker, M., O'Leary, P., Computation of Homographies, to appear in\n% Proceedings of the British Machine Vision Conference 2005, Oxford,\n% England.\n% Hartley, R., Zisserman, A., Multiple View Geometry in Computer Vision,\n% Cambridge University Press, Cambridge, 2001\n%\n% Cite this as :\n%\n% Author : Matthew Harker\n% Date : July 25, 2005\n% Version : 1.0\n%--------------------------------------------------------------------------\n% (c) 2005, O'Leary, Harker, University of Leoben, Leoben, Austria\n% email: automation@unileoben.ac.at, url: automation.unileoben.ac.at\n%--------------------------------------------------------------------------\n% History:\n% Date: Comment:\n% July 25, 2005 Original Version 1.0\n%--------------------------------------------------------------------------\n%\n% Check input parameters:\n%\nif nargin == 2\n %\n if ~is2DData( DataA ) | ~is2DData( DataB )\n %\n error('Input does not represent 2D data') ;\n %\n end\n %\n [mA,nA] = size( DataA ) ;\n [mB,nB] = size( DataB ) ;\n %\n if (nA ~= nB)\n %\n error('Data sets must be the same size') ;\n %\n end\n %\n %\nelseif nargin == 4\n %\n if ~is2dcovdata( DataA, LA ) | ~is2dcovdata( DataB, LB )\n %\n error('Input data does not match') ;\n %\n end\n %\n [mA,nA] = size( DataA ) ;\n [mB,nB] = size( DataB ) ;\n %\n if (nA ~= nB)\n %\n error('Data sets must be the same size') ;\n %\n end\n %\n %\n error('Error propagation not implemented as of yet') ;\n %\nelse\n %\n error('Incorrect number of input parameters') ;\n %\nend\n%\n% Normalize the input data:\n%\nif nargin == 2\n %\n [DataA,TA,TAi] = normalizeData( DataA ) ;\n [DataB,TB,TBi] = normalizeData( DataB ) ;\n %\nelseif nargin == 4 \n %\n [DataA,TA,TAi,LA] = normalizeData( DataA, LA ) ;\n [DataB,TB,TBi,LB] = normalizeData( DataB, LB ) ;\n %\nend\n%\n% Construct the orthogonalized design matrix :\n%\nC1 = -DataB(1,:) .* DataA(1,:) ;\nC2 = -DataB(1,:) .* DataA(2,:) ;\n%\nC3 = -DataB(2,:) .* DataA(1,:) ;\nC4 = -DataB(2,:) .* DataA(2,:) ;\n%\nmC1 = mean( C1 ) ;\nmC2 = mean( C2 ) ;\nmC3 = mean( C3 ) ;\nmC4 = mean( C4 ) ;\n%\nMx = [ C1' - mC1, C2' - mC2, -DataB(1,:)' ] ;\nMy = [ C3' - mC3, C4' - mC4, -DataB(2,:)' ] ;\n%\nPp = pinv(DataA(1:2,:)') ;\n%\nBx = Pp * Mx ;\nBy = Pp * My ;\n%\nD = [ Mx - DataA(1:2,:)'*Bx ;...\n My - DataA(1:2,:)'*By ] ;\n%\n% Find v_min and backsubstitute :\n%\n[U,S,V] = svd( D, 0 ) ;\n%\nh789 = V(:,end) ;\nh12 = -Bx * h789 ;\nh45 = -By * h789 ;\nh3 = -[mC1, mC2] * h789(1:2) ;\nh6 = -[mC3, mC4] * h789(1:2) ;\n%\n% Reshape vector h to matrix H, and transform :\n%\nH = reshape( [h12; h3; h45; h6; h789], 3, 3)' ;\n%\nH = TB * H * TAi ;\n%\n% Compute the covariance of the output :\n%\n%\n%\n% END\n%\n\nfunction [DataN, T, Ti, LN] = normalizeData( Data, L ) ;\n%\n% Purpose : Computes a set of data corresponding to the input data with its\n% centroid subtracted, and scaled such that the root-mean-square distance\n% to the origin is sqrt(2). The transformation T, carries the scaled data\n% back to its original form. Optionally, the first order estimation of\n% covariance matrices are computed.\n%\n% Uses (syntax) :\n% [DataN, T, LN] = normalizeData( Data, L )\n% [DataN, T] = normalizeData( Data )\n%\n% Input Parameters :\n% Data := a 3xn matrix of homogeneous points.\n% L := is a 3x3 covariance matrix (all points have identical covariance), or\n% a 3x3xn array of n covariance matrices.\n%\n% Return Parameters :\n% DataN := mean-free data scaled s.t. d_RMS = sqrt(2)\n% T := transformation to bring DataN to the Affine coordinates\n% corresponding to Data (NOTE: T*DataN is in affine coords).\n% LN := the covariance of the scaled normalized data (size is\n% generally 2x2xn, due to the normalization)\n%\n% Description and algorithms:\n%\n% References :\n% Clarke, J.C., Modelling Uncertainty: A Primer, Dept. of Engineering\n% Science, Oxford University, Technical Report.\n%\n% Cite this as :\n%\n% Author : Matthew Harker\n% Date : July 7, 2005\n% Version :\n%\n% (c) 2005, Institute for Automation, University of Leoben, Leoben, Austria\n% email: automation@unileoben.ac.at, url: automation.unileoben.ac.at\n%\n% History:\n% Date: Comment:\n% Original Version 1.0\n%--------------------------------------------------------------------------\n%\n% Check input arguments :\n%\nif nargin == 1\n %\n if ~is2DData( Data )\n %\n error('Input does not represent 2D data') ;\n %\n end\n %\nelseif nargin == 2\n %\n if ~is2dcovdata( Data, L )\n %\n error('Input data and covariances do not match') ;\n %\n end\n %\nelse\n %\n error('Not enough input arguments') ;\n %\nend\n%\ns = Data(1,:) ;\nt = Data(2,:) ;\nu = Data(3,:) ;\n%\nx = s./u ;\ny = t./u ;\n%\nxm = mean( x ) ;\nym = mean( y ) ;\n%\nxh = x - xm ;\nyh = y - ym ;\n%\nn = length( xh ) ;\n%\nkappa = sum( xh.^2 + yh.^2 ) ;\n%\nbeta = sqrt( 2*n / kappa ) ;\n%\nxn = beta * xh ;\nyn = beta * yh ;\n%\nDataN = [ xn; yn; ones(size(xn)) ] ;\n%\nT = [ 1/beta, 0 , xm ;...\n 0 , 1/beta, ym ;...\n 0 , 0 , 1 ] ;\n%\nTi = [ beta , 0 , -beta * xm ; ...\n 0 , beta , -beta * ym ; ...\n 0 , 0 , 1 ] ;\n%\n%\n%\nif nargin == 1\n %\n % Just the data is needed.\n %\n if nargout == 4\n warning('No covariance matrix for the input data given.') ;\n LN = [] ;\n end\n %\n %\n %\nelseif nargin == 2\n %\n % There is a 3x3 homogeneous covariance matrix given\n %\n if nargout == 4\n %\n % The 2x2 covariance matrix of the Euclidean output data is required\n %\n dim = length( size( L ) ) ;\n %\n % dim == 2 --> all covariance matrices are assumed the same\n % dim == 3 --> each point has a given covariance\n %\n % DEHOMOGENIZE\n %\n for k = 1:n\n %\n %\n % Jacobian for dehomogenizing:\n Jd = ( 1/u(k)^2 ) * [ u(k), 0 , -s(k) ;...\n 0 , u(k), -t(k) ] ;\n %\n %\n if dim == 2\n LN(:,:,k) = Jd * L * Jd' ;\n else\n LN(:,:,k) = Jd * L(:,:,k) * Jd' ;\n end\n %\n % NOTE: If all data has the same covariance, after\n % dehomogenizing they will generally all have different\n % covariance matrices (as implemented here). Only if the data\n % is already affine, and the covariance matrix is Euclidean\n % will the \"normalized\" points all have the same covariance.\n %\n end\n %\n % SUBTRACT MEAN, SCALE:\n % \n % Jacobian for subtracting mean:\n Jm = [ (1-(1/n)), 0 , -1 , 0 ;...\n 0 , (1-(1/n)) , 0 , -1 ] ;\n %\n % Covariance of the mean value:\n Lm = (1/n^2) * [ sum(LN(1,1,:)), sum(LN(1,2,:)) ;...\n sum(LN(2,1,:)), sum(LN(2,2,:)) ] ;\n %\n %\n Lkappa = 0 ;\n %\n for k = 1:n\n %\n % Subtract Mean Covariance\n %\n LN(:,:,k) = Jm * [ LN(:,:,k) , zeros(2,2) ; zeros(2,2) , Lm ] * Jm' ;\n %\n % Compute Covariance of 'kappa':\n %\n Jk = 2 * [ xh(k), yh(k) ] ;\n Lkappa = Lkappa + Jk*LN(:,:,k)*Jk' ;\n %\n end\n %\n %\n for k = 1:n\n %\n % Jacobian for scaling the data:\n %\n a = kappa^(-3/2) ;\n b = kappa^(-1/2) ;\n %\n Js = sqrt(2*n) * [ (b - a*xh(k)^2) , -a*xh(k)*yh(k) , -(a*xh(k))/2 ;...\n -a*xh(k)*yh(k) , (b - a*yh(k)^2) , -(a*yh(k))/2 ] ;\n %\n LN(:,:,k) = Js * [ LN(:,:,k), [0;0] ; [0,0] , Lkappa ] * Js' ; \n %\n %\n %\n end\n %\n %\n %\n elseif nargout == 3\n %\n warning('No covariance matrix has been returned') ;\n %\n end\n %\n %\nend\n%\n% END\n% \n", "meta": {"author": "tobycollins", "repo": "IPPE", "sha": "3304dfa40c7cbd046ba0d540b8b1143283c83f4e", "save_path": "github-repos/MATLAB/tobycollins-IPPE", "path": "github-repos/MATLAB/tobycollins-IPPE/IPPE-3304dfa40c7cbd046ba0d540b8b1143283c83f4e/matlab/homogEstimationMethods/harker/homographyHarker.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7149707980799354}} {"text": "function dd=tritrig(a,b,c,A,B,C)\nif A==90 | B==90\n 'error, right angle can only be C'\n \nend\nx=0;\nif C==90\n if a~=0 & b~=0\n c=sqrt(a^2+b^2);\n A=asind(a/c);\n B=asind(b/c);\n x=1;\n \n end\n if a~=0 & c~=0 & x==0\n b=sqrt(c^2-a^2);\n A=asind(a/c);\n B=asind(b/c);\n x=1;\n \n end\n if b~=0 & c~=0 & x==0\n a=sqrt(c^2-b^2);\n A=asind(a/c);\n B=asind(b/c);\n x=1;\n \n end\n if A~=0 & x==0\n B=90-A;\n if a~=0\n b=a/tand(A);\n c=a/sind(a);\n x=1;\n \n end\n if b~=0 & x==0\n a=tand(A)*b;\n c=b/cosd(A);\n x=1;\n \n end\n if c~=0 & x==0\n a=sind(A)*c;\n b=cosd(A)*c;\n x=1;\n \n end\n end\n if B~=0 & x==0\n A=90-B;\n if a~=0\n b=a/tand(A);\n c=a/sind(a);\n x=1;\n \n end\n if b~=0 & x==0\n a=tand(A)*b;\n c=b/cosd(A);\n x=1;\n \n end\n if c~=0 & x==0\n a=sind(A)*c;\n b=cosd(A)*c;\n x=1;\n \n end\n end\nend\n\n\nif a~=0 & b~=0 & c~=0 & x==0\n A=acosd((b^2+c^2-a^2)/2/b/c);\n B=asind(sind(A)*b/a);\n C=180-A-B;\n x=1;\n \nend\nif a~=0 & b~=0 & C~=0 & x==0\n c=sqrt(a^2+b^2-2*a*b*cosd(C));\n A=asind(sind(B)*a/b);\n B=asind(sind(A)*b/a);\n x=1;\n \nend\nif a~=0 & c~=0 & B~=0 & x==0\n b=sqrt(a^2+c^2-2*a*c*cosd(B));\n A=asind(sind(B)*a/b);\n C=180-B-A;\n x=1;\n \nend\nif b~=0 & c~=0 & A~=0 & x==0\n a=sqrt(b^2+c^2-2*b*c*cosd(A));\n B=asind(sind(A)*b/a);\n C=180-A-B;\n x=1;\n \nend\nif A~=0 & B~=0 & x==0\n C=180-A-B;\n if a~=0 \n b=sind(B)*a/sind(A);\n c=sind(C)*a/sind(A);\n x=1;\n \n end\n if b~=0 & x==0\n a=sind(A)*b/sind(B);\n c=sind(C)*b/sind(B);\n x=1;\n \n end\n if c~=0 & x==0\n a=sind(A)*c/sind(C);\n b=sind(B)*c/sind(C);\n x=1;\n \n end\nend\nif A~=0 & C~=0 & x==0\n B=180-A-C;\n if a~=0\n b=sind(B)*a/sind(A);\n c=sind(C)*a/sind(A);\n x=1;\n \n end\n if b~=0 & x==0\n a=sind(A)*b/sind(B);\n c=sind(C)*b/sind(B);\n x=1;\n \n end\n if c~=0 & x==0\n a=sind(A)*c/sind(C);\n b=sind(B)*c/sind(C);\n x=1;\n \n end\nend\nif B~=0 & C~=0 & x==0\n A=180-B-C;\n if a~=0\n b=sind(B)*a/sind(A);\n c=sind(C)*a/sind(A);\n x=1;\n \n end\n if b~=0 & x==0\n a=sind(A)*b/sind(B);\n c=sind(C)*b/sind(B);\n x=1;\n \n end\n if c~=0 & x==0\n a=sind(A)*c/sind(C);\n b=sind(B)*c/sind(C);\n x=1;\n \n end\nend\nif x==0\n 'not enough information was given'\nelse\na\nb\nc\nA\nB\nC\nend\n%How to use tritrig:\n%tritrig is in the form 'tritrig(a,b,c,A,B,C)' where a b c A B C are the\n%angles and the lengths of a triangle. If your triangle has a right angle\n%in it, it must be 'C' and the hypotenuse must be 'c'. The angles and\n%lengths that you do not know must be typed as '0'\n%Eg.\n%tritrig(3,4,5,0,0,0)\n%A = \n% 36.8699\n%B= \n% 53.1301\n%C=\n% 90.0000", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/32826-tritrig/tritrig.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133515091157, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.7149457093853331}} {"text": "%MVDR_FF: Minimum Variance Distortionless Response Beamformer using\n%Free-field Steering Vector\n%--------------------\n% Input parameters\n%--------------------\n%nChannels : The steering vector, or relative transfer function [numChannels x numFreqs ]\n%dMic : The distance between two microphones [a real positive value]\n%DOA: The direction of arrival in degree [ 0~360 ]\n%freqVec: The frequencies vector [ numFreqs]\n%Phi_u: The PSD matrix of the interfering signal [numChannels x numChannels x numFreqs ]\n%--------------------\n% Output parameters\n%--------------------\n%H_mvdr: An mvdr beamformer [ numChannels x numFreqs ] \nfunction H_mvdr = mvdrFF(nChannels, dMic, DOA, freqVec, Phi_u)\n\nc = 340;\ntheta0 = DOA * pi / 180; \nd = exp(-1j*[0:nChannels-1]'*2*pi*freqVec*cos(theta0)*dMic/c) ./ nChannels; % steering vector\n\nH_mvdr = zeros(nChannels, length(freqVec));\n%Phi_u_inv = zeros(nChannels, nChannels);\nfor f = 1:length(freqVec) \n Phi_u_inv = pinv(Phi_u(:,:,f));\n df = d(:, f);\n H_mvdr(:, f) = (Phi_u_inv * df) / (df' * Phi_u_inv * df);\nend\n\nend", "meta": {"author": "chenwj1989", "repo": "Beamforming_Examples", "sha": "403cd9e2b63310e2dfcdea5335a74c666156b53c", "save_path": "github-repos/MATLAB/chenwj1989-Beamforming_Examples", "path": "github-repos/MATLAB/chenwj1989-Beamforming_Examples/Beamforming_Examples-403cd9e2b63310e2dfcdea5335a74c666156b53c/beamformer/mvdrFF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.7149456928055841}} {"text": "function [idx,D]=fastknnsearch(varargin)\n% KNNSEARCH Linear k-nearest neighbor (KNN) search\n% IDX = knnsearch(Q,R,K) searches the reference data set R (n x d array\n% representing n points in a d-dimensional space) to find the k-nearest\n% neighbors of each query point represented by eahc row of Q (m x d array).\n% The results are stored in the (m x K) index array, IDX. \n%\n% IDX = knnsearch(Q,R) takes the default value K=1.\n%\n% IDX = knnsearch(Q) or IDX = knnsearch(Q,[],K) does the search for R = Q.\n%\n% Rationality\n% Linear KNN search is the simplest appraoch of KNN. The search is based on\n% calculation of all distances. Therefore, it is normally believed only\n% suitable for small data sets. However, other advanced approaches, such as\n% kd-tree and delaunary become inefficient when d is large comparing to the\n% number of data points. On the other hand, the linear search in MATLAB is\n% relatively insensitive to d due to the vectorization. In this code, the \n% efficiency of linear search is further improved by using the JIT\n% aceeleration of MATLAB. Numerical example shows that its performance is\n% comparable with kd-tree algorithm in mex.\n%\n% See also, kdtree, nnsearch, delaunary, dsearch\n\n% By Yi Cao at Cranfield University on 25 March 2008\n\n% Example 1: small data sets\n%{\nR=randn(100,2);\nQ=randn(3,2);\nidx=knnsearch(Q,R);\nplot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'ro',R(idx,1),R(idx,2),'gx');\n%}\n\n% Example 2: ten nearest points to [0 0]\n%{\nR=rand(100,2);\nQ=[0 0];\nK=10;\nidx=knnsearch(Q,R,10);\nr=max(sqrt(sum(R(idx,:).^2,2)));\ntheta=0:0.01:pi/2;\nx=r*cos(theta);\ny=r*sin(theta);\nplot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'co',R(idx,1),R(idx,2),'gx',x,y,'r-','linewidth',2);\n%}\n\n% Example 3: cputime comparion with delaunay+dsearch I, a few to look up\n%{\nR=randn(10000,4);\nQ=randn(500,4);\nt0=cputime;\nidx=knnsearch(Q,R);\nt1=cputime;\nT=delaunayn(R);\nidx1=dsearchn(R,T,Q);\nt2=cputime;\nfprintf('Are both indices the same? %d\\n',isequal(idx,idx1));\nfprintf('CPU time for knnsearch = %g\\n',t1-t0);\nfprintf('CPU time for delaunay = %g\\n',t2-t1);\n%}\n% Example 4: cputime comparion with delaunay+dsearch II, lots to look up\n%{\nQ=randn(10000,4);\nR=randn(500,4);\nt0=cputime;\nidx=knnsearch(Q,R);\nt1=cputime;\nT=delaunayn(R);\nidx1=dsearchn(R,T,Q);\nt2=cputime;\nfprintf('Are both indices the same? %d\\n',isequal(idx,idx1));\nfprintf('CPU time for knnsearch = %g\\n',t1-t0);\nfprintf('CPU time for delaunay = %g\\n',t2-t1);\n%}\n% Example 5: cputime comparion with kd-tree by Steven Michael (mex file) \n% kd-tree by Steven Michael \n%{\nQ=randn(10000,10);\nR=randn(500,10);\nt0=cputime;\nidx=knnsearch(Q,R);\nt1=cputime;\ntree=kdtree(R);\nidx1=kdtree_closestpoint(tree,Q);\nt2=cputime;\nfprintf('Are both indices the same? %d\\n',isequal(idx,idx1));\nfprintf('CPU time for knnsearch = %g\\n',t1-t0);\nfprintf('CPU time for delaunay = %g\\n',t2-t1);\n%}\n\n% Check inputs\n[Q,R,K,fident] = parseinputs(varargin{:});\n\n% Check outputs\nnargoutchk(0,2);\n\n% C2 = sum(C.*C,2)';\n[N,M] = size(Q);\nL=size(R,1);\nidx = zeros(N,K);\nD = idx;\n\nif K==1\n % Loop for each query point\n for k=1:N\n d=zeros(L,1);\n for t=1:M\n d=d+(R(:,t)-Q(k,t)).^2;\n end\n if fident\n d(k)=inf;\n end\n [D(k),idx(k)]=min(d);\n end\nelse\n for k=1:N\n d=zeros(L,1);\n for t=1:M\n d=d+(R(:,t)-Q(k,t)).^2;\n end\n if fident\n d(k)=inf;\n end\n [s,t]=sort(d);\n idx(k,:)=t(1:K);\n D(k,:)=s(1:K);\n end\nend\nif nargout>1\n D=sqrt(D);\nend\n\nfunction [Q,R,K,fident] = parseinputs(varargin)\n% Check input and output\nnarginchk(1,3);\n\nQ=varargin{1};\n\nif nargin<2\n R=Q;\n fident = true;\nelse\n fident = false;\n R=varargin{2};\nend\n\nif isempty(R)\n fident = true;\n R=Q;\nend\n\nif ~fident\n fident = isequal(Q,R);\nend\n\nif nargin<3\n K=1;\nelse\n K=varargin{3};\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/fastknnsearch.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7148996039668045}} {"text": "function centroid = voronoi_polygon_centroid ( node, neighbor_num, ...\n neighbor_index, node_num, node_xy )\n\n%*****************************************************************************80\n%\n%% VORONOI_POLYGON_CENTROID computes the centroid of a Voronoi polygon.\n%\n% Discussion:\n%\n% It is assumed that the Voronoi polygon is finite! Every Voronoi\n% diagram includes some regions which are infinite, and for those,\n% this formula is not appropriate.\n%\n% The routine is given the indices of the nodes that are neighbors of a \n% given \"center\" node. A node is a neighbor of the center node if the\n% Voronoi polygons of the two nodes share an edge. The triangles of the \n% Delaunay triangulation are formed from successive pairs of these neighbor \n% nodes along with the center node.\n%\n% The assumption that the polygon is a Voronoi polygon is\n% used to determine the location of the boundaries of the polygon,\n% which are the perpendicular bisectors of the lines connecting\n% the center point to each of its neighbors.\n%\n% The finiteness assumption is employed in part in the\n% assumption that the polygon is bounded by the finite\n% line segments from point 1 to 2, 2 to 3, ...,\n% M-1 to M, and M to 1, where M is the number of neighbors.\n%\n% It is assumed that this subroutine is being called by a\n% process which has computed the Voronoi diagram of a large\n% set of nodes, so the arrays X and Y are dimensioned by\n% NODE_NUM, which may be much greater than the number of neighbor\n% nodes.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 February 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Atsuyuki Okabe, Barry Boots, Kokichi Sugihara, Sung Nok Chiu,\n% Spatial Tessellations: Concepts and Applications of Voronoi Diagrams,\n% Second Edition,\n% Wiley, 2000, page 490.\n%\n% Parameters:\n%\n% Input, integer NODE, the index of the node whose Voronoi\n% polygon is to be analyzed. 1 <= NODE <= NODE_NUM.\n%\n% Input, integer NEIGHBOR_NUM, the number of neighbor nodes of\n% the given node.\n%\n% Input, integer NEIGHBOR_INDEX(NEIGHBOR_NUM), the indices\n% of the neighbor nodes. These indices are used to access the\n% X and Y arrays. The neighbor nodes should be listed in the\n% (counter-clockwise) order in which they occur as one circles \n% the center node.\n%\n% Input, integer NODE_NUM, the total number of nodes.\n%\n% Input, real NODE_XY(2,NODE_NUM), the nodes.\n%\n% Output, real CENTROID(2), the coordinates of the centroid\n% of the Voronoi polygon of node NODE.\n%\n dim_num = 2;\n\n centroid(1:dim_num,1) = 0.0;\n\n if ( node < 1 | node_num < node )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'VORONOI_POLYGON_CENTROID - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of input parameter NODE.\\n' );\n error ( 'VORONOI_POLYGON_CENTROID - Fatal error!' )\n end\n\n pc(1:dim_num) = node_xy(1:dim_num,node)';\n\n i = neighbor_num;\n i = neighbor_index(i);\n\n pi(1:dim_num) = node_xy(1:dim_num,i)';\n\n j = 1;\n j = neighbor_index(j);\n\n pj(1:dim_num) = node_xy(1:dim_num,j)';\n\n a = ( pi(1) * pi(1) + pi(2) * pi(2) - pc(1) * pc(1) - pc(2) * pc(2) );\n b = ( pj(1) * pj(1) + pj(2) * pj(2) - pc(1) * pc(1) - pc(2) * pc(2) );\n c = 2.0 * ( ( pi(1) - pc(1) ) * ( pj(2) - pc(2) ) ...\n - ( pj(1) - pc(1) ) * ( pi(2) - pc(2) ) );\n uj(1) = ( a * ( pj(2) - pc(2) ) - b * ( pi(2) - pc(2) ) ) / c;\n uj(2) = ( a * ( pj(1) - pc(1) ) - b * ( pi(1) - pc(1) ) ) / c;\n\n for i = 1 : neighbor_num\n\n pi(1:dim_num) = pj(1:dim_num);\n ui(1:dim_num) = uj(1:dim_num);\n\n j = i4_wrap ( i+1, 1, neighbor_num );\n pj(1:dim_num) = node_xy(1:dim_num,j)';\n\n a = ( pi(1) * pi(1) + pi(2) * pi(2) - pc(1) * pc(1) - pc(2) * pc(2) );\n b = ( pj(1) * pj(1) + pj(2) * pj(2) - pc(1) * pc(1) - pc(2) * pc(2) );\n c = 2.0 * ( ( pi(1) - pc(1) ) * ( pj(2) - pc(2) ) ...\n - ( pj(1) - pc(1) ) * ( pi(2) - pc(2) ) );\n uj(1) = ( a * ( pj(2) - pc(2) ) - b * ( pi(2) - pc(2) ) ) / c;\n uj(2) = ( a * ( pj(1) - pc(1) ) - b * ( pi(1) - pc(1) ) ) / c;\n\n centroid(1) = centroid(1) + ( ui(2) - uj(2) ) ...\n * ( ( uj(1) + ui(1) )^2 - uj(1) * ui(1) );\n centroid(2) = centroid(2) + ( ui(1) - uj(1) ) ...\n * ( ( uj(2) + ui(2) )^2 - uj(2) * ui(2) );\n\n end\n\n area = voronoi_polygon_area ( node, neighbor_num, neighbor_index, ...\n node_num, node_xy );\n\n centroid(1:dim_num) = centroid(1:dim_num) / ( 6.0 * area );\n\n return\nend\n", "meta": {"author": "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/voronoi_polygon_centroid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7148996033980872}} {"text": "function AIC=aic(nParameters, nObservations, Residuals)\n%Computes Akaike information criterion for a model\n%\n%\n%\n% Implements http://en.wikipedia.org/wiki/Akaike_information_criterion\n\n% HISTORY: \n% ER wrote it 01/2010\n\nAIC =2*(nParameters)+nObservations*(log(sum(Residuals.^2)/nObservations)); ", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrDiffusion/statistics/aic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425311777928, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7148380165592064}} {"text": "function [soln,eqn,info] = PoissonP2(node,elem,bdFlag,pde,option)\n%% POISSONP2 Poisson equation: P2 quadratic element.\n%\n% u = PoissonP2(node,elem,bdFlag,pde,option) produces the quadratic\n% finite element approximation of the Poisson equation\n% \n% -div(d*grad(u))=f in \\Omega, with \n% Dirichlet boundary condition u=g_D on \\Gamma_D, \n% Neumann boundary condition d*grad(u)*n=g_N on \\Gamma_N,\n% Robin boundary condition g_R*u + d*grad(u)*n=g_N on \\Gamma _R\n%\n% [soln,eqn,info] = PoissonP2(node,elem,pde,bdFlag,option)\n%\n% The usage is the same as Poisson. Quadratic element on a triangle is\n% summarized in PoissonP2femrate for detail.\n% \n% Example\n% clear all\n% node = [0,0; 1,0; 1,1; 0,1];\n% elem = [2,3,1; 4,1,3]; \n% for k = 1:3\n% [node,elem] = uniformrefine(node,elem);\n% end\n% % Homogenous Dirichlet boundary condition\n% pde.f = inline('ones(size(p,1),1)','p');\n% pde.g_D = 0;\n% u = PoissonP2(node,elem,[],pde);\n% figure(1); \n% showresult(node,elem,u);\n%\n% See also Poisson, Poisson3, Poisson3P2 \n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n\n%% Preprocess\nif ~exist('bdFlag','var'), bdFlag = []; end\nif ~exist('option','var'), option = []; end\n\n%% Construct data structure\ntime = cputime; % record assembling time\n[elem2dof,edge,bdDof] = dofP2(elem);\n% important constants\nN = size(node,1); NT = size(elem,1); NE = size(edge,1);\nNdof = N + NE;\nelem2edge = elem2dof(:,4:6) - N;\n\n%% Compute geometric quantities and gradient of local basis\n[Dlambda,area] = gradbasis(node,elem);\n\n%% Assemble stiffness matrix\n% generate sparse pattern\nii = zeros(21*NT,1); \njj = zeros(21*NT,1); \nindex = 0;\nfor i = 1:6\n for j = i:6\n ii(index+1:index+NT) = double(elem2dof(:,i)); \n jj(index+1:index+NT) = double(elem2dof(:,j)); \n index = index + NT;\n end\nend\n% quadrature points\nif ~isfield(pde,'d'), pde.d = []; end\nif ~isfield(option,'quadorder')\n % diffusion is piecewise constant\n option.quadorder = 2; % default order\n if ~isempty(pde.d) && isnumeric(pde.d) % numerical diffusion\n option.quadorder = 3; % exact for linear diffusion coefficient\n end\nend\n[lambda, w] = quadpts(option.quadorder);\nnQuad = size(lambda,1);\n% compute non-zeros\nsA = zeros(21*NT,nQuad);\nfor p = 1:nQuad\n % Dphi at quadrature points\n Dphip(:,:,6) = 4*(lambda(p,1)*Dlambda(:,:,2)+lambda(p,2)*Dlambda(:,:,1));\n Dphip(:,:,1) = (4*lambda(p,1)-1).*Dlambda(:,:,1); \n Dphip(:,:,2) = (4*lambda(p,2)-1).*Dlambda(:,:,2); \n Dphip(:,:,3) = (4*lambda(p,3)-1).*Dlambda(:,:,3); \n Dphip(:,:,4) = 4*(lambda(p,2)*Dlambda(:,:,3)+lambda(p,3)*Dlambda(:,:,2));\n Dphip(:,:,5) = 4*(lambda(p,3)*Dlambda(:,:,1)+lambda(p,1)*Dlambda(:,:,3));\n index = 0;\n for i = 1:6\n for j = i:6\n Aij = 0;\n if isempty(pde.d) || isnumeric(pde.d)\n Aij = Aij + w(p)*dot(Dphip(:,:,i),Dphip(:,:,j),2);\n else\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n Aij = Aij + w(p)*dot(Dphip(:,:,i),Dphip(:,:,j),2).*pde.d(pxy);\n end\n if ~isempty(pde.d) && isnumeric(pde.d) % d is piecewise constant\n Aij = pde.d.*Aij;\n end\n Aij = Aij.*area;\n sA(index+1:index+NT,p) = Aij;\n index = index + NT;\n end\n end\nend\nsA = sum(sA,2);\n% assemble the matrix\ndiagIdx = (ii == jj); \nupperIdx = ~diagIdx;\nA = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Ndof,Ndof);\nAU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Ndof,Ndof);\nA = A + AU + AU';\nclear Aij ii jj sA\n\n%% Assemble right hand side by high order quadrature rule\nb = zeros(Ndof,1);\nif ~isfield(option,'fquadorder')\n option.fquadorder = 4; % default order\nend\nif ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n pde.f = [];\nend\nif ~isempty(pde.f) \n % quadrature points in the barycentric coordinate\n [lambda,w] = quadpts(option.fquadorder);\n nQuad = size(lambda,1);\n phi(:,6) = 4*lambda(:,1).*lambda(:,2);\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 phi(:,4) = 4*lambda(:,2).*lambda(:,3);\n phi(:,5) = 4*lambda(:,3).*lambda(:,1);\n bt = zeros(NT,6);\n for p = 1:nQuad\n % quadrature points in the x-y coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ...\n + lambda(p,3)*node(elem(:,3),:);\n if isfield(pde,'f') && isnumeric(pde.f)\n fp = pde.f; % piecewise constant \n else\n fp = pde.f(pxy); % function handle\n end\n for j = 1:6\n bt(:,j) = bt(:,j) + w(p)*phi(p,j)*fp;\n end\n end\n bt = bt.*repmat(area,1,6);\n b = accumarray(elem2dof(:),bt(:),[Ndof 1]); \nend\n\n%% Boundary Conditions\n[AD,b,u,freeDof,isPureNeumann] = getbdP2(b);\n\n%% Record assembeling time\nassembleTime = cputime - time;\nif ~isfield(option,'printlevel'), option.printlevel = 1; end\nif option.printlevel >= 2\n fprintf('Time to assemble matrix equation %4.2g s\\n',assembleTime);\nend\n\n%% Solve the system of linear equations\nif isempty(freeDof), return; end\n% Set up solver\nif isempty(option) || ~isfield(option,'solver') % no option.solver\n if Ndof <= 2e3 % Direct solver for small size systems\n option.solver = 'direct';\n else % Multigrid-type solver for large size systems\n option.solver = 'mg';\n end\nend\nsolver = option.solver;\n% solve\nswitch solver\n case 'direct'\n tic;\n u(freeDof) = AD(freeDof,freeDof)\\b(freeDof);\n residual = norm(b - AD*u);\n info = struct('solverTime',toc,'itStep',0,'err',residual,'flag',2,'stopErr',residual);\n case 'none'\n info = struct('solverTime',[],'itStep',0,'err',[],'flag',3,'stopErr',[]);\n case 'mg'\n option.x0 = u;\n option.solver = 'CG';\n option.tol = 1e-9;\n [u,info] = mg(AD,b,elem,option,edge);\n case 'amg'\n option.solver = 'CG';\n option.tol = 1e-9;\n [u(freeDof),info] = amg(AD(freeDof,freeDof),b(freeDof),option); \nend\n% post-process for pure Neumann problem\nif isPureNeumann\n patchArea = accumarray(elem2edge(:),[area;area;area]/3, [NE 1]); \n uc = sum(u(N+1:end).*patchArea)/sum(area);\n u = u - uc; % normalization for pure Neumann problem \n% Here we use 3 middle points rule to compute the integral which is exact\n% for quadratic elements. We can also use the following formulae \n% intuh = sum(1/3*u(elem2dof(:,4:6)),2).*area; %Compute the integrable of uh\n% uc = sum(intuh)/sum(area);\n% u = u -uc;\nend\n\n%% Compute Du\nDu = [];\n\n%% Output\nif nargout == 1\n soln = u;\nelse\n soln = struct('u',u,'Du',Du);\n eqn = struct('A',AD,'b',b,'edge',edge,'freeDof',freeDof,'Lap',A);\n info.assembleTime = assembleTime;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbdP2\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function [AD,b,u,freeDof,isPureNeumann] = getbdP2(b)\n %% Boundary conditions for Poisson equation: P2 quadratic FEM.\n %\n % The set up of boundary condition consists of two parts: \n %\n % 1) Modify the matrix for Dirichlet boundary nodes, which are not degree\n % of freedom. Values at these nodes are evaluatation of pde.g_D. The\n % original stiffness matrix A is turn into the matrix AD by enforcing\n % AD(fixedDof,fixedDof)=I, AD(fixedDof,freeDof)=0, AD(freeDof,fixedDof)=0.\n %\n % 2) Modify the right hand side b. The Neumann boundary integral is added\n % to b. For Dirichlet boundary ndoes, b(fixedDof) is the evaluation of\n % pde.g_D.\n %\n % Special attentation should be given for the pure Neumann boundary\n % condition. To enforce the compatible condition, the vector b should have\n % mean value zero. To avoid a singular matrix, the 1st node is chosen as\n % fixedDof. \n %\n % The order of assigning Neumann and Dirichlet boundary condition is\n % important to get the right setting at the intersection nodes of Dirichlet\n % and Neumann boundary edges.\n\n u = zeros(Ndof,1);\n %% Set up boundary and basic parameter\n if ~isfield(pde,'g_D'), pde.g_D = []; end\n if ~isfield(pde,'g_N'), pde.g_N = []; end\n if ~isfield(pde,'g_R'), pde.g_R = []; end\n\n %% Part 1: Modify the matrix for Dirichlet and Robin condition\n % Robin boundary condition\n Robin = [];\n idxR = (bdFlag(:) == 3); % index of Robin edges in bdFlag\n if any(idxR) \n isRobin = false(NE,1);\n isRobin(elem2edge(idxR)) = true;\n Robin = edge(isRobin,:); % Robin edges \n end\n if ~isempty(Robin) && ~isempty(pde.g_R) && ~(isnumeric(pde.g_R) && (pde.g_R == 0))\n if ~isfield(option,'gRquadorder')\n option.gRquadorder = 5; % default order exact for linear gR\n end\n [lambdagR,weightgR] = quadpts1(option.gRquadorder);\n nQuadgR = size(lambdagR,1);\n % quadratic bases (1---3---2)\n bdphi = zeros(nQuadgR,3);\n bdphi(:,1) = (2*lambdagR(:,1)-1).*lambdagR(:,1);\n bdphi(:,2) = (2*lambdagR(:,2)-1).*lambdagR(:,2);\n bdphi(:,3) = 4*lambdagR(:,1).*lambdagR(:,2);\n % length of edge\n el = sqrt(sum((node(Robin(:,1),:) - node(Robin(:,2),:)).^2,2));\n NR = size(Robin,1);\n ss = zeros(NR,3,3);\n for pp = 1:nQuadgR\n ppxy = lambdagR(pp,1)*node(Robin(:,1),:) ...\n + lambdagR(pp,2)*node(Robin(:,2),:);\n gRp = pde.g_R(ppxy);\n for iR = 1:3\n for jR = iR:3 % only compute half of the off-diagonal part\n ss(:,iR,jR) = ss(:,iR,jR) + ...\n weightgR(pp)*gRp*bdphi(pp,iR).*bdphi(pp,jR);\n end\n end\n end\n ss(:) = ss(:).*repmat(el,9,1);\n index = 0;\n Robin(:,3) = find(isRobin)+N; % the third one maps to corresponding dof\n for iR = 1:3\n for jR = 1:3\n iiR(index+1:index+NR) = double(Robin(:,iR)); \n jjR(index+1:index+NR) = double(Robin(:,jR)); \n if jR>=iR\n ssR(index+1:index+NR) = ss(:,iR,jR);\n else\n ssR(index+1:index+NR) = ss(:,jR,iR);\n end\n index = index + NR;\n end\n end\n A = A + sparse(iiR,jjR,ssR,Ndof,Ndof);\n end\n\n % Find Dirichlet boundary dof: fixedDof\n fixedDof = []; \n freeDof = [];\n isFixedDof = false(Ndof,1); \n if ~isempty(bdFlag) \n isDirichlet(elem2edge(bdFlag(:)==1)) = true;\n isFixedDof(edge(isDirichlet,:)) = true;\n isFixedDof(N + find(isDirichlet')) = true;\n fixedDof = find(isFixedDof);\n freeDof = find(~isFixedDof); \n end\n if isempty(bdFlag) && ~isempty(pde.g_D) && isempty(pde.g_N) && isempty(pde.g_R)\n fixedDof = bdDof;\n isFixedDof(fixedDof) = true;\n freeDof = find(~isFixedDof); \n end\n isPureNeumann = false; \n if isempty(fixedDof) && isempty(Robin) % pure Neumann boundary condition\n % pde.g_N could be empty which is homogenous Neumann boundary condition\n isPureNeumann = true;\n fixedDof = 1;\n freeDof = 2:Ndof; % eliminate the kernel by enforcing u(1) = 0;\n end\n % Modify the matrix\n % Build Dirichlet boundary condition into the matrix AD by enforcing\n % |AD(fixedDof,fixedDof)=I, AD(fixedDof,freeDof)=0,\n % AD(freeDof,fixedDof)=0|.\n if ~isempty(fixedDof)\n bdidx = zeros(Ndof,1); \n bdidx(fixedDof) = 1;\n Tbd = spdiags(bdidx,0,Ndof,Ndof);\n T = spdiags(1-bdidx,0,Ndof,Ndof);\n AD = T*A*T + Tbd;\n else\n AD = A;\n end\n\n %% Part 2: Find boundary edges and modify the load b\n % Find boundary edges: Neumann and Robin\n Neumann = [];\n if ~isempty(bdFlag) \n idxN = (bdFlag(:) == 2); % all Neumann edges in bdFlag \n Neumannidx = elem2edge(idxN | idxR); % index of Neumann and Robin edges\n % since boundary integral is also needed for Robin edges\n Neumann = edge(Neumannidx,:);\n end\n if isempty(bdFlag) && (~isempty(pde.g_N) || ~isempty(pde.g_R))\n % no bdFlag, only pde.g_N or pde.g_R is given in the input\n Neumannidx = find(bdDof>N);\n Neumann = edge(Neumannidx,:);\n end\n\n % Neumann boundary condition\n if ~isempty(pde.g_N) && ~isempty(Neumann) && ~(isnumeric(pde.g_N) && (pde.g_N == 0))\n if ~isfield(option,'gNquadorder')\n option.gNquadorder = 4; % default order\n end\n [lambdagN,weightgN] = quadpts1(option.gNquadorder);\n nQuadgN = size(lambdagN,1);\n % quadratic bases on an edge (1---3---2)\n bdphi = zeros(nQuadgN,3); \n bdphi(:,1) = (2*lambdagN(:,1)-1).*lambdagN(:,1);\n bdphi(:,2) = (2*lambdagN(:,2)-1).*lambdagN(:,2);\n bdphi(:,3) = 4*lambdagN(:,1).*lambdagN(:,2);\n % length of edge\n el = sqrt(sum((node(Neumann(:,1),:) - node(Neumann(:,2),:)).^2,2));\n ge = zeros(size(Neumann,1),3);\n for pp = 1:nQuadgN\n ppxy = lambdagN(pp,1)*node(Neumann(:,1),:) ...\n + lambdagN(pp,2)*node(Neumann(:,2),:);\n gNp = pde.g_N(ppxy);\n ge(:,1) = ge(:,1) + weightgN(pp)*gNp*bdphi(pp,1);\n ge(:,2) = ge(:,2) + weightgN(pp)*gNp*bdphi(pp,2);\n ge(:,3) = ge(:,3) + weightgN(pp)*gNp*bdphi(pp,3); % interior bubble\n end\n % update RHS\n ge = ge.*repmat(el,1,3); \n b(1:N) = b(1:N) + accumarray(Neumann(:), [ge(:,1); ge(:,2)],[N,1]);\n b(N+Neumannidx) = b(N+Neumannidx) + ge(:,3);\n end\n\n % Dirichlet boundary conditions\n if ~isPureNeumann && ~isempty(fixedDof) && ...\n ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && (pde.g_D == 0))\n idx = (fixedDof > N); % index of edge nodes\n u(fixedDof(~idx)) = pde.g_D(node(fixedDof(~idx),:)); % bd value at vertex dofs\n bdEdgeIdx = fixedDof(idx) - N;\n bdEdgeMid = (node(edge(bdEdgeIdx,1),:) + node(edge(bdEdgeIdx,2),:))/2;\n u(fixedDof(idx)) = pde.g_D(bdEdgeMid);\n b = b - A*u;\n end\n if ~isPureNeumann % non-empty Dirichlet boundary condition\n b(fixedDof) = u(fixedDof);\n end\n\n % Pure Neumann boundary condition\n if isPureNeumann\n b = b - mean(b); % compatilbe condition: sum(b) = 0\n b(1) = 0; \n end\n end % end of getbdP2\nend % end of function PoissonP2", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/PoissonP2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7148380087823955}} {"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\nD1 = WignerD(g,'order',1);\nD2 = WignerD(g,'order',2);\nD1D2_ref = D1(:) * D2(:).'\n\n%% expansion into Wigner functions of lower order\n\n% zero order component\nD0 = WignerD(g,'order',0);\nCG0 = ClebschGordanTensor(1,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(1,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(1,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(1,2,3);\nC3 = EinsteinSum(CG3,[1 3 -1],D3,[-1 -2],CG3,[2 4 -2])\n\n\na = reshape(matrix(C0 + C1 + C2 + C3),[9,25]) ./ D1D2_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_ClebschCordan3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.7148380036466291}} {"text": "%Kalman Demo 1 (Sinc Regression)\n%\n% The benefit from the state space formulation is that the \n% computational complexity is linear with respect to the number\n% of data points. Due to efficient matrix solvers in Matlab \n% (favoring the traditional GP solution over sequential looping),\n% the advantages in speed start to show in datasets with thousands\n% of data points.\n%\n% The take-home message from this demo is that the GP can be\n% set up exactly as any other GP regression model in GPstuff, \n% and then solved by Kalman filtering methods by specifying the\n% 'type' in the GP structure to be 'KALMAN'.\n%\n% The implementation that is used below is primarily based on the\n% methods presented in the following publications:\n%\n% [1] Simo Sarkka, Arno Solin, Jouni Hartikainen (2013).\n% Spatiotemporal learning via infinite-dimensional Bayesian\n% filtering and smoothing. IEEE Signal Processing Magazine,\n% 30(4):51-61.\n%\n% [2] Jouni Hartikainen and Simo Sarkka (2010). Kalman filtering and \n% smoothing solutions to temporal Gaussian process regression \n% models. Proceedings of IEEE International Workshop on Machine \n% Learning for Signal Processing (MLSP).\n%\n% [3] Simo Sarkka (2013). Bayesian filtering and smoothing. Cambridge \n% University Press.\n%\n% Copyright (c) 2014 Arno Solin and Jukka Koskenranta\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%% Generate data\n \n % Discretize x (measurement points)\n x = 10*rand(32,1)-5;\n \n % Test points (evaluation points)\n xt = linspace(-5,5,128)';\n \n % Measurement noise variance\n sigma2 = .01;\n \n % Simulate data\n y = sinc(x) + sqrt(sigma2)*randn(size(x));\n \n \n%% Do the inference\n\n % Noise variance prior\n ps2 = prior_logunif(); \n\n % The likelihood model\n lik = lik_gaussian('sigma2', 1, 'sigma2_prior', ps2);\n \n % Covariance function hyperparameter priors\n pl = prior_logunif(); \n pm = prior_logunif();\n \n % The GP covariance function\n gpcf = gpcf_matern52('lengthScale', 1, ...\n 'magnSigma2', 1, ...\n 'lengthScale_prior', pl, ...\n 'magnSigma2_prior', pm);\n \n % Define Gaussian process model using type 'KALMAN'\n gp = gp_set('lik', lik, 'cf', gpcf, 'type', 'KALMAN');\n\n % Hyperparameter optimization (full model)\n gp_full = gp_optim(gp_set(gp,'type','FULL'), x, y);\n \n % Hyperparameter optimization (state space model)\n gp = gp_optim(gp, x, y);\n \n % Predict values at test inputs xt\n [Eft,Varft] = gp_pred(gp, x, y, 'xt', xt);\n \n \n%% Compare against full GP solution (table)\n\n % Show table with comparison to full GP results\n fprintf('\\n%12s | %8s | %8s \\n', ...\n 'Parameter','FULL', 'KALMAN')\n \n fprintf('-----------------------------------\\n')\n \n fprintf('%12s | %8.4f | %8.4f \\n', ...\n 'magnSigma2',gp_full.cf{1}.magnSigma2,gp.cf{1}.magnSigma2)\n fprintf('%12s | %8.4f | %8.4f \\n', ...\n 'lengthScale',gp_full.cf{1}.lengthScale,gp.cf{1}.lengthScale)\n fprintf('%12s | %8.4f | %8.4f \\n', ...\n 'sigma2',gp_full.lik.sigma2,gp.lik.sigma2)\n \n \n%% Show result\n\n % Plot the state space prediction\n figure(1); clf; hold on\n \n % Draw 95% uncertainty interval\n color=0.85*[1,1,1];\n p=patch([xt; flipud(xt)], ...\n [Eft+1.96*sqrt(Varft); flipud(Eft-1.96*sqrt(Varft))],color);\n set(p,'EdgeColor','none')\n \n % Show data and predicted mean\n h=plot(xt,sinc(xt),'-r', ...\n x,y,'+k', ...\n xt,Eft,'--','LineWidth', 1, 'MarkerSize',5);\n \n % Legend and labels \n xlabel('Input, x');\n ylabel('Output, y');\n title('Kalman Demo 1 (Sinc Regression)');\n legend([h;p], 'Sinc function', ...\n 'Noisy measurements', ...\n 'Estimated mean', ...\n '95% confidence region');\n \n % Bring axes to front\n box on; set(gca,'Layer','top')\n \n \n%% Compare the full posteriors\n\n % Return the posterior mean EFT and covariance COVFT of latent \n % variables:\n % Eft = E[f | xt,x,y,th] = K_fy*(Kyy+s^2I)^(-1)*y\n % Covft = Var[f | xt,x,y,th] = K_fy - K_fy*(Kyy+s^2I)^(-1)*K_yf.\n\n figure(2); clf\n \n % The full GP\n subplot(121)\n \n % Calculate\n [Eft,Covft] = gp_jpred(gp_full,x,y,xt); \n \n % Plot\n imagesc(Covft)\n axis equal tight\n\n % Title\n title('The full GP posterior covariance')\n \n % The state space model ('KALMAN')\n subplot(122)\n \n % Calculate\n [Eft,Covft] = gp_jpred(gp,x,y,xt); \n \n % Plot\n imagesc(Covft)\n axis equal tight\n \n % Title\n title('The state space GP posterior covariance')\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_kalman1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.714799255932519}} {"text": "function [XN,IOTA,EPS,U]=quasi_idempotence(X,K)\n%QUASI_IDEMPOTENCE Connection matrix quasi-idempotence\n%\n% [XN,IOTA,EPS,U]=quasi_idempotence(X)\n% [XN,IOTA,EPS,U]=quasi_idempotence(X,K)\n%\n% The degree of quasi-idempotence of a matrix represents how close it \n% is to being idempotent, i.e. invariant to squaring. In turn, this \n% reflects how closely related the edges in the graph it corresponds to \n% are to the sums of all triangles between the corresponding nodes, \n% spanning the entirety of the network. This probes a form of \n% self-similarity, intended not as between nodes and modules, but \n% between as edges and triangles (or more generally paths).\n% Networks wherein the edge strengths are weakly related to the \n% nodal strengths have low quasi-idempotence, and networks wherein the \n% edge strengths are significantly influenced by the strengths of the\n% corresponding nodes have high quasi-idempotence. In other words the\n% degree of quasi-idempotence may be viewed as a measure of\n% \"collectivity\", meaning how strongly individual nodes participate\n% in collective dynamics.\n% \n% Inputs:\n% X,\n% undirected weighted/binary connection matrix with \n% non-negative weights,\n% K,\n% number of iterations (optional),\n% K0)=0; % null the diagonal in the initial matrix\nX=X/norm(X); % normalize to unit norm\nXN=X;\nmask=triu(ones(N),1)>0; % create mask for superdiagonal elements\nU=0; % initialize iterations counter\nIOTA=[]; % this vector will contain the correlation coefficients\nEPS=inf; % and this will contain the errors\nif isinf(K)\n while EPS(end)>eps('double') % iterate until error below precision\n U=U+1; % increase iteration counter\n XN_hat=XN; % save the initial matrix\n XN=XN^2; % square the matrix\n XN=XN/norm(XN); % normalize it again (for numerical reasons)\n IOTA(end+1)=corr(X(mask),XN(mask)); % calculate correlation coefficient\n EPS(end+1)=norm(XN_hat-XN); % calculate error\n end\nelse\n while U 1E6 alphaX = 1E-6; else alphaX = 0; end\n X = max(1E6*eps,pinv(A'*A + alpha_reg + alphaX*I)*A'*Y); %Updating of X \n \n % Estimation of A \n hA = X*X';\n hA = hA + (lambda + 1E8*exp(-k))*eye(R); % Levenberg-Marquardt regularization\n GA = X*Y' - hA*A'; % Gradient\n HA = kron(speye(M),-hA); % Hessian\n \ncond_HA = condest(HA);\nif cond_HA > 1E17\nfprintf(1,'Hessian is singular in %d iteration(s). Restart is needed.\\n',k) \nbreak; end\nA = A'; A(:) = A(:) - .9*inv(HA)*GA(:); % Newton iterations\nA(A <= 0) = 1E2*eps; A = A';\nA = A*diag(1./sum(A,1)); % Normalization to unit L1-column norm\nend\nA = repmat(1./mx,[1,size(A,2),1]).*A; % De-scaling \n \n \n \n", "meta": {"author": "aludnam", "repo": "MATLAB", "sha": "020b5cb02cc843e09a0ed689589382f18cce5e6d", "save_path": "github-repos/MATLAB/aludnam-MATLAB", "path": "github-repos/MATLAB/aludnam-MATLAB/MATLAB-020b5cb02cc843e09a0ed689589382f18cce5e6d/NMFLABSP_ver1.2/user_alg1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7147605692996808}} {"text": "function r8poly_values_horner_test ( )\n\n%*****************************************************************************80\n%\n%% R8POLY_VALUES_HORNER_TEST tests R8POLY_VALUES_HORNER.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 December 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8POLY_VALUES_HORNER_TEST\\n' );\n fprintf ( 1, ' R8POLY_VALUES_HORNER evaluates a polynomial at a\\n' );\n fprintf ( 1, ' point, using Horner''s method.\\n' );\n\n m = 4;\n c = [ 24.0, -50.0, +35.0, -10.0, 1.0 ];\n r8poly_print ( m, c, ' The polynomial:' );\n\n n = 16;\n x_lo = 0.0;\n x_hi = 5.0;\n x = r8vec_linspace ( n, x_lo, x_hi );\n\n p = r8poly_values_horner ( m, c, n, x );\n\n r8vec2_print ( n, x, p, ' X, P(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/r8lib/r8poly_values_horner_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.8872045862611166, "lm_q1q2_score": 0.7147605646230907}} {"text": "function [intersects, edgeIndices] = intersectLinePolyline(line, poly, varargin)\n%INTERSECTLINEPOLYLINE Intersection points between a line and a polyline\n%\n% P = intersectLinePolyline(LINE, POLY)\n% Returns the intersection points of the lines LINE with polyline POLY. \n% LINE is a 1-by-4 row vector containing parametric representation of the\n% line (in the format [x0 y0 dx dy], see the function 'createLine' for\n% details). \n% POLY is a NV-by-2 array containing coordinates of the polyline vertices\n% P is a K-by-2 array containing the coordinates of the K intersection\n% points.\n%\n% P = intersectLinePolyline(LINE, POLY, TOL)\n% Specifies the tolerance for geometric tests. Default is 1e-14.\n%\n% [P INDS] = intersectLinePolyline(...)\n% Also returns the indices of edges involved in intersections. INDS is a\n% K-by-1 column vector, such that P(i,:) corresponds to intersection of\n% the line with the i-th edge of the polyline. If the intersection occurs\n% at a polyline vertex, the index of only one of the two neighbor edges\n% is returned. \n% Note that due to numerical approximations, the use of function\n% 'isPointOnEdge' may give results not consistent with this function.\n%\n%\n% Examples\n% % compute intersections between a square and an horizontal line\n% poly = [0 0;10 0;10 10;0 10];\n% line = [5 5 1 0];\n% intersectLinePolyline(line, poly)\n% ans =\n% 10 5\n% % also return indices of edges\n% [inters inds] = intersectLinePolyline(line, poly)\n% inters =\n% 10 5\n% inds =\n% 2\n% \n% % compute intersections between a square and a diagonal line\n% poly = [0 0;10 0;10 10;0 10];\n% line = [5 5 1 1];\n% intersectLinePolyline(line, poly)\n% ans =\n% 0 0\n% 10 10\n%\n% See Also\n% lines2d, polylines2d, intersectLines, intersectLinePolygon\n%\n\n% ---------\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 31/10/2003.\n%\n\n% HISTORY\n% 2008-11-24 rename 'pi' as 'intersects', update doc\n% 2009-07-23 removed forgotten occurence of 'pi' variable (thanks to Bala\n% Krishnamoorthy)\n% 2010-01-26 rewrite using vectorisation\n% 2011-05-20 returns unique results\n% 2011-07-20 returns intersected edge indices\n% 2012-11-33 add 'diag' option for linePosition\n\n% get computation tolerance\ntol = 1e-14;\nif ~isempty(varargin)\n tol = varargin{1};\nend\n\n% create the array of edges\nN = size(poly, 1);\nedges = [poly(1:N-1, :) poly(2:N, :)];\n\n% compute intersections with supporting lines of polyline edges\nsupportLines = edgeToLine(edges);\nintersects = intersectLines(line, supportLines, tol);\n\n% find edges that are not parallel to the input line\ninds = find(isfinite(intersects(:, 1)));\n\n% compute position of intersection points on corresponding lines\npos = linePosition(intersects(inds, :), supportLines(inds, :), 'diag');\n\n% and keep only intersection points located on edges\nb = pos > -tol & pos < 1+tol;\ninds = inds(b);\nintersects = intersects(inds, :);\n\n% remove multiple vertices (can occur for intersections located at polyline\n% vertices)\n[intersects, I, J] = unique(intersects, 'rows'); %#ok\n\nif nargout > 1\n % return indices of edges involved in intersection\n % (in case of intersection located at a vertex, only one of the\n % neighbor edges is returned)\n edgeIndices = inds(I);\nend\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/polygons2d/intersectLinePolyline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7146296792083676}} {"text": "function d = ipdm(data1,varargin)\n% ipdm: Inter-Point Distance Matrix\n% usage: d = ipdm(data1)\n% usage: d = ipdm(data1,data2)\n% usage: d = ipdm(data1,prop,value)\n% usage: d = ipdm(data1,data2,prop,value)\n%\n% Arguments: (input)\n% data1 - array of data points, each point is one row. p dimensional\n% data will be represented by matrix with p columns.\n% If only data1 is provided, then the distance matrix\n% is computed between all pairs of rows of data1.\n%\n% If your data is one dimensional, it MUST form a column\n% vector. A row vector of length n will be interpreted as\n% an n-dimensional data set.\n%\n% data2 - second array, supplied only if distances are to be computed\n% between two sets of points.\n%\n%\n% Class support: data1 and data2 are assumed to be either\n% single or double precision. I have not tested this code to\n% verify its success on integer data of any class.\n%\n%\n% Additional parameters are expected to be property/value pairs.\n% Property/value pairs are pairs of arguments, the first of which\n% (properties) must always be a character string. These strings\n% may be shortened as long as the shortening is unambiguous.\n% Capitalization is ignored. Valid properties for ipdm are:\n%\n% 'Metric', 'Subset', 'Limit', 'Result'\n%\n% 'Metric' - numeric flag - defines the distance metric used\n% metric = 2 --> (DEFAULT) Euclidean distance = 2-norm\n% The standard distance metric.\n%\n% metric = 1 --> 1-norm = sum of absolute differences\n% Also sometimes known as the \"city block\n% metric\", since this is the sum of the\n% differences in each dimension.\n%\n% metric = inf --> infinity-norm = maximum difference\n% over all dimensions. The name refers\n% to the limit of the p-norm, as p\n% approaches infinity.\n%\n% metric = 0 --> minimum difference over all dimensions.\n% This is not really a useful norm in\n% practice.\n%\n% Note: while other distance metrics exist, IMHO, these\n% seemed to be the common ones.\n%\n%\n% 'Result' - A string variable that denotes the style of returned\n% result. Valid result types are 'Array', 'Structure'.\n% Capitalization is ignored, and the string may be\n% shortened if you wish.\n%\n% result = 'Array' --> (DEFAULT) A matrix of all\n% interpoint distances will be generated.\n% This array may be large. If this option\n% is specified along with a minimum or\n% maximum value, then those elements above\n% or below the limiting values will be\n% set as -inf or +inf, as appropriate.\n%\n% When any of 'LargestFew', 'SmallestFew',\n% or 'NearestNeighbor' are set, then the\n% resulting array will be a sparse matrix\n% if 'array' is specified as the result.\n%\n% result = 'Structure' --> A list of all computed distances,\n% defined as a structure. This structure\n% will have fields named 'rowindex',\n% 'columnindex', and 'distance'.\n%\n% This option will be useful when a subset\n% criterion for the distances has been\n% specified, since then the distance matrix\n% may be very sparsely populated. Distances\n% for pairs outside of the criterion will\n% not be returned.\n%\n%\n% 'Subset' - Character string, any of:\n%\n% 'All', 'Maximum', 'Minimum', 'LargestFew', 'SmallestFew',\n% 'NearestNeighbor', 'FarthestNeighbor', or empty\n%\n% Like properties, capitalization is ignored here, and\n% any unambiguous shortening of the word is acceptable.\n%\n% DEFAULT = 'All'\n%\n% Some interpoint distance matrices can be huge. Often\n% these matrices are too large to be fully retained in\n% memory, yet only the pair of points with the largest\n% or smallest distance may be needed. When only some\n% subset of the complete set of distances is of interest,\n% these options allow you to specify which distances will\n% be returned.\n%\n% If 'result' is defined to be an array, then a sparse\n% matrix will be returned for the 'LargestFew', 'SmallestFew',\n% 'NearestNeighbor', and 'FarthestNeighbor' subset classes.\n% 'Minimum' and 'Maximum' will yield full matrices by\n% default. If a structure is specified, then only those\n% elements which have been identified will be returned.\n%\n% Where a subset is specified, its limiting value is\n% specified by the 'Limit' property. Call that value k.\n%\n%\n% 'All' --> (DEFAULT) Return all interpoint distances\n%\n% 'Minimum' --> Only look for those distances above\n% the cutoff k. All other distances will\n% be returned as -inf.\n%\n% 'Maximum' --> Only look for those distances below\n% the cutoff k. All other distances will\n% be returned as +inf.\n%\n% 'SmallestFew' --> Only return the subset of the k\n% smallest distances. Where only one data\n% set is provided, only the upper triangle\n% of the inter-point distance matrix will\n% be generated since that matrix is symmetric.\n%\n% 'LargestFew' --> Only return the subset of the k\n% largest distances. Where only one data\n% set is provided, only the upper triangle\n% of the inter-point distance matrix will\n% be generated since that matrix is symmetric.\n%\n% 'NearestNeighbor' --> Only return the single nearest\n% neighbor in data2 to each point in data1.\n% No limiting value is required for this\n% option. If multiple points have the same\n% nearest distance, then return the first\n% such point found. With only one input set,\n% a point will not be its own nearest\n% neighbor.\n%\n% Note that exact replicates in a single set\n% will cause problems, since a sparse matrix\n% is returned by default. Since they will have\n% a zero distance, they will not show up in\n% the sparse matrix. A structure return will\n% show those points as having a zero distance\n% though.\n%\n% 'FarthestNeighbor' --> Only return the single farthest\n% neighbor to each point. No limiting value\n% is required for this option. If multiple\n% points have the same farthest distance,\n% then return the first such point found.\n%\n%\n% 'Limit' - scalar numeric value or []. Used only when some\n% Subset is specified.\n%\n% DEFAULT = []\n%\n%\n% 'ChunkSize' - allows a user with lower RAM limits\n% to force the code to only grab smaller chunks of RAM\n% at a time (where possible). This parameter is specified\n% in bytes of RAM. The default is 32 megabytes, or 2^22\n% elements in any piece of the distance matrix. Only some\n% options will break the problem into chunks, thus as long\n% as a full matrix is expected to be returned, there seems\n% no reason to break the problem up into pieces.\n%\n% DEFAULT = 2^25\n%\n%\n% Arguments: (output)\n% d - array of interpoint distances, or a struct wth the\n% fields {'rowindex', 'columnindex', 'distance'}.\n%\n% d(i,j) represents the distance between point i\n% (from data1) and point j (from data2).\n%\n% If only one (n1 x p) array is supplied, then d will\n% be an array of size == [n1,n1].\n%\n% If two arrays (of sizes n1 x p and n2 x p) then d\n% will be an array of size == [n1,n2].\n%\n%\n% Efficiency considerations:\n% Where possible, this code will use bsxfun to compute its\n% distances.\n%\n%\n% Example:\n% Compute the interpoint distances between all pairs of points\n% in a list of 5 points, in 2 dimensions and using Euclidean\n% distance as the distance metric.\n%\n% A = randn(5,2);\n% d = ipdm(A,'metric',2)\n% d =\n% 0 2.3295 3.2263 2.0263 2.8244\n% 2.3295 0 1.1485 0.31798 1.0086\n% 3.2263 1.1485 0 1.4318 1.8479\n% 2.0263 0.31798 1.4318 0 1.0716\n% 2.8244 1.0086 1.8479 1.0716 0\n%\n% (see the demo file for many other examples)\n%\n% See also: pdist\n%\n% Author: John D'Errico\n% e-mail: woodchips@rochester.rr.com\n% Release: 1.0\n% Release date: 2/26/08\n\n% Default property values\nparams.Metric = 2;\nparams.Result = 'array';\nparams.Subset = 'all';\nparams.Limit = [];\nparams.ChunkSize = 2^25;\n\n% untangle the arguments\nif nargin<1\n % if called with no arguments, then the user probably\n % needs help. Give it to them.\n help ipdm\n return\nend\n\n% were two sets of data provided?\npvpairs = {};\nif nargin==1\n % only 1 set of data provided\n dataflag = 1;\n data2 = [];\nelse\n if ischar(varargin{1})\n dataflag = 1;\n data2 = [];\n pvpairs = varargin;\n else\n dataflag = 2;\n data2 = varargin{1};\n if nargin>2\n pvpairs = varargin(2:end);\n end\n end\nend\n\n% get data sizes for later\n[n1,dim] = size(data1);\nif dataflag == 2\n n2 = size(data2,1);\nend\n\n% Test the class of the input variables\nif ~(isa(data1,'double') || isa(data1,'single')) || ...\n ((dataflag == 2) && ~(isa(data2,'double') || isa(data2,'single')))\n error('data points must be either single or double precision variables.')\nend\n\n% do we need to process any property/value pairs?\nif nargin>2\n params = parse_pv_pairs(params,pvpairs);\n \n % check for problems in the properties\n \n % was a legal Subset provided?\n if ~isempty(params.Subset) && ~ischar(params.Subset)\n error('If provided, ''Subset'' must be character')\n elseif isempty(params.Subset)\n params.Subset = 'all';\n end\n valid = {'all','maximum','minimum','largestfew','smallestfew', ...\n 'nearestneighbor','farthestneighbor'};\n ind = find(strncmpi(params.Subset,valid,length(params.Subset)));\n if (length(ind)==1)\n params.Subset = valid{ind};\n else\n error(['Invalid Subset: ',params.Subset])\n end\n \n % was a limit provided?\n if ~ismember(params.Subset,{'all','nearestneighbor','farthestneighbor'}) && ...\n isempty(params.Limit)\n error('No limit provided, but a Subset that requires a limit value was specified')\n end\n % check the limit values for validity\n if length(params.Limit)>1\n error('Limit must be scalar or empty')\n end\n \n switch params.Subset\n case {'largestfew', 'smallestfew'}\n % must be at least 1, and an integer\n if (params.Limit<1) || (round(params.Limit)~=params.Limit)\n error('Limit must be a positive integer for LargestFew or NearestFew')\n end\n end\n \n % was a legal Result provided?\n if isempty(params.Result)\n params.result = 'Array';\n elseif ~ischar(params.Result)\n error('If provided, ''Result'' must be character or empty')\n end\n valid = {'array','structure'};\n ind = find(strncmpi(params.Result,valid,length(params.Result)));\n if (length(ind)==1)\n params.Result = valid{ind};\n else\n error(['Invalid Result: ',params.Subset])\n end\n\n % check for the metric\n if isempty(params.Metric)\n params.Metric = 2;\n elseif (length(params.Metric)~=1) || ~ismember(params.Metric,[0 1 2 inf])\n error('If supplied, ''Metric'' must be a scalar, and one of [0 1 2 inf]')\n end\nend % if nargin>2\n \n% If Metric was given as 2, but the dimension is only 1, then it will\n% be slightly faster (and equivalent) to use the 1-norm Metric.\nif (dim == 1) && (params.Metric == 2)\n params.Metric = 1;\nend\n\n% Can we use bsxfun to compute the interpoint distances?\n% Older Matlab releases will not have bsxfun, but if it is\n% around, it will ne both faster and less of a memory hog.\nparams.usebsxfun = (5==exist('bsxfun','builtin'));\n\n% check for dimension mismatch if 2 sets\nif (dataflag==2) && (size(data2,2)~=dim)\n error('If 2 point sets provided, then both must have the same number of columns')\nend\n\n% Total number of distances to compute, in case I must do it in batches\nif dataflag==1\n n2 = n1;\nend\nntotal = n1*n2;\n\n% FINALLY!!! Compute inter-point distances\nswitch params.Subset\n case 'all'\n % The complete set of interpoint distances. There is no need\n % to break this into chunks, since we must return all distances.\n % If that is too much to compute in memory, then it will fail\n % anyway when we try to store the result. bsxfun will at least\n % do the computation efficiently.\n \n % One set or two?\n if dataflag == 1\n d = distcomp(data1,data1,params);\n else\n d = distcomp(data1,data2,params);\n end\n \n % Must we return it as a struct?\n if params.Result(1) == 's'\n [rind,cind] = ndgrid(1:size(d,1),1:size(d,2));\n ds.rowindex = rind(:);\n ds.columnindex = cind(:);\n ds.distance = d(:);\n d = ds;\n end\n \n case {'minimum' 'maximum'}\n % There is no reason to break this into pieces if the result\n % sill be filled in the end with +/- inf. Only break it up\n % if the final result is a struct.\n if ((ntotal*8)<=params.ChunkSize) || (params.Result(1) == 'a')\n % its small enough to do it all at once\n \n % One set or two?\n if dataflag == 1\n d = distcomp(data1,data1,params);\n else\n d = distcomp(data1,data2,params);\n end\n \n % Must we return it as a struct?\n if params.Result(1) == 'a'\n % its an array, fill the unwanted distances with +/- inf\n if params.Subset(2) == 'i'\n % minimum\n d(d<=params.Limit) = -inf;\n else\n % maximum\n d(d>=params.Limit) = +inf;\n end\n else\n % a struct will be returned\n if params.Subset(2) == 'i'\n % minimum\n [dist.rowindex,dist.columnindex] = find(d>=params.Limit);\n else\n % maximum\n [dist.rowindex,dist.columnindex] = find(d<=params.Limit);\n end\n dist.distance = d(dist.rowindex + n1*(dist.columnindex-1));\n d = dist;\n end\n \n else\n % we need to break this into chunks. This branch\n % will always return a struct.\n \n % this is the number of rows of data1 that we will\n % process at a time.\n bs = floor(params.ChunkSize/(8*n2));\n bs = min(n1,max(1,bs));\n \n % Accumulate the result into a cell array. Do it this\n % way because we don't know in advance how many elements\n % that we will find satisfying the minimum or maximum\n % limit specified.\n accum = cell(0,1);\n \n % now loop over the chunks\n batch = 1:bs;\n while ~isempty(batch)\n \n % One set or two?\n if dataflag == 1\n dist = distcomp(data1(batch,:),data1,params);\n else\n dist = distcomp(data1(batch,:),data2,params);\n end\n \n % big or small as requested\n if ('i'==params.Subset(2))\n % minimum value specified\n [I,J,V] = find(dist>=params.Limit);\n else\n % maximum limit\n [I,J] = find(dist<=params.Limit);\n I = I(:);\n J = J(:);\n V = dist(I + (J-1)*length(batch));\n I = I + (batch(1)-1);\n end\n\n % and stuff them into the cell structure\n if ~isempty(V)\n accum{end+1,1} = [I,J,V(:)]; %#ok\n end\n\n % increment the batch\n batch = batch + bs;\n if batch(end)>n1\n batch(batch>n1) = [];\n end\n\n end\n\n % convert the cells into one flat array\n accum = cell2mat(accum);\n\n if isempty(accum)\n d.rowindex = [];\n d.columnindex = [];\n d.distance = [];\n else\n % we found something\n\n % sort on the second column, to put them in a reasonable order\n accum = sortrows(accum,[2 1]);\n\n d.rowindex = accum(:,1);\n d.columnindex = accum(:,2);\n d.distance = accum(:,3);\n end\n\n end\n\n case {'smallestfew' 'largestfew'}\n % find the k smallest/largest distances. k is\n % given by params.Limit\n\n % if only 1 set, params.Limit must be less than n*(n-1)/2\n if dataflag == 1\n params.Limit = min(params.Limit,n1*(n1-1)/2);\n end\n\n % is this a large problem?\n if ((ntotal*8) <= params.ChunkSize)\n % small potatoes\n\n % One set or two?\n if dataflag == 1\n dist = distcomp(data1,data1,params);\n % if only one data set, set the diagonal and\n % below that to +/- inf so we don't find it.\n temp = find(tril(ones(n1,n1),0));\n if params.Subset(1) == 's'\n dist(temp) = inf;\n else\n dist(temp) = -inf;\n end\n else\n dist = distcomp(data1,data2,params);\n end\n\n % sort the distances to find those we need\n if ('s'==params.Subset(1))\n % smallestfew\n [val,tags] = sort(dist(:),'ascend');\n else\n % largestfew\n [val,tags] = sort(dist(:),'descend');\n end\n val = val(1:params.Limit);\n tags = tags(1:params.Limit);\n\n % recover the row and column index from the linear\n % index returned by sort in tags.\n [d.rowindex,d.columnindex] = ind2sub([n1,size(dist,2)],tags);\n\n % create the matrix as a sparse one or a struct?\n if params.Result(1)=='a'\n % its an array, so make the array sparse.\n d = sparse(d.rowindex,d.columnindex,val,n1,size(dist,2));\n else\n % a structure\n d.distance = val;\n end\n\n else\n % chunks\n\n % this is the number of rows of data1 that we will\n % process at a time.\n bs = floor(params.ChunkSize/(8*n2));\n bs = min(n1,max(1,bs));\n\n % We need to find the extreme cases. There are two possible\n % algorithms, depending on how many total elements we will\n % search for.\n % 1. Only a very few total elements.\n % 2. A relatively large number of total elements, forming\n % a significant fraction of the total set.\n %\n % Case #1 would suggest to retain params.Limit numberr of\n % elements from each batch, then at the end, sort them all\n % to find the best few. Case #2 will result in too many\n % elements to retain, so we must distinguish between these\n % alternatives.\n if (8*params.Limit*n1/bs) <= params.ChunkSize\n % params.Limit is small enough to fall into case #1.\n\n % Accumulate the result into a cell array. Do it this\n % way because we don't know in advance how many elements\n % that we will find satisfying the minimum or maximum\n % limit specified.\n accum = cell(0,1);\n\n % now loop over the chunks\n batch = (1:bs)';\n while ~isempty(batch)\n % One set or two?\n if dataflag == 1\n dist = distcomp(data1(batch,:),data1,params);\n k = find(tril(ones(length(batch),n2),batch(1)-1));\n if ('s'==params.Subset(1))\n dist(k) = inf;\n else\n dist(k) = -inf;\n end\n else\n dist = distcomp(data1(batch,:),data2,params);\n end\n\n % big or small as requested, keeping only the best\n % params.Limit number of elements\n if ('s'==params.Subset(1))\n % minimum value specified\n [tags,tags] = sort(dist(:),1,'ascend');\n tags = tags(1:bs);\n [I,J] = ndgrid(batch,1:n2);\n ijv = [I(tags),J(tags),dist(tags)];\n else\n % maximum limit\n [tags,tags] = sort(dist(:),1,'descend');\n tags = tags(1:bs);\n [I,J] = ndgrid(batch,1:n2);\n ijv = [I(tags),J(tags),dist(tags)];\n end\n % and stuff them into the cell structure\n accum{end+1,1} = ijv; %#ok\n\n % increment the batch\n batch = batch + bs;\n if batch(end)>n1\n batch(batch>n1) = [];\n end\n end\n\n % convert the cells into one flat array\n accum = cell2mat(accum);\n\n % keep only the params.Limit best of those singled out\n accum = sortrows(accum,3);\n if ('s'==params.Subset(1))\n % minimum value specified\n accum = accum(1:params.Limit,:);\n else\n % minimum value specified\n accum = accum(end + 1 - (1:params.Limit),:);\n end\n d.rowindex = accum(:,1);\n d.columnindex = accum(:,2);\n d.distance = accum(:,3);\n\n % create the matrix as a sparse one or a struct?\n if params.Result(1)=='a'\n % its an array, so make the array sparse.\n d = sparse(d.rowindex,d.columnindex,d.distance,n1,size(dist,2));\n end\n\n else\n % params.Limit forces us into the domain of case #2.\n % Here we cannot retain params.Limit elements from each chunk.\n % so we will grab each chunk and append it to the best elements\n % found so far, then filter out the best after each chunk is\n % done. This may be slower than we want, but its the only way.\n ijv = zeros(0,3);\n\n % loop over the chunks\n batch = (1:bs)';\n while ~isempty(batch)\n % One set or two?\n if dataflag == 1\n dist = distcomp(data1(batch,:),data1,params);\n k = find(tril(ones(length(batch),n2),batch(1)-1));\n if ('s'==params.Subset(1))\n dist(k) = inf;\n else\n dist(k) = -inf;\n end\n else\n dist = distcomp(data1(batch,:),data2,params);\n end\n\n [I,J] = ndgrid(batch,1:n2);\n ijv = [ijv;[I(:),J(:),dist(:)]]; %#ok\n\n % big or small as requested, keeping only the best\n % params.Limit number of elements\n if size(ijv,1) > params.Limit\n if ('s'==params.Subset(1))\n % minimum value specified\n [tags,tags] = sort(ijv(:,3),1,'ascend');\n else\n [tags,tags] = sort(ijv(:,3),1,'ascend');\n end\n ijv = ijv(tags(1:params.Limit),:);\n end\n\n % increment the batch\n batch = batch + bs;\n if batch(end)>n1\n batch(batch>n1) = [];\n end\n end\n\n % They are fully trimmed down. stuff a structure\n d.rowindex = ijv(:,1);\n d.columnindex = ijv(:,2);\n d.distance = ijv(:,3);\n\n % create the matrix as a sparse one or a struct?\n if params.Result(1)=='a'\n % its an array, so make the array sparse.\n d = sparse(d.rowindex,d.columnindex,d.distance,n1,size(dist,2));\n end\n\n end\n\n end\n \n case {'nearestneighbor' 'farthestneighbor'}\n % find the closest/farthest neighbor for every point\n\n % is this a large problem? Or a 1-d problem?\n if dim == 1\n % its a 1-d nearest/farthest neighbor problem. we can\n % special case these easily enough, and all the distance\n % metric options are the same in 1-d.\n\n % first split it into the farthest versus nearest cases.\n if params.Subset(1) == 'f'\n % farthest away\n\n % One set or two?\n if dataflag == 1\n [d2min,minind] = min(data1);\n [d2max,maxind] = max(data1);\n else\n [d2min,minind] = min(data2);\n [d2max,maxind] = max(data2);\n end\n\n d.rowindex = (1:n1)';\n d.columnindex = repmat(maxind,n1,1);\n d.distance = repmat(d2max,n1,1);\n\n % which endpoint was further away?\n k = abs((data1 - d2min)) >= abs((data1 - d2max));\n if any(k)\n d.columnindex(k) = minind;\n d.distance(k) = d2min;\n end\n\n else\n % nearest. this is mainly a sort and some fussing around.\n d.rowindex = (1:n1)';\n d.columnindex = ones(n1,1);\n d.distance = zeros(n1,1);\n\n % One set or two?\n if dataflag == 1\n % if only one data point, then we are done\n if n1 == 2\n % if exactly two data points, its trivial\n d.columnindex = [2 1];\n d.distance = repmat(abs(diff(data1)),2,1);\n elseif n1>2\n % at least three points. do a sort.\n [sorted_data,tags] = sort(data1);\n\n % handle the first and last points separately\n d.columnindex(tags(1)) = tags(2);\n d.distance(tags(1)) = sorted_data(2) - sorted_data(1);\n d.columnindex(tags(end)) = tags(end-1);\n d.distance(tags(end)) = sorted_data(end) - sorted_data(end-1);\n\n ind = (2:(n1-1))';\n\n d1 = sorted_data(ind) - sorted_data(ind-1);\n d2 = sorted_data(ind+1) - sorted_data(ind);\n\n k = d1 < d2;\n d.distance(tags(ind(k))) = d1(k);\n d.columnindex(tags(ind(k))) = tags(ind(k)-1);\n k = ~k;\n d.distance(tags(ind(k))) = d2(k);\n d.columnindex(tags(ind(k))) = tags(ind(k)+1);\n end % if n1 == 2\n else\n % Two sets of data. still really a sort and some fuss.\n if n2 == 1\n % there is only one point in data2\n d.distance = abs(data1 - data2);\n % d.columnindex is already set correctly\n else\n % At least two points in data2\n % We need to sort all the data points together, but also\n % know which points from each set went where. ind12 and\n % bool12 will help keep track.\n ind12 = [1:n1,1:n2]';\n bool12 = [zeros(n1,1);ones(n2,1)];\n [sorted_data,tags] = sort([data1;data2]);\n\n ind12 = ind12(tags);\n bool12 = bool12(tags);\n\n % where did each point end up after the sort?\n loc1 = find(~bool12);\n loc2 = find(bool12);\n\n % for each point in data1, what is the (sorted) data2\n % element which appears most nearly to the left of it?\n cs = cumsum(bool12);\n leftelement = cs(loc1);\n\n % any points which fell below the minimum element in data2\n % will have a zero for the index of the element on their\n % left. fix this.\n leftelement = max(1,leftelement);\n\n % likewise, any point greater than the max in data2 will\n % have an n2 in left element. this too will be a problem\n % later, so fix it.\n leftelement = min(n2-1,leftelement);\n\n % distance to the left hand element\n dleft = abs(sorted_data(loc1) - sorted_data(loc2(leftelement)));\n dright = abs(sorted_data(loc1) - sorted_data(loc2(leftelement+1)));\n\n % find the points which are closer to the left element in data2\n k = (dleft < dright);\n d.distance(ind12(loc1(k))) = dleft(k);\n d.columnindex(ind12(loc1(k))) = ind12(loc2(leftelement(k)));\n k = ~k;\n d.distance(ind12(loc1(k))) = dright(k);\n d.columnindex(ind12(loc1(k))) = ind12(loc2(leftelement(k)+1));\n\n end % if n2 == 1\n end % if dataflag == 1\n end % if params.Subset(1) == 'f'\n\n % create the matrix as a sparse one or a struct?\n if params.Result(1)=='a'\n % its an array, so make the array sparse.\n d = sparse(d.rowindex,d.columnindex,d.distance,n1,n2);\n end\n\n elseif (ntotal>1000) && (((params.Metric == 0) && (params.Subset(1) == 'n')) || ...\n ((params.Metric == inf) && (params.Subset(1) == 'f')))\n % nearest/farthest neighbour in n>1 dimensions, but for an\n % infinity norm metric. Reduce this to a sequence of\n % 1-d problems, each of which will be faster in general.\n % do this only if the problem is moderately large, since\n % we must overcome the extra overhead of the recursive\n % calls to ipdm.\n\n % do the first dimension\n if dataflag == 1\n d = ipdm(data1(:,1),data1(:,1),'subset',params.Subset,'metric',params.Metric,'result','struct');\n else\n d = ipdm(data1(:,1),data2(:,1),'subset',params.Subset,'metric',params.Metric,'result','struct');\n end\n\n % its slightly different for nearest versus farthest here\n % now, loop over dimensions\n for i = 2:dim\n if dataflag == 1\n di = ipdm(data1(:,i),data1(:,i),'subset',params.Subset,'metric',params.Metric,'result','struct');\n else\n di = ipdm(data1(:,i),data2(:,i),'subset',params.Subset,'metric',params.Metric,'result','struct');\n end\n\n % did any of the distances change?\n if params.Metric == 0\n % the 0 norm, with nearest neighbour, so take the\n % smallest distance in any dimension.\n k = d.distance > di.distance;\n else\n % inf norm. so take the largest distance across dimensions\n k = d.distance < di.distance;\n end\n\n if any(k)\n d.distance(k) = di.distance(k);\n d.columnindex(k) = di.columnindex(k);\n end\n end\n\n % create the matrix as a sparse one or a struct?\n if params.Result(1)=='a'\n % its an array, so make the array sparse.\n d = sparse(d.rowindex,d.columnindex,d.distance,n1,n2);\n end\n\n elseif ((ntotal*8) <= params.ChunkSize)\n % None of the other special cases apply, so do it using brute\n % force for the small potatoes problem.\n\n % One set or two?\n if dataflag == 1\n dist = distcomp(data1,data1,params);\n else\n dist = distcomp(data1,data2,params);\n end\n\n % if only one data set and if a nearest neighbor\n % problem, set the diagonal to +inf so we don't find it.\n if (dataflag==1) && (n1>1) && ('n'==params.Subset(1))\n diagind = (1:n1) + (0:n1:(n1^2-1));\n dist(diagind) = +inf;\n end\n\n if ('n'==params.Subset(1))\n % nearest\n [val,j] = min(dist,[],2);\n else\n % farthest\n [val,j] = max(dist,[],2);\n end\n\n % create the matrix as a sparse one or a struct?\n if params.Result(1)=='a'\n % its an array, so make the array sparse.\n d = sparse((1:n1)',j,val,n1,size(dist,2));\n else\n % a structure\n d.rowindex = (1:n1)';\n d.columnindex = j;\n d.distance = val;\n end\n\n else\n\n % break it into chunks\n bs = floor(params.ChunkSize/(8*n2));\n bs = min(n1,max(1,bs));\n\n % pre-allocate the result\n d.rowindex = (1:n1)';\n d.columnindex = zeros(n1,1);\n d.distance = zeros(n1,1);\n\n % now loop over the chunks\n batch = 1:bs;\n while ~isempty(batch)\n\n % One set or two?\n if dataflag == 1\n dist = distcomp(data1(batch,:),data1,params);\n else\n dist = distcomp(data1(batch,:),data2,params);\n end\n\n % if only one data set and if a nearest neighbor\n % problem, set the diagonal to +inf so we don't find it.\n if (dataflag==1) && (n1>1) && ('n'==params.Subset(1))\n diagind = 1:length(batch);\n diagind = diagind + (diagind-2+batch(1))*length(batch);\n dist(diagind) = +inf;\n end\n\n % big or small as requested\n if ('n'==params.Subset(1))\n % nearest\n [val,j] = min(dist,[],2);\n else\n % farthest\n [val,j] = max(dist,[],2);\n end\n\n % and stuff them into the result structure\n d.columnindex(batch) = j;\n d.distance(batch) = val;\n\n % increment the batch\n batch = batch + bs;\n if batch(end)>n1\n batch(batch>n1) = [];\n end\n\n end\n\n % did we need to return a struct or an array?\n if params.Result(1) == 'a'\n % an array. make it a sparse one\n d = sparse(d.rowindex,d.columnindex,d.distance,n1,n2);\n end\n\n end % if dim == 1\n\nend % switch params.Subset\n\n% End of mainline\n\n% ======================================================\n% begin subfunctions\n% ======================================================\nfunction d = distcomp(set1,set2,params)\n% Subfunction to compute all distances between two sets of points\ndim = size(set1,2);\n% can we take advantage of bsxfun?\n% Note: in theory, there is no need to loop over the dimensions. We\n% could Just let bsxfun do ALL the work, then wrap a sum around the\n% outside. In practice, this tends to create large intermediate\n% arrays, especially in higher numbers of dimensions. Its also when\n% we might gain here by use of a vectorized code. This will only be\n% a serious gain when the number of points is relatively small and\n% the dimension is large.\nif params.usebsxfun\n % its a recent enough version of matlab that we can\n % use bsxfun at all.\n n1 = size(set1,1);\n n2 = size(set2,1);\n if (dim>1) && ((n1*n2*dim)<=params.ChunkSize)\n % its a small enough problem that we might gain by full\n % use of bsxfun\n switch params.Metric\n case 2\n d = sum(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim])).^2,3);\n case 1\n d = sum(abs(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim]))),3);\n case inf\n d = max(abs(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim]))),[],3);\n case 0\n d = min(abs(bsxfun(@minus,reshape(set1,[n1,1,dim]),reshape(set2,[1,n2,dim]))),[],3);\n end\n else\n % too big, so that the ChunkSize will have been exceeded, or just 1-d\n if params.Metric == 2\n d = bsxfun(@minus,set1(:,1),set2(:,1)').^2;\n else\n d = abs(bsxfun(@minus,set1(:,1),set2(:,1)'));\n end\n for i=2:dim\n switch params.Metric\n case 2\n d = d + bsxfun(@minus,set1(:,i),set2(:,i)').^2;\n case 1\n d = d + abs(bsxfun(@minus,set1(:,i),set2(:,i)'));\n case inf\n d = max(d,abs(bsxfun(@minus,set1(:,i),set2(:,i)')));\n case 0\n d = min(d,abs(bsxfun(@minus,set1(:,i),set2(:,i)')));\n end\n end\n end\nelse\n % Cannot use bsxfun. Sigh. Do things the hard (and slower) way.\n n1 = size(set1,1);\n n2 = size(set2,1);\n if params.Metric == 2\n % Note: While some people might use a different Euclidean\n % norm computation based on expanding the square of the\n % difference of two numbers, that computation is inherantly\n % inaccurate when implemented in floating point arithmetic.\n % While it might be faster, I won't use it here. Sorry.\n d = (repmat(set1(:,1),1,n2) - repmat(set2(:,1)',n1,1)).^2;\n else\n d = abs(repmat(set1(:,1),1,n2) - repmat(set2(:,1)',n1,1));\n end\n for i=2:dim\n switch params.Metric\n case 2\n d = d + (repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1)).^2;\n case 1\n d = d + abs(repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1));\n case inf\n d = max(d,abs(repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1)));\n case 0\n d = min(d,abs(repmat(set1(:,i),1,n2) - repmat(set2(:,i)',n1,1)));\n end\n end\nend\n% if 2 norm, then we must sqrt at the end\nif params.Metric==2\n d = sqrt(d);\nend\n\n% ==============================================================\n% end main ipdm\n% begin included function - 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 % Use setfield for comptability issues with older releases.\n params = setfield(params,p_i,v_i); %#ok\n\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/+prtExternal/+IPDM/ipdm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7146296697432705}} {"text": "function unicycle_check ( n, p )\n\n%*****************************************************************************80\n%\n%% UNICYCLE_CHECK checks that a vector represents a unicycle.\n%\n% Discussion:\n%\n% A unicycle is a permutation with a single cycle. This might be called\n% a cyclic permutation, except that that name is used with at least two\n% other meanings. So, to be clear, a unicycle is a permutation of N\n% objects in which each object is returned to itself precisely after\n% N applications of the permutation.\n%\n% This routine verifies that each of the integers from 1\n% to N occurs among the N entries of the permutation.\n%\n% Any permutation of the integers 1 to N describes a unicycle.\n% The permutation ( 3, 4, 2, 1 ) indicates that the unicycle\n% sends 3 to 4, 4 to 2, 2 to 1 and 1 to 3. This is the sequential\n% description of a unicycle.\n%\n% The standard sequence \"rotates\" the permutation so that it begins\n% with 1. The above sequence becomes a standard sequence when\n% written as ( 1, 3, 4, 2 ).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 June 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries.\n%\n% Input, integer P(N), the unicycle sequence vector.\n%\n ierror = 0;\n\n for iseek = 1 : n\n\n ierror = iseek;\n\n for ifind = 1 : n\n if ( p(ifind) == iseek )\n ierror = 0\n break\n end\n end\n\n if ( ierror ~= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'UNICYCLE_CHECK - Fatal error!\\n' );\n fprintf ( 1, ' The input array does not represent\\n' );\n fprintf ( 1, ' a unicycle. In particular, the\\n' );\n fprintf ( 1, ' array is missing the value %d\\n', ierror );\n error ( 'UNICYCLE_CHECK - Fatal error!' )\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/unicycle/unicycle_check.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8740772450055545, "lm_q1q2_score": 0.7146232457381994}} {"text": "function [P, beta] = x2p(X, u, tol)\n%X2P Identifies appropriate sigma's to get kk NNs up to some tolerance \n%\n% [P, beta] = x2p(xx, kk, tol)\n% \n% Identifies the required precision (= 1 / variance^2) to obtain a Gaussian\n% kernel with a certain uncertainty for every datapoint. The desired\n% uncertainty can be specified through the perplexity u (default = 15). The\n% desired perplexity is obtained up to some tolerance that can be specified\n% by tol (default = 1e-4).\n% The function returns the final Gaussian kernel in P, as well as the \n% employed precisions per instance in beta.\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n \n if ~exist('u', 'var') || isempty(u)\n u = 15;\n end\n if ~exist('tol', 'var') || isempty(tol)\n tol = 1e-4; \n end\n \n % Initialize some variables\n n = size(X, 1); % number of instances\n P = zeros(n, n); % empty probability matrix\n beta = ones(n, 1); % empty precision vector\n logU = log(u); % log of perplexity (= entropy)\n \n % Compute pairwise distances\n% disp('Computing pairwise distances...');\n D = squareform(pdist(X, 'euclidean') .^ 2);\n\n % Run over all datapoints\n% disp('Computing P-values...');\n for i=1:n\n \n% if ~rem(i, 500)\n% disp(['Computed P-values ' num2str(i) ' of ' num2str(n) ' datapoints...']);\n% end\n \n % Set minimum and maximum values for precision\n betamin = -Inf; \n betamax = Inf;\n \n % Compute the Gaussian kernel and entropy for the current precision\n Di = D(i, [1:i-1 i+1:end]);\n [H, thisP] = Hbeta(Di, beta(i));\n \n % Evaluate whether the perplexity is within tolerance\n Hdiff = H - logU;\n tries = 0;\n while abs(Hdiff) > tol && tries < 50\n \n % If not, increase or decrease precision\n if Hdiff > 0\n betamin = beta(i);\n if isinf(betamax)\n beta(i) = beta(i) * 2;\n else\n beta(i) = (beta(i) + betamax) / 2;\n end\n else\n betamax = beta(i);\n if isinf(betamin) \n beta(i) = beta(i) / 2;\n else\n beta(i) = (beta(i) + betamin) / 2;\n end\n end\n \n % Recompute the values\n [H, thisP] = Hbeta(Di, beta(i));\n Hdiff = H - logU;\n tries = tries + 1;\n end\n \n % Set the final row of P\n P(i, [1:i - 1, i + 1:end]) = thisP;\n end \n% disp(['Mean value of sigma: ' num2str(mean(sqrt(1 ./ beta)))]);\n% disp(['Minimum value of sigma: ' num2str(min(sqrt(1 ./ beta)))]);\n% disp(['Maximum value of sigma: ' num2str(max(sqrt(1 ./ beta)))]);\nend\n \n\n\n% Function that computes the Gaussian kernel values given a vector of\n% squared Euclidean distances, and the precision of the Gaussian kernel.\n% The function also computes the perplexity of the distribution.\nfunction [H, P] = Hbeta(D, beta)\n P = exp(-D * beta);\n sumP = sum(P);\n H = log(sumP) + beta * sum(D .* P) / sumP;\n P = P / sumP;\nend\n\n", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/x2p.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7146232396353026}} {"text": "function [X,rho,eta,F] = nu(A,b,k,nu,s)\n%NU Brakhage's nu-method.\n%\n% [X,rho,eta,F] = nu(A,b,k,nu,s)\n%\n% Performs k steps of Brakhage's nu-method for the problem\n% min || A x - b || .\n% The routine returns all k solutions, stored as columns of\n% the matrix X. The solution norm and residual norm are returned\n% in eta and rho, respectively.\n%\n% If nu is not specified, nu = .5 is the default value, which gives\n% the Chebychev method of Nemirovskii and Polyak.\n%\n% If the singular values s are also provided, nu computes the\n% filter factors associated with each step and stores them\n% columnwise in the matrix F.\n\n% Reference: H. Brakhage, \"On ill-posed problems and the method of\n% conjugate gradients\"; in H. W. Engl & G. W. Groetsch, \"Inverse and\n% Ill-Posed Problems\", Academic Press, 1987.\n\n% Martin Hanke, Institut fuer Praktische Mathematik, Universitaet\n% Karlsruhe and Per Christian Hansen, IMM, 03/21/92.\n\n% Set parameter.\nl_steps = 3; % Number of Lanczos steps for est. of || A ||.\nfudge = 0.99; % Scale A and b by fudge/|| A*L_p ||.\nfudge_thr = 1e-4; % Used to prevent filter factors from exploding.\n\n% Initialization.\nif (k < 1), error('Number of steps k must be positive'), end\nif (nargin==3), nu = .5; end\n[m,n] = size(A); X = zeros(n,k);\nif (nargout > 1)\n rho = zeros(k,1); eta = rho;\nend;\nif (nargin==5)\n F = zeros(n,k); Fd = zeros(n,1); s = s.^2;\nend\nV = zeros(n,l_steps); B = zeros(l_steps+1,l_steps);\nv = zeros(n,1); eta = zeros(l_steps+1,1);\n\n% Compute a rough estimate of the norm of A by means of a few\n% steps of Lanczos bidiagonalization, and scale A and b such\n% that || A || is slightly less than one.\nbeta = norm(b); u = b/beta;\nfor i=1:l_steps\n r = A'*u - beta*v;\n alpha = norm(r); v = r/alpha;\n B(i,i) = alpha; V(:,i) = v;\n p = A*v - alpha*u;\n beta = norm(p); u = p/beta;\n B(i+1,i) = beta;\nend\nscale = fudge/norm(B); A = scale*A; b = scale*b;\nif (nargin==5), s = scale^2*s; end\n\n% Prepare for iteration.\nx = zeros(n,1);\nd = A'*b;\nr = d;\nif (nargout>1), z = b; end\n\n% Iterate.\nfor j=0:k-1\n\n % Updates.\n alpha = 4*(j+nu)*(j+nu+0.5)/(j+2*nu)/(j+2*nu+0.5);\n beta = (j+nu)*(j+1)*(j+0.5)/(j+2*nu)/(j+2*nu+0.5)/(j+nu+1);\n Ad = A*d; AAd = A'*Ad;\n x = x + alpha*d;\n r = r - alpha*AAd;\n d = r + beta*d;\n X(:,j+1) = x;\n if (nargout>1)\n z = z - alpha*Ad; rho(j+1) = norm(z)/scale;\n end;\n if (nargout>2), eta(j+1) = norm(x); end;\n\n % Filter factors.\n if (nargin==5)\n if (j==0)\n F(:,1) = alpha*s;\n Fd = s - s.*F(:,1) + beta*s;\n else\n F(:,j+1) = F(:,j) + alpha*Fd;\n Fd = s - s.*F(:,j+1) + beta*Fd;\n end\n if (j > 1)\n f = find(abs(F(:,j)-1) < fudge_thr & abs(F(:,j-1)-1) < fudge_thr);\n if ~isempty(f), F(f,j+1) = ones(length(f),1); end\n end\n end\n\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/nu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7146232338075098}} {"text": "function value = r8_invgam_sample ( beta, alpha )\n\n%*****************************************************************************80\n%\n%% R8_INVGAM_SAMPLE samples an inverse gamma distribution.\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 FORTRAN90 version by Guannan Zhang.\n% MATLAB version by John Burkardt.\n%\n% Parameters:\n%\n% Input, real BETA, the rate parameter.\n% 0.0 < BETA.\n%\n% Input, real ALPHA, the shape parameter.\n% 0.0 < ALPHA.\n%\n% Output, real VALUE, a sample value.\n%\n value = r8_gamma_sample ( beta, alpha );\n\n if ( value ~= 0.0 )\n value = 1.0 / value;\n end\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/pdflib/r8_invgam_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.7146232289079759}} {"text": "function [F,G,rho,u,v,p] = EulerFluxes2D(Q, gamma)\n \n% function [F,G,rho,u,v,p] = EulerFluxes2D(Q, gamma)\n% Purpose: evaluate primitive variables and Euler flux functions\n\n% extract conserved variables\nrho = Q(:,:,1); rhou = Q(:,:,2); rhov = Q(:,:,3); Ener = Q(:,:,4);\n\n% compute primitive variables\nu = rhou./rho; v = rhov./rho; p = (gamma-1)*(Ener - 0.5*(rhou.*u + rhov.*v));\n\n% compute flux functions\nF = zeros(size(Q)); \nF(:,:,1) = rhou; \nF(:,:,2) = rhou.*u + p; \nF(:,:,3) = rhov.*u; \nF(:,:,4) = u.*(Ener+p);\n\nG = zeros(size(Q));\nG(:,:,1) = rhov; \nG(:,:,2) = rhou.*v; \nG(:,:,3) = rhov.*v + p; \nG(:,:,4) = v.*(Ener+p);\nreturn;\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/CFD2D/EulerFluxes2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9539661015270469, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.7146038083988168}} {"text": "function y = GUSFT_Toeplitz(x,lambda);\n% GUSFT_Toeplitz: Gram matrix associated with the nonuniform FT\n% Usage:\n% y = GUSFT_Toeplitz(x,lambda);\n% Inputs:\n% x vector of length n\n% lambda Fourier multiplier of length 2n -1 \n% Outputs:\n% y vector of length n \n% Description: \n% Performs A'A where A is the nonuniform FT in the\n% Fourier domain. A'A has a Toeplitz structure which can be\n% embedded in a larger circulant matrix. Applying A'A is a\n% multiplication in Fourier space with weights lambda. Note that\n% lambda specifies the unequispaced grid).\n% See Also\n% USFT_simple, USFFT, MakeFourierDiagonal\n%\n% By Emmanuel candes, 2003-2004\n\n n = length(x);\n extended.x = [x;zeros(n-1,1)];\n y = fft(ifft(extended.x) .* lambda);\n y = y(1:n);\n\t\n \n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/CurveLab-2.1.3/fdct_usfft_matlab/USFFT/GUSFT_Toeplitz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936262, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7146000064962778}} {"text": "function img = discreteReuleauxRevol(varargin)\n%DISCRETEREULEAUXREVOL Discretize the revolution of a Reuleaux triangle\n%\n% A Reuleaux triangle is formed by 3 circle arcs, and has the property to\n% have a constant width whatever the orientation.\n% In 3 dimension, the surface of revolution obtained by rotating a\n% Reuleaux triangle around one of its axis of symetry has also a constant\n% width. The resulting shape looks like a hazelnut.\n%\n% IMG = discreteReuleauxRevol(LX, LY, LZ, REULEAUX)\n% REULEAUX is the domaine enclosed by the revolution of a Reuleaux\n% triangle around one of its axis. REULEAUX is defined by:\n% [XC YC ZC R THETA PHI]\n% where (XC, YC, ZC) is the geometric centroid the triangle, R is the\n% radius of the circle arcs, and THETA and PHI define the orientation of\n% the Reuleaux Apex: THETA is the colatitude, between 0 and 180 degrees,\n% and PHI is the azimut, between 0 and 360 degrees.\n%\n% IMG = discreteReuleauxRevol(LX, LY, LZ, REULEAUX, D)\n% Use the dilation of a Reuleaux shape by a ball of radius D. The\n% constant diameter of the resulting shape equals R + 2*D.\n%\n% IMG = discreteReuleauxRevol(DIM, ...)\n% DIM is the size of image, with the format [x0 dx x1;y0 dy y1;z0 dz z1]\n%\n% Examples\n% % Display oriented reuleaux triangle revolution\n% reuleaux = [50 50 50 60 30 40];\n% img = discreteReuleauxRevol(1:100, 1:100, 1:100, reuleaux);\n% figure();\n% isosurface(img, .5); \n% axis equal;\n%\n% % The same, with a little bit dilation\n% reuleaux = [50 50 50 60 30 40]\n% img2 = discreteReuleauxRevol(1:100, 1:100, 1:100, reuleaux, 10);\n% figure();\n% isosurface(img2, .5); \n% axis equal;\n%\n% % Alternative syntax\n% img = discreteReuleauxRevol([1 1 100;1 1 100;1 1 100], reuleaux);\n%\n% See Also\n% imShapes, discreteEllipsoid, discreteTorus, discreteBall\n%\n\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2006-02-27\n% Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).\n\n% HISTORY\n% 04/01/2007: concatenate transforms before transforming points\n% 04/03/2009: use meshgrid\n% 30/04/2009: update transforms\n% 29/05/2009: use more possibilities for specifying grid\n\n\n% compute coordinate of image voxels\n[lx, ly, lz, varargin] = parseGridArgs3d(varargin{:});\n[x, y, z] = meshgrid(lx, ly, lz);\n\n% parameters of Revolved Reuleaux triangle\nreul = varargin{1};\ncenter = reul(1:3);\nR = reul(4);\ntheta = deg2rad(reul(5));\nphi = deg2rad(reul(6));\nvarargin(1) = [];\n\n% extract dilation factor if present\ndil = 0;\nif ~isempty(varargin)\n dil = varargin{1};\nend\n\n% top point of triangle\nx1 = 0;\ny1 = 0;\nz1 = 0;\n\n% the height of the triangle\nh = R * sqrt(3) / 2;\ndil2 = dil * sqrt(3) / 2;\n\n% create empty image\nimg = false(size(x));\n\n% transforms voxels according to shape orientation\ntrans = composeTransforms3d(...\n createTranslation3d(-center),...\n createRotationOz(-phi),...\n createRotationOy(-theta), ...\n createTranslation3d([0 0 h*2/3]));\n[x, y, z] = transformPoint3d(x, y, z, trans);\n\n\n% distance of the points to the revolution axis\nrho = hypot(x-x1, y-y1);\n\n% points above the top of the triangle\nind = find((z <= z1) & (z >= z1-dil));\ndist = rho(ind).^2 + (z(ind)-z1).^2;\nimg(ind) = dist <= dil ^ 2;\n\n% points above the basis of the triangle and below the top\nind = find(z >= z1-dil2 & z <= (z1+h));\ndist = (rho(ind)+R/2).^2 + (z(ind)-z1-h).^2;\nimg(ind) = dist < (R+dil)^2;\n\n% points around the 2 lower corners\ndist = (rho-R/2).^2 + (z-z1-h).^2;\nimg(dist < dil^2) = 1;\nind = find(z > z1+h & z <= z1+h+dil2);\ndist = rho(ind) ;\nimg(ind(dist < R/2)) = 1;\n\n% points below the basis of the triangle\nind = find(z >= z1+h+dil2);\ndist = rho(ind).^2 + (z(ind)-z1).^2;\nimg(ind) = dist < (R+dil)^2;\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/discreteReuleauxRevol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7145589861961373}} {"text": "function [s_map1 s_map2 s3] = s3_map(img, show_res)\n% Input: img is a gray scale image, in double type, range from 0 - 255. \n% You have to convert to gray scale if your image\n% is color. You also have to cast img to double in order to run this code\n% Parameter show_res = 1 to show results\n% Output: \n% s_map1: The sharpness map measure based on spectral slope\n% s_map2: The sharpness map measure based on total variation (spatial) \n% s3: the final sharpness map (combination of s_map1 and s_map2)\nif nargin < 2\n show_res = 0;\nend\n\n% ----------------------------------------------------------------------\n% blr_map1\ns_map1 = spectral_map(img, 16);\n\n%-----------------------------------------------------------------------\n% blr_map2\ns_map21 = spatial_map(img, 8); % Spatial map, blocks start from (1,1)\ns_map22 = spatial_map(img, 4); % Spatial map, blocks start from (5,5) \ns_map2 = max(s_map21, s_map22);\n\n%-----------------------------------------------------------------------\n% combine\ns_map1(s_map1 < -99) = 0;\ns_map2(s_map2 < -99) = 0;\n\nalpha = 0.5;\ns3 = (s_map1.^alpha) .* ((s_map2).^(1-alpha));\nif show_res\n figure; imshow(s_map1);\n figure; imshow(s_map2);\n figure; imshow(img/255);\n figure; imshow(s3);\nend\nend %function\n\n%% Spectral Sharpness, slope of power spectrum\nfunction res = spectral_map(img, pad_len)\nblk_size = 32; %big block size for more coefficients of the power spectrum\nd_blk = blk_size/4; % Distance b/w blocks\n\npad_L = fliplr(img(:, 1:pad_len)); % Take 16 columns on the left of the\n % original image to pad to the left\npad_R = fliplr(img(:, end-pad_len:end));%Take 16 columns on the right of the\n % original image to pad to the\n % right\nimg = [pad_L img pad_R]; %Pad left and right\n\npad_T = flipud(img(1:pad_len, :)); %Similarly, pad top and bottom\npad_B = flipud(img(end-pad_len:end, :));\nimg = [pad_T; img; pad_B];\n\nnum_rows = size(img, 1);\nnum_cols = size(img, 2);\nres = zeros(num_rows, num_cols) - 100;\ncontrast_thresold = 0;\n\n%disp_progress; % Just to show progress\nfor r = blk_size/2+1:d_blk:num_rows-blk_size/2 % Just start from inside blocks\n % of the padded image\n %disp_progress(r, num_rows);\n for c = blk_size/2+1:d_blk:num_cols-blk_size/2\n gry_blk = img(...\n r-blk_size/2:r+blk_size/2-1,...\n c-blk_size/2:c+blk_size/2-1 ...\n );\n contrastMap = contrast_map_overlap(gry_blk);\n if(max(contrastMap(:))> contrast_thresold) % Avoid the case when contrast = 0\n val = blk_amp_spec_slope_eo_toy_1(gry_blk); % Val(1) will be the slope of\n % power spectrum of the block\n val(1) = 1 - 1 ./ (1 + exp(-3*(val(1) - 2))); %Input to a sigmoid function\n %if(max(gry_blk(:))==min(gry_blk(:))) % Black block\n % val_1 = 0;\n %else\n val_1 = val(1);\n %end\n else\n val_1 = 0;\n end\n res(...\n r-d_blk/2:r+d_blk/2-1,...\n c-d_blk/2:c+d_blk/2-1 ...\n ) = val_1;\n end\nend\n% Remove padded parts\nres = res(pad_len+1:end-pad_len-1, pad_len+1:end-pad_len-1);\nend % function\n\n%% ---Spatial Sharpness, local total variation\nfunction res = spatial_map(img, pad_len)\n% pad_len = 8 if we dont want to shift img\n% pad_len = 4 if we want to shift img by 4;\nblk_size = 8;\n\npad_L = fliplr(img(:, 1:pad_len)); % Take pad_len columns on the left of\n % the original image to pad to the left\npad_R = fliplr(img(:, end-pad_len:end));%Take pad_len columns on the right\n % of the original image to pad to the right\nimg = [pad_L img pad_R]; %Pad left and right\n\npad_T = flipud(img(1:pad_len, :)); %Similarly, pad top and bottom\npad_B = flipud(img(end-pad_len:end, :));\nimg = [pad_T; img; pad_B];\n\n[num_rows, num_cols] = size(img);\nres = zeros(num_rows, num_cols);\n\nfor r = blk_size/2+1 : blk_size : num_rows-blk_size/2\n for c = blk_size/2+1 : blk_size : num_cols-blk_size/2\n gry_blk = img(...\n r-blk_size/2 : r+blk_size/2-1,...\n c-blk_size/2 : c+blk_size/2-1 ...\n );\n % Measure local total variation for every 2x2 block of gry_blk\n tmp_idx = 1;\n for i = 1 : blk_size - 1\n for j = 1 : blk_size - 1\n tv_tmp(tmp_idx) = (abs(gry_blk(i,j) - gry_blk(i,j+1))...\n + abs(gry_blk(i,j) - gry_blk(i+1,j))...\n + abs(gry_blk(i,j) - gry_blk(i+1,j+1))...\n + abs(gry_blk(i+1,j+1) - gry_blk(i+1,j))...\n + abs(gry_blk(i+1,j) - gry_blk(i,j+1))...\n + abs(gry_blk(i+1,j+1) - gry_blk(i,j+1)))/255; %Each pixel ranges\n %from 0 - 255, so divide by 255 to make it from 0 - 1\n tmp_idx = tmp_idx + 1;\n end\n end\n\n tv_max = max(tv_tmp) / 4; % Normalize tv_max to be from 0 -1. We can\n % easily see that the maximum value of total\n % variation for each 2x2 block is 4, in\n % blocks like 1 0\n % 0 1\n \n res(...\n r - blk_size/2 : r + blk_size/2-1,...\n c - blk_size/2 : c + blk_size/2-1 ...\n ) = tv_max; \n end\nend\nres = res(pad_len + 1 : end-pad_len - 1, pad_len + 1 : end-pad_len - 1);\n\nend % function\n\n\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/去噪算法/CGCSF-master/functions/S3codes_Oct2011/s3_map.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.71455776932389}} {"text": "function K = slkernel(varargin)\n%SLKERNEL Computes the kernel for samples\n%\n% $ Syntax $\n% - K = slkernel(X0, kernel_type, ...)\n% - K = slkernel(X0, X, kernel_type, ...)\n%\n% $ Description $\n% - K = slkernel(X0, kernel_type, ...) Computes the Gram matrix for\n% the samples in matrix X0 using the kernel specified by kernel_type. \n% kernel_type can be name of a built-in kernel type, or the name, \n% handle of an user-specified function. The user-specified function\n% should take in two d x n matrix containing n pairs of vectors, and\n% output a 1 x n vector of their kernel values. The available builtin\n% kernels are given as follows:\n% \\*\n% \\t Table 1. Built-in Kernel Types \\\\\n% \\h name & description \\\\\n% 'lin' & Linear Kernel: \n% x1' * x2, \n% with no parameters \\\\\n% 'gauss' & Gaussian RBF Kernel:\n% exp(- ||x1 - x2||^2 / (2 * sigma^2)), \n% with one parameter sigma \\\\ \n% 'poly' & Polynomial Kernel:\n% ((x1' * x2) + a)^k,\n% with two parameters: k and a \\\\\n% 'sigmoid' & Sigmoidal Kernel:\n% tanh(k * (x1' * x2) + a), \n% with two parameters: k and a \\\\\n% 'invquad' & Inverse Quadratic Kernel:\n% 1 / sqrt(||x1 - x2||^2 + a), \n% with one parameter: a \\\\\n% \\* \n%\n% - K = slkernel(X0, X, kernel_type, p1, p2, ...) Computes the empirical\n% kernel mapping for samples X with respect to data set X0. Suppose\n% there are n0 samples in X0, n samples in X, then K will be an n0 * n\n% matrix. Each column in K corresponds to a column in X.\n%\n% $ History $\n% - Created by Dahua Lin on Jul 13rd, 2005\n% - Modified by Dahua Lin on May 2nd, 2005\n% - base on sltoolbox v4\n% - re-organize the code structure\n% - add the ability of user-specified kernel functions.\n%\n\n%% parse and verify input arguments\n\n% for X0\nif ~isnumeric(varargin{1})\n error('sltoolbox:invalidarg', ...\n 'The first argument should be an numeric matrix');\nend\nX0 = varargin{1};\nif ndims(X0) ~= 2\n error('sltoolbox:invaliddims', ...\n 'The X0 should be a 2D matrix');\nend\n\n% for X\nif isnumeric(varargin{2})\n X = varargin{2}; \n if ndims(X) ~= 2\n error('sltoolbox:invaliddims', ...\n 'X should be a 2D matrix');\n end\n ipkt = 3; % argument index of kernel type \nelse\n X = X0;\n ipkt = 2; \nend\n\n% for kernel type\nif nargin < ipkt || isempty(varargin{ipkt})\n error('sltoolbox:invalidarg', ...\n 'kernel type is not specified');\nend\nkernel_type = varargin{ipkt};\n\n% for extra parameters\nif nargin == ipkt % no extra parameters\n params = {};\nelse\n params = varargin(ipkt+1:end);\nend\n\n\n%% Determine the computation routine and delegate to it\n\n% determine for the built-in ones\n\nbik = false;\nif ischar(kernel_type)\n switch kernel_type\n case 'lin'\n bik = true; % bik means built-in kernel\n fh_kernel = @lin_kernel;\n case 'gauss'\n bik = true;\n fh_kernel = @gauss_kernel;\n case 'poly'\n bik = true;\n fh_kernel = @poly_kernel;\n case 'sigmoid'\n bik = true;\n fh_kernel = @sigmoid_kernel;\n case 'invquad'\n bik = true;\n fh_kernel = @invquad_kernel;\n end\nend\n\n% delegate\nif bik\n K = fh_kernel(X0, X, params{:});\nelse\n K = slpweval(X0, X, kernel_type, params{:});\nend\n\n\n%% The built-in kernel functions\n\n% Linear Kernel\nfunction K = lin_kernel(X0, X)\n\nK = X0' * X;\n\n\n% Gaussian Radius Base Function Kernel\nfunction K = gauss_kernel(X0, X, sigma)\n\nD2 = slmetric_pw(X0, X, 'sqdist');\nK = exp(- D2 / (2 * sigma * sigma));\n\n\n% Polynomial Kernel\nfunction K = poly_kernel(X0, X, k, a)\n\nK = (X0' * X + a).^k;\n\n\n% Sigmoidal Kernel\nfunction K = sigmoid_kernel(X0, X, k, a)\n\nK = tanh(k * (X0' * X) + a);\n\n\n% Inverse Quadratic Kernel\nfunction K = invquad_kernel(X0, X, a)\n\nD2 = slmetric_pw(X0, X, 'sqdist');\nK = 1 ./ sqrt(D2 + a);\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/kernel/slkernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7143631726072849}} {"text": "function [x,e_conn,index_b] = twod_mesh(x_l, x_r, y_l, y_r, ...\n etype, ...\n n_nodesx, n_nodesy, ...\n fig_num )\n%-----------------------------------------------------------------------\n% twod_mesh.m - Generate a rectangular mesh with a prescribed density.\n% This routine returns nodal coordinates, element\n% connectivity, and the nodal indices of boundary nodes.\n%\n% Copyright (c) 2001, Jeff Borggaard, Virginia Tech\n% Version: 1.0\n%\n% Usage: [x,e_conn,index_b] = twod_mesh(x_l,x_r,y_l,y_r,etype,...\n% n_nodex,n_nodesy,fig_num)\n%\n% Variables: (x_l,y_l) \n% coordinates of lower left corner\n% (x_r,y_r) \n% coordinates of upper right corner\n%\n% etype\n% element type\n% 'linear', 'quadratic', 'cubic'\n%\n% n_nodesx, n_nodesy\n% number of nodes in x and y directions\n% (must be compatible with element type)\n%\n% fig_num (optional)\n% specifies the figure number for mesh plot\n% Outputs:\n% x \n% node coordinates of mesh\n% e_conn \n% element connectivity of mesh\n% index_b \n% node numbers of boundary nodes\n%-----------------------------------------------------------------------\n\n if ( strcmp( etype, 'linear' ) )\n % Generate node coordinates\n dx = (x_r-x_l)/(n_nodesx-1);\n dy = (y_r-y_l)/(n_nodesy-1);\n for i=1:n_nodesx\n for j=1:n_nodesy\n k = i+(j-1)*n_nodesx;\n x(k,1) = x_l + dx*(i-1);\n x(k,2) = y_l + dy*(j-1);\n end\n end\n\n % Generate element connectivity\n e_conn = zeros(n_elements, 3);\n ie = 0;\n for j=1:n_nodesy-1\n for i=1:n_nodesx-1\n ie = ie + 1;\n k = i + (j-1)*n_nodesx;\n e_conn(ie,:) = [k, k+1+n_nodesx, k+n_nodesx];\n ie = ie + 1;\n e_conn(ie,:) = [k, k+1, k+1+n_nodesx];\n end\n end\n\n elseif ( strcmp( etype, 'quadratic') )\n % Generate a mesh with quadratic elements\n n_nodes = n_nodesx*n_nodesy;\n n_elements = 2*(n_nodesx-1)*(n_nodesy-1)/4;\n\n dx = (x_r-x_l)/(n_nodesx-1);\n dy = (y_r-y_l)/(n_nodesy-1);\n for i=1:n_nodesx\n for j=1:n_nodesy\n k = i+(j-1)*n_nodesx;\n x(k,1) = x_l + dx*(i-1);\n x(k,2) = y_l + dy*(j-1);\n end\n end\n\n % Generate element connectivity\n e_conn = zeros(n_elements, 6);\n ie = 0;\n for j=1:2:n_nodesy-1\n for i=1:2:n_nodesx-1\n ie = ie + 1;\n k = i + (j-1)*n_nodesx;\n e_conn(ie,:) = [k, k+2+2*n_nodesx, k+2*n_nodesx, ...\n k + 1 + n_nodesx, k+1+2*n_nodesx, k+n_nodesx ];\n ie = ie + 1;\n e_conn(ie,:) = [k, k+2, k+2+2*n_nodesx, ...\n k+1, k+2+n_nodesx, k+1+n_nodesx ];\n end\n end\n\n elseif ( strcmp( etype, 'cubic' ) )\n error('twod_mesh: cubic elements are not currently implemented\\n')\n else\n error('twod_mesh: etype is not a valid string\\n')\n end\n \n if ( nargout==3 )\n index_b = [ 2:n_nodesx-1, ...\n 1:n_nodesx:(n_nodesy-1)*n_nodesx, ...\n n_nodesx:n_nodesx:n_nodesy*n_nodesx, ...\n (n_nodesy-1)*n_nodesx+1:n_nodes-1 ];\n end\n \n if ( nargin==8 )\n twod_plotm2(fig_num,x,e_conn,'+')\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/twod/twod_mesh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.808067208930584, "lm_q1q2_score": 0.7143631623918152}} {"text": "function [ y, m, d, f ] = jed_to_ymdf_hindu_solar ( jed )\n\n%*****************************************************************************80\n%\n%% JED_TO_YMDF_HINDU_SOLAR converts a JED to a Hindu solar YMDF date.\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, real JED, the Julian Ephemeris Date.\n%\n% Output, integer Y, M, D, real F, the YMDF date.\n%\n\n%\n% Date = JF.\n%\n jf = jed;\n%\n% Date = JED_EPOCH + JF\n%\n jed_epoch = epoch_to_jed_hindu_solar ( );\n jf = jf - jed_epoch;\n%\n% Date = JED_EPOCH + Y years + JF\n%\n y = floor ( jf / year_length_hindu_solar ( ) );\n jf = jf - floor ( y * year_length_hindu_solar ( ) );\n%\n% Date = JED_EPOCH + Y years + ( M - 1 ) months + JF\n%\n m = 1 + floor ( jf / month_length_hindu_solar ( ) );\n jf = jf - floor ( ( m - 1 ) * month_length_hindu_solar ( ) );\n%\n% Date = JED_EPOCH + Y years + ( M - 1 ) months + ( D - 1 ) days + f\n%\n d = floor ( jf ) + 1;\n f = jf - ( d - 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/calpak/jed_to_ymdf_hindu_solar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7143631602634513}} {"text": "function e=v_rotro2eu(m,r)\n%V_ROTRO2EU converts a 3x3 rotation matrix into the corresponding euler angles\n% inverse of v_roteu2ro\n% M a string of n characters from the set determining the order of rotation axes\n% as listed below. Note that the control characters 'rdoOaA' may occur anywhere in the string:\n% 'x','y','z' rotate around the given axis by the corresponding angle\n% given in e()\n% '1','2','3' 90 degree rotation around x,y or z axis; doesn't use a value from e()\n% '4','5','6' 180 degree rotation around x,y or z axis; doesn't use a value from e()\n% '7','8','9' 270 degree rotation around x,y or z axis; doesn't use a value from e()\n% 'r','d' all angles are given in radians or degrees [default='r']\n% 'R','D' all angles are given in radians or degrees and are negated\n% 'o','O','a','A' selects whether to rotate the object or the coordinate axes and\n% whether the rotation axes remain fixed in space for consecutive\n% rotations (extrinsic) or else move with each rotation (intrinsic).\n% 'o' = object-extrinsic [default]\n% 'O' = object-intrinsic\n% 'a' = axes-extrinsic\n% 'A' = axes-intrinsic\n%\n% R(3,3,...) Input rotation matrix (or array of matrices)\n%\n% Outputs:\n%\n% E(K,...) K Euler angles in radians (or degrees if 'd' or 'D' specified) per quaternion where K is the number of 'xyz' characters in M.\n% A positive rotation is clockwise if looking along the +ve axis away from the origin or anti-clockwise if 'R' or 'D' is given.\n% The x, y, z axes form a right-handed triple.\n%\n% The string M specifies the seqeunce of axes about which the rotations are performed. There are 12\n% possible 3-character sequences that avoid consecutive repetitions. These are 'Euler angles' if\n% there is a repeated axis or 'Tait-Bryan angles' if not. Common choices are:\n% (1) 'zxz' the most common Euler angle set\n% (2) 'xyz' corresponds to 'roll, pitch, yaw' for an aeroplane heading in the x direction with y to\n% the right and z down. The intrinsic equivalent is 'Ozyx' corresponding to 'yaw, pitch, roll'.\n% (3) 'z1z1z' involves 5 rotations, in which all the non-fixed rotations are around the z axis.\n%\n% The Euler angles are not, in general, unique. In particular:\n% (1) v_roteu2ro('zxz',[a b c]) = v_roteu2ro('zxz',[a+pi -b c+pi])\n% (2) v_roteu2ro('xyz',[a b c]) = v_roteu2ro('xyz',[a+pi pi-b c+pi])\n\n% Copyright (C) Mike Brookes 2007-2020\n% Version: $Id: v_rotro2eu.m 11260 2020-07-18 20:07:58Z 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 mch mvch rtr rtci rtsi scai w6 th6 x6 pmw\nif isempty(mvch)\n mch=''; % cached rotation code string\n mvch=[0;0;1;1;0;0;1];\n rtr=[1 4 7 2 5 8 3 6 9]; % indices to transpose a vectorized 3x3 matrix\n rtci=[2 3 5 6 8 9; 3 1 6 4 9 7; 1 2 4 5 7 8]';\n rtsi=[3 2 6 5 9 8; 1 3 4 6 7 9; 2 1 5 4 8 7]';\n scai=[0 0 0 1; 0 0 0 2; 0 0 0 3; 1 -1 0 1; 1 -1 0 2; 1 -1 0 3; 0 0 -1 1; 0 0 -1 2; 0 0 -1 3; -1 1 0 1; -1 1 0 2; -1 1 0 3]'; % [sin; -sin; cos; xyz] for fixed rotations\n w6=ones(6,1); %\n th6=3*w6;\n x6=[2 1 2 1 2 1]'; % Index for sin components\n pmw=[1; -1];\nend\n\nif ~nargout\n v_rotro2qr(r);\nelse\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Convert the m string\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n if ischar(m) && strcmp(m,mch) % check if the rotation code string is cached\n mv=mvch;\n else\n mv=v_roteucode(m); % else decode the string\n mch=m; % and save the result in the cache for next time.\n mvch=mv;\n end\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Now calculate euler angles\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n nm=size(mv,2)-1; % number of rotation codes\n sz=size(r);\n r=reshape(r,9,[]); % vectorize the rotation matrices\n nr=size(r,2); % number of rotation matrices\n if mv(end)<0\n r=r(rtr,:); % transpose rotation matrix\n end\n e=zeros(mv(2,end),nr); % initialize array of euler angles\n ef=mv(end-3);\n for i=nm:-1:1 % process rotations in reverse order\n mvi=mv(:,i);\n mi=mvi(1);\n if mi<=3 % rotation around x,y or z\n if mvi(6)~=0 % skip if this rotation is redundant\n [si,ci,ri,ti]=v_atan2sc(mvi(7)*r(mvi(4),:),mvi(7)*r(mvi(5),:));\n e(mv(2,i),:)=ti*mvi(6)/ef; % save the euler angle\n si=mvi(6)*pmw*si; % make -si available and correct sign\n r(rtci(:,mi),:)=ci(w6,:).*r(rtci(:,mi),:)-si(x6,:).*r(rtsi(:,mi),:); % apply reverse rotation\n end\n else % fixed rotation\n ai=scai(4,mi); % axis of rotation: 1, 2 or 3\n r(rtci(:,ai),:)=scai(th6,mi).*r(rtci(:,ai),:)-scai(x6,mi).*r(rtsi(:,ai),:); % apply reverse rotation\n end\n end\n if nr>1 % if there was >1 input matrix\n e=reshape(e,[size(e,1) sz(3:end)]); % restore the shape of the Euler angle array\n end\nend", "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_rotro2eu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7143631557515906}} {"text": "function [fx,dF_dX,dF_dTheta] = f_vanDerPol(Xt,Theta,ut,inF)\n% evolution function for the Van Der Pol (limit cycle) oscillator.\n% function [fx,dF_dX,dF_dTheta,d2F_dXdTheta] = f_vanDerPol(Xt,Theta,ut,inF)\n% IN:\n% - Xt: current hidden state\n% - Theta: evolution parameter\n% - ut: current input to the system\n% - in: user-defined input structure (containing the time decimation)\n% OUT:\n% - fx: the predicted hidden state\n% - dF_dX: the jacobian of the system\n% - dF_dTheta: the derivative of the evolution function w.r.t the\n% evolution parameters\n\ndeltat = inF.deltat;\n\nx = Xt;\nmu = Theta(1);\n\nfx = zeros(2,1);\nfx(1) = x(2);\nfx(2) = mu.*(1-x(1).^2).*x(2) - x(1);\nfx = deltat.*fx + x;\n\nJ = zeros(2,2);\nJ(1,:) = [0,1];\nJ(2,:) = [-2.*mu.*x(1).*x(2)-1,mu.*(1-x(1).^2)];\ndF_dX = deltat.*J';\n\ndF_dTheta = zeros(1,2);\ndF_dTheta(1,:) = [0,(1-x(1).^2).*x(2)];\ndF_dTheta = deltat.*dF_dTheta;\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/demos/_models/f_vanDerPol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9572778024535095, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.7142622955733517}} {"text": "function [x,tspan] = impliciteuler(f,tspan,x0)\n%% IMPLICITEULER - Numerical ODE solver: Implicit Euler method\n%\n% Syntax:\n% [x,tspan] = euler(f,tspan,x0)\n%\n% In:\n% f - Function handle, f(x,t)\n% tspan - Time steps to simulate, [t0,...,tend]\n% x0 - Initial condition\n%\n% Out:\n% x - Solved values\n% tspan - Time steps\n% \n% Description:\n% Integrates the system of differential equations\n% x' = f(x,t), for x(0) = x0\n% over the time interval defined in tspan.\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%%\n\n % Number of steps\n steps = numel(tspan);\n \n % Allocate space\n x = zeros(size(x0,1),steps);\n\n % Initial state\n x(:,1) = x0;\n \n % Iterate\n for k=2:steps\n\n % Time discretization\n dt = tspan(k)-tspan(k-1);\n\n % Step solve the algebraic problem\n x(:,k) = fsolve(@(z) x(:,k-1) + f(z,tspan(k))*dt - z, ...\n x(:,k-1), optimset('display','none'));\n \n end\n \n ", "meta": {"author": "AaltoML", "repo": "SDE", "sha": "91111b0f1849ef0a0540c683bb2cf454ab4f2aff", "save_path": "github-repos/MATLAB/AaltoML-SDE", "path": "github-repos/MATLAB/AaltoML-SDE/SDE-91111b0f1849ef0a0540c683bb2cf454ab4f2aff/matlab/impliciteuler.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7142585349063538}} {"text": "function v = m2v(h,k,l,cs)\n% Miller-indece --> cartesian coordinates\n% Input\n% h,k,l - \n% cs - crystal symmetry (optional)\n%\n% Output\n% v - @vector3d\n\nif any(h == 0 & k == 0 & l ==0)\n error('(0,0,0) is not a valid Miller index');\nend\n\na = cs.axes;\nV = dot(a(1),cross(a(2),a(3)));\na_star = cross(a(2),a(3)) ./ V;\nb_star = cross(a(3),a(1)) ./ V;\nc_star = cross(a(1),a(2)) ./ V;\n\n% reciprocal space\nv = h * a_star + k * b_star + l * c_star;\n% v = v ./ norm(v);\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/@Miller/private/m2v.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067179697695, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.7142262806105337}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Sample Data and Metch Registration Sessions %\n% %\n% by Qianqian Fang %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% first of all, make sure you've already add the metch root\n% folder to your matlab/octave search path list\n\n% load the sample data, where\n% no: the node coordinates of a surface mesh\n% el: the surface triangles\n% pt: the point cloud to be registered\n\ndisp('(*)First load the mesh and point cloud. Hit Enter to continue...');\npause;\n\nload sampledata\nif(exist('OCTAVE_VERSION')~=0)\n\ttrimesh(el,no(:,1),no(:,2),no(:,3));\nelse\n\tcla;\n\ttrisurf(el,no(:,1),no(:,2),no(:,3));\nend\ntitle('Metch toolbox demonstration');\naxis equal;\nhold on;\n\n% use metch functions to perform the registration\n\npnum=size(pt,1);\n\n% define a number of point pairs to initialize the registration\ndisp('(*)Create 4 mapping pairs to initialize the mapping. Hit Enter to continue...');\npause;\n\n% select 4 land-marks on the point cloud (specified by their indicies)\nptidx=[4 107 1 190];\nptselected=pt(ptidx,:);\n\n% find the corresponding land-marks on the mesh\nmeshidx=[3173 1715 156 1740];\nmeshselected=no(meshidx,:);\n\n% calculate the affine mapping using these point pairs\n[A0,b0]=affinemap(ptselected,meshselected)\n\ndisp('(*)Display the updated points. Hit Enter to continue...');\npause;\n\n% a rough registration from the selected point pairs\npoints_after_initmap=(A0*pt'+repmat(b0(:),1,pnum))';\nplot3(points_after_initmap(:,1),points_after_initmap(:,2),points_after_initmap(:,3),'r.');\n\ndisp('(*)Optimize the mapping matrix to fit the surface. Hit Enter to continue...');\npause;\n\n% set pmask: if pmask(i) is -1, it is a free nodes to be optimized\n% if pmask(i) is 0, it is fixed\n% if pmask(i) is a positive number, it is the index of \n% the mesh node to map to\n\npmask=-1*ones(pnum,1);\npmask(ptidx)=meshidx;\n\n% perform mesh registration with Gauss-Newton method using A0/b0 \n% as initial guess\n[A,b,newpos]=regpt2surf(no,el,pt,pmask,A0,b0,ones(12,1),10);\nA\nb\n\ndisp('(*)Display the optimized point cloud. Hit Enter to continue...');\npause;\n\n% update point cloud with the optimized mapping\npoints_after_optimize=(A*pt'+repmat(b(:),1,pnum))';\n\nplot3(points_after_optimize(:,1),points_after_optimize(:,2),points_after_optimize(:,3),'g+');\n\ndisp('(*)Project the point cloud on the surface. Hit Enter to continue...');\npause;\n\n% project the optimized point cloud onto the surface, and make\n% sure the comformity\n\nnv=nodesurfnorm(no,el);\n[d2surf,cn]=dist2surf(no,nv,points_after_optimize);\n[points_after_proj eid weights]=proj2mesh(no,el,points_after_optimize,nv,cn);\n\ndisp('(*)Display the final results. Hit Enter to continue...');\npause;\n\nplot3(points_after_proj(:,1),points_after_proj(:,2),points_after_proj(:,3),'c*');\n\nlegend('surface mesh','points after initial map','points after optimized map',...\n 'points after projection');\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_registration_ex1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7142155369924543}} {"text": "function ell = inertiaEllipsoid(points)\n%INERTIAELLIPSOID Inertia ellipsoid of a set of 3D points.\n%\n% Note: Deprecated! Use equivalentEllipsoid instead.\n%\n%\n% ELL = inertiaEllipsoid(PTS)\n% Compute the inertia ellipsoid of the set of points PTS. The result is\n% an ellipsoid defined by:\n% ELL = [XC YC ZC A B C PHI THETA PSI]\n% where [XC YC ZY] is the center, [A B C] are lengths of semi-axes (in\n% decreasing order), and [PHI THETA PSI] are euler angles representing \n% the ellipsoid orientation, in degrees.\n%\n% Example\n% pts = randn(300, 3);\n% pts = transformPoint3d(pts, createScaling3d([6 4 2]));\n% pts = transformPoint3d(pts, createRotationOx(pi/6));\n% pts = transformPoint3d(pts, createRotationOy(pi/4));\n% pts = transformPoint3d(pts, createRotationOz(pi/3));\n% pts = transformPoint3d(pts, createTranslation3d([5 4 3]));\n% elli = inertiaEllipsoid(pts);\n% figure; drawPoint3d(pts); axis equal;\n% hold on; drawEllipsoid(elli, ...\n% 'drawEllipses', true, 'EllipseColor', 'b', 'EllipseWidth', 3);\n%\n% See also\n% equivalentEllipsoid\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@inra.fr\n% Created: 2011-03-12, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2011 INRA - Cepia Software Platform\n\n% deprecation warning\nwarning('geom3d:deprecated', ...\n [mfilename ' is deprecated, use ''equivalentEllipsoid'' instead']);\n\n% number of points\nn = size(points, 1);\n\n% compute centroid\ncenter = mean(points);\n\n% compute the covariance matrix\ncovPts = cov(points)/n;\n\n% perform a principal component analysis with 2 variables, \n% to extract inertia axes\n[U, S] = svd(covPts);\n\n% extract length of each semi axis\nradii = sqrt(5) * sqrt(diag(S)*n)';\n\n% sort axes from greater to lower\n[radii, ind] = sort(radii, 'descend');\n\n% format U to ensure first axis points to positive x direction\nU = U(ind, :);\nif U(1,1) < 0\n U = -U;\n % keep matrix determinant positive\n U(:,3) = -U(:,3);\nend\n\n% convert axes rotation matrix to Euler angles\nangles = rotation3dToEulerAngles(U);\n\n% concatenate result to form an ellipsoid object\nell = [center, radii, angles];\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/deprecated/geom3d/inertiaEllipsoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7142155368231592}} {"text": "function value = r8_gamma_01_pdf ( alpha, rval )\n\n%*****************************************************************************80\n%\n%% R8_GAMMA_01_PDF evaluates the PDF of a standard gamma distribution.\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% John Burkardt.\n%\n% Parameters:\n%\n% Input, real ALPHA, the shape parameter.\n% 0.0 < ALPHA.\n%\n% Input, real RVAL, the point where the PDF is evaluated.\n%\n% Output, real VALUE, the value of the PDF at RVAL.\n%\n if ( alpha <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_GAMMA_01_PDF - Fatal error!\\n' );\n fprintf ( 1, ' Parameter ALPHA is not positive.\\n' );\n error ( 'R8_GAMMA_01_PDF - Fatal error!' );\n end if\n\n if ( rval <= 0.0 )\n\n value = 0.0;\n\n else\n\n temp = ( alpha - 1.0 ) * log ( rval ) - rval - r8_gamma_log ( alpha );\n\n value = exp ( temp );\n\n end\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/pdflib/r8_gamma_01_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7141624647962298}} {"text": "function [J, grad] = linearRegCostFunction(X, y, theta, lambda)\n%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear \n%regression with multiple variables\n% [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the \n% cost of using theta as the parameter for linear regression to fit the \n% data points in X and y. Returns the cost in J and the gradient in grad\n\n% Initialize some useful values\nm = length(y); % number of training examples\n\n% You need to return the following variables correctly \nJ = 0;\ngrad = zeros(size(theta));\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Compute the cost and gradient of regularized linear \n% regression for a particular choice of theta.\n%\n% You should set J to the cost and grad to the gradient.\n%\n\nreal_theta = theta(2:end, :);\n\nregularization = lambda * sum(real_theta .^ 2) / (2 * m);\nprediction = sum(((X * theta) .- y) .^ 2) / (2 * m);\nJ = prediction + regularization;\n\nmask = ones(size(theta));\nmask(1) = 0;\n\ngradient0 = sum(((X * theta) .- y) .* X) / m;\noffset = lambda * (theta .* mask) / m;\ngradient = gradient0 .+ offset';\ngrad = gradient;\n\n% =========================================================================\n\ngrad = grad(:);\n\nend\n", "meta": {"author": "ecmadao", "repo": "Coding-Guide", "sha": "baac530f78b239488003de039b346ca0ba24ed6c", "save_path": "github-repos/MATLAB/ecmadao-Coding-Guide", "path": "github-repos/MATLAB/ecmadao-Coding-Guide/Coding-Guide-baac530f78b239488003de039b346ca0ba24ed6c/Notes/ml/coursera/machine-learning-ex5/ex5/linearRegCostFunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7141327151663358}} {"text": "function [cubR,cubS,cubW, Ncub] = Cubature2D(Corder)\n\n% function [cubR,cubS,cubW, Ncub] = Cubature2D(Corder)\n% Purpose: provide multidimensional quadrature (i.e. cubature) \n% rules to integrate up to Corder polynomials\n \nCubatureData2D;\n\nif(Corder<=28)\n cubR = cub2D{Corder}(:,1);\n cubS = cub2D{Corder}(:,2);\n cubW = cub2D{Corder}(:,3); \nelse\n cubNA = ceil( (Corder+1)/2);\n [cubA,cubWA] = JacobiGQ(0,0, cubNA-1);\n cubNB = ceil( (Corder+1)/2);\n [cubB,cubWB] = JacobiGQ(1,0, cubNB-1);\n \n cubA = ones(cubNB,1)*cubA';\n cubB = cubB*ones(1,cubNA);\n\n cubR = 0.5*(1+cubA).*(1-cubB)-1;\n cubS = cubB;\n cubW = 0.5*cubWB*(cubWA');\n\n cubR = cubR(:);\n cubS = cubS(:);\n cubW = cubW(:);\nend\nNcub = length(cubW(:));\nreturn\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/Codes2D/Cubature2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7141295417213093}} {"text": "function [Y,Z,dy,dz] = define_grid_coordinates(Ly,Lz,Ny,Nz,HubHt)\ndy = Ly/(Ny-1); % Spacing along Y axis\ndz = Lz/(Nz-1); % Spacing along Z axis\nif isequal(mod(Ny,2),0)\n iky = flip([(-Ny/2:-1) (1:Ny/2)]);\nelse\n iky = flip(-floor(Ny/2):ceil(Ny/2-1));\nend\n\nif isequal(mod(Nz,2),0)\n ikz = [(-Nz/2:-1) (1:Nz/2)];\nelse\n ikz = -floor(Nz/2):ceil(Nz/2-1);\nend\n\n% define Y and Z coordinates for each grid-point\n[Y,Z] = ndgrid(iky*dy,(ikz*dz + HubHt));\nY = Y';\nZ = Z';\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/turbulent_wind_generator/define_grid_coordinates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7141295388924566}} {"text": "function [logPr] = calcLogPrMatrixNormalInvWishart( A, invSigma, PP )\n\n[logPrSigma, cholInvSigma] = calcLogPrInvWishart( invSigma, PP );\n\nlogDetInvSigma = 2*sum( log( diag( cholInvSigma ) ) );\nlogDetSigma = -logDetInvSigma; % det(S) = 1/det(inv(S))\n\nCC = PP.invAScaleMat;\n[D DR] = size( CC );\n\nif isfield( PP, 'MeanMat') && ~isempty( PP.MeanMat )\n UU = A - PP.MeanMat;\nelse\n UU = A; % assume zero mean\nend\n\nlogPrA = 0.5*D*log( det(CC) ) - 0.5*DR*D*log( 2*pi ) ...\n - 0.5*DR*logDetSigma ...\n - 0.5*trace( UU'*invSigma*UU*CC );\n \n \nlogPr = logPrA + logPrSigma;\n", "meta": {"author": "michaelchughes", "repo": "NPBayesHMM", "sha": "22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd", "save_path": "github-repos/MATLAB/michaelchughes-NPBayesHMM", "path": "github-repos/MATLAB/michaelchughes-NPBayesHMM/NPBayesHMM-22e164b5eb68ea2b1e5ef38807a56fd8aa3660dd/code/BayesCalc/calcLogPrMatrixNormalInvWishart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465188527686, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7141218804411178}} {"text": "function jdate = julian (month, day, year)\n\n% Julian date\n\n% Input\n\n% month = calendar month [1 - 12]\n% day = calendar day [1 - 31]\n% year = calendar year [yyyy]\n\n% Output\n\n% jdate = Julian date\n\n% special notes\n\n% (1) calendar year must include all digits\n\n% (2) will report October 5, 1582 to October 14, 1582\n% as invalid calendar dates and stop\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ny = year;\nm = month;\nb = 0;\nc = 0;\n\nif (m <= 2)\n y = y - 1;\n m = m + 12;\nend\n\nif (y < 0)\n c = -.75;\nend\n\n% check for valid calendar date\n\nif (year < 1582)\n % null\nelseif (year > 1582)\n a = fix(y / 100);\n b = 2 - a + floor(a / 4);\nelseif (month < 10)\n % null\nelseif (month > 10)\n a = fix(y / 100);\n b = 2 - a + floor(a / 4);\nelseif (day <= 4)\n % null\nelseif (day > 14)\n a = fix(y / 100);\n b = 2 - a + floor(a / 4);\nelse\n clc; home;\n\n fprintf('\\n\\n this is an invalid calendar date!!\\n');\n\n keycheck;\n\n return;\nend\n\njd = fix(365.25 * y + c) + fix(30.6001 * (m + 1));\n\njdate = jd + day + b + 1720994.5;\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/julian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7141218699035143}} {"text": "function b_n = beamWeightsDifferential2Spherical(a_n)\n%BEAMWEIGHTSDIFFERENTIAL2SPHERICAL Transform differential to spherical coefficients.\n%\n% For a set of a_n coefficients describing a pattern of a differential \n% array of the form\n% D(theta)=Sum_{n=1}^{N} a_n * cos^n(theta), \n% generate the beamweights for the same pattern in the SHD. Since the \n% pattern is axisymmetric only the N+1 coefficients of m=0 are returned.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% BEAMWEIGHTSDIFFERENTIAL2SPHERICAL.M - 10/4/2013\n% Archontis Politis, archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% order N (or polynomial degree)\nN = length(a_n)-1;\n\n% build Legendre polynomial matrix\nP_N = zeros(N+1);\nfor n = 0:N\n P_N(1:n+1,n+1) = returnLegePolyCoeffs(n);\nend\n% build the normalisation matrix\nw = sqrt((2*(0:N)+1)/(4*pi));\nW = diag(w);\nW_inv = diag(1./w);\n% convert coefficients\nb_n = W_inv * inv(P_N) * a_n;\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/beamWeightsDifferential2Spherical.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645894, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.7141053362515566}} {"text": "function [AIC, HQIC, BIC] = IC(S, E, T, K)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% 'IC' computes various information criteria\n\n% Inputs:\n% - llf, log marginal likelihood\n% - T, sample size\n% - K, number of regressors\n\n% Filippo Ferroni, 6/1/2015\n% Revised, 2/15/2017\n% Revised, 3/21/2018\n% Revised, 9/11/2019\n% Revised, 9/11/2020\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% E = var.e_ols;\n% S = var.Sigma_ols; \niS = pinv(S);\nN = size(S,1);\nllf = - (T * N / 2) * (1 + log(2 * pi)) - T / 2 * log(det(S));\nllf = llf - 1 /2 * trace( iS * E' * E);\n\nAIC = - 2 * llf / T + 2 * K / T;\n% SIC = - 2 * llf / T + K * log(T) / T;\nHQIC = - 2 * llf / T + 2 * K * log(log(T)) / T;\nBIC = - 2 * llf / T + K * log(T) / T;\n", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/bvartools/IC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7141053349652212}} {"text": "function momentMat=quasiMoments2Moments(quasiMomentMat,muN,SigmaN)\n%%QUASIMOMENTS2MOMENTS Convert a set of (multivariate) quasi-moments taken\n% with respect to a particular mean vector and covariance\n% matrix into noncentral moments. Quasi-moments are used in\n% generalized Edgeworth series approximations of\n% distributions.\n%\n%INPUTS: quasiMomentMat A matrix taking n indices, where \n% quasiMomentMat(a1,a2,a3...an) corresponds to the quasi-\n% moment whose multivariate order is given by a1-1,a2-1, etc.\n% It is assumed that quasi moments only up to an order equal\n% to the size of the first dimension of the matrix are\n% available (other entries in quasiMomentMat are ignored).\n% All other dimensions must be at least the same size as the\n% first. Also, the zero-th order moment must be 1 (as the PDF\n% integrates to 1). If a univariate distribution is used,\n% then this is a column vector.\n% muN The nX1 mean vector with respect to with the quasi-moments\n% are computed. If this parameter is omitted or an empty\n% matrix is passed, a zero mean vector is used.\n% SigmaN The nXn covariance matrix with respect to which the\n% quasi-moments are computed. If this parameter is omitted or\n% an empty matrix is passed, the identity matrix is used.\n%\n%OUTPUTS: momentMat A matrix taking n indices, where \n% momentMat(a1,a2,a3...an) corresponds to the coefficient of \n% a E(x1^(a1-1)*x2^(a2-1)*x3^(a3-1)...xn^(an-1)) moment.\n% The order of the moment is a1+a2+..an.\n%\n%Quasi-moments are introduced in [2] and are defined in terms of a certain\n%mean vector and covariance matrix. If mean vector and covariance matrix\n%coincide with those of the moments associated with the quasi-moments, then\n%the quasi-moments are called proper quasi-moments.\n%\n%The conversion is based on Equation 2.11 in [1]. The equation is\n%m_\\alpha=\\sum_{\\beta}^{\\alpha}C_{\\alpha}^\\beta m^N_{\\alpha-\\beta} q_\\beta\n%where q's represent quasi moments, m^N's represent moments of the Normal\n%distribution having covariance matrix Sigma, m's are moments of the\n%distribution that are to be converted. The indexation is vector based.\n%Thus, beta is actually a vector of beta(1)...beta(n) and alpha goes from\n%alpha(1)...alpha(n). The sum is actually multiple sums. The\n%C_{\\alpha}^\\beta} is equal to the product of binomial(alpha(i),beta(i))\n%over i.\n%\n%REFERENCES:\n%[1] I. E. Poloskov, \"CAS Mathematica in random studies,\" in Proceedings\n% of Computational Science - ICCS 2003, Melbourne, Australia and St.\n% Petersburg, Russia, 2-4 Jun. 2003, pp. 781-790.\n%[2] P. I. Kuznetsov, R. L. Stratonovich, and V. I. Tikhonov, \"Quasi-moment\n% functions in the theory of random processes,\" Theory of Probability \n% and its Applications, vol. V, no. 1, pp. 80-97, 1960.\n%\n%September 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDimList=size(quasiMomentMat);\nmaxDeg=numDimList(1)-1;\nnumIdx=length(numDimList);\n\n%If the last dimension is just a singleton dimension, then shrink\n%everything by one.\nif(numIdx==2&&numDimList(2)==1&&(nargin<3||size(SigmaN,2)==1))\n numIdx=1;\nend\n\n%Do the conversion with respect to the standard normal distribution if no\n%further details are given.\nif(nargin<2||isempty(muN))\n muN=zeros(numIdx,1);\nend\nif(nargin<3||isempty(SigmaN))\n SigmaN=eye(numIdx,numIdx);\nend\n\n%Allocate space to hold a table of binomial values that can be quickly\n%looked up in the loops rather than having to compute them again and again.\nbinomTable=makeBinomTable(maxDeg);\n\n%This is a table that will hold values of moments for the normal\n%distribution with zero mean and covariance matrix Sigma. These moments\n%play a role in the conversion to quasi-moments as they are related to\n%hermite polynomials.\nmomentMatN=zeros(numDimList);\nmomentMatN(1)=1;%Zeroth-order moment is always 1.\nfor curDeg=1:maxDeg\n curPart=getNextMPartition(numIdx+curDeg,numIdx);\n \n while(~isempty(curPart))\n %Go through all permutation of the orders of each index.\n powTable=genAllMultisetPermutations(curPart-1);\n numVals=size(powTable,2);\n for curVal=1:numVals\n numDerivs=powTable(:,curVal);\n momentVal=GaussianD.momentGenFun(muN,SigmaN,numDerivs);\n curEl=nDim2Index(numDimList,numDerivs+1);\n momentMatN(curEl)=momentVal;\n end\n \n curPart=getNextMPartition(curPart);\n end\nend\n\n%Allocate space for the return values.\nmomentMat=zeros(numDimList);\n%The zeroth-order moment is always 1.\nmomentMat(1)=1;\n\n%First, fill in the values for the case where only the first dimension has\n%nonzero exponents. This is just Equation 11 for the scalar case.\nfor n=1:maxDeg\n for i=0:n\n momentMat(n+1)=momentMat(n+1)+binomTable(n+1,i+1)*momentMatN(n-i+1)*quasiMomentMat(i+1);\n end\nend\n\nfor numNonzeroIdx=2:numIdx\n %For a given new index that will be nonzero. \n %We start with the last index (not visited) being nonzero, because we\n %have already considered all of the instances where it is zero.\n for nonzeroDegVal=1:maxDeg\n %curDeg is the degree of all elements except the last one, which is\n %nonzero and which we go through in the outer loop.\n for curDeg=0:(maxDeg-nonzeroDegVal)\n %Fixing the order of highest index, we must now go through all\n %partitions of possible values that the other elements can\n %take.\n curPart=getNextMPartition(numNonzeroIdx-1+curDeg,numNonzeroIdx-1);\n while(~isempty(curPart))\n %curPart-1 is the (unordered) degrees of the indices before\n %the current index (the last nonzero index).\n %For the given partition, we must go through all possible\n %multiset permutations of the values.\n lowerIdxPerms=genAllMultisetPermutations(curPart);\n numPerms=size(lowerIdxPerms,2);\n \n for curPerm=1:numPerms\n r=[lowerIdxPerms(:,curPerm)-1;nonzeroDegVal];\n idxVal=nDim2Index(numDimList(1:numNonzeroIdx),r+1);\n\n %Use Equation 2.11 to compute the moment term.\n momentMat(idxVal)=equation211Update(r,momentMatN,quasiMomentMat,binomTable);\n end\n curPart=getNextMPartition(curPart);\n end\n end\n end\nend\nend\n\nfunction sumVal=equation211Update(alpha,momentMatN,quasiMomentMat,binomTable)\n%This implements Equation 2.11 in [1] for a given alpha vector.\n\nnumIdx=length(alpha);\nmaxDim=size(quasiMomentMat);\nmaxDim=maxDim(1:numIdx);%Only the first numIdx indices are considered.\n\n%This stores cumulative values of the product of the binomials going down\n%each sum. This way, the values do not have to be constantly recomputed.\nbinomProdVal=ones(numIdx-1,1);\n\n%This vector holds all of the i values. Initially, all sums start at zero.\niVec=zeros(numIdx,1);\n\n%The loop goes through all of the values in the sums.\ncurLevel=numIdx;\nisAscending=false;\nsumVal=0;\nwhile(curLevel>=1)\n if(curLevel==numIdx)\n %Go through the innermost sum\n for i=0:alpha(numIdx)\n binomVal=binomProdVal(numIdx-1)*binomTable(alpha(numIdx)+1,i+1);\n \n iVec(numIdx)=i;\n kIdxVec=alpha-iVec;\n \n idx=nDim2Index(maxDim,iVec+1);\n kidx=nDim2Index(maxDim,kIdxVec+1);\n \n sumVal=sumVal+binomVal*momentMatN(kidx)*quasiMomentMat(idx);\n end\n curLevel=curLevel-1;\n isAscending=true;\n continue;\n elseif(isAscending)\n %Try incrementing the order at this level...\n iVec(curLevel)=iVec(curLevel)+1;\n if(iVec(curLevel)<=alpha(curLevel))\n %If the value is valid, then update the binomial product value\n %and descend to the next level.\n if(curLevel~=1)\n binomProdVal(curLevel)=binomProdVal(curLevel-1)*binomTable(alpha(curLevel)+1,iVec(curLevel)+1);\n else\n binomProdVal(curLevel)=binomTable(alpha(curLevel)+1,iVec(curLevel)+1);\n end\n isAscending=false;\n curLevel=curLevel+1;\n continue;\n else\n %If the value is invalid, then just keep ascending.\n curLevel=curLevel-1;\n continue;\n end\n else%We are descending in the sums here.\n iVec(curLevel)=0;\n binomProdVal(curLevel)=binomProdVal(curLevel-1);\n curLevel=curLevel+1;\n end\nend\n\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Statistics/quasiMoments2Moments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7140814611941353}} {"text": "function [Alp,blp] = coordinate_constraint(V,C)\n % COORDINATE_CONSTRAINT Build a \"coordinate constraint\" matrix for enforcing\n % linear precision in generalized barycentric coordinates or skinning\n % weights.\n %\n % [Alp,blp] = coordinate_constraint(V,C)\n % \n % Inputs:\n % V #V by dim list of sample locations\n % C #C by dim list of cage/control vertex positions\n % Outputs:\n % Alp #V*dim by #V*c sparse matrix of constraint coefficients\n % blp #V*dim list of right hand sides\n %\n % Example:\n % % fine mesh in (V,F) cage in (C,CF), boundary conditions in (b,bc)\n % [Alp,blp] = coordinate_constraint(V,C)\n % W = min_quad_with_fixed(Q,[],b,bc,Alp,blp)\n % max(abs(Alp*W(:) - blp))\n % \n\n % dimensions\n n = size(V,1);\n d = size(C,2);\n assert(d == size(V,2));\n c = size(C,1);\n AlpI = reshape(repmat(1:n,c,1),n*c,1);\n AlpJ = reshape(bsxfun(@plus,repmat((1:c)-1,n,1)*n,(1:n)')',n*c,1);\n %% Handle each dimension\n AlpI = reshape(bsxfun(@plus,AlpI,((1:d)-1)*n),n*c*d,1);\n AlpJ = repmat(AlpJ(:),d,1);\n AlpV = reshape(repmat(C,n,1),n*c*d,1);\n Alp = sparse(AlpI(:),AlpJ(:),AlpV(:),n*d,c*n);\n blp = V(:);\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/coordinate_constraint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.7140659666766505}} {"text": "function sumll=LLtwoCIR(para,Y, tau, nrow, ncol) \n% Initialize the parameters for CIR model\ntheta1=para(1); \nkappa1=para(2);\nsigma1=para(3);\nlambda1=para(4);\ntheta2=para(5); \nkappa2=para(6);\nsigma2=para(7);\nlambda2=para(8);\nsigmai=para(9:end);\n\nR=eye(ncol);\nfor i=1:ncol \n R(i,i)=sigmai(i)^2;\nend\ndt=1/12;\n\n% System Matrices Initialization\nC=[theta1*(1-exp(-kappa1*dt));theta2*(1-exp(-kappa2*dt))]; % eqn b.3\nF=[exp(-kappa1*dt),0 ; 0,exp(-kappa2*dt)]; % eqn b.3\nA=zeros(ncol,1);\nH=zeros(ncol,2);\n\n% Create A and B\nfor i=1:ncol % System Matrices are made for each tau\n % Factor 1\n AffineG11=sqrt((kappa1+lambda1)^2+2*sigma1^2); % eqn a.8 & a.9 & a.10\n AffineG12=kappa1+lambda1+AffineG11;\n AffineG13=2*kappa1*theta1/sigma1^2;\n AffineG14=2*AffineG11+AffineG12*(exp(AffineG11*tau(i))-1);\n AffineA1=((2*AffineG11*exp(AffineG12*tau(i)/2))/AffineG14)^AffineG13;\n A1=-log(AffineA1)/tau(i);\n AffineB1=2*(exp(AffineG11*tau(i))-1)/AffineG14;\n B1=AffineB1/tau(i);\n % Factor 2\n AffineG21=sqrt((kappa2+lambda2)^2+2*sigma2^2); % % eqn a.8 & a.9 & a.10\n AffineG22=kappa2+lambda2+AffineG21;\n AffineG23=2*kappa2*theta2/sigma2^2;\n AffineG24=2*AffineG21+AffineG22*(exp(AffineG21*tau(i))-1);\n AffineA2=((2*AffineG21*exp(AffineG22*tau(i)/2))/AffineG24)^AffineG23;\n A2=-log(AffineA2)/tau(i);\n AffineB2=2*(exp(AffineG21*tau(i))-1)/AffineG24;\n B2=AffineB2/tau(i);\n \n A(i,1)=A1+A2; % eqn b.2\n H(i,1)=B1; % eqn b.2\n H(i,2)=B2; % eqn b.2\nend\n\n%% Kalman filter\n% Step 1\ninitx=[theta1;theta2]; % eqn c.1\ninitV=[(sigma1^2*theta1)/(2*kappa1),0;...\n 0,(sigma2^2*theta2)/(2*kappa2)]; % eqn c.2\n% Starting values \nAdjS=initx;\nVarS=initV;\nLL=zeros(nrow,1); % log-likelihood vector initialization\n\nfor i=1:nrow\n PredS=C+F*AdjS; % eqn c.10\n Q=[(theta1*sigma1*sigma1*(1-exp(-kappa1*dt))^2/(2*kappa1)+sigma1*sigma1/kappa1*(exp(-kappa1*dt)-exp(-2*kappa1*dt)))*AdjS(1),0;...\n 0,(theta2*sigma2*sigma2*(1-exp(-kappa2*dt))^2/(2*kappa2)+sigma2*sigma2/kappa2*(exp(-kappa2*dt)-exp(-2*kappa2*dt)))*AdjS(2)]; % eqn b.4\n VarS=F*VarS*F'+Q; % eqn c.11\n % Step 2\n PredY=A+H*PredS; % eqn c.4\n VarY=H*VarS*H'+R; % eqn c.5\n % Step 3\n PredError=Y(i,:)'-PredY; % eqn c.6\n InvVarY=inv(VarY);\n DetY=det(VarY);\n KalmanGain=VarS*H'*InvVarY; % eqn c.8\n AdjS=PredS+KalmanGain*PredError; % eqn c.7\n VarS=VarS*(1-KalmanGain*H); % eqn c.9\n \n % Step 5\n LL(i)=-(ncol/2)*log(2*pi)-0.5*log(DetY)-0.5*PredError'*InvVarY*PredError; % eqn c.10\nend\nsumll=-sum(LL);\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/27705-kalman-filter-application-two-factor-cir/LLtwoCIR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012655937034, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.7139995447799308}} {"text": "function triangle_wandzura_rule_test04 ( )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_WANDZURA_RULE_TEST04 tests WANDZURA_RULE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 December 2006\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_WANDZURA_RULE_TEST04\\n' );\n fprintf ( 1, ' WANDZURA_RULE returns the points and weights of\\n' );\n fprintf ( 1, ' a Wandzura 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 = wandzura_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 = wandzura_order_num ( rule );\n\n [ xy, w ] = wandzura_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\n return\nend\n", "meta": {"author": "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_wandzura_rule/triangle_wandzura_rule_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8152324915965391, "lm_q1q2_score": 0.7139700113089928}} {"text": "function out=prox_sum_k_largest_abs(x,k,alpha)\n%PROX_SUM_K_LARGEST_ABS computes the proximal operator of the function\n% alpha*(sum of k largest absolute values of x(:))\n%\n% Usage: \n% out = PROX_SUM_K_LARGEST_ABS(x,k,alpha)\n% ===========================================\n% INPUT:\n% x - point to be projected (vector/matrix)\n% k - positive integer\n% alpha - positive scalar\n% ===========================================\n% Assumptions:\n% k in {1,...,length(x(:))}\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\n\nif (nargin < 3)\n error ('usage: prox_sum_k_largest_abs(x,k,alpha)') ;\nend\n\nif (alpha < 0)\n error('usage: prox_sum_k_largest_abs(x,k,alpha) - alpha should be positive')\nend\n\neps = 1e-10 ; % default value\nif ((k < 1) || ( k > length(x(:))) || (abs(round(k) - k) > eps))\n error('usage: prox_sum_k_largest_abs(x,k,alpha) - k should be in {1,...,length(x(:))}')\nend\n\nout = x - alpha * proj_l1ball_box (x/alpha,ones(size(x)),k,ones(size(x))) ;\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_sum_k_largest_abs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7139700007369927}} {"text": "function rad=sec2rad(sec)\n% SEC2RAD Converts seconds of arc to radians. Vectorized.\n% Version: 2 Feb 98\n% Useage: rad=sec2rad(sec)\n% Input: sec - vector of angles in seconds of arc\n% Output: rad - vector of angles in radians\n\n% Copyright (c) 2011, Michael R. Craymer\n% All rights reserved.\n% Email: mike@craymer.com\n\nrad=sec.*pi./180./3600;\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/15285-geodetic-toolbox/geodetic/sec2rad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.713969994839778}} {"text": "function value = r8_besi1 ( x )\n\n%*****************************************************************************80\n%\n%% R8_BESI1 evaluates the Bessel function I of order 1 of an R8 argument.\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 X, the argument.\n%\n% Output, real VALUE, the Bessel function I of order 1 of X.\n%\n persistent bi1cs\n persistent nti1\n persistent xmax\n persistent xmin\n persistent xsml\n\n if ( isempty ( nti1 ) )\n\n bi1cs = [ ...\n -0.19717132610998597316138503218149E-02, ...\n +0.40734887667546480608155393652014, ...\n +0.34838994299959455866245037783787E-01, ...\n +0.15453945563001236038598401058489E-02, ...\n +0.41888521098377784129458832004120E-04, ...\n +0.76490267648362114741959703966069E-06, ...\n +0.10042493924741178689179808037238E-07, ...\n +0.99322077919238106481371298054863E-10, ...\n +0.76638017918447637275200171681349E-12, ...\n +0.47414189238167394980388091948160E-14, ...\n +0.24041144040745181799863172032000E-16, ...\n +0.10171505007093713649121100799999E-18, ...\n +0.36450935657866949458491733333333E-21, ...\n +0.11205749502562039344810666666666E-23, ...\n +0.29875441934468088832000000000000E-26, ...\n +0.69732310939194709333333333333333E-29, ...\n +0.14367948220620800000000000000000E-31 ]';\n\n nti1 = r8_inits ( bi1cs, 17, 0.1 * r8_mach ( 3 ) );\n xmin = 2.0 * r8_mach ( 1 );\n xsml = sqrt ( 8.0 * r8_mach ( 3 ) );\n xmax = log ( r8_mach ( 2 ) );\n\n end\n\n y = abs ( x );\n\n if ( y <= xmin )\n value = 0.0;\n elseif ( y <= xsml )\n value = 0.5 * x;\n elseif ( y <= 3.0 )\n value = x * ( 0.875 + r8_csevl ( y * y / 4.5 - 1.0, bi1cs, nti1 ) );\n elseif ( y <= xmax )\n value = exp ( y ) * r8_besi1e ( x );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_BESI1 - Fatal error!\\n' );\n fprintf ( 1, ' Result overflows.\\n' );\n error ( 'R8_BESI1 - 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/fn/r8_besi1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7139345791182647}} {"text": "function [A,AE] = adjacency_incident_angle_matrix(V,E)\n % ADJACENCY_INCIDENT_ANGLE_MATRIX Compute an adjacency matrix between *edges*\n % where non-zeros are the angles between adjacent edges (edges that share a\n % vertex).\n %\n % [A] = adjacency_incident_angle_matrix(V,E)\n %\n % Inputs:\n % V #V by dim list of vertex positions\n % E #E by 2 list of edge indices into rows of V\n % Outputs:\n % A #E by #E adjacency matrix so that A(i,j) = h ≠ 0 implies that edges\n % E(i,:) and E(j,:) meet at a coincident vertex with angle h.\n % AE #E by #E adjacency_matrix so that A(i,j) ≠ 0 implies that edges \n % E(i,:) and E(j,:) meet at a coincident vertex (just in case h==0)\n %\n\n assert(size(E,1)==size(unique(sort(E,2),'rows'),1));\n\n V2E = sparse(E,repmat(1:size(E,1),2,1)',1,size(V,1),size(E,1));\n spy(V2E)\n AE = V2E'*V2E;\n spy(AE)\n [I,J] = find(triu(AE,1));\n C = sparse(repmat(1:numel(I),4,1)',[E(I,:) E(J,:)],1,numel(I),size(V,1));\n MI = (1:numel(I))';\n % get center vertex\n [~,M2] = max(C==2,[],2);\n C(sub2ind(size(C),MI,M2)) = 0;\n % get other vertex (who cares which order)\n [~,M1] = max(C,[],2);\n C(sub2ind(size(C),MI,M1)) = 0;\n % get other vertex (who cares which order)\n [~,M3] = max(C,[],2);\n V12 = normalizerow(V(M1,:)-V(M2,:));\n V23 = normalizerow(V(M3,:)-V(M2,:));\n H = acos(sum(V12.*V23,2));\n % rebuild A\n A = sparse([I J],[J I],[H H],size(E,1),size(E,1));\nend\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_gptoolbox/mesh/adjacency_incident_angle_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252812, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7139345661725476}} {"text": "% function [lik,likv] = hmm_cl(X,T,K,Mu,Cov,P,Pi);\n% \n% Calculate Likelihood for Hidden Markov Model \n%\n% X - N x p data matrix\n% T - length of each sequence (N must evenly divide by T, default T=N)\n% K - number of states\n% Mu - mean vectors\n% Cov - output covariance matrix (full, tied across states)\n% P - state transition matrix\n% Pi - priors\n%\n% lik - log likelihood of X \n% likv - vector of log likelihoods of each sequence\n%\n% If 0 or 1 output arguments requested, lik is returned. If 2 output\n% arguments requested, [lik likv] is returned.\n% \n% Machine Learning Toolbox\n% Version 1.0 01-Apr-96\n% Copyright (c) by Zoubin Ghahramani\n% http://mlg.eng.cam.ac.uk/zoubin/software.html\n%\n% ------------------------------------------------------------------------------\n% The MIT License (MIT)\n% \n% Copyright (c) 1996, Zoubin Ghahramani\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\nfunction [lik,likv] = ZG_hmm_cl(X,T,K,Mu,Cov,P,Pi)\n\np = length(X(1,:));\nN = length(X(:,1));\ntiny = exp(-700);\n\nif (rem(N,T) ~= 0)\n error('Data matrix length must be multiple of sequence length T');\nend;\nN = N/T;\n\nalpha = zeros(T,K);\nB = zeros(T,K); % P( output | s_i) \n\t\nk1 = (2*pi)^(-p/2);\n\nScale = zeros(T,1);\n\nlikv = zeros(1,N);\n\nfor n = 1:N\n \n B = zeros(T,K); \n iCov = inv(Cov); \n k2 = k1/sqrt(det(Cov));\n for i = 1:T\n for l = 1:K\n d = Mu(l,:)-X((n-1)*T+i,:);\n B(i,l) = k2*exp(-0.5*d*iCov*d');\n end; \n end; \n \n scale = zeros(T,1);\n alpha(1,:) = Pi(:)'.*B(1,:);\n scale(1) = sum(alpha(1,:)); \n alpha(1,:) = alpha(1,:)/(scale(1)+tiny);\n for i = 2:T\n alpha(i,:) = (alpha(i-1,:)*P).*B(i,:); \n scale(i) = sum(alpha(i,:));\n alpha(i,:) = alpha(i,:)/(scale(i)+tiny);\n end;\n\n likv(n) = sum(log(scale+(scale == 0)*tiny));\n Scale = Scale+log(scale+(scale == 0)*tiny);\nend;\n\nlik = sum(Scale);\n\nend", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/ZG_hmm/ZG_hmm_cl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7139345618992713}} {"text": "%% THE FACTORIZE OBJECT for solving linear systems\n%\n% Copyright 2009, Timothy A. Davis, University of Florida. May 19, 2009.\n% davis@cise.ufl.edu\n% http://www.cise.ufl.edu/~davis\n%\n% This is a demonstration of the FACTORIZE object for solving linear\n% systems and least-squares problems, and for computations with the\n% matrix inverse and pseudo-inverse.\n\n%% Rule Number One: never multiply by the inverse, inv(A)\n%\n% Use backslash or a matrix factorization instead (LU, CHOL, or QR).\n\n%% Rule Number Two: never break Rule Number One\n%\n% However, the problem with Rule Number One is that it can be hard to\n% figure out which matrix factorization to use and how to use it.\n% BACKSLASH (MLDIVIDE) is great, but it can't be reused when solving\n% multiple systems (x=A\\b and y=A\\c). Its syntax doesn't match the use of\n% the inverse in mathematical expressions, either.\n%\n% The goal of the FACTORIZE object is to solve this problem ...\n%\n% \"Don't let that INV go past your eyes; to solve that system, FACTORIZE!\"\n\n%% How to use BACKSLASH solve A*x=b\n%\n% First, let's create a square matrix A and a right-hand-side b for a\n% linear system A*x=b. There are many ways to solve this system. The best\n% way is to use x=A\\b. The residual r is a vector of what's left over in\n% each equation, and its norm tells you how accurately the system was\n% solved.\n\nformat compact ;\nA = rand (3)\nb = rand (3,1)\nx = A\\b\nr = b-A*x ;\nnorm (r)\n\n%% BACKSLASH versus INV ... let the battle begin\n%\n% The backslash operation x=A\\b is mathematically the same as x=inv(A)*b.\n% However, backslash is faster and more accurate since it uses a matrix\n% factorization instead of multiplying by the inverse. Even though your\n% linear algebra textbook might write x=A^(-1)*b as the solution to the\n% system A*x=b, your textbook author never means for you to compute the\n% inverse.\n%\n% These next statements give the same answer, so what's the big deal?\n\nS = inv(A) ;\nx = S*b\nx = A\\b\n\n%%\n% The big deal is that you should care about speed and you should care even\n% more about accuracy. BACKSLASH relies on matrix factorization (LU, CHOL,\n% QR, or other specialized methods). It's faster and more reliable than\n% multiplying by the inverse, particularly for large matrices and sparse\n% matrices. Here's an illustration of how pathetic inv(A)*b can be.\n\nA = gallery ('frank',16) ; xtrue = ones (16,1) ; b = A*xtrue ;\n\nx = inv(A)*b ; norm (A*x-b)\nx = A\\b ; norm (A*x-b)\n\n%%\n% The performance difference between BACKSLASH and INV for even small\n% sparse matrices is striking.\n\nload west0479 ;\nA = west0479 ;\nn = size (A,1)\nb = rand (n,1) ;\ntic ; x = A\\b ; toc\nnorm (b-A*x)\ntic ; x = inv(A)*b ; toc\nnorm (b-A*x)\n\n%%\n% What if you want to solve multiple systems? Use a matrix factorization.\n% But which one? And how do you use it? Here are some alternatives using\n% LU for the sparse west0479 matrix, but some are faster than others.\n\ntic ; [L,U] = lu(A) ; x1 = U \\ (L \\ b) ; t1=toc ; nz1=nnz(L+U);\ntic ; [L,U,P] = lu(A) ; x2 = U \\ (L \\ P*b) ; t2=toc ; nz2=nnz(L+U);\ntic ; [L,U,P,Q] = lu(A) ; x3 = Q * (U \\ (L \\ P*b)) ; t3=toc ; nz3=nnz(L+U);\n\nfprintf ('1: nnz(L+U): %5d time: %8.4f resid: %e\\n', nz1,t1, norm(b-A*x1));\nfprintf ('2: nnz(L+U): %5d time: %8.4f resid: %e\\n', nz2,t2, norm(b-A*x2));\nfprintf ('3: nnz(L+U): %5d time: %8.4f resid: %e\\n', nz3,t3, norm(b-A*x3));\n\n%% LU and LINSOLVE are fast and accurate but complicated to use\n%\n% A quick look at ``help lu'' will scroll off your screen. For full\n% matrices, [L,U,p] = lu (A,'vector') is fastest. Then for the\n% forward/backsolves, use LINSOLVE instead of BACKSLASH for even faster\n% performance. But for sparse matrices, use the optional 'Q' output of LU\n% so you get a good fill-reducing ordering. But you can't use 'Q' if the\n% matrix is full. But LINSOLVE doesn't work on sparse matrices.\n%\n% But ... Ack! That's getting complicated ...\n%\n% Here's the best way to solve A*x=b and A*y=c when A is full and\n% unsymmetric:\n\nn = 1000 ;\nA = rand (n) ;\nb = rand (n,1) ;\nc = rand (n,1) ;\ntic ; [L,U,p] = lu (A, 'vector') ; LUtime = toc\n\ntic ; x = U \\ (L \\ b (p,:)) ;\n y = U \\ (L \\ c (p,:)) ; toc\n\ntic ; opL = struct ('LT', true) ;\n opU = struct ('UT', true) ;\n x = linsolve (U, linsolve (L, b(p,:), opL), opU) ;\n y = linsolve (U, linsolve (L, c(p,:), opL), opU) ; toc\n\n%% INV is easy to use, but slow and inaccurate\n%\n% Oh bother! Using LU and LINSOLVE is too complicated. You just want to\n% solve your system. Let's just compute inv(A) and use it twice. Easy to\n% write, but slower and less accurate ...\n\nS = inv (A) ;\nx = S*b ; norm (b-A*x)\ny = S*c ; norm (c-A*y)\n\n%%\n% Sometimes using the inverse seems inevitable. For example, your textbook\n% might show the Schur complement formula as S = A-B*inv(D)*C. This can be\n% done without inv(D) in one of two ways: SLASH or BACKSLASH (MRDIVIDE or\n% MLDIVIDE to be precise).\n%\n% inv(A)*B and A\\B are mathematically equivalent, as are B*inv(A) and B/A,\n% so these three methods give the same results (ignoring computational\n% errors, which are worse for inv(D)). Only the first equation looks like\n% the equation in your textbook, however.\n\nA = rand (200) ; B = rand (200) ; C = rand (200) ; D = rand (200) ;\n\ntic ; S1 = A - B*inv(D)*C ; toc ;\ntic ; S2 = A - B*(D\\C) ; toc ;\ntic ; S3 = A - (B/D)*C ; toc ;\n\n%% So the winner is ... nobody\n%\n% BACKSLASH: mostly simple to use (except remember that Schur complement\n% formuala?). Fast and accurate ... but slow if you want to solve\n% two linear systems with the same matrix A.\n%\n% LU, QR, CHOL: fast and accurate. Awful syntax to use. Drag out your\n% linear algebra textbook if you want to use these in MATLAB.\n% Whenever I use them I have to derive them from scratch, even\n% though I *wrote* most of the sparse factorizations used in MATLAB!\n%\n% INV: slow and inaccurate. Wins big on ease-of-use, though, since it's a\n% direct plug-in for all your nice mathematical formulas.\n%\n% No method is best on all three criterion: speed, accuracy, and ease of\n% use.\n%\n% Is there a solution? Yes ... keeping reading ...\n\n%% The FACTORIZE object to the rescue\n%\n% The FACTORIZE method is just as easy to use as INV, but just as fast and\n% accurate as BACKSLASH, LU, QR, CHOL, and LINSOLVE.\n%\n% F = factorize(A) computes the factorization of A and returns it as an\n% object that you can reuse to solve a linear system with x=F\\b. It picks\n% LU, QR, or Cholesky for you, just like BACKSLASH.\n%\n% S = inverse(A) is simpler yet. It does NOT compute inv(A), but\n% factorizes A. When multiplying S*b, it doesn't mulitply by the inverse,\n% but uses the correct forward/backsolve equations to solve the linear\n% system.\n\nn = 1000 ;\nA = rand (n) ;\nb = rand (n,1) ;\nc = rand (n,1) ;\n\ntic ; x = A\\b ; y = A\\c ; toc\ntic ; S = inv(A) ; x = S*b ; y = S*c ; toc\ntic ; F = factorize(A) ; x = F\\b ; y = F\\c ; toc\ntic ; S = inverse(A) ; x = S*b ; y = S*c ; toc\n\n%% Least-squares problems\n%\n% Here are some different methods for solving a least-squares problem when\n% your system is over-determined. The last two methods are the same.\n\nA = rand (1000,200) ;\nb = rand (1000,1) ;\n\ntic ; x = A\\b ; toc, norm (A'*A*x-A'*b)\ntic ; x = pinv(A)*b ; toc, norm (A'*A*x-A'*b)\ntic ; x = inverse(A)*b ; toc, norm (A'*A*x-A'*b)\ntic ; x = factorize(A)\\b ; toc, norm (A'*A*x-A'*b)\n\n%%\n% FACTORIZE is better than BACKSLASH because you can reuse the\n% factorization for different right-hand-sides. For full-rank matrices,\n% it's better than PINV because it's faster (and PINV fails for sparse\n% matrices).\n\nA = rand (1000,200) ;\nb = rand (1000,1) ;\nc = rand (1000,1) ;\n\ntic ; ; x = A\\b ; y = A\\c ; toc\ntic ; S = pinv(A) ; x = S*b ; y = S*c ; toc\ntic ; S = inverse(A) ; x = S*b ; y = S*c ; toc\ntic ; F = factorize(A) ; x = F\\b ; y = F\\c ; toc\n\n%% Underdetermined systems\n%\n% The under-determined system A*x=b where A has more columns than rows has\n% many solutions. x=A\\b finds a basic solution (some of the entries in x\n% are zero). pinv(A)*b finds a minimum 2-norm solution, but it's slow. QR\n% factorization will do the same if A has full rank. That's what the\n% factorize(A) and inverse(A) methods do.\n\nA = rand (200,1000) ;\nb = rand (200,1) ;\n\ntic ; x = A\\b ; toc, norm (x)\ntic ; x = pinv(A)*b ; toc, norm (x)\ntic ; x = inverse(A)*b ; toc, norm (x)\ntic ; x = factorize(A)\\b ; toc, norm (x)\n\n%% Computing selected entries in the inverse or pseudo-invers\n%\n% If you want just a few entries from the inverse, it's still better to\n% formulate the problem as a system of linear equations and to use a\n% matrix factorization instead of computing inv(A). The FACTORIZE object\n% does this for you, by overloading the subsref operator.\n\nA = rand (1000) ;\n\ntic ; S = inv (A) ; S (2:3,4), toc\ntic ; S = inverse (A) ; S (2:3,4), toc\n\n%% Computing the entire inverse or pseudo-inverse\n%\n% Rarely, and I mean RARELY, you really do need the inverse. More\n% frequently what you want is the pseudo-inverse. You can force a\n% factorization to become a plain matrix by converting it to double. Note\n% that inverse(A) only handles full-rank matrices (either dense or sparse),\n% whereas pinv(A) works for all dense matrices (not sparse).\n\nA = rand (500) ;\ntic ; S1 = inv (A) ; ; toc\ntic ; S2 = double (inverse (A)) ; toc\nnorm (S1-S2)\n\nA = rand (500,400) ;\ntic ; S1 = pinv (A) ; toc\ntic ; S2 = double (inverse (A)) ; toc\nnorm (S1-S2)\n\n%% Update/downdate of a dense Cholesky factorization\n%\n% Wilkinson considered the update/downdate of a matrix factorization to be\n% a key problem in computational linear algebra. The idea is that you\n% first factorize a matrix. Next, make a low-rank change to A, and patch\n% up (or down...) the factorization so that it becomes the factorization of\n% the new matrix. In MATLAB, this only works for dense symmetric positive\n% definite matrices, via cholupdate. This is much faster than computing\n% the new factorization from scratch.\n\nn = 1000 ;\nA = rand (n) ;\nA = A*A' + n*eye (n) ;\nw = rand (n,1) ; t = rand (n,1) ; b = rand (n,1) ;\nF = factorize (A) ;\n\ntic ; F = F + w ; x = F\\b ; toc\ntic ; y = (A+w*w')\\b ; toc\nnorm (x-y)\n\ntic ; F = F - t ; x = F\\b ; toc\ntic ; y = (A+w*w'-t*t')\\b ; toc\nnorm (x-y)\n\n%% Caveat Executor\n%\n% One caveat: If you have a large number of very small systems to solve,\n% the object-oriented overhead of creating and using an object can dominate\n% the run time, at least in MATLAB R2009a. For this case, if you want the\n% best performance, stick with BACKSLASH, or LU and LINSOLVE (just extract\n% the appropriate formulas from factorize.m and mldivide.m in the\n% @factorize directory).\n%\n% Hopefully the object-oriented overhead will drop in future versions of\n% MATLAB, and you can ignore this caveat.\n\nA = rand (10) ; b = rand (10,1) ; F = factorize (A) ;\n\ntic ; for k = 1:10000, x = F\\b ; end ; toc\n\ntic ; for k = 1:10000, x = A\\b ; end ; toc\n\n[L,U,p] = lu (A, 'vector') ;\nopL = struct ('LT', true) ;\nopU = struct ('UT', true) ;\ntic ; \nfor k = 1:10000\n x = linsolve (U, linsolve (L, b(p,:), opL), opU) ;\nend\ntoc\n\n%% Summary\n%\n% So ... don't use INV, and don't worry about how to use LU, CHOL, or QR\n% factorization. Just install the FACTORIZE package, and you're on your\n% way. Assuming you are now in the Factorize/ directory, cut-and-paste\n% these commands into your command window:\n%\n% addpath (pwd)\n% savepath\n%\n% And remember ...\n%\n% \"Don't let that INV go past your eyes; to solve that system, FACTORIZE!\"\n\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/SuiteSparse/MATLAB_Tools/Factorize/factorize_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7138866782053261}} {"text": "function [ n_data, x, fx ] = arcsinh_values ( n_data )\n\n%*****************************************************************************80\n%\n%% ARCSINH_VALUES returns some values of the hyperbolic arc sine function.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% ArcSinh[x]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 June 2007\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 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 X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 20;\n\n fx_vec = [ ...\n -2.3124383412727526203, ...\n -0.88137358701954302523, ...\n 0.00000000000000000000, ...\n 0.099834078899207563327, ...\n 0.19869011034924140647, ...\n 0.29567304756342243910, ...\n 0.39003531977071527608, ...\n 0.48121182505960344750, ...\n 0.56882489873224753010, ...\n 0.65266656608235578681, ...\n 0.73266825604541086415, ...\n 0.80886693565278246251, ...\n 0.88137358701954302523, ...\n 1.4436354751788103425, ...\n 1.8184464592320668235, ...\n 2.0947125472611012942, ...\n 2.3124383412727526203, ...\n 2.9982229502979697388, ...\n 5.2983423656105887574, ...\n 7.6009027095419886115 ];\n\n x_vec = [ ...\n -5.0, ...\n -1.0, ...\n 0.0, ...\n 0.1, ...\n 0.2, ...\n 0.3, ...\n 0.4, ...\n 0.5, ...\n 0.6, ...\n 0.7, ...\n 0.8, ...\n 0.9, ...\n 1.0, ...\n 2.0, ...\n 3.0, ...\n 4.0, ...\n 5.0, ...\n 10.0, ...\n 100.0, ...\n 1000.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/arcsinh_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7138866748841194}} {"text": "function x = sample_paths2_eigen ( n, n2, rhomin, rhomax, rho0, correlation2 )\n\n%*****************************************************************************80\n%\n%% SAMPLE_PATHS2_EIGEN: sample paths for nonstationary correlation functions.\n%\n% Discussion:\n%\n% This function does not assume that the correlation function\n% C(S,T) is actually a function of ||S-T||.\n%\n% This method uses the eigen-decomposition of the correlation matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 November 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points on each path.\n%\n% Input, integer N2, the number of paths.\n%\n% Input, real RHOMIN, RHOMAX, the minimum and maximum values of RHO.\n%\n% Input, real RHO0, the correlation length.\n%\n% Input, @CORRELATION2, a handle for a correlation function, which has\n% the form c = correlation2 ( m, n, s, t, rho0 ).\n%\n% Output, real X(N,N2), the sample paths.\n%\n\n%\n% Choose 2 equal N vectors of equally spaced sample points from RHOMIN to RHOMAX.\n%\n s = linspace ( rhomin, rhomax, n );\n%\n% Evaluate the correlation function.\n%\n cor = correlation2 ( n, n, s, s, rho0 );\n%\n% Get the eigendecomposition of COR:\n%\n% COR = V * D * V'.\n%\n% Because COR is symmetric, V is orthogonal.\n%\n [ v, d ] = eig ( cor );\n%\n% We assume COR is non-negative definite, and hence that there\n% are no negative eigenvalues. If this is not the case,\n% warn the user, hope the numbers are only slightly negative,\n% and reset them to 0.\n%\n dmin = min ( min ( d ) );\n\n if ( dmin < - sqrt ( eps ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SAMPLE_PATHS2_EIGEN - Warning!\\n' );\n fprintf ( 1, ' Negative eigenvalues observed as low as %g\\n', dmin );\n end\n\n d = max ( d, 0.0 );\n%\n% Compute the eigenvalues of the factor C.\n%\n sqrt_d = sqrt ( d );\n%\n% Compute C, such that C' * C = COR.\n%\n c = v * sqrt_d * v';\n%\n% Compute N independent random normal values.\n%\n r(1:n,1:n2) = randn ( n, n2 );\n%\n% Get the variables X which have correlation COR.\n%\n x(1:n,1:n2) = c(1:n,1:n) * r(1:n,1:n2);\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/correlation/sample_paths2_eigen.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7138674585515669}} {"text": "function out=proj_l1_ball(x,r)\n%PROJ_L1_BALL computes the orthogonal projection onto the l1 ball {x: norm(x(:),1) <= r} \n% \n% Usage: \n% out = PROJ_L1_BALL(x,[r])\n% =============================================================\n% x:\n% x - point to be projected (vector/matrix)\n% r - a positive scalar [default: 1]\n% ==============================================================\n% Assumptions:\n% r > 0\n% ==============================================================\n% Output:\n% out - projection vector\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 < 1)\n error ('usage: prox_l1_ball(x,[r])') ;\nend\n\nif (nargin < 2)\n %setting default value to 1\n r = 1;\nend\n\nout = sign(x) .* proj_simplex(abs(x),r,'ineq') ;\n\nend\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/proj_l1_ball.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7138674504874792}} {"text": "function [ x, w ] = rule04 ( n )\n\n%*****************************************************************************80\n%\n%% RULE04 returns the rule of degree 4.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 July 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This 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 N, the number of nodes.\n%\n% Output, real X(3,N), the coordinates of the nodes.\n%\n% Output, real W(N), the weights.\n%\n xs = [ ...\n -.1459612280979987E-01,-.2937244896309993, ...\n 0.3230878337158274,-.8819654179396583E-01, ...\n 0.1270203663314710,-.4414307688091184, ...\n 0.3939418589633429,-.6034469714614210E-01, ...\n -.8914059834601185E-01,0.6545213033603760, ...\n -.7307642259677857 ];\n ys = [ ...\n 0.2426564579199708E-02,0.1764396506764613, ...\n -.1932070410956556,0.2317884270105980E-01, ...\n 0.5451410677215219,-.3848225631590180, ...\n 0.2068744670639530,-.4573739074927080, ...\n 0.7268092659599459,-.3970356243870571, ...\n -.2669420088648982 ];\n zs = [ ...\n 0.7093565780103633,0.1108860494941134, ...\n 0.1695426396704650,-.2011819391325586, ...\n 0.1309503990759315,0.9225429679162532E-01, ...\n -.3111560426198242,-.3302215329322376, ...\n -.3507931737363739,-.2970424833951137, ...\n -.3861037570241846 ];\n ws = [ ...\n 0.1033787090646894,0.1070356256090164, ...\n 0.1504792582740940,0.1877987156186583, ...\n 0.7395274312521298E-01,0.7712199925411270E-01, ...\n 0.6745419368701999E-01,0.5819413648173244E-01, ...\n 0.5378646711152148E-01,0.5366953183949744E-01, ...\n 0.3811216334909158E-01 ];\n\n x(1,1:n) = xs(1:n);\n x(2,1:n) = ys(1:n);\n x(3,1:n) = zs(1:n);\n w(1:n) = ws(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/tetrahedron_arbq_rule/rule04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616712, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7138674383273321}} {"text": "% QUATERNION MULTIPLICATION\nfunction [qv] = qMultiply(q,v)\n% Calculate the product of two quaternions\n% Associated block:\n% \"Quaternion Multiplication\"\n% Multiply the quaternion elements\n\nassert(size(q,1) == 4 && size(v,1) == 4,...\n 'Both quaternion must be provided as 4x1 column vectors')\n% Quaternion projection matrix\nqv = [v(1), -v(2), -v(3), -v(4);\n v(2), v(1), -v(4), v(3);\n v(3), v(4), v(1), -v(2);\n v(4), -v(3), v(2), v(1)]*q; % Confirmed with matlab website\n% Re-normalise the output\nqv = unit(qv);\nend", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/environment/common/qMultiply.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.7138576424150055}} {"text": "function Gs = lp_trfia(freq,A,B,C,D,E)\n%\n% Computes the transfer function for systems\n% .\n% E*x = A*x + B*u\n% y = C*x + D*u\n%\n% on the imaginary axis (more precisely, on the points \n% sqrt(-1)*freq(i), where i = 1,...,length(freq) ). This routine can only \n% be applied to systems, where the matrices are given explicitely.\n%\n% Calling sequence:\n%\n% Gs = lp_trfia(freq,A,B,C,D,E)\n%\n% Input:\n%\n% freq (row) vector containing frequency points; \n% A system matrix A (n-x-n matrix);\n% B system matrix B (n-x-m matrix);\n% C system matrix C (q-x-n matrix);\n% D system matrix D (q-x-m matrix);\n% Set D = [] if D is not existing or the zero matrix!\n% E system matrix E. Set E = [] if E is not existing or the \n% (sparse) identity matrix!\n%\n% Output:\n%\n% Gs transfer function sampling matrix, which is a\n% q*m-x-length(freq) matrix);\n% Gs(:,i) contains the stacked columns of the matrix\n% D + C*(sqrt(-1)*freq(i)*E-A)^(-1)*B.\n%\n% Remarks: \n%\n% The vector freq can easily be computed by the function 'lp_lpfrq'.\n%\n% The permutation of the matrices A and/or E before calling this\n% routine is not necessary.\n%\n%\n% LYAPACK 1.0 (Thilo Penzl, May 1999)\n\n% Input data not completely checked!\n\nna = nargin;\n\nif length(A)==0,\n Gs = [];\n return;\nend\n\nif na<6, E = []; end\nwith_E = length(E)>0;\nwith_D = length(D)>0;\n\n[n,m] = size(B);\nq = size(C,1);\nnop = length(freq);\n\nif ~with_D\n D = zeros(q,m);\nend\n\nGs = zeros(m*q,nop);\n\nj = sqrt(-1);\n\nfor i = 1:nop\n if with_E\n G0 = D + C*(((j*freq(i))*E-A)\\B);\n else\n G0 = D + C*(((j*freq(i))*speye(n)-A)\\B);\n end\n for k = 1:m\n Gs((k-1)*q+1:k*q,i) = G0(:,k);\n end\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/21-lyapack/lyapack/routines/lp_trfia.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7138576379033232}} {"text": "% Section 7.5.2: Experiment design\n% Boyd & Vandenberghe, \"Convex Optimization\"\n% Original version by Lieven Vandenberghe\n% Updated for CVX by Almir Mutapcic - Jan 2006\n% (a figure is generated)\n%\n% This is an example of D-optimal, A-optimal, and E-optimal\n% experiment designs.\n\n% problem data\nm = 10;\nangles1 = linspace(3*pi/4,pi,m);\nangles2 = linspace(0,-pi/2,m);\n\n% sensor positions\nV = [3.0*[cos(angles1); sin(angles1)], ...\n 1.5*[cos(angles2); sin(angles2)]];\np = size(V,2);\nn = 2;\nnoangles = 5000;\n\n% D-optimal design\n%\n% maximize log det V*diag(lambda)*V'\n% subject to sum(lambda)=1, lambda >=0\n%\n\n% setup the problem and solve it\ncvx_begin\n variable lambda(p)\n maximize ( det_rootn( V*diag(lambda)*V' ) )\n subject to\n sum(lambda) == 1;\n lambda >= 0;\ncvx_end\nlambdaD = lambda; % save the solution for confidence ellipsoids\n\n% plot results\nfigure(1)\n% draw ellipsoid v'*W*v <= 2\nW = inv(V*diag(lambda)*V');\nangles = linspace(0,2*pi,noangles);\nR = chol(W); % W = R'*R\nellipsoid = sqrt(2)*(R\\[cos(angles); sin(angles)]);\nd = plot(ellipsoid(1,:), ellipsoid(2,:), '--', 0,0,'+');\nset(d, 'Color', [0 0.5 0]); set(d(2),'MarkerFaceColor',[0 0.5 0]);\nhold on;\n\ndot=plot(V(1,:),V(2,:),'o');\nind = find(lambda > 0.001);\ndots = plot(V(1,ind),V(2,ind),'o');\nset(dots,'MarkerFaceColor','blue');\n\n% print out nonzero lambda\ndisp('Nonzero lambda values for D design:');\nfor i=1:length(ind)\n text(V(1,ind(i)),V(2,ind(i)), ['l',int2str(ind(i))]);\n disp(['lambda(',int2str(ind(i)),') = ', num2str(lambda(ind(i)))]);\nend;\n\n%axis([-4.5 4.5 -4.5 4.5])\naxis([-5 5 -5 5])\nset(gca,'Xtick',[]);\nset(gca,'Ytick',[]);\nhold off, axis off\n% print -deps Ddesign.eps\n\n% A-optimal design\n%\n% minimize Trace (sum_i lambdai*vi*vi')^{-1}\n% subject to lambda >= 0, 1'*lambda = 1\n%\n\n% SDP formulation\ne = eye(2,2);\ncvx_begin sdp\n variables lambda(p) u(n)\n minimize ( sum(u) )\n subject to\n for k = 1:n\n [ V*diag(lambda)*V' e(:,k);\n e(k,:) u(k) ] >= 0;\n end\n sum(lambda) == 1;\n lambda >= 0;\ncvx_end\nlambdaA = lambda; % save the solution for confidence ellipsoids\n\n% plot results\nfigure(2)\n% draw ellipsoid v'*W*v <= mu\nW = inv(V*diag(lambda)*V')^2;\nmu = diag(V'*W*V);\nmu = mean(mu(ind));\nangles = linspace(0,2*pi,noangles);\nR = chol(W); % W = R'*R\nellipsoid = sqrt(mu)*(R\\[cos(angles); sin(angles)]);\nd = plot(ellipsoid(1,:), ellipsoid(2,:), '--',0,0,'+');\nset(d, 'Color', [0 0.5 0]);\nset(d(2), 'MarkerFaceColor', [0 0.5 0]);\nhold on\n\ndot = plot(V(1,:),V(2,:),'o');\nind = find(lambda > 0.001);\ndots = plot(V(1,ind),V(2,ind),'o');\nset(dots,'MarkerFaceColor','blue');\n\ndisp('Nonzero lambda values for A design:');\nfor i=1:length(ind)\n text(V(1,ind(i)),V(2,ind(i)), ['l',int2str(ind(i))]);\n disp(['lambda(',int2str(ind(i)),') = ', num2str(lambda(ind(i)))]);\nend;\n%axis([-4.5 4.5 -4.5 4.5])\naxis([-5 5 -5 5])\nset(gca,'Xtick',[]);\nset(gca,'Ytick',[]);\naxis off, hold off\n% print -deps Adesign.eps\n\n% E-optimal design\n%\n% minimize w\n% subject to sum_i lambda_i*vi*vi' >= w*I\n% lambda >= 0, 1'*lambda = 1;\n%\n\ncvx_begin sdp\n variables t lambda(p)\n maximize ( t )\n subject to\n V*diag(lambda)*V' >= t*eye(n,n);\n sum(lambda) == 1;\n lambda >= 0;\ncvx_end\n\nlambdaE = lambda; % save the solution for confidence ellipsoids\n\nfigure(3)\n% draw ellipsoid v'*W*v <= mu\nmu = diag(V'*W*V);\nmu = mean(mu(ind));\nangles = linspace(0,2*pi,noangles);\nR = chol(W); % W = R'*R\nellipsoid = sqrt(mu)*(R\\[cos(angles); sin(angles)]);\nd = plot(ellipsoid(1,:), ellipsoid(2,:), '--', 0, 0, '+');\nset(d, 'Color', [0 0.5 0]);\nset(d(2), 'MarkerFaceColor', [0 0.5 0]);\nhold on\n\ndot = plot(V(1,:),V(2,:),'o');\nlambda = lambda(1:p);\nind = find(lambda > 0.001);\ndots = plot(V(1,ind),V(2,ind),'o');\nset(dots,'MarkerFaceColor','blue');\n\ndisp('Nonzero lambda values for E design:');\nfor i=1:length(ind)\n text(V(1,ind(i)),V(2,ind(i)), ['l',int2str(ind(i))]);\n disp(['lambda(',int2str(ind(i)),') = ', num2str(lambda(ind(i)))]);\nend;\n%axis([-4.5 4.5 -4.5 4.5])\naxis([-5 5 -5 5])\nset(gca,'Xtick',[]);\nset(gca,'Ytick',[]);\naxis off, hold off\n% print -deps Edesign.eps\n\n\n% confidence ellipsoids\neta = 6.2514; % chi2inv(.9,3) value (command available in stat toolbox)\n% draw 90 percent confidence ellipsoid for D design\nW = V*diag(lambdaD)*V';\nangles = linspace(0,2*pi,noangles);\nR = chol(W); % W = R'*R\nellipsoid = sqrt(eta)*(R\\[cos(angles); sin(angles)]);\n\nfigure(4)\nplot(0,0,'ok',ellipsoid(1,:), ellipsoid(2,:), '-');\ntext(ellipsoid(1,1100),ellipsoid(2,1100),'D');\nhold on\n\n% draw 90 percent confidence ellipsoid for A design\nW = V*diag(lambdaA)*V';\nangles = linspace(0,2*pi,noangles);\nR = chol(W); % W = R'*R\nellipsoid = sqrt(eta)*(R\\[cos(angles); sin(angles)]);\nplot(0,0,'ok',ellipsoid(1,:), ellipsoid(2,:), '-');\ntext(ellipsoid(1,1),ellipsoid(2,1),'A');\n\n% draw 90 percent confidence ellipsoid for E design\nW = V*diag(lambdaE)*V';\nangles = linspace(0,2*pi,noangles);\nR = chol(W); % W = R'*R\nellipsoid = sqrt(eta)*(R\\[cos(angles); sin(angles)]);\nd=plot(0,0,'ok',ellipsoid(1,:), ellipsoid(2,:), '-');\nset(d,'Color',[0 0.5 0]);\ntext(ellipsoid(1,4000),ellipsoid(2,4000),'E');\n\n% draw 90 percent confidence ellipsoid for uniform design\nW_u = inv(V*V'/p);\nR = chol(W_u); % W = R'*R\nellipsoid_u = sqrt(eta)*(R\\[cos(angles); sin(angles)]);\nplot(ellipsoid_u(1,:), ellipsoid_u(2,:), '--');\ntext(ellipsoid_u(1),ellipsoid_u(2),'U');\nset(gca,'Xtick',[]);\nset(gca,'Ytick',[]);\naxis off\n% print -deps confidence.eps\nhold off\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/cvxbook/Ch07_statistical_estim/expdesign.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.787931185683219, "lm_q1q2_score": 0.7138576293915798}} {"text": "function a = gk324 ( m, n, x )\n\n%*****************************************************************************80\n%\n%% GK324 returns the GK324 matrix.\n%\n% Discussion:\n%\n% This is Gregory and Karney example matrix 3.24.\n%\n% Example:\n%\n% M = N = 5\n%\n% X = ( 11, 12, 13, 14 )\n%\n% 1 1 1 1 1\n% 11 1 1 1 1\n% 11 12 1 1 1\n% 11 12 13 1 1\n% 11 12 13 14 1\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% 18 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Robert Gregory, David Karney,\n% A Collection of Matrices for Testing Computational Algorithms,\n% Wiley, 1969, page 51, \n% LC: QA263.G68.\n%\n% Parameters:\n%\n% Input, integer M, N, the order of the matrix.\n%\n% Input, \n% * real X(N-1), the first N-1 entries of the\n% last row, if M <= N, \n% or \n% * real X(N), the N entries of the last row,\n% if N < M.\n%\n% Output, real A(M,N), the matrix.\n%\n a = zeros ( m, n );\n\n for i = 1 : m\n for j = 1 : n\n if ( i <= j )\n a(i,j) = 1.0;\n else\n a(i,j) = x(j);\n end\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/test_mat/gk324.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.713841018626443}} {"text": "function box_display_test04 ( )\n\n%*****************************************************************************80\n%\n%% BOX_DISPLAY_TEST04 plots Smolyak Clenshaw Curtis index sets.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BOX_DISPLAY_TEST04:\\n' );\n fprintf ( 1, ' Plot Smolyak Clenshaw Curtis monomial indices.\\n' );\n fprintf ( 1, '\\n' );\n\n m = 20;\n n = 20;\n title_string = 'Log2(X-1)+Log2(Y-1) <= 1';\n box_display ( m, n, @cc_0, @cc_1, title_string );\n print ( '-dpng', 'cc1.png' );\n fprintf ( 1, ' Created \"cc1.png\".\\n' );\n\n m = 20;\n n = 20;\n title_string = 'Log2(X-1)+Log2(Y-1) <= 2';\n box_display ( m, n, @cc_1, @cc_2, title_string );\n print ( '-dpng', 'cc2.png' );\n fprintf ( 1, ' Created \"cc2.png\".\\n' );\n\n m = 20;\n n = 20;\n title_string = 'Log2(X-1)+Log2(Y-1) <= 3';\n box_display ( m, n, @cc_2, @cc_3, title_string );\n print ( '-dpng', 'cc3.png' );\n fprintf ( 1, ' Created \"cc3.png\".\\n' );\n\n m = 20;\n n = 20;\n title_string = 'Log2(X-1)+Log2(Y-1) <= 4';\n box_display ( m, n, @cc_3, @cc_4, title_string );\n print ( '-dpng', 'cc4.png' );\n fprintf ( 1, ' Created \"cc4.png\".\\n' );\n\n m = 20;\n n = 20;\n title_string = 'Log2(X-1)+Log2(Y-1) <= 5';\n box_display ( m, n, @cc_4, @cc_5, title_string );\n print ( '-dpng', 'cc5.png' );\n fprintf ( 1, ' Created \"cc5.png\".\\n' );\n\n m = 20;\n n = 20;\n title_string = 'Log2(X-1)+Log2(Y-1) <= 6';\n box_display ( m, n, @cc_5, @cc_6, title_string );\n print ( '-dpng', 'cc6.png' );\n fprintf ( 1, ' Created \"cc6.png\".\\n' );\n\n m = 20;\n n = 20;\n title_string = 'Log2(X-1)+Log2(Y-1) <= 7';\n box_display ( m, n, @cc_6, @cc_7, title_string );\n print ( '-dpng', 'cc7.png' );\n fprintf ( 1, ' Created \"cc7.png\".\\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/box_display/box_display_test04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.713840995463306}} {"text": "function [z_ic A T mean_z] = myICA(z,NUM,varargin)\n%--------------------------------------------------------------------------\n% Syntax: z_ic = myICA(z,NUM);\n% z_ic = myICA(z,NUM,'true');\n% z_ic = myICA(z,NUM,'false');\n% [z_ic A T mean_z] = myICA(z,NUM);\n% [z_ic A T mean_z] = myICA(z,NUM,'true');\n% [z_ic A T mean_z] = myICA(z,NUM,'false');\n%\n% Inputs: z is an M x N matrix containing N samples of an\n% M-dimensional multivariate random variable\n%\n% NUM is the desired number of independent components.\n%\n% display can be {'true','false'}. The default is 'true'.\n%\n% Outputs: z_ic is a NUM x N matrix containing the NUM independent\n% components (scaled to have variance 1) of each of the N\n% samples in z.\n%\n% A and T are the ICA transformation matrices such that:\n% z_LD = T \\ pinv(A) * z_ic + repmat(mean_z,1,size(z,2));\n% is the NUM-dimensional ICA approximation of z\n%\n% mean_z is the M x 1 sample mean vector of z.\n%\n% Description: This function performs independent component analysis (ICA)\n% on the input samples of a multivariate random variable and\n% returns the NUM independent components of each sample.\n%\n% Author: Brian Moore\n% brimoor@umich.edu\n%\n% Date: July 20, 2012\n%--------------------------------------------------------------------------\n\neps = 1e-4; % Convergence criteria\nmaxSamples = 1000; % Max number of data points in sample mean calculations\nmaxIters = 100; % Maximum number of iterations allowed\n\n% Parse user input\nif (nargin == 3)\n display = varargin{1};\nelse\n display = 'true';\nend\n\n% Center and whiten the input data\n[z_cw T mean_z] = myCenterAndWhiten(z);\n\n% Get data dimension\n[m,n] = size(z_cw);\n\nif (n > maxSamples)\n % Draw maxSamples data points at random for sample mean calculations\n z_cw_trimmed = z_cw(:,randperm(n,maxSamples));\nelse\n % Use all data points for sample mean calculations\n z_cw_trimmed = z_cw;\nend\n\n% Choose random weights initially\nw = rand(NUM,m);\nfor i = 1:NUM\n w(i,:) = w(i,:) / norm(w(i,:));\nend\n\n% Initialize loop variables\nerr = ones(NUM,1);\nits = 0;\n\nwhile ((max(err) > eps) && (its < maxIters))\n % Increment iteration counter\n its = its + 1;\n \n % Save last weight matrix\n w_old = w;\n \n % for each weight vector\n for i = 1:NUM\n % Last independent components\n si = w_old(i,:) * z_cw_trimmed;\n \n % Compute negentropy scores\n % negentropy function : f(u) = -exp(-u^2/2)\n g = si .* exp(-0.5 * (si.^2));\n gp = -1.0 * ((si.^2) .* exp(-0.5 * (si.^2)));\n \n % Update weights in the direction of maximum negentropy\n w(i,:) = mean(z_cw_trimmed .* repmat(g,m,1),2)' - mean(gp) * w_old(i,:);\n \n % Normalize weight vector\n w(i,:) = w(i,:) / norm(w(i,:));\n end\n \n % Decorrelate weight vectors\n [U,S,~] = svd(w,'econ');\n Sinv = diag(1./diag(S));\n w = U * Sinv * U' * w;\n \n % Compute innovation\n for i = 1:NUM\n err(i) = 1 - w(i,:) * w_old(i,:)';\n end\n \n % Display innovation\n if strcmpi(display,'true')\n disp(['Iteration ' num2str(its) ': max(1 - ) = ' num2str(max(err))])\n end\nend\n\n% Return transformation matrix\nA = w;\n\n% Compute independent components\nz_ic = A * z_cw;\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/38300-pca-and-ica-package/PCA and ICA/myICA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7138277763085293}} {"text": "function pdf = discrete_pdf ( x, a, b )\n\n%*****************************************************************************80\n%\n%% DISCRETE_PDF evaluates the Discrete PDF.\n%\n% Discussion:\n%\n% PDF(X)(A,B) = B(X) if 1 <= X <= A\n% = 0 otherwise\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer X, the item whose probability is desired.\n%\n% Input, integer A, the number of probabilities assigned.\n%\n% Input, real B(A), the relative probabilities of\n% outcomes 1 through A. Each entry must be nonnegative.\n%\n% Output, real PDF, the value of the PDF.\n%\n b_sum = sum ( b(1:a) );\n\n if ( 1 <= x & x <= a )\n pdf = b(x) / b_sum;\n else\n pdf = 0.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/discrete_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7138277736691127}} {"text": "function pass = test_linearKDV( pref )\n% Check that we can solve linear KDV equations. \n% Alex Townsend, April 2013. \n\nif ( nargin < 1 ) \n pref = chebfunpref(); \nend \ntol = 100*pref.cheb2Prefs.chebfun2eps;\n\n% Simple example. \nd = [-1 1 0 1];\nexact = chebfun2(@(x,t) exp(-t).*exp(x),d);\n\nN = chebop2(@(u) diffy(u) + diffx(u,3),d);\nN.dbc = @(x) exp(x);\nN.rbc = @(t,u) [u - exp(-t).*exp(1) ; diff(u)-exp(-t).*exp(1)];\nN.lbc = @(t) exp(-t).*exp(-1);\nu = N \\ 0;\n \npass(1) = ( norm(u-exact) < tol); \n\n\n% Another simple example. \nd = [-1 1 0 1];\nexact = chebfun2(@(x,t) exp(-t).*exp(x),d);\n\nN = chebop2(@(u) diffy(u) + diffx(u,3),d);\nN.dbc = @(x) exp(x);\nN.rbc = @(t,u) [u - exp(-t).*exp(1) ; diff(u)-exp(-t).*exp(1)];\nN.lbc = @(t,u) diff(u) - exp(-t).*exp(-1);\nu = N \\ 0;\n \npass(2) = ( norm(u-exact) < 2*tol); \n\n% Different boundary conditions. \nd = [-1 1 0 1];\nexact = chebfun2(@(x,t) exp(-t).*exp(x),d);\n\nN = chebop2(@(u) diffy(u) + diffx(u,3),d);\nN.dbc = @(x) exp(x);\nN.rbc = @(t,u) [u - exp(-t).*exp(1) ; diff(u,2)-exp(-t).*exp(1)];\nN.lbc = @(t,u) diff(u) - exp(-t).*exp(-1);\nu = N \\ 0;\n \npass(3) = ( norm(u-exact) < 300*tol);\n\n% Different boundary conditions. \nd = [-1 1 0 1];\nexact = chebfun2(@(x,t) exp(-t).*exp(x),d);\n\nN = chebop2(@(u) diffy(u) + diffx(u,3),d);\nN.dbc = @(x) exp(x);\nN.rbc = @(t,u) [u - exp(-t).*exp(1) ; diff(u,2)-exp(-t).*exp(1)];\nN.lbc = @(t,u) u - exp(-t).*exp(-1);\nu = N \\ 0;\n \npass(4) = ( norm(u-exact) < 100*tol); \n\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/tests/chebop2/test_linearKDV.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7138277721213028}} {"text": "function order = circle_xy_size ( rule )\n\n%*****************************************************************************80\n%\n%% CIRCLE_XY_SIZE sizes an XY quadrature rule inside the unit circle in 2D.\n%\n% Integration region:\n%\n% X*X + Y*Y <= 1.0.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 02 April 2008\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% Frank Lether,\n% A Generalized Product Rule for the Circle,\n% SIAM Journal on Numerical Analysis,\n% Volume 8, Number 2, June 1971, pages 249-253.\n%\n% Arthur Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971,\n% ISBN: 0130438936,\n% LC: QA311.S85.\n%\n% Parameters:\n%\n% Input, integer RULE, the rule desired.\n% 1, 1 point 1-st degree;\n% 2, 4 point 3-rd degree, Stroud S2:3-1;\n% 3, 4 point 3-rd degree, Lether #1;\n% 4, 4 point 3-rd degree, Stroud S2:3-2;\n% 5, 5 point 3-rd degree;\n% 6, 7 point 5-th degree;\n% 7, 9 point 5-th degree;\n% 8, 9 point 5-th degree, Lether #2;\n% 9, 12 point 7-th degree;\n% 10, 16 point 7-th degree, Lether #3;\n% 11, 21 point 9-th degree, Stroud S2:9-3;\n% 12, 25 point 9-th degree, Lether #4 (after correcting error);\n% 13, 64 point 15-th degree Gauss product rule.\n%\n% Output, integer ORDER, the order of the desired rule.\n%\n if ( rule == 1 )\n\n order = 1;\n\n elseif ( rule == 2 )\n\n order = 4;\n\n elseif ( rule == 3 )\n\n order = 4;\n\n elseif ( rule == 4 )\n\n order = 4;\n\n elseif ( rule == 5 )\n\n order = 5;\n\n elseif ( rule == 6 )\n\n order = 7;\n\n elseif ( rule == 7 )\n\n order = 9;\n\n elseif ( rule == 8 )\n\n order = 9;\n\n elseif ( rule == 9 )\n\n order = 12;\n\n elseif ( rule == 10 )\n\n order = 16;\n\n elseif ( rule == 11 )\n\n order = 21;\n\n elseif ( rule == 12 )\n\n order = 25;\n\n elseif ( rule == 13 )\n\n order = 64;\n\n else\n\n order = -1;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CIRCLE_XY_SIZE - Fatal error!\\n' );\n fprintf ( 1, ' There is no rule of index %d\\n', rule );\n error ( 'CIRCLE_XY_SIZE - Fatal error!\\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/stroud/circle_xy_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8198933293122507, "lm_q1q2_score": 0.7137968873799639}} {"text": "function wts = cliqfs ( nt, t, kind, alpha, beta, lo )\n\n%*****************************************************************************80\n%\n%% CLIQFS computes the weights of a quadrature formula in the default interval.\n%\n% Discussion:\n%\n% This routine computes the weights of an interpolatory quadrature formula\n% with a classical weight function, in the default interval A, B,\n% using only simple knots.\n%\n% It can optionally print knots and weights and a check of the moments.\n%\n% To evaluate a quadrature computed by CLIQFS, call EIQFS.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real T(NT), the knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, integer LO, chooses the printing option.\n% > 0, compute weights, print them, print the moment check results.\n% 0, compute weights.\n% < 0, compute weights and print them.\n%\n% Output, real WTS(NT), the weights.\n%\n key = 1;\n\n mlt = zeros(nt,1);\n mlt(1:nt) = 1;\n\n ndx = zeros(nt,1);\n\n wts = ciqfs ( nt, t, mlt, nt, ndx, key, kind, alpha, beta, lo );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/toms655/cliqfs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.8198933271118222, "lm_q1q2_score": 0.7137968854642769}} {"text": "function new_model = rotate_3D_model_around_z(model,phi)\n\nr = [cosd(phi) -sind(phi) 0 ; sind(phi) cosd(phi) 0 ; 0 0 1];\nnew_model = transform_3d_rigid(model,r,[0;0;0]);\n\nend\n\n", "meta": {"author": "lmb-freiburg", "repo": "orion", "sha": "db5df75e16e3068952e65a08cfb04bb7e353ce34", "save_path": "github-repos/MATLAB/lmb-freiburg-orion", "path": "github-repos/MATLAB/lmb-freiburg-orion/orion-db5df75e16e3068952e65a08cfb04bb7e353ce34/tools/general/rotate_3D_model_around_z.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7137738086656762}} {"text": "% JCR library for cretaceous chalk\ndata{3}=[0.079 0.1\n0.1 0.02\n0.3 0.015\n0.54 0.0\n0.68 -0.4\n0.747 -0.7];\n% fit model to data\npc1=data{3}(:,2)*1e5; % Pa\nsw1=data{3}(:,1);\nsw_plot=linspace(0,1,5000);\n% pc_plot=interp1(sw, pc, sw_plot, 'linear', 'extrap');\n% plot(sw, pc, 'o', sw_plot, pc_plot)\n% plot(diff(pc_plot)./diff(sw_plot))\n% log(pc)=log(pce)-(1/labda)*log((sw-sw0)/(1-sw0-sor))\n% ind0=find(pc==0, 1);\n% p1=polyfit(sw(1:ind0-1), log(pc(1:ind0-1)), 1)\n% plot(sw(1:ind0-1), log(pc(1:ind0-1)), 'o')\n\n% pc=@(sw, cwi, coi, awi, aoi, swc, sor)(cwi./((sw-swc)/(1-swc)).^awi+coi./((1-sw-sor)/(1-sor)).^aoi);\n% swc0=0.0789;\n% sor0=0.2529;\n% labda=2.4;\n% f=@(x, sw)pc(sw, x(1), x(2), 1/labda, 1/labda, swc0, sor0);\n% f2=@(x, sw)pc(sw, x(1), x(2), x(3), x(4), swc0, sor0);\n% fw=@(x, sw)pc(sw, x(1), 0.0 , x(3), x(4), swc0, sor0);\n% fo=@(x, sw)pc(sw, 0.0, x(2), x(3), x(4), swc0, sor0);\n% % x=lsqcurvefit(f2, [1e3, -1e3, 1.0, 1.0],sw1, pc1)\n% x=lsqnonlin(@(x)(sum((f2(x, sw1)-pc1).^2)), [0.5e3, -1e3, 1.0, 1.0])\n% fit a spline\n% first, do an extrapolation to assign values to sw=0 and sw=1\nsw_end = [0,1];\npc_end = interp1(sw1, pc1, sw_end, 'linear', 'extrap');\npc_pp = makima([sw_end(1); sw1; sw_end(2)], [pc_end(1); pc1; pc_end(2)]);\npc = @(sw)ppval(pc_pp, sw);\npcder = @(sw)ppval(fnder(pc_pp, 1), sw);\nplot(sw1, pc1, 'o', sw_plot, pc(sw_plot), '--' )%, ...\n% sw_plot, fw(x, sw_plot), '--', ...\n% sw_plot, fo(x, sw_plot), '-.'); \ngrid;\n\n% Note:\n% Looking at the above data, it is better to go with interpolation of the\n% data\n% note 2: fnder requires spline toolbox\n% see this: https://se.mathworks.com/matlabcentral/answers/95194-how-do-i-find-the-derivative-of-a-spline-curve-in-matlab-7-9-r2009b", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Examples/Advanced/pc_chalk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.7137737893775769}} {"text": "function x = grid2 ( i1, i2, ndim, nstep, x1, x2 )\n\n%*****************************************************************************80\n%\n%% GRID2 computes grid points between X1 and X2 in N dimensions.\n%\n% Discussion:\n%\n% However, X1 need not be the first point computed, nor X2 the last.\n% The user must specify the steps on which X1 and X2 are passed\n% through. These steps may even be outside the range of 1 through NSTEP.\n%\n% We assume that a set of equally spaced points have\n% been drawn on the line through X1 and X2, and that\n% they have been numbered, with X1 labeled I1 and X2\n% labeled I2. I1 or I2 may be between 1 and NSTEP,\n% in which case X1 or X2 will actually be returned in the\n% X array, but there is no requirement that I1 or I2\n% satisfy this condition.\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% Parameters:\n%\n% Input, integer I1, I2. I1 specifies the step on which\n% X1 would be computed, and similarly for I2.\n% I1 and I2 must be distinct.\n%\n% Input, integer NDIM, the dimension of the points X1 and X2.\n%\n% Input, integer NSTEP, this is the number of equally\n% spaced points that are to be generated.\n% NSTEP should be at least 1.\n%\n% Input, real X1(NDIM), X2(NDIM), the points that define\n% the line along which the equally spaced points are generated, and\n% which may or may not be included in the set of computed points.\n%\n% Output, real X(NDIM,NSTEP), the set of equally spaced points.\n% Each column of X represents one point.\n% If 1 <= I1 <= NSTEP, then X(*,I1) = X1, and similarly for I2.\n%\n if ( i1 == i2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'GRID2 - Fatal error!\\n' );\n fprintf ( 1, ' I1 = I2, leading to zero denominator.\\n' );\n fprintf ( 1, ' I1 = %d\\n', i1 );\n fprintf ( 1, ' I2 = %d\\n', i2 );\n error ( 'GRID2 - Fatal error!' );\n end\n\n for i = 1 : nstep\n for j = 1 : ndim\n x(j,i) = ( ( i2 - i ) * x1(j) ...\n + ( i - i1 ) * x2(j) ) ...\n / ( i2 - i1 );\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/subpak/grid2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.849971175657575, "lm_q1q2_score": 0.7137496609238081}} {"text": "function p = vonMises_prob( x, m, k, use_log )\n%VONMIS_PROB Calculates the probability of x coming from a Von Mises\n%distribution with mean mu and concentration parameter k. \n% p = vonMises_prob( x, m, k, use_log )\n\nif nargin < 4, use_log = 0; end\n[d N] = size(x);\n\nm = m(:);\nM = m*ones(1,N);\n\ndenom = (2*pi)*besseli(0,k);\nmahal = (k*cos(x-M)); \n\nif use_log\n p = mahal-log(denom);\nelse\n p = exp(mahal)/denom;\nend\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/KPMstats/vonMises_prob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7136162503895355}} {"text": "function y=logsum(x,d,k)\n%LOGSUM logsum(x,d,k)=log(sum(k.*exp(x),d))\n%\n% Usage: (1) y=logsum(x) % log(sum(exp(x)))\n% (2) f=0.1*log(10); y=logsm(x*f)/f; % add powers in dB\n%\n% Inputs: X(M,N,...) data matrix to sum\n% D optional dimension to sum along [1st non-singular dimension]\n% K(M,N,...) optional scaling matrix. It must either be idential\n% in size to X, or else be a vector whose length is\n% equal to the size of dimension D of X\n%\n% Outputs: Y(1,N,...) = log(sum(exp(X).*K,D))\n%\n% This routine evaluates the given expression for Y but takes care to avoid\n% overflow or underflow.\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: logsum.m 8178 2016-07-12 06:57:25Z 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==1 || ~numel(d)\n d=[find(size(x)-1) 1];\n d=d(1);\nend\nn=size(x,d);\nif n<=1, % use efficient computation if only one term in the sum\n if nargin<3\n y=x;\n else\n y=x+log(k);\n end\n return;\nend\ns=size(x);\np=[d:ndims(x) 1:d-1];\nz=reshape(permute(x,p),n,prod(s)/n);\nq=max(z,[],1); % we subtract y from each row to avoid dynamic range problems\na=(q==Inf)|(q==-Inf); % check for infinities\nif nargin<3\n y=q+log(sum(exp(z-q(ones(n,1),:)),1));\nelseif numel(k)==n\n y=q+log(sum(exp(z-q(ones(n,1),:)).*repmat(k(:),1,prod(s)/n),1));\nelse\n y=q+log(sum(exp(z-q(ones(n,1),:)).*reshape(permute(k,p),n,prod(s)/n),1));\nend\ny(a)=q(a); % correct any column whose max is +-Inf\ns(d)=1; % update the dimension of the summed component\ny=ipermute(reshape(y,s(p)),p);\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/logsum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7136162493302264}} {"text": "function A = spm_mesh_area(M,PF)\n% Compute the surface area of a triangle mesh\n% M - patch structure: vertices and faces must be mx3 and nx3 arrays\n% or 3xm array of edge distances\n% PF - logical indicating whether to return surface area as a whole\n% or per face [default: false]\n%\n% A - surface area\n%__________________________________________________________________________\n%\n% Computed using numerically stable version of Heron's formula:\n% See https://www.wikipedia.org/wiki/Heron%27s_formula\n%__________________________________________________________________________\n% Copyright (C) 2010-2018 Wellcome Trust Centre for Neuroimaging\n\n% Guillaume Flandin\n% $Id: spm_mesh_area.m 7367 2018-07-06 16:04:27Z guillaume $\n\nif isnumeric(M)\n A = M;\nelse\n A = M.vertices(M.faces',:);\n A = permute(reshape(A',3,3,[]),[2 1 3]);\n A = squeeze(sqrt(sum((A([1 2 3],:,:) - A([2 3 1],:,:)).^2,2)));\nend\nA = sort(A,1,'descend');\nA = ( A(1,:) + ( A(2,:) + A(3,:) ) ) .* ...\n ( A(3,:) - ( A(1,:) - A(2,:) ) ) .* ...\n ( A(3,:) + ( A(1,:) - A(2,:) ) ) .* ...\n ( A(1,:) + ( A(2,:) - A(3,:) ) );\nA(A<0) = 0;\nA = 1/4 * sqrt(A);\n\nif nargin < 2 || ~PF\n A = sum(A);\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_mesh_area.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.713616248270917}} {"text": "function y = ngaussian(x)\n\n% NGAUSSIAN Compute a Gaussian with mean 0 and variance 1.\n% FORMAT\n% DESC computes a the likelihood of a normalised Gaussian \n% distribution, i.e. with mean 0 and variance 1.\n% ARG x : input value(s) for which to compute the distribution.\n% RETURN y : probability of the input values under the Gaussian.\n%\n% SEEALSO : cumGaussian, gaussOverDiffcumGaussian\n%\n% COPYRIGHT : Neil D. Lawrence, 2004\n\n% NDLUTIL\n\nx2 = x.*x;\ny = exp(-.5*x2);\ny = y/sqrt(2*pi);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ndlutil/ngaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7136162446512425}} {"text": "function ex7bvp\n%EX7BVP Example 7 of the BVP tutorial.\n% This is the first example problem for D02HBF from the NAG library. \n% The problem is y'' = (y^3 - y')/(2x), y(0) = 0.1, y(16) = 1/6. The\n% singularity at the origin is handled by using a series to represent \n% the solution and its derivative at a \"small\" distance d > 0, namely\n% \n% y(d) = 0.1 + y'(0)*sqrt(d)/10 + d/100 \n% y'(d) = y'(0)/(20*sqrt(d)) + 1/100\n% \n% The value y'(0) is treated as an unknown parameter p. The problem is\n% solved numerically on [d, 16]. Two boundary conditions are that the\n% computed solution and its first derivative agree with the values from\n% the series at d. The remaining boundary condition is y(16) = 1/6.\n% \n% The results from the documentation for D02HBF are here compared to \n% curves produced by bvp4c.\n\n% Copyright 2004, The MathWorks, Inc.\n\n options = bvpset('stats','on');\n\n d = 0.1; % The known parameter, visible in nested functions.\n solinit = bvpinit(linspace(d,16,5),[1 1],0.2);\n\n sol = bvp4c(@ex7ode,@ex7bc,solinit,options);\n\n % Augment the solution array with the values y(0) = 0.1, y'(0) = p\n % to get a solution on [0, 16].\n x = [0 sol.x];\n y = [[0.1; sol.parameters] sol.y];\n \n % Solution obtained using D02HBF, augmented with the values y(0), y'(0).\n nagx = [0.00 0.10 3.28 6.46 9.64 12.82 16.00]';\n nagy = [0.1000 4.629e-2\n 0.1025 0.0173\n 0.1217 0.0042\n 0.1338 0.0036\n 0.1449 0.0034\n 0.1557 0.0034\n 0.1667 0.0035];\n \n figure\n plot(x,y(1,:),x,y(2,:),'--',nagx,nagy,'*')\n axis([-1 16 0 0.18])\n title('Problem with singular behavior at the origin.')\n xlabel('x')\n ylabel('y, dy/dx (--), and D02HBF (*) solutions')\n \n % --------------------------------------------------------------------------\n % Nested functions\n %\n\n function dydx = ex7ode(x,y,p)\n %EX7ODE ODE function for Example 7 of the BVP tutorial.\n dydx = [ y(2)\n (y(1)^3 - y(2))/(2*x) ];\n end % ex7ode\n \n % --------------------------------------------------------------------------\n\n function res = ex7bc(ya,yb,p)\n %EX7BC Boundary conditions for Example 7 of the BVP tutorial.\n % The boundary conditions at x = d are that y and y' have\n % values yatd and ypatd obtained from series expansions.\n % The unknown parameter p = y'(0) and known parameter d are \n % used in the expansions.\n yatd = 0.1 + p*sqrt(d)/10 + d/100;\n ypatd = p/(20*sqrt(d)) + 1/100;\n res = [ ya(1) - yatd\n ya(2) - ypatd\n yb(1) - 1/6 ];\n end % ex7bc\n \n % --------------------------------------------------------------------------\n\nend % ex7bvp\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/ex7bvp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7136126727148744}} {"text": "% check latlon2local\n\norigin = [30.5298813668333; 114.350355321667; 20.8869];\nlla = [30.5298266666667; 114.350367833333; 20.8];\nlla = [30.5299376666667; 114.35528; 17.6];\n% matlab functions\n[e1, n1, u1] = geodetic2enu(lla(1), lla(2), lla(3), origin(1),...\n origin(2), origin(3), wgs84Ellipsoid, 'degrees');\n[e2, n2, u2] = latlon2local(lla(1), lla(2), lla(3), origin);\n\nassert(abs(e1 - e2) < 1e-8);\nassert(abs(n1 - n2) < 1e-8);\nassert(abs(u1 - u2) < 1e-8);\n\n% our own implementation\nCe2n0=llh2dcm_v000(origin(1:2) * pi/ 180,[0;1]);\nqs02e=rotro2qr(Ce2n0');\norigin_xyz = ecef2geo_v000([origin(1:2) * pi / 180; origin(3)],1);\nxyz = ecef2geo_v000([lla(1:2) * pi / 180; lla(3)],1);\nned = quatrot_v000(qs02e, xyz - origin_xyz ,1)';\n\nassert(abs(e1 - ned(2)) < 1e-8);\nassert(abs(n1 - ned(1)) < 1e-8);\nassert(abs(u1 + ned(3)) < 1e-8);", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/tests/test_latlon2local.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240177362489, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.7135846412931997}} {"text": "function weight = gradAscent\n%%\n%\n% Description : LogisticRegression using gradAsscent\n% Author : Liulongpo\n% Time:2015-4-18 10:57:25\n%\n%%\nclc\nclose all\nclear\n%%\n\ndata = load('testSet.txt');\n[row , col] = size(data);\ndataMat = data(:,1:col-1);\ndataMat = [ones(row,1) dataMat] ;\nlabelMat = data(:,col);\nalpha = 0.001;\nmaxCycle = 500;\nweight = ones(col,1);\nfor i = 1:maxCycle\n h = sigmoid((dataMat * weight)');\n error = (labelMat - h');\n weight = weight + alpha * dataMat' * error;\nend\n\nfigure\nscatter(dataMat(find(labelMat(:) == 0),2),dataMat(find(labelMat(:) == 0),3),3);\nhold on\nscatter(dataMat(find(labelMat(:) == 1),2),dataMat(find(labelMat(:) == 1),3),5);\nhold on\nx = -3:0.1:3;\ny = (-weight(1)-weight(2)*x)/weight(3);\nplot(x,y)\nhold off\n\nend\n\nfunction returnVals = sigmoid(inX)\n % 注意这里的sigmoid函数要用点除\n returnVals = 1.0./(1.0+exp(-inX));\nend\n", "meta": {"author": "llp1992", "repo": "MachineLearning", "sha": "315c00285b758a7aee0c8a80db2d2f6dfbbe9aef", "save_path": "github-repos/MATLAB/llp1992-MachineLearning", "path": "github-repos/MATLAB/llp1992-MachineLearning/MachineLearning-315c00285b758a7aee0c8a80db2d2f6dfbbe9aef/Logistic-regression/gradAscent.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7135454312095388}} {"text": "function besselk_test ( )\n\n%*****************************************************************************80\n%\n%% BESSELK_TEST examines the besselk correlation.\n%\n% Discussion:\n%\n% This code is based substantially on a document by Toby Driscoll.\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% Reference:\n%\n% Toby Driscoll,\n% Mercer's theorem and the Karhunen-Loeve expansion,\n% Oxford University Mathematical Institute,\n% http://www2.maths.ox.ac.uk/chebfun/examples/stats/pdf/MercerKarhunenLoeve.pdf\n%\n rmpath ( '/usr/local/matlab/toolbox/datafeed/datafeed' )\n addpath ( '../chebfun' )\n\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BESSELK_TEST:\\n' );\n fprintf ( 1, ' Demonstrate Mercer''s theorem and the KL expansion\\n' );\n fprintf ( 1, ' for the besselk kernel.\\n' );\n%\n% Set the interval.\n%\n a = 0.0;\n b = 10.0;\n fprintf ( 1, ' Using interval [%g,%g]\\n', a, b );\n s_num = 21;\n s_vec = linspace ( a, b, s_num );\n%\n% FRED is a function from the CHEBFUN library.\n%\n% It constructs a \"chebop\" representing the Fredholm integral operator\n% with kernel K for functions in domain [A,B].\n%\n F = fred ( @besselk_correlation, domain ( [ a, b ] ) );\n%\n% EIGS has been extended to be able to compute the eigenvalues Lambda\n% and eigenfunctions Psi of the Fredholm integral operator represented by F.\n%\n% The \"LM\" switch requests that we return the eigenvalues of largest magnitude.\n%\n% Each Psi is a CHEBFUN, that is, it takes a real number argument.\n%\n eigen_num = 20;\n [ Psi, Lambda ] = eigs ( F, eigen_num, 'lm' );\n\n eigen_found = length ( Lambda );\n fprintf ( 1, ' Requested %d eigenmodes, computed %d\\n', eigen_num, eigen_found );\n eigen_num = min ( eigen_num, eigen_found );\n%\n% Print the eigenvalues.\n%\n lambda_vec = diag ( Lambda );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I Lambda(I)\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : eigen_num\n fprintf ( 1, ' %2d %10g\\n', i, lambda_vec(i) );\n end\n%\n% Plot the eigenvalues.\n%\n figure ( 1 )\n clf\n plot ( lambda_vec, 'Linewidth', 2 );\n hold on\n plot ( lambda_vec, 'b.', 'Markersize', 20 );\n title ( 'besselk: Mercer eigenvalues' );\n xlabel ( '<--- N --->')\n grid on\n print -dpng 'besselk_figure1.png'\n%\n% Plot selected eigenfunctions.\n%\n figure ( 2 )\n subplot ( 4, 1, 1 )\n plot ( Psi(:,1), 'Linewidth', 2 );\n title ( 'besselk: Mercer eigenfunction PSI(1)' )\n grid on\n subplot ( 4, 1, 2 )\n plot ( Psi(:,2), 'Linewidth', 2 );\n title ( 'besselk: Mercer eigenfunction PSI(2)' )\n grid on\n subplot ( 4, 1, 3 )\n plot ( Psi(:,3), 'Linewidth', 2 );\n title ( 'besselk: Mercer eigenfunction PSI(3)' )\n grid on\n subplot ( 4, 1, 4 )\n plot ( Psi(:,4), 'Linewidth', 2 );\n title ( 'besselk: Mercer eigenfunction PSI(4)' )\n grid on\n print -dpng 'besselk_figure2.png'\n%\n% Orthonormality check.\n%\n ptp = Psi' * Psi;\n error_frobenius = r8mat_is_identity ( eigen_num, ptp );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Frobenius norm of I - Psi'' * Psi = %g\\n', error_frobenius );\n%\n% K(S,S) should be exactly 1.\n% Because we are using a truncated representation of K, our estimate of K(S,S)\n% will be smaller than 1.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Truncated estimate of K(s,s) = 1 for S in the interval.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' S K(s,s) estimate\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : 21\n s = s_vec(i);\n ptlp = Psi(s,:) * Lambda * Psi(s,:)';\n fprintf ( 1, ' %10g %14g\\n', s, ptlp );\n end\n%\n% Look at eigenvalue decay.\n%\n x = diff ( log ( ( 1:eigen_num ) ) );\n y = diff ( log ( lambda_vec ) )';\n c = y ./ x;\n figure ( 3 );\n clf\n plot ( c, 'Linewidth', 2 );\n grid on\n hold on\n plot ( c, 'b.', 'Markersize', 20 );\n xlabel ( '<-- N -->' )\n title ( 'besselk: Eigenvalue decay rate' );\n print -dpng 'besselk_figure3.png'\n%\n% Look at eigenvalue sum.\n%\n% The trace of K(s,s) over [a,b] should be the integral of 1 over [a,b],\n% that is, b - a.\n%\n% We compare the trace to the partial sums of the lambda's to see how much\n% of the variance of the process we have captured.\n%\n trace_K = b - a;\n lambda_cum = cumsum ( lambda_vec ) / trace_K;\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Index Cumulative Eigenvalue sum\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : eigen_num\n fprintf ( 1, ' %5d %10g\\n', i, lambda_cum(i) );\n end\n%\n% We decide to use no more than 10 eigenfunctions.\n%\n eigen_use = min ( 10, eigen_num );\n%\n% Find 400 realizations of the process by selecting, for each realization,\n% 10 random parameters Z in the truncated KL expansion.\n%\n Z = randn ( eigen_use, 400 );\n X = Psi(:,1:eigen_use) * ( sqrt ( Lambda(1:eigen_use,1:eigen_use) ) * Z ); \n%\n% Plot 40 of the realizations;\n% Plot their mean, computed from all 400.\n%\n figure ( 4 )\n clf\n plot ( X(:,1:40) )\n mu = sum ( X, 2 ) / 400;\n hold on;\n plot ( mu, 'k', 'linewidth', 3 );\n title ( 'besselk: 40 Random Realizations X(t,omega), and their Mean.' )\n print -dpng 'besselk_figure4.png'\n%\n% Estimate the covariance from the data.\n%\n figure ( 5 )\n clf\n [ S, T ] = meshgrid ( s_vec, s_vec );\n C = cov ( X(s_vec,:)' );\n mesh ( S, T, C );\n hold on;\n D = besselk_correlation ( S, T );\n plot3 ( S, T, D, 'k.', 'markersize', 10 )\n title ( 'besselk: Covariance K(S,T) (dots), and Estimate from Realizations (mesh)' )\n print -dpng 'besselk_figure5.png'\n%\n% Using just 10 functions in the expansion,\n% reduce the correlation length,\n% and examine the sum of the lambda's.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Use a fixed number of eigenfunctions = %d\\n', eigen_use );\n fprintf ( 1, ' but vary the correlation length RHOBAR.\\n' );\n fprintf ( 1, ' (We used RHOBAR = 1 above.)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The sum of the eigenvalues, divided by (B-A),\\n' );\n fprintf ( 1, ' discloses the relative amount of the total variation\\n' );\n fprintf ( 1, ' that is captured by the truncated expansion.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' RHOBAR VARSUM\\n' );\n fprintf ( 1, '\\n' );\n rhobar = 4.0;\n for i = 1 : 10\n F = fred ( @besselk_correlation, domain ( [ a, b ] ) );\n lambda_vec = eigs ( F, eigen_use, 'lm' );\n varsum = sum ( lambda_vec(1:eigen_use) ) / ( b - a );\n fprintf ( 1, ' %10g %10g\\n', rhobar, varsum );\n rhobar = rhobar / 2.0;\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BESSELK_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n rmpath ( '../chebfun' )\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/correlation_chebfun/besselk_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8056321819811829, "lm_q1q2_score": 0.71349322397907}} {"text": "function x = normal_ms_cdf_inv ( cdf, mu, sigma )\n\n%*****************************************************************************80\n%\n%% NORMAL_MS_CDF_INV inverts the Normal CDF.\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% Parameters:\n%\n% Input, real CDF, the value of the CDF.\n% 0.0 <= CDF <= 1.0.\n%\n% Input, real MU, SIGMA, the parameters of the PDF.\n% 0.0 < SIGMA.\n%\n% Output, real X, the corresponding argument.\n%\n if ( cdf < 0.0 | 1.0 < cdf )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'NORMAL_MS_CDF_INV - Fatal error!\\n' );\n fprintf ( 1, ' CDF < 0 or 1 < CDF.\\n' );\n error ( 'NORMAL_MS_CDF_INV - Fatal error!' );\n end\n\n x2 = normal_01_cdf_inv ( cdf );\n\n x = mu + sigma * x2;\n\n return\nend\n", "meta": {"author": "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/normal_ms_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809304, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.7134932138860436}} {"text": "%% Tire comparison\n% Comparison between tire models.\n%\n% \n% \n% \n%\n%% Description\n% The typical relation between the lateral force and the slip angle can be observed in the figure below (Adapted from [1]). Besides, its possible to verify the definition of slip angle.\n%\n% <>\n%\n%% Equivalence\n% Given a reference Pacejka tire model it is possible to obtain an equivalent linear and polynomial model. The cornering stiffness of all models must be equal and the maximal lateral force of the Pacejka and Polynomial models must be the same.\n%\n% The Pacejka model depends on the parameters \\(a_0\\), \\(a_1\\), \\(a_2\\), \\(a_3\\), \\(a_4\\), \\(a_5\\), \\(a_6\\) e \\(a_7\\) that defines the constants \\(B\\), \\(C\\), \\(D\\) and \\(E\\) wich can be used to define the constants of the equivalent models.\n%\n% The equivalent linear tire model has cornering stiffness \\(K\\) given by\n%\n% \\[ K = B C D \\]\n%\n% The equivalent polynomial tire model has coeficients \\(k_1\\) and \\(k_2\\) given by\n%\n% \\[ k_1 = B C D \\]\n%\n% \\[ k_2 = (4 k_1^3)/(27 F_{y, Max}^2) \\]\n%\n% where \\(F_{y, Max}\\) is the maximal lateral force of the reference characteristic curve.\n%\n%% Model comparison\n%\n\n% Code start\n\nclear ; close all ; clc\n\nderiva = (0:0.1:15)*pi/180; % ngulo de deriva [rad]\n\na0 = 1.3;\na1 = 2.014156;\na2 = 710.5013;\na3 = 5226.341;\na4 = 78.87699;\na5 = 0.01078379;\na6 = -0.004759443;\na7 = -1.8572;\na8 = 0;\na9 = 0;\na10 = 0;\na11 = 0;\na12 = 0;\na13 = 0;\n\nTirePac = VehicleDynamicsLateral.TirePacejka();\n\nFz = 4e+03;\ncamber = 0;\nTirePac.a0 = a0;\nTirePac.a1 = a1;\nTirePac.a2 = a2;\nTirePac.a3 = a3;\nTirePac.a4 = a4;\nTirePac.a5 = a5;\nTirePac.a6 = a6;\nTirePac.a7 = a7;\nTirePac.a8 = a8;\nTirePac.a9 = a9;\nTirePac.a10 = a10;\nTirePac.a11 = a11;\nTirePac.a12= a12;\nTirePac.a13 = a13;\n\nmuy0 = TirePac.a1 * Fz/1000 + TirePac.a2;\nD = muy0 * Fz/1000;\nBCD = TirePac.a3 * sin(2 * atan(Fz/1000/TirePac.a4))*(1-TirePac.a5 * abs(camber));\n\n% Linear tire model\n\nK = BCD * 180/pi;\n\nTireLin = VehicleDynamicsLateral.TireLinear();\nTireLin.k = K;\n\n% Polynomial tire MODEL\n\nk1 = BCD * 180/pi;\nk2 = (4 * k1^3)/(27 * D^2);\n\nTirePol = VehicleDynamicsLateral.TirePolynomial();\nTirePol.k1 = k1;\nTirePol.k2 = k2;\n\n% Lateral force\nFyPac = TirePac.Characteristic(deriva, Fz, muy0/1000);\nFyLin = TireLin.Characteristic(deriva);\nFyPol = TirePol.Characteristic(deriva);\n\n% Graphics\ng = VehicleDynamicsLateral.Graphics(TirePac);\n\nfigure(1)\nax = gca;\nset(ax, 'NextPlot', 'add', 'Box', 'on', 'XGrid', 'on', 'YGrid', 'on')\np = plot(deriva * 180/pi,-FyLin, 'Color', 'g', 'Marker', 's', 'MarkerFaceColor', 'g', 'MarkeredgeColor', 'k', 'MarkerSize', 7);\ng.changeMarker(p, 10);\np = plot(deriva * 180/pi,-FyPol, 'Color', 'b', 'Marker', '^', 'MarkerFaceColor', 'b', 'MarkeredgeColor', 'k', 'MarkerSize', 7);\ng.changeMarker(p, 10);\np = plot(deriva * 180/pi,-FyPac, 'Color', 'r', 'Marker', 'o', 'MarkerFaceColor', 'r', 'MarkeredgeColor', 'k', 'MarkerSize', 7);\ng.changeMarker(p, 10);\nxlabel('\\(\\alpha\\) [grau]', 'Interpreter', 'Latex')\nylabel('\\(F_y\\) [N]', 'Interpreter', 'Latex')\nl = legend('Linear', 'Polynomial', 'Pacejka');\nset(l, 'Interpreter', 'Latex', 'Location', 'NorthWest')\n\n%%\n% In the above figure the 3 characteristic curves are plotted. For small slip angles all models are equivalents.\n%\n%% Comparison treatment slip angle\n%\n\nderiva180 = (0:0.1:180)*pi/180; % ngulo de deriva de 0 180 graus [rad]\n\n% Sem tratamento\nALPHA = deriva180 * 180/pi;\nC = a0;\nmuy = muy0;\nE = a6 * Fz/1000 + a7;\nB = BCD/(C * D);\nSh = a8 * camber + a9 * Fz/1000 + a10;\nSv = a11 * Fz/1000 * camber + a12 * Fz/1000 + a13;\nALPHAeq = muy0/muy*(ALPHA + Sh);\n% Reference characteristics\nfy = D * sin(C * atan(B * ALPHAeq - E*(B * ALPHAeq - atan(B * ALPHAeq))));\n% Lateral force\nFyPacSem180 = -muy/muy0*(fy + Sv);\n\n% Com tratamento\nFyPacCom180 = TirePac.Characteristic(deriva180, Fz, muy0/1000);\n\nfigure(2)\nax = gca;\nset(ax, 'NextPlot', 'add', 'Box', 'on', 'XGrid', 'on', 'YGrid', 'on')\np = plot(deriva180 * 180/pi,-FyPacSem180, 'Color', 'm', 'Marker', 'd', 'MarkerFaceColor', 'm', 'MarkeredgeColor', 'k', 'MarkerSize', 7);\ng.changeMarker(p, 10);\np = plot(deriva180 * 180/pi,-FyPacCom180, 'Color', 'r', 'Marker', 'o', 'MarkerFaceColor', 'r', 'MarkeredgeColor', 'k', 'MarkerSize', 7);\ng.changeMarker(p, 10);\nplot([90 90],[0 3000],'--k') % Linha vertical de simetria\nxlabel('\\(\\alpha\\) [grau]', 'Interpreter', 'Latex')\nylabel('\\(F_y\\) [N]', 'Interpreter', 'Latex')\nl = legend('Pacejka without treatment', 'Pacejka with treatment ');\nset(l, 'Interpreter', 'Latex', 'Location', 'SouthEast')\n\n%%\n% In the above figure we can see that the curve is symmetric to a vertical line positioned at \\(\\alpha = 90 [graus]\\).\n%\n%% References\n% [1] GILLESPIE, T. D. Fundamentals of vehicle dynamics. [S.l.]: Society of Automotive Engineers Warrendale, PA, 1992.\n%\n%% See Also\n%\n% <../../../index.html Home>\n%\n", "meta": {"author": "andresmendes", "repo": "Vehicle-Dynamics-Lateral", "sha": "a1e9a07da58ef887164bf0046991f0db2ca3b647", "save_path": "github-repos/MATLAB/andresmendes-Vehicle-Dynamics-Lateral", "path": "github-repos/MATLAB/andresmendes-Vehicle-Dynamics-Lateral/Vehicle-Dynamics-Lateral-a1e9a07da58ef887164bf0046991f0db2ca3b647/Examples/TireComparison/TireComparison.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7134300524607151}} {"text": "function asa006_test02 ( )\n\n%*****************************************************************************80\n%\n%% TEST02 demonstrates the use of CHOLESKY.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 February 2008\n%\n% Author:\n%\n% John Burkardt\n%\n n_max = 15;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST02:\\n' );\n fprintf ( 1, ' CHOLESKY computes the Cholesky factorization\\n' );\n fprintf ( 1, ' of a positive definite symmetric matrix.\\n' );\n fprintf ( 1, ' A compressed storage format is used.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Here we look at the Hilbert matrix\\n' );\n fprintf ( 1, ' A(I,J) = 1 / ( I + J - 1 )\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' We expect errors to grow quickly with N.\\n' );\n\n for n = 1 : n_max\n\n nn = ( n * ( n + 1 ) ) / 2;\n%\n% Set A to the Hilbert matrix.\n%\n k = 0;\n for i = 1 : n\n for j = 1 : i\n k = k + 1;\n a(k) = 1.0 / ( i + j - 1 );\n end\n end\n\n [ u, nullty, ifault ] = cholesky ( a, n, nn );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n fprintf ( 1, ' Maxtrix nullity NULLTY = %d\\n', nullty );\n\n k = 0;\n for j = 1 : n\n for i = 1 : j\n k = k + 1;\n ufull(i,j) = u(k);\n end\n for i = j + 1 : n\n ufull(i,j) = 0.0;\n end\n end\n%\n% Compute U' * U and compare to A.\n%\n k = 0;\n diff = 0.0;\n for i = 1 : n\n for j = 1 : i\n k = k + 1;\n utu = 0.0;\n for l = 1 : n\n utu = utu + ufull(l,i) * ufull(l,j);\n end\n diff = diff + ( a(k) - utu ) * ( a(k) - utu );\n end\n end\n\n diff = sqrt ( diff );\n\n fprintf ( 1, ' RMS ( A - U''*U ) = %f\\n', diff );\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/asa006/asa006_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7134300462485381}} {"text": "% QUATERNION DIVISION\nfunction [qDiv] = qDivide(q,r)\n% The function compute the division of quaternion q, by\n% quaterion v.\n% Associated block:\n% \"Quaternion Division\"\n\nqDiv = zeros(4,1);\n% Normalise the second vector\nqDiv(1) = q(1)*r(1) + q(2)*r(2) + q(3)*r(3) + q(4)*r(4);\nqDiv(2) = -q(1)*r(2) + q(2)*r(1) + q(3)*r(4) - q(4)*r(3);\nqDiv(3) = q(1)*r(3) + q(2)*r(4) + q(3)*r(1) + q(4)*r(2);\nqDiv(4) = -q(1)*r(4) + q(2)*r(3) - q(3)*r(2) + q(4)*r(1);\nqDiv = qDiv./(norm(r));\nend", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/environment/common/qDivide.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.7133955509800005}} {"text": "function y = TpFerwerda(x)\n%\n% y = TpFerwerda(x)\n%\n%\n% The gamma function used in Ferwerda TMO for Photopic levels\n%\n% Input:\n% -x: a value\n%\n% Output:\n% -y: application of the gamma function\n%\n% \n% Copyright (C) 2010-15 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\nt = log10(x);\n\nif(t <= -2.6)\n y = -0.72;\nelse\n if(t >= 1.9)\n y = t - 1.255;\n else\n y = (0.249 * t + 0.65).^2.7 - 0.72;\n end\nend\n\ny = 10.^y;\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/Tmo/util/TpFerwerda.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333004, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.7133955197073478}} {"text": "%% Machine Learning Online Class\n% Exercise 5 | Regularized Linear Regression and Bias-Variance\n%\n% Instructions\n% ------------\n%\n% This file contains code that helps you get started on the\n% exercise. You will need to complete the following functions:\n%\n% linearRegCostFunction.m\n% learningCurve.m\n% validationCurve.m\n%\n% For this exercise, you will not need to change any code in this file,\n% or any other files other than those mentioned above.\n%\n\n%% Initialization\nclear ; close all; clc\n\n%% =========== Part 1: Loading and Visualizing Data =============\n% We start the exercise by first loading and visualizing the dataset.\n% The following code will load the dataset into your environment and plot\n% the data.\n%\n\n% Load Training Data\nfprintf('Loading and Visualizing Data ...\\n')\n\n% Load from ex5data1:\n% You will have X, y, Xval, yval, Xtest, ytest in your environment\nload ('ex5data1.mat');\n\n% m = Number of examples\nm = size(X, 1);\n\n% Plot training data\nplot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);\nxlabel('Change in water level (x)');\nylabel('Water flowing out of the dam (y)');\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% =========== Part 2: Regularized Linear Regression Cost =============\n% You should now implement the cost function for regularized linear\n% regression.\n%\n\ntheta = [1 ; 1];\nJ = linearRegCostFunction([ones(m, 1) X], y, theta, 1);\n\nfprintf(['Cost at theta = [1 ; 1]: %f '...\n '\\n(this value should be about 303.993192)\\n'], J);\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% =========== Part 3: Regularized Linear Regression Gradient =============\n% You should now implement the gradient for regularized linear\n% regression.\n%\n\ntheta = [1 ; 1];\n[J, grad] = linearRegCostFunction([ones(m, 1) X], y, theta, 1);\n\nfprintf(['Gradient at theta = [1 ; 1]: [%f; %f] '...\n '\\n(this value should be about [-15.303016; 598.250744])\\n'], ...\n grad(1), grad(2));\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n\n%% =========== Part 4: Train Linear Regression =============\n% Once you have implemented the cost and gradient correctly, the\n% trainLinearReg function will use your cost function to train\n% regularized linear regression.\n%\n% Write Up Note: The data is non-linear, so this will not give a great\n% fit.\n%\n\n% Train linear regression with lambda = 0\nlambda = 0;\n[theta] = trainLinearReg([ones(m, 1) X], y, lambda);\n\n% Plot fit over the data\nplot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);\nxlabel('Change in water level (x)');\nylabel('Water flowing out of the dam (y)');\nhold on;\nplot(X, [ones(m, 1) X]*theta, '--', 'LineWidth', 2)\nhold off;\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n\n%% =========== Part 5: Learning Curve for Linear Regression =============\n% Next, you should implement the learningCurve function.\n%\n% Write Up Note: Since the model is underfitting the data, we expect to\n% see a graph with \"high bias\" -- slide 8 in ML-advice.pdf\n%\n\nlambda = 0;\n[error_train, error_val] = ...\n learningCurve([ones(m, 1) X], y, ...\n [ones(size(Xval, 1), 1) Xval], yval, ...\n lambda);\n\nplot(1:m, error_train, 1:m, error_val);\ntitle('Learning curve for linear regression')\nlegend('Train', 'Cross Validation')\nxlabel('Number of training examples')\nylabel('Error')\naxis([0 13 0 150])\n\nfprintf('# Training Examples\\tTrain Error\\tCross Validation Error\\n');\nfor i = 1:m\n fprintf(' \\t%d\\t\\t%f\\t%f\\n', i, error_train(i), error_val(i));\nend\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% =========== Part 6: Feature Mapping for Polynomial Regression =============\n% One solution to this is to use polynomial regression. You should now\n% complete polyFeatures to map each example into its powers\n%\n\np = 8;\n\n% Map X onto Polynomial Features and Normalize\nX_poly = polyFeatures(X, p);\n[X_poly, mu, sigma] = featureNormalize(X_poly); % Normalize\nX_poly = [ones(m, 1), X_poly]; % Add Ones\n\n% Map X_poly_test and normalize (using mu and sigma)\nX_poly_test = polyFeatures(Xtest, p);\nX_poly_test = bsxfun(@minus, X_poly_test, mu);\nX_poly_test = bsxfun(@rdivide, X_poly_test, sigma);\nX_poly_test = [ones(size(X_poly_test, 1), 1), X_poly_test]; % Add Ones\n\n% Map X_poly_val and normalize (using mu and sigma)\nX_poly_val = polyFeatures(Xval, p);\nX_poly_val = bsxfun(@minus, X_poly_val, mu);\nX_poly_val = bsxfun(@rdivide, X_poly_val, sigma);\nX_poly_val = [ones(size(X_poly_val, 1), 1), X_poly_val]; % Add Ones\n\nfprintf('Normalized Training Example 1:\\n');\nfprintf(' %f \\n', X_poly(1, :));\n\nfprintf('\\nProgram paused. Press enter to continue.\\n');\npause;\n\n\n\n%% =========== Part 7: Learning Curve for Polynomial Regression =============\n% Now, you will get to experiment with polynomial regression with multiple\n% values of lambda. The code below runs polynomial regression with\n% lambda = 0. You should try running the code with different values of\n% lambda to see how the fit and learning curve change.\n%\n\nlambda = 1;\n[theta] = trainLinearReg(X_poly, y, lambda);\n\n% Plot training data and fit\nfigure(1);\nplot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);\nplotFit(min(X), max(X), mu, sigma, theta, p);\nxlabel('Change in water level (x)');\nylabel('Water flowing out of the dam (y)');\ntitle (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));\n\nfigure(2);\n[error_train, error_val] = ...\n learningCurve(X_poly, y, X_poly_val, yval, lambda);\nplot(1:m, error_train, 1:m, error_val);\n\ntitle(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));\nxlabel('Number of training examples')\nylabel('Error')\naxis([0 13 0 100])\nlegend('Train', 'Cross Validation')\n\nfprintf('Polynomial Regression (lambda = %f)\\n\\n', lambda);\nfprintf('# Training Examples\\tTrain Error\\tCross Validation Error\\n');\nfor i = 1:m\n fprintf(' \\t%d\\t\\t%f\\t%f\\n', i, error_train(i), error_val(i));\nend\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n\n%% =========== Part 8: Validation for Selecting Lambda =============\n% You will now implement validationCurve to test various values of\n% lambda on a validation set. You will then use this to select the\n% \"best\" lambda value.\n%\n\n[lambda_vec, error_train, error_val] = ...\n validationCurve(X_poly, y, X_poly_val, yval);\n\nclose all;\nplot(lambda_vec, error_train, lambda_vec, error_val);\nlegend('Train', 'Cross Validation');\nxlabel('lambda');\nylabel('Error');\n\nfprintf('lambda\\t\\tTrain Error\\tValidation Error\\n');\nfor i = 1:length(lambda_vec)\n\tfprintf(' %f\\t%f\\t%f\\n', ...\n lambda_vec(i), error_train(i), error_val(i));\nend\n\nfprintf('Program paused. Press enter to continue.\\n');\npause;\n", "meta": {"author": "benoitvallon", "repo": "coursera-machine-learning", "sha": "74ec09a5072eb5f3fec942fee45076e4f05b35af", "save_path": "github-repos/MATLAB/benoitvallon-coursera-machine-learning", "path": "github-repos/MATLAB/benoitvallon-coursera-machine-learning/coursera-machine-learning-74ec09a5072eb5f3fec942fee45076e4f05b35af/machine-learning-ex5/ex5/ex5.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.7133443299282409}} {"text": "% function [IDX_SC, Uk, Dk, time_SC] = SC(G,lap_type)\n%\n% This is an implementation of the classical Spectral CLustering algorithm \n% using either: \n% - the combinatorial Laplacian if lap_type='combinatorial' (in this case, \n% the features are not normalized);\n% - or the normalized Laplacian if lap_type='normalized' (in this case, \n% the features are normalized). \n% See the paper cited below for many references on this algorithm. \n%\n% Copyright (C) 2016 Nicolas Tremblay, Gilles Puy.\n% This file is part of the CSCbox (Compressive Spectral Clustering toolbox)\n%\n% The CSCbox 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 CSCbox 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% If you use this toolbox please kindly cite\n% N. Tremblay, G. Puy, R. Gribonval and P. Vandergheynst.\n% Compressive Spectral Clustering.\n% ArXiv e-prints:1602.02018 Feb. 2016.\n\n\nfunction [IDX_SC, Uk, Dk, time_SC] = SC(G,lap_type)\n\nnormBOOL=strcmp(lap_type,'normalized');\nG = gsp_create_laplacian(G,lap_type);\n\n% eigs\nif isfield(G, 'G.Dk'), % if it was already calculated, do not do it again\n Dk=G.Dk;\n Uk=G.Uk;\n time_SC.eigs=G.time_SC_eigs;\nelse % run eigs\n tic;\n opts.isreal=1;opts.issym=1;opts.maxit=10000;\n [Uk,Dk]=eigs(G.L,G.k,'SA',opts);Dk=diag(Dk);\n time_SC.eigs=toc;\nend\n\nif normBOOL % kmeans on Yk\n tic;\n Yk=Uk./repmat(sqrt(sum(Uk.^2,2)),1,G.k);\n IDX_SC = kmeans(Yk, G.k,'Replicates',20);\n time_SC.kmeans=toc;\nelse % kmeans on Uk\n tic;\n IDX_SC = kmeans(Uk, G.k,'Replicates',20);\n time_SC.kmeans=toc;\nend\n\ntime_SC.total=time_SC.eigs+time_SC.kmeans;\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/codes/SC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7133443121357185}} {"text": "% StackExchange Signal Processing Q75231\n% https://dsp.stackexchange.com/questions/75231\n% Image Denoising Using Total Variation (TV) Minimization with ADMM\n% References:\n% 1. \n% Remarks:\n% 1. B\n% TODO:\n% \t1. C\n% Release Notes\n% - 1.0.000 18/05/2021\n% * First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 79;\n\nrun('InitScript.m');\n\nfigureIdx = 0;\nfigureCounterSpec = '%04d';\n\ngenerateFigures = ON;\n\nCONV_SHAPE_FULL = 1;\nCONV_SHAPE_SAME = 2;\nCONV_SHAPE_VALID = 3;\n\n\n%% Simulation Parameters\n\nimageFileName = 'Lena256.png';\n\nparamLambda = 0.025; % 500, Very Good!\n% cvx_solver('Gurobi');\n\nhRunTime = tic();\n\ncvx_begin('quiet')\n % cvx_precision('best');\n variable vX(numRows * numCols);\n minimize( (0.5 * sum_square(vX - vY)) + (paramLambda * norm(mD * vX, 1)) );\ncvx_end\n\nrunTime = toc(hRunTime);\n\nDisplayRunSummary(solverString, hObjFun, vX, runTime, cvx_status);\n\nsCvxSol.vXCvx = vX(:);\nsCvxSol.cvxOptVal = hObjFun(vX);\n\n\n%% Display Result\n\nhAxes = axes(hFigure, 'Units', 'pixels', 'Position', [010, 010, 256, 256]);\nhImgObj = image(repmat(reshape(vX, numRows, numCols), [1, 1, 3]));\nset(get(hAxes, 'Title'), 'String', {['Denoised Image - CVX']}, ...\n 'FontSize', fontSizeTitle);\nset(hAxes, 'XTick', [], 'XTickLabel', []);\nset(hAxes, 'YTick', [], 'YTickLabel', []);\n\n\n%% Solution by ADMM\n%{\nSolving:\n\n$$ \\arg \\min_{ x \\in \\mathbb{R}^{n} } \\frac{1}{2} {\\left\\| x - y \\right|}_{2}^{2} + \\lambda {\\left\\| D x \\right\\|}_{1} $$\n%}\n\nsolverIdx = solverIdx + 1;\ncLegendString{solverIdx} = ['ADMM'];\n\nhRunTime = tic();\n\n[vX, mX] = SolveProxTvAdmm(vXInit, vY, mD, paramLambda, 'numIterations', numIterations);\n\nrunTime = toc(hRunTime);\n\nDisplayRunSummary(cLegendString{solverIdx}, hObjFun, vX, runTime);\n\n[mObjFunValMse, mSolMse] = UpdateAnalysisData(mObjFunValMse, mSolMse, mX, hObjFun, sCvxSol, solverIdx);\n\n\n%% Display Results\n\nhAxes = axes(hFigure, 'Units', 'pixels', 'Position', [276, 010, 256, 256]);\nhImgObj = image(repmat(reshape(vX, numRows, numCols), [1, 1, 3]));\nset(get(hAxes, 'Title'), 'String', {['Denoised Image - ADMM']}, ...\n 'FontSize', fontSizeTitle);\nset(hAxes, 'XTick', [], 'XTickLabel', []);\nset(hAxes, 'YTick', [], 'YTickLabel', []);\n\nif(generateFigures == ON)\n % saveas(hFigure, ['Figure', num2str(figureIdx, figureCounterSpec), '.png']);\n print(hFigure, ['Figure', num2str(figureIdx, figureCounterSpec), '.png'], '-dpng', '-r0'); %.\n\nX = randn(v, m) * H_inv_upper_chol; \n\n\n% At this point, X'*X is Wishart distributed\n% G = inv(X'*X);\n\n% Rather compute inv(X'*X) using the SVD\n[U,S,V] = svd(X, 0);\nSSi = 1 ./ (diag(S) .^ 2);\nG = (V .* repmat(SSi', m, 1)) * V';", "meta": {"author": "naffe15", "repo": "BVAR_", "sha": "4c935f440a2e98475ead4f873ebdfd03378a0eee", "save_path": "github-repos/MATLAB/naffe15-BVAR_", "path": "github-repos/MATLAB/naffe15-BVAR_/BVAR_-4c935f440a2e98475ead4f873ebdfd03378a0eee/bvartools/rand_inverse_wishart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7132928580692965}} {"text": "function [ p, l, u ] = plu_plu ( n, pivot )\n\n%*****************************************************************************80\n%\n%% PLU_PLU returns the PLU factors of the PLU matrix.\n%\n% Example:\n%\n% Input:\n%\n% N = 5\n% PIVOT = ( 1, 3, 3, 5, 5 )\n%\n% Output:\n%\n% P:\n%\n% 1 0 0 0 0\n% 0 0 1 0 0\n% 0 1 0 0 0\n% 0 0 0 0 1\n% 0 0 0 1 0\n%\n% L:\n%\n% 1 0 0 0 0\n% 0.25 1 0 0 0\n% 0.125 0.375 1 0 0\n% 0.0625 0.1875 0.3125 1 0\n% 0.03125 0.09375 0.15625 0.21875 1\n%\n% U:\n%\n% 11 12 13 14 15\n% 0 22 23 24 25\n% 0 0 33 34 35\n% 0 0 0 44 45\n% 0 0 0 0 55\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, integer PIVOT(N), the list of pivot rows. PIVOT(I)\n% must be a value between I and N, reflecting the choice of\n% pivot row on the I-th step. For no pivoting, set PIVOT(I) = I.\n%\n% Output, real P(N,N), L(N,N), U(N,N), the P, L and U factors\n% of A, as defined by Gaussian elimination with partial pivoting.\n% P is a permutation matrix, L is unit lower triangular, and U\n% is upper trianguler.\n%\n\n%\n% Check that the pivot vector is legal.\n%\n for i = 1 : n\n\n if ( pivot(i) < i )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PLU_PLU - Fatal error!\\n' );\n fprintf ( 1, ' PIVOT(%d) = %d\\n', i, pivot(i) );\n fprintf ( 1, ' but PIVOT(I) must be no less than I!\\n' );\n error ( 'PLU_PLU - Fatal error!' )\n elseif ( n < pivot(i) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PLU_PLU - Fatal error!\\n' );\n fprintf ( 1, ' PIVOT(%d) = %d\\n', i, pivot(i) );\n fprintf ( 1, ' but PIVOT(I) must be no greater than N\\n' );\n fprintf ( 1, ' and N = %d\\n', n );\n error ( 'PLU_PLU - Fatal error!' )\n end\n\n end\n%\n% Compute U.\n%\n u = zeros ( n, n );\n for i = 1 : n\n for j = 1 : n\n\n if ( i <= j )\n u(i,j) = 10 * i + j;\n else\n u(i,j) = 0.0;\n end\n\n end\n end\n%\n% Compute L.\n%\n l = zeros ( n, n );\n for i = 1 : n\n for j = 1 : n\n\n if ( i < j )\n l(i,j) = 0.0;\n elseif ( j == i )\n l(i,j) = 1.0;\n else\n l(i,j) = ( 2 * j - 1 ) / 2^i;\n end\n\n end\n end\n%\n% Compute P.\n%\n p = zeros ( n, n );\n for i = 1 : n\n for j = 1 : n\n if ( i == j )\n p(i,j) = 1.0;\n else\n p(i,j) = 0.0;\n end\n end\n end\n%\n% Apply the pivot permutations, in reverse order.\n%\n for i = n : -1 : 1\n\n if ( pivot(i) ~= i )\n for j = 1 : n\n temp = p(i,j);\n p(i,j) = p(pivot(i),j);\n p(pivot(i),j) = temp;\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/test_mat/plu_plu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7132722039361763}} {"text": "function [lng] = spm_lg_gamma(p,b)\n% Log of generalised gamma function\n% FORMAT [lng] = spm_lg_gamma(p,b)\n%\n% p - dimension parameter\n% b - degrees of freedom type parameter\n%__________________________________________________________________________\n%\n% References:\n% * Bayesian Inference in Statistical Analysis, Box & Tiao, 1992, p. 427.\n% * Aspects of Multivariate Statistical Theory, R.J. Muirhead, p. 62.\n%__________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: spm_lg_gamma.m 2784 2009-02-24 19:11:20Z guillaume $\n\nif b <= (p-1)/2\n warning('Parameter out of range');\n lng = NaN;\n return\nend\n\nlng = (p*(p-1)/2) * gammaln(0.5);\nfor alpha = 1:p\n lng = lng + gammaln(b+0.5*(alpha-1));\nend\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_lg_gamma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7132283784643302}} {"text": "% Author: Jai Juneja\n% Date: 12/02/2013\n% \n% Function transforms a point p_r from robot's local frame to the global\n% frame.\n%\n% Inputs: \n% r = [x y alpha]'\t: Robot frame\n% p_r :\tPoint in robot's frame (2*n matrix for n points)\n%\n% Outputs:\n% p_g : Point in global frame (2*n matrix)\n% Optional:\n% PG_r : Jacobian of p_g wrt. robot frame\n% PG_pr : Jacobian of p_g wrt. p_r\nfunction [p_g, PG_r, PG_pr] = transToGlobal(r, p_r)\n\n r_pos = r(1:2); % Robot's position\n r_ang = r(3); % Robot's orientation\n \n % Transformation matrix:\n R = [cos(r_ang), -sin(r_ang) ; ...\n sin(r_ang), cos(r_ang)];\n \n % Hence point p_r tranformed to global co-ordinate frame is:\n p_g = R * p_r;\n p_g = [p_g(1, :) + r_pos(1); p_g(2, :) + r_pos(2)];\n \n if nargout > 1 % Compute Jacobians\n pr_x = p_r(1); pr_y = p_r(2);\n \n PG_r = [...\n 1, 0, - pr_y*cos(r_ang) - pr_x*sin(r_ang); ...\n 0, 1, pr_x*cos(r_ang) - pr_y*sin(r_ang)];\n\n PG_pr = R;\n end\nend", "meta": {"author": "jaijuneja", "repo": "ekf-slam-matlab", "sha": "d0746d0396aa2c24eee6633f3dfc5e1b9f1d7f87", "save_path": "github-repos/MATLAB/jaijuneja-ekf-slam-matlab", "path": "github-repos/MATLAB/jaijuneja-ekf-slam-matlab/ekf-slam-matlab-d0746d0396aa2c24eee6633f3dfc5e1b9f1d7f87/tools/transToGlobal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7132167977150974}} {"text": "% SOLVE_LINEAR_ELASTICITY: Solve a linear elasticity problem on a NURBS domain.\n% For a planar domain it is the plane strain model.\n%\n% The function solves the linear elasticity problem\n%\n% - div (sigma(u)) = f in Omega = F((0,1)^n)\n% sigma(u) \\cdot n = g on Gamma_N\n% u = h on Gamma_D\n%\n% with sigma(u) = mu*(grad(u) + grad(u)^t) + lambda*div(u)*I.\n%\n% u: displacement vector\n% sigma: Cauchy stress tensor\n% lambda, mu: Lame' parameters\n% I: identity tensor\n%\n% USAGE:\n%\n% [geometry, msh, space, u] = solve_linear_elasticity (problem_data, method_data)\n%\n% INPUT:\n%\n% problem_data: a structure with data of the problem. It contains the fields:\n% - geo_name: name of the file containing the geometry\n% - nmnn_sides: sides with Neumann boundary condition (may be empty)\n% - drchlt_sides: sides with Dirichlet boundary condition\n% - press_sides: sides with pressure boundary condition (may be empty)\n% - symm_sides: sides with symmetry boundary condition (may be empty)\n% - lambda_lame: first Lame' parameter\n% - mu_lame: second Lame' parameter\n% - f: source term\n% - h: function for Dirichlet boundary condition\n% - g: function for Neumann condition (if nmnn_sides is not empty)\n%\n% method_data : a structure with discretization data. Its fields are:\n% - degree: degree of the spline functions.\n% - regularity: continuity of the spline functions.\n% - nsub: number of subelements with respect to the geometry mesh \n% (nsub=1 leaves the mesh unchanged)\n% - nquad: number of points for Gaussian quadrature rule\n%\n% OUTPUT:\n%\n% geometry: geometry structure (see geo_load)\n% msh: mesh object that defines the quadrature rule (see msh_cartesian)\n% space: space object that defines the discrete basis functions (see sp_vector)\n% u: the computed degrees of freedom\n%\n% See also EX_LIN_ELAST_HORSESHOE for an example.\n%\n% Copyright (C) 2010 Carlo de Falco\n% Copyright (C) 2011, 2015 Rafael Vazquez\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\nfunction [geometry, msh, sp, u] = ...\n solve_linear_elasticity (problem_data, method_data)\n\n% Extract the fields from the data structures into local variables\ndata_names = fieldnames (problem_data);\nfor iopt = 1:numel (data_names)\n eval ([data_names{iopt} '= problem_data.(data_names{iopt});']);\nend\ndata_names = fieldnames (method_data);\nfor iopt = 1:numel (data_names)\n eval ([data_names{iopt} '= method_data.(data_names{iopt});']);\nend\n\n% Construct geometry structure\ngeometry = geo_load (geo_name);\ndegelev = max (degree - (geometry.nurbs.order-1), 0);\nnurbs = nrbdegelev (geometry.nurbs, degelev);\n[rknots, zeta, nknots] = kntrefine (nurbs.knots, nsub-1, nurbs.order-1, regularity);\n\nnurbs = nrbkntins (nurbs, nknots);\ngeometry = geo_load (nurbs);\n\n% Construct msh structure\nrule = msh_gauss_nodes (nquad);\n[qn, qw] = msh_set_quad_nodes (geometry.nurbs.knots, rule);\nmsh = msh_cartesian (geometry.nurbs.knots, qn, qw, geometry);\n\n% Construct space structure\nspace_scalar = sp_nurbs (nurbs, msh);\nscalar_spaces = repmat ({space_scalar}, 1, msh.rdim);\nsp = sp_vector (scalar_spaces, msh);\nclear space_scalar scalar_spaces\n\n% Assemble the matrices\nmat = op_su_ev_tp (sp, sp, msh, lambda_lame, mu_lame); \nrhs = op_f_v_tp (sp, msh, f);\n\n% Apply Neumann boundary conditions\nfor iside = nmnn_sides\n% Restrict the function handle to the specified side, in any dimension, gside = @(x,y) g(x,y,iside)\n gside = @(varargin) g(varargin{:},iside);\n dofs = sp.boundary(iside).dofs;\n rhs(dofs) = rhs(dofs) + op_f_v_tp (sp.boundary(iside), msh.boundary(iside), gside);\nend\n\n% Apply pressure conditions\nfor iside = press_sides\n msh_side = msh_eval_boundary_side (msh, iside);\n sp_side = sp_eval_boundary_side (sp, msh_side);\n\n x = cell (msh_side.rdim, 1);\n for idim = 1:msh_side.rdim\n x{idim} = reshape (msh_side.geo_map(idim,:,:), msh_side.nqn, msh_side.nel);\n end\n pval = reshape (p (x{:}, iside), msh_side.nqn, msh_side.nel);\n\n rhs(sp_side.dofs) = rhs(sp_side.dofs) - op_pn_v (sp_side, msh_side, pval);\nend\n\n% Apply symmetry conditions\nsymm_dofs = [];\nfor iside = symm_sides\n if (~strcmpi (sp.transform, 'grad-preserving'))\n error ('The symmetry condition is only implemented for spaces with grad-preserving transform')\n end\n msh_side = msh_eval_boundary_side (msh, iside);\n for idim = 1:msh.rdim\n normal_comp(idim,:) = reshape (msh_side.normal(idim,:,:), 1, msh_side.nqn*msh_side.nel);\n end\n\n parallel_to_axes = false;\n for ind = 1:msh.rdim\n ind2 = setdiff (1:msh.rdim, ind);\n if (all (all (abs (normal_comp(ind2,:)) < 1e-10)))\n symm_dofs = union (symm_dofs, sp.boundary(iside).dofs(sp.boundary(iside).comp_dofs{ind}));\n parallel_to_axes = true;\n break\n end\n end\n if (~parallel_to_axes)\n error ('solve_linear_elasticity: We have only implemented the symmetry condition for boundaries parallel to the axes')\n end\n\nend\n\n% Apply Dirichlet boundary conditions\nu = zeros (sp.ndof, 1);\n[u_drchlt, drchlt_dofs] = sp_drchlt_l2_proj (sp, msh, h, drchlt_sides);\nu(drchlt_dofs) = u_drchlt;\n\nint_dofs = setdiff (1:sp.ndof, [drchlt_dofs, symm_dofs]);\nrhs(int_dofs) = rhs(int_dofs) - mat (int_dofs, drchlt_dofs) * u_drchlt;\n\n% Solve the linear system\nu(int_dofs) = mat(int_dofs, int_dofs) \\ rhs(int_dofs);\n\nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/solve/solve_linear_elasticity.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7132167961711667}} {"text": "function [xmin, fmin] = golden(npd, f, ax, bx, cx, tol, varargin)\n%\n%GOLDEN Minimize function of one variable using golden section search\n%\n% [xmin, fmin] = golden(npd, f, ax, bx, cx, tol) computes a local minimum\n% of f. xmin is the computed local minimizer of f and fmin is\n% f(xmin). xmin is computed to an relative accuracy of TOL.\n%\n% The parameters ax, bx and cx must satisfy the following conditions:\n% ax < bx < cx, f(bx) < f(ax) and f(bx) < f(cx).\n%\n% xmin satisfies ax < xmin < cx. golden is guaranteed to succeed if f\n% is continuous between ax and cx\n%\n% Roman Geus, ETH Zuerich, 9.12.97\n%\n% ATI -- added \"npd\" argument & made private to KDE class\nC = (3-sqrt(5))/2;\nR = 1-C;\n \nx0 = ax;\nx3 = cx;\nif (abs(cx-bx) > abs(bx-ax)),\n x1 = bx;\n x2 = bx + C*(cx-bx);\nelse\n x2 = bx;\n x1 = bx - C*(bx-ax);\nend\nf1 = feval(f,x1,npd,varargin{:});\nf2 = feval(f,x2,npd,varargin{:});\n \nk = 1;\nwhile abs(x3-x0) > tol*(abs(x1)+abs(x2)),\n% fprintf(1,'k=%4d, |a-b|=%e\\n', k, abs(x3-x0));\n if f2 < f1,\n x0 = x1;\n x1 = x2;\n x2 = R*x1 + C*x3; % x2 = x1+c*(x3-x1)\n f1 = f2;\n f2 = feval(f,x2,npd,varargin{:});\n else\n x3 = x2;\n x2 = x1;\n x1 = R*x2 + C*x0; % x1 = x2+c*(x0-x2)\n f2 = f1;\n f1 = feval(f,x1,npd,varargin{:});\n end\n k = k+1;\n \n% [x0,x1,x2,x3,f1,f2]\nend\n \nif f1 < f2,\n xmin = x1;\n fmin = f1;\nelse\n xmin = x2;\n fmin = f2;\nend\n", "meta": {"author": "ShapeNet", "repo": "RenderForCNN", "sha": "c0bee04aad3dc2f0ae5de71daf6d51664ce02e76", "save_path": "github-repos/MATLAB/ShapeNet-RenderForCNN", "path": "github-repos/MATLAB/ShapeNet-RenderForCNN/RenderForCNN-c0bee04aad3dc2f0ae5de71daf6d51664ce02e76/render_pipeline/kde/matlab_kde_package/private/golden.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8175744850834648, "lm_q1q2_score": 0.7132089502398637}} {"text": "%%\n% Simple example of gradient flow in metric space.\n\n\nrep = '../results/gradflow-metric/';\n[~,~] = mkdir(rep);\n\nf = @(x,y)x.^2 + y.^2;\nGx = @(x,y)2*x;\nGy = @(x,y)2*y;\n\n% background image\nN = 256;\ntx = linspace(-.05,1,N);\nty = linspace(-.08,.5,N);\n[Y,X] = meshgrid(ty,tx);\nF = f(X,Y);\nclf; hold on;\nimagesc(tx,ty,F');\ncontour(tx,ty,F', 15, 'k');\n\n% for the implicit stepping\nN1 = 2048;\ntx1 = linspace(min(tx),max(tx),N1);\nty1 = linspace(min(ty),max(ty),N1);\n[Y1,X1] = meshgrid(ty1,tx1);\n\n\nplist = [1 1];\nplist = [1 1.3 1.5 1.8 2 3 5 10 Inf];\n\n\ngmode = 'explicit';\ngmode = 'implicit';\n\ntau = .25; niter = 70;\n \nlgd = {};\nfor ip=1:length(plist)\n p=plist(ip);\n \n % conjugate exponent\n q = conjexp(p);\n ri = @(r,p)sign(r).*abs(r).^(1/(p-1));\n \n \n \n grad = @(gx,gy)ri([gx, gy],p);\n if p==1\n grad = @(gx,gy)[gx.*(gx==max(gx,gy)), gy.*(gy==max(gx,gy))];\n elseif p==Inf\n grad = @(gx,gy)[sign(gx),sign(gy)];\n end\n grad = @(gx,gy)grad(gx,gy)*norm([gx,gy],q)/norm(grad(gx,gy),q);\n \n \n % initial point\n x = .95; y = .45;\n U = []; V = [];\n % do the descent\n for i=1:niter\n U(end+1) = x; V(end+1) = y;\n switch gmode\n case 'explicit'\n g = grad(Gx(x,y), Gy(x,y));\n x = x - tau*g(1);\n y = y - tau*g(2);\n case 'implicit'\n E = ( abs(X1-x).^p + abs(Y1-y).^p ).^(2/p) + tau * ( X1.^2 + Y1.^2 );\n if p==Inf\n E = max(abs(X1-x),abs(Y1-y)).^2 + tau * ( X1.^2 + Y1.^2 );\n end\n [tmp,i] = min(E(:));\n x = X1(i); y = Y1(i);\n end\n end\n \n lgd{end+1} = ['p=' num2str(p)];\n c = (ip-1)/(length(plist)-1);\n plot(U,V, '.-', 'Color', [c 0 1-c], 'LineWidth', 2, 'MarkerSize', 23);\n colormap parula(256);\n axis image; axis off;\n axis([min(tx) max(tx) min(ty) max(ty)]);\n drawnow;\n \nend\n\nsaveas(gcf, [rep 'gradflow-' gmode '.eps'], 'epsc');", "meta": {"author": "optimaltransport", "repo": "optimaltransport.github.io", "sha": "2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203", "save_path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io", "path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io/optimaltransport.github.io-2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203/code/gradflow-metric/gradFlow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7131461714531662}} {"text": "function [wc,w0,a0,ak,bk,c0,ck]=get_harmonics(y,pas)\n%[wc,w0,a0,ak,bk,c0,ck]=get_harmonics(y,pas)\n% given a signal x(t),y=x(t)\n% the function get_harmoniques returns the pulse w0(rd/s) of the signal y(t)\n% the coefficients ak (a1,a2,...) and bk (b1,b2,...) of the trigonomical\n% representation of the signal y(t):\n% y(t)= a0/2+ a1.cos(w0t)+b1.sin(w0t)+a2.cos(2w0t) +b2*sin(t*w0)+...\n% it also returns the coefficients c0 and ck of the complex representation\n% y(t)= ...+c(-1).exp(-jw0t)+c(0)+c(1).exp(jw0t)+c(2).exp(2jw0t)+...\n% wc is the interval pulse;\n% to plot the amplitude spectrum: stem(wc,abs(ck))\n%[wc,w0,a0,ak,bk,c0,ck]=get_harmoniques(y,pas)\n% be a signal x(t).\n% For more theorical details look at www.azzimalik.com\nN=length(y);\nY=fft(y);\nif size(Y,2)==1;\n Y=Y';\nend\nw=2*(0:(N-1))*pi/(N*pas);\nw0=w(2);\nnc2=fix(N/2);\nif nc2~=N/2;\n nc3=nc2+1;\n wc=[fliplr(-w(2:nc2+1)) w(1:nc2+1)];\n Yc=[Y(nc2+2:N) Y(1:nc2+1)];Yc=Yc/N;\nelse\n nc3=nc2;\n wc=[fliplr(-w(2:nc2+1)) w(1:nc2+1)];\n Yc=[Y(nc2+1:N) Y(1:nc2+1)];Yc=Yc/N;\nend\n%-------------------------------------------------------------\nN1=length(Yc);\nfor l=2:nc2+1\n ak(l-1)=real(Y(l)+Y(N-l+2))/N;\n bk(l-1)=-imag(Y(l)-Y(N-l+2))/N;\n ckp(l-1)=(ak(l-1)-j*bk(l-1))/2;\n ckm(l-1)=(ak(l-1)+j*bk(l-1))/2;\nend\na0=2*Y(1)/N;\nc0=a0/2;ck=[fliplr(ckm) c0 ckp];\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/37654-get-harmoniques-of-a-real-signal/get_harmonics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7131461641025727}} {"text": "function h = p31_h ( n, x )\n\n%*****************************************************************************80\n%\n%% P31_H evaluates the Hessian for problem 31.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 15 January 2001\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real H(N,N), the N by N Hessian matrix.\n%\n h = zeros ( n, n );\n\n m = 5;\n a = [ 4.0, 4.0, 4.0, 4.0; ...\n 1.0, 1.0, 1.0, 1.0; ...\n 8.0, 8.0, 8.0, 8.0; ...\n 6.0, 6.0, 6.0, 6.0; ...\n 3.0, 7.0, 3.0, 7.0 ]';\n\n c = [ 0.1, 0.2, 0.2, 0.4, 0.6 ]';\n\n for ii = 1 : n\n for jj = 1 : n\n for j = 1 : m\n d = c(j) + sum ( ( x(1:n) - a(1:n,j) ).^2 );\n h(ii,jj) = h(ii,jj) - 8.0 * ( x(ii) - a(ii,j) ) * ( x(jj) - a(jj,j) ) / d^3;\n if ( ii == jj )\n h(ii,jj) = h(ii,jj) + 2.0 / d^2;\n end\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_opt/p31_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7956580976404296, "lm_q1q2_score": 0.7131096537355209}} {"text": "function phi = basis_brick8 ( n, p )\n\n%*****************************************************************************80\n%\n%% BASIS_BRICK8: BRICK8 basis functions at natural coordinates.\n%\n% Discussion:\n%\n% 8------7 t s\n% /| /| | /\n% 5------6 | |/\n% | | | | 0-------r\n% | 4----|-3\n% |/ |/\n% 1------2\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 March 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of evaluation points.\n%\n% Input, real P(3,N), natural coordinates of evaluation\n% points.\n%\n% Output, real PHI(8,N), the basis function values.\n%\n phi(1,1:n) = ( 1.0 - p(1,1:n) ) .* ( 1.0 - p(2,1:n) ) .* ( 1.0 - p(3,1:n) );\n phi(2,1:n) = ( 1.0 + p(1,1:n) ) .* ( 1.0 - p(2,1:n) ) .* ( 1.0 - p(3,1:n) );\n phi(3,1:n) = ( 1.0 + p(1,1:n) ) .* ( 1.0 + p(2,1:n) ) .* ( 1.0 - p(3,1:n) );\n phi(4,1:n) = ( 1.0 - p(1,1:n) ) .* ( 1.0 + p(2,1:n) ) .* ( 1.0 - p(3,1:n) );\n phi(5,1:n) = ( 1.0 - p(1,1:n) ) .* ( 1.0 - p(2,1:n) ) .* ( 1.0 + p(3,1:n) );\n phi(6,1:n) = ( 1.0 + p(1,1:n) ) .* ( 1.0 - p(2,1:n) ) .* ( 1.0 + p(3,1:n) );\n phi(7,1:n) = ( 1.0 + p(1,1:n) ) .* ( 1.0 + p(2,1:n) ) .* ( 1.0 + p(3,1:n) );\n phi(8,1:n) = ( 1.0 - p(1,1:n) ) .* ( 1.0 + p(2,1:n) ) .* ( 1.0 + p(3,1:n) );\n\n phi(1:8,1:n) = phi(1:8,1:n) / 8.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/fem3d_pack/basis_brick8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7130985216358459}} {"text": "function [a,b,alpha,p,chiopt,Cab,Calphap]=...\n wtls_line(xin,yin,uxin,uyin,guck);\n% function [a,b,alpha,p,chiopt,Cab,Calphap]=...\n% wtls_line(xin,yin,uxin,uyin,guck);\n%\n% weighted total least squares (wtls) fit of a straigth line \n% to a set of points with uncertainties in both coordinates\n%\n% input: xin abscissa vector\n% yin ordinate vector\n% uxin (standard) uncertainties of xin, same size as xin\n% uyin (standard) uncertainties of yin, same size as yin\n% guck flag, if >0, chisquare is plotted over whole\n% alpha-interval, optimum alpha is shown as red +\n%\n% output: a, b usual straight line parameters\n% y=a*x+b\n% alpha,p more stable parametrisation\n% y*cos(alpha)-x*sin(alpha)-p=0\n% alpha: slope angle in radians\n% p: distance of straight line from (0,0)\n% conversion: a=tan(alpha),b=p/cos(alpha)\n% chiopt minimum chisquare found\n% Cab covariances, [var(a),var(b),cov(a,b)]\n% Calphap covariances, [var(alpha),var(p),cov(alpha,p)]\n%\n% algorithm: M. Krystek & M. Anton\n% Physikalisch-Technische Bundesanstalt Braunschweig, Germany\n% Meas. Sci. Tech. 18 (2007), pp3438-3442\n%\n% tested for Matlab 6 and Matlab 7\n% testdata: script file pearson_york_testdata.m\n%\n% 2007-03-08\n\ntol=1e-6; %\"tolerance\" parameter of fnimbnd, see there\n\nglobal ux uy x y\n% inputs\nif nargin<5,guck=0;end\n% force column vectors\nx=xin(:);\ny=yin(:);\nux=uxin(:);\nuy=uyin(:);\n% \"initial guess\": \np0=polyfit(x,y,1);\nalpha0=atan(p0(1));\n% one-dimensional search, use p=p^\n[alphaopt,chiopt,exitflag] = ...\n fminbnd(@chialpha,alpha0-pi/2,alpha0+pi/2,optimset('TolX',tol));\n% get optimum p from alphaopt\nalpha=alphaopt;\nuk2=ux.^2*sin(alpha)^2+uy.^2*cos(alpha)^2;\nu2=1./mean(1./uk2);\nw=u2./uk2;\nxbar=mean(w.*x);\nybar=mean(w.*y);\np=ybar*cos(alpha)-xbar*sin(alpha);\n% convert to a, b parameters y=a*x+b\na=sin(alpha)/cos(alpha);\nb=p/cos(alpha);\n% --- uncertainty calculation, covariance matrix = 2*inv(Hessian(chi2)) ---\nn=length(x);\nvk=y.*cos(alpha)-x*sin(alpha)-p;\nvka=-y*sin(alpha)-x*cos(alpha);\nvkaa=-vk-p;\nfk=vk.*vk;\nfka=2*vk.*vka;\nfkaa=2*(vka.^2+vk.*vkaa);\ngk=uk2;\ngka=2*sin(alpha)*cos(alpha)*(ux.^2-uy.^2);\ngkaa=2*(ux.^2-uy.^2)*(cos(alpha)^2-sin(alpha)^2);\nHpp=2*n/u2;\nHalphap=-2*sum((vka.*gk-gka.*vk)./gk.^2);\nHalphaalpha=...\n sum(fkaa./gk-2*fka.*gka./gk.^2+2*gka.^2.*fk./gk.^3-gkaa.*fk./gk.^2);\nNN=2/(Hpp*Halphaalpha-Halphap^2);\nvar_p=NN*Halphaalpha;\nvar_alpha=NN*Hpp;\ncov_alphap=-NN*Halphap;\nCalphap=[var_alpha,var_p,cov_alphap];\n% ------ convert to a & b covariance matrix, following DIN 1319 (4)\nvar_a=var_alpha/cos(alpha)^4;\nvar_b=(var_alpha*p*p*sin(alpha)^2+var_p*cos(alpha)^2+...\n 2*cov_alphap*p*sin(alpha)*cos(alpha))/cos(alpha)^4;\ncov_ab=(var_alpha*p*sin(alpha)+cov_alphap*cos(alpha))/cos(alpha)^4;\nCab=[var_a,var_b,cov_ab];\n% ------ end of uncertainty calculation -----------------------------------\n%\n%-------------------- plotting section ------------------------------------\nif guck~=0\n alphatest=linspace(alpha-pi/2,alpha+pi/2,1000);\n for k=1:length(alphatest),chitest(k)=chialpha(alphatest(k));end\n plot(alphatest,chitest,alphaopt,chiopt,'+r')\n xlabel('alpha')\n ylabel('\\chi^2')\n grid on\n disp([mfilename,' :: paused, hit any key to continue'])\n pause\nend\n% ------------------ end of plotting section ------------------------------\nreturn\n% ------------------ subfunction ------------------------------------------\nfunction chi=chialpha(alpha)\n global ux uy x y\n uk2=ux.^2*sin(alpha)^2+uy.^2*cos(alpha)^2;\n u2=1./mean(1./uk2);\n w=u2./uk2;\n xbar=mean(w.*x);\n ybar=mean(w.*y);\n p=ybar*cos(alpha)-xbar*sin(alpha);\n chi=sum((y*cos(alpha)-x*sin(alpha)-p).^2./uk2);\nreturn\n% ----------- end of subfunction ------------------------------------------\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/17466-weighted-total-least-squares-straight-line-fit/wtls_line.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.7130985020680825}} {"text": "function [theta,b,QMin]=LTSRegression(x,y,h)\n%%LTSREGRESSION Perform least trimmed squares (LTS) regression using the\n% fast, approximate algorithm of [1] that is identified as\n% best for <600 data points. This means find theta and b that\n% minimizes \n% sum_{i=1}^h r_i^2\n% where r_i is the ith largest value of\n% abs(y(i)-theta*x(:,i)-b)\n% This type of regression is robust to outliers.\n%\n%INPUTS: x,y These are the real samples of data. x is an xDimXN set of N\n% vectors and y is a set of corresponding scalar values. The\n% regression searches for theta and b to fit a line such that\n% y=theta'*x(:,i)+b.\n% h The trim value of the estimator. This must be between\n% fix((N+xDim+2)/2) and n. The default if omitted or an empty\n% matrix is passed is the value that allows for the highest\n% breakdown value, which is fix((N+xDim+2)/2).\n%\n%OUTPUTS: theta An xDimX1 vector. The multivariate slope of the line.\n% b The scalar y intercept of the data.\n% QMin The residual of the data.\n%\n%The algorithm described in [1] without the y intercept adjustment is used.\n%\n%EXAMPLE:\n%This is similar to an example in [1]. There is a distribution that one\n%might expect to be well approximated with a line corrupted by a minority\n%of samples of a different distribution at the side. The plot is zoomed in\n%so not all samples are shown. The standard linear regression result is\n%shown for comparison.\n% x=100*randn(1,800/2);\n% y=x+1+randn(1,800/2);\n% \n% xy=GaussianD.rand(200/2,[50;0],25*eye(2,2));\n% x=[x,xy(1,:)];\n% y=[y,xy(2,:)];\n% \n% figure(1)\n% clf\n% hold on\n% scatter(x,y,'b','filled')\n% \n% coeffs=multilinRegress([x;y]);\n% numPoints=100;\n% xEst=linspace(-200,200,numPoints);\n% yEst=xEst*coeffs(1)+coeffs(2);\n% plot(xEst,yEst,'--k','linewidth',2)\n% [theta,b]=LTSRegression(x,y);\n% yEst=theta*xEst+b;\n% plot(xEst,yEst,'-r','linewidth',2)\n% axis([-30-20,70+20,-30-20,50+20])%Zoom in.\n% legend('Samples','Least Squares Fit','LTS Fit','location','NorthWest')\n% h1=xlabel('x');\n% h2=ylabel('y');\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%REFERENCES:\n%[1] P. J. Rousseeuw and V. Katrien, \"Computing LTS regression for large\n% data sets,\" Data Mining and Knowledge Discovery, vol. 12, no. 1, pp.\n% 26-45, Jan. 2006.\n%\n%August 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nn=size(x,2);\n\nx=[x;ones(1,n)];\n\ny=y(:);\n\np=size(x,1);%p>=2\n\nif(nargin<3||isempty(h))\n h=fix((n+p+1)/2);\nend\n\nif(hn)\n error('Invalid value of h provided.') \nend\n\ntotalStarts=binomial(n,p);\nQ3Heap=BinaryHeap(10,false);\nfor k=1:min(totalStarts,500)\n if(totalStarts<500)\n %Do all possible initializations.\n idx=unrankCombination(k-1,n,p)+1;\n else \n %Get a random subset of points in x.\n idx=randCombination(n,p)+1;\n end\n\n xCur=x(:,idx);\n yCur=y(idx);\n %If what we get is not full rank, then we just use a\n %pseudoinverse. This skips issues of determining which and how\n %many additional columns to add.\n if(rank(xCur)Q3)\n Q3Heap.deleteTop();\n Q3Heap.insert(Q3,idx);\n end\n end\nend\n\n%For the 10 Q3 values in the heap, iterate the C-step in Section 2\n%until convergence.\ntheta0List=zeros(p,10);\nQList=zeros(10,1);\nfor k=1:10\n topEl=Q3Heap.getTop();\n Q3Heap.deleteTop();\n\n idx=topEl.value;\n xCur=x(:,idx);\n yCur=y(idx);\n theta0=pinv(xCur)'*yCur;\n idxOld=zeros(h,1);\n\n %It was noted that convergence should be for fewer than 10\n %iterations, so we make the maximum 10.\n for curIter=1:10 \n if(all(idx(:)==idxOld(:)))\n break;\n end\n r0=y'-sum(bsxfun(@times,x,theta0),1);\n [~,idx]=sort(abs(r0),'ascend');\n idx=idx(1:h);\n\n xCur=x(:,idx);\n yCur=y(idx);\n theta0=pinv(xCur)'*yCur;\n end\n\n r2=(y'-sum(bsxfun(@times,x,theta0),1)).^2;\n Q=sum(mink(r2,h));\n \n QList(k)=Q;\n theta0List(:,k)=theta0;\nend\n\n[QMin,idx]=min(QList);\ntheta0Min=theta0List(:,idx);\n\ntheta=theta0Min(1:(p-1));\nb=theta0Min(p);\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/Robust_Statistics/LTSRegression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7130610172131474}} {"text": "function rbfBasis = rbfComputeBasis( X, k, cluster, scale, show )\n% Get locations and sizes of radial basis functions for use in rbf network.\n%\n% Radial basis function are a simple, fast method for universal function\n% approximation / regression. The idea is to find a mapping X->y where X\n% and y are continuous real variables. The mapping is linear over features\n% of X: y=rbfWeight*features(X). The features are of the form:\n% f_j(x) = exp(-||x-mu_j||_2^2 / 2 sig_j^2 ).\n% The number of basis functions controls the complexity of the network. Too\n% many basis functions can lead to overfitting, too few to bad\n% interpolation. Rbf networks are trained in two phases. First, the radial\n% basis functions are found in an unsupervised manner (using only Xtrain),\n% for example by clustering Xtrain. Next, given the basis functions,\n% Xtrain and ytrain, the basis weights are found by solving the system:\n% rbfWeight * features(Xtrain) = ytrain\n% At this point, to interpolate any new points, Xtest, use:\n% ytest = rbfWeight * features(Xtest)\n% The code below achieves all three steps:\n% rbfBasis = rbfComputeBasis( Xtrain, k, cluster, scale, show );\n% rbfWeight = rbfComputeFtrs(Xtrain,rbfBasis) \\ ytrain;\n% ytest = rbfComputeFtrs(Xtest,rbfBasis) * rbfWeight;\n% Note, in the returned rbfBasis struct there are a number of flags that\n% control how the rbf features are computed. These can be altered to\n% achieve the desired effect.\n%\n% For an in depth discussion of rbf networks see:\n% Christopher M. Bishop. \"Neural Networks for Pattern Recognition\"\n%\n% USAGE\n% rbfBasis = rbfComputeBasis( X, k, [cluster], [scale], [show] )\n%\n% INPUTS\n% X - [N x d] N points of d dimensions each\n% k - number of basis functions to use\n% cluster - [1]: Computes cluster centers for use as rbf functions.\n% - 0: Evenly centered basis functions (ok for small d)\n% scale - [5] Alter computed value of sigma by given factor\n% set larger for smoother results, too small -> bad interp\n% show - [0] will display results in figure(show)\n% if show<0, assumes X is array Nxs^2 of N sxs patches\n%\n% OUTPUTS\n% rfbBasis\n% .d - feature vector size\n% .k - number of basis functions actually used\n% .mu - [d x k] rbf centers\n% .vars - [1 x k] rbf widths\n% .var - rbf average width\n% .globalVar - [1] if true use single average var for rbfs\n% .constant - [0] if true include extra basis with constant activation\n% .normalize - [0] if true normalize overall rbf response to sum to 1\n%\n% EXAMPLE\n%\n% See also RBFDEMO, RBFCOMPUTEFTRS\n%\n% Piotr's Computer Vision Matlab Toolbox Version 2.50\n% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n% Licensed under the Simplified BSD License [see external/bsd.txt]\n\nif( nargin<2 || isempty(k)); error('k not specified'); end\nif( nargin<3 || isempty(cluster)); cluster=1; end\nif( nargin<4 || isempty(scale)); scale=5; end\nif( nargin<5 || isempty(show)); show=0; end\n[N, d] = size(X);\n\nif( cluster )\n %%% CLUSTERS subsample, run kmeans\n maxN=5000; if( N>maxN ); X=X(randSample(N,maxN),:); N=maxN; end\n prm.nTrial=5; prm.display=0;\n [IDX,mu] = kmeans2( X, k, prm );\n mu = mu'; k = size(mu,2);\nelse\n %%% GRID generate locations evenly spaced on grid\n if( d>4 ); error('d too high. curse of dimensionality..'); end\n nBPer = round( k ^ (1/d) ); k = nBPer ^ d; rg=[min(X)' max(X)'];\n del=(rg(:,2)-rg(:,1))/(nBPer-1); rg=rg+[-del del]/2;\n loc=cell(1,d); for i=1:d; loc{i}=linspace(rg(i,1),rg(i,2),nBPer); end\n grid=cell(1,d); if(d>1); [grid{:}]=ndgrid(loc{:}); else grid=loc; end\n mu=zeros(d,k); for i=1:d; mu(i,:) = grid{i}(:); end\nend\n\n%%% Set var to be equal to average distance of neareast neighbor.\ndist = pdist2( mu', mu' );\ndist = dist + realmax * eye( k );\nvars = min(dist)* scale;\nvar = mean(vars);\nvars = max( vars, var/100 );\n\n%%% store results\nrbfBasis = struct('d',d, 'k',k, 'mu',mu, 'vars',vars, 'var',var, ...\n 'globalVar',1, 'constant',0, 'normalize',0);\n\n%%% optionally display\nif( abs(show) )\n if( show<0 ) % if images can display\n siz = sqrt(d);\n I = clusterMontage( reshape(X,siz,siz,N), IDX, 25, 1 );\n figure(-show); clf; montage2( I );\n figure(-show+1); clf; montage2(reshape(mu,siz,siz,[]));\n elseif( d==1 ) % 1D data\n figure(show); clf; hold on;\n minX = min(X,[],1 ); maxX = max(X,[],1 );\n xs = linspace( minX, maxX, 500 )';\n for i=1:k\n ys = exp( -(xs-mu(i)).^2 / 2 / var );\n plot( xs, ys );\n end\n elseif( d==2 ) % 2D data\n figure(show); clf;\n minX = min(X,[],1 ); maxX = max(X,[],1 );\n xs1 = linspace(minX(1),maxX(1),25);\n xs2 = linspace(minX(2),maxX(2),25);\n [xs1,xs2] = ndgrid( xs1, xs2 );\n xs = [xs1(:) xs2(:)]; n = size(xs,1);\n for i=1:k\n mui = repmat(mu(:,i),[1 n])';\n ys = exp( - sum( ((xs - mui)).^2, 2 ) / 2 / var );\n surf( xs1, xs2, reshape(ys,size(xs1)) );\n hold on;\n end;\n elseif( d==3 ) % 3D data (show data+centers)\n figure(show); clf; hold on;\n scatter3( X(:,1),X(:,2),X(:,3),12,'filled');\n scatter3( mu(1,:),mu(2,:),mu(3,:),30,'filled');\n end\nend\n", "meta": {"author": "pdollar", "repo": "toolbox", "sha": "e87332637bbe8e8b92dd487c87567d9628404523", "save_path": "github-repos/MATLAB/pdollar-toolbox", "path": "github-repos/MATLAB/pdollar-toolbox/toolbox-e87332637bbe8e8b92dd487c87567d9628404523/classify/rbfComputeBasis.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.7130277697001731}} {"text": "function Q=quatMult(quat2,quat1,handed)\n%%QUATMULT Multiply two quaternions together. Quaternions are an extension\n% of complex numbers. The type of product performed here is\n% deemed the Grassman product. Unit-magnitude quaternions are\n% often used to represent rotations and the multiplication\n% quat2*quat1 is the orientation obtained by rotating by quat1\n% and then rotating by quat2. Quaternion multiplication is not\n% commutative. The quaternions can be either left or\n% right-handed.\n%\n%INPUTS:quat2 A 4XN set of N quaternions, where the first element in each\n% column is the scalar part of the quaternion (sometimes called\n% q0 or q4) and the next three elements are the (hypercomplex)\n% vector part. That is, the hypercomplex quaternion given by\n% quat2(:,1) can be written in hypercomplex, non-vector form\n% as quat2(1,1)+i*quat2(2,1)+j*quat2(3,1)+k*quat2(4,1), where\n% i, j, and k are all roots of -1. When considering unit\n% quaternions, this means that it has the form\n% [cos(theta/2);sin(theta/2)u'], where theta is an angle and u\n% is a 3X1 unit vector.\n% quat1 A 4XN set of N quaternions that are to be left-multiplied by\n% the corresponding quaternions in quat2.\n% handed The handedness of the quaternions. If omitted or an empty\n% matrix is passed,, it is assumed that the quaternions are\n% right-handed (the standard). Possible values are\n% 'right' The default if omitted. The quaternion multiplication\n% is assumed right-handed (standard).\n% 'left' The quaternion multiplication is assumed left-handed.\n% This is used in someplaces, including the reference\n% from Shuster, below.\n%\n%OUTPUTS: Q The 4XN matrix of quaternions products such that\n% Q(:,i)=quat2(:,i)*quat1(:,1), where the multiplication\n% operation is quaternion multiplication.\n%\n%Properties of quaternions including multiplication are described in [1].\n%Details of rotation using unit quaternions are given in [2].\n%\n%The difference in multiplication between right-handed and left-handed\n%quaternions lies in the sign used for the cross product.\n%\n%A quaternion of the 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] Weisstein, Eric W. \"Quaternion.\" From MathWorld--A Wolfram Web\n% Resource. http://mathworld.wolfram.com/Quaternion.html\n%[2] M. D. Shuster, \"A survey of attitude representations,\" The Journal of\n% the Astronautical Sciences, vol. 41, no. 4, pp. 439-517, Oct.-Dec.\n% 1993.\n%\n%September 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%The number of quaternions.\nN=size(quat2,2);\n\nif(nargin<3||isempty(handed))\n handed='right';\nend\n\nQ=zeros(4,N);\n%The handedness switches the sign of the cross product\nswitch(handed)\n case 'right'\n for curQuat=1:N\n s1=quat1(1,curQuat);\n v1=quat1(2:4,curQuat);\n s2=quat2(1,curQuat);\n v2=quat2(2:4,curQuat);\n\n Q(:,curQuat)=[s1*s2-dot(v1,v2);\n s1*v2+s2*v1+cross(v2,v1)];\n end\n case 'left'\n %Flip the algebra to left-handed for the formula below.\n for curQuat=1:N\n s1=quat1(1,curQuat);\n v1=quat1(2:4,curQuat);\n s2=quat2(1,curQuat);\n v2=quat2(2:4,curQuat);\n\n Q(:,curQuat)=[s1*s2-dot(v1,v2);\n s1*v2+s2*v1-cross(v2,v1)];\n end\n otherwise\n error('Invalid handedness provided.')\nend\nend\n\n%LICENSE:\n%\n%The source code is in the public domain and not licensed or under\n%copyright. The information and software may be used freely by the public.\n%As required by 17 U.S.C. 403, third parties producing copyrighted works\n%consisting predominantly of the material produced by U.S. government\n%agencies must provide notice with such work(s) identifying the U.S.\n%Government material incorporated and stating that such material is not\n%subject to copyright protection.\n%\n%Derived works shall not identify themselves in a manner that implies an\n%endorsement by or an affiliation with the Naval Research Laboratory.\n%\n%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE\n%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL\n%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS\n%OF RECIPIENT IN THE USE OF THE SOFTWARE.\n", "meta": {"author": "USNavalResearchLaboratory", "repo": "TrackerComponentLibrary", "sha": "9f6e329de5be06a371757c4b853200beb6def2d0", "save_path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary", "path": "github-repos/MATLAB/USNavalResearchLaboratory-TrackerComponentLibrary/TrackerComponentLibrary-9f6e329de5be06a371757c4b853200beb6def2d0/Mathematical_Functions/Quaternions/quatMult.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.798186787341014, "lm_q1q2_score": 0.71302776492003}} {"text": "function [x, c, funVal, ValueL]=mtLogisticC(A, y, z, opts)\n%\n%%\n% Function mtLogisticC:\n% Logistic Loss for Multi-task Learning\n% with the (group) L1/Lq-norm Constraint\n%\n%% Problem\n%\n% min \\sum_i - weight_i * log (p_i) + z * sum_j ||x^j||_q\n%\n% p_i= 1/ (1+ exp(-y_i (x_l' * a_i + c_l) ) ) denotes the probability\n%\n% a_i denotes a training sample,\n% and a_i' corresponds to the i-th row of the data matrix A\n%\n% x^j denotes the j-th row of x\n% x_l denotes the l-th column of x, for the l-th task\n% c_l is the intercept for the l-th task\n%\n% y_i (either 1 or -1) is the response\n%\n% weight_i denotes the weight for the i-th sample\n% In this implementation, we assume weight_{il}=1/m\n%\n% For the case that the multi tasks share the same data\n% matrix, please refer to the functions:\n% mcLeastR and mcLogisticR.\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 m x 1)\n% z - L1/Lq norm regularization parameter (z >=0)\n% opts- Optional inputs (default value: opts=[])\n%\n%% Output parameters:\n% x- The obtained weight of size n x k\n% c- The obtained intercept if size 1 x k\n% funVal- Function value during iterations\n%\n%% Copyright (C) 2009-2010 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 February 19, 2010.\n%\n%% Related papers\n%\n% [1] Jun Liu, Shuiwang Ji, and Jieping Ye, Multi-Task Feature Learning\n% Via Efficient L2,1-Norm Minimization, UAI, 2009\n%\n% [2] Jun Liu, Lei Yuan, Songcan Chen and Jieping Ye, Multi-Task Feature Learning\n% Via Efficient L2,1-Norm Minimization, Technical Report ASU, 2009.\n%\n%% Related functions:\n%\n% sll_opts, initFactor, pathSolutionLeast\n% mtLeastR, mtLeastC, mtLogisticR, ep21d\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<=0)\n error('\\n z should be positive!\\n');\nend\n\nopts=sll_opts(opts); % run sll_opts to set default values (flags)\n\n%% Detailed initialization\n%%\n\n% Initialize ind and q\nif ~isfield(opts,'ind')\n error('\\n In mtLeastR, .ind should be specified');\nelse\n ind=opts.ind;\n k=length(ind)-1;\n\n if ind(k+1)~=m\n error('\\n Check opts.ind');\n end\nend\n\n% Initialize q\nif (~isfield(opts,'q'))\n q=2; opts.q=2;\nelse % currently, we only implement q=2\n q=opts.q;\n if (q~=2)\n error('\\n Currently, we only implement the case q=2');\n end\nend\n\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%% Starting point initialization\n\np_flag=(y==1); % the indices of the postive samples\n\nfor i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n\n m1(1,i)=sum(p_flag(ind_i)); % the total number of the positive samples\n m2(1,i)=length(ind_i)-m1(1,i); % the total number of the negative samples\nend\n\n% initialize a starting point\nif opts.init==2\n x=zeros(n,k); c=zeros(1,k);\nelse\n if isfield(opts,'x0')\n x=opts.x0;\n if ( size(x,1)~=n || size(x,2)~=k )\n error('\\n Check the input .x0');\n end\n else\n x=zeros(n,k);\n end\n\n if isfield(opts,'c0')\n c=opts.c0;\n\n if ( length(c)~=k )\n error('\\n Check the input .c0');\n end\n else\n c=log(m1./m2);\n end\nend\n\nAx=zeros(m,1); % m x 1\n% compute Ax: Ax_i= A_i * x_i\nfor i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n m_i=ind(i+1)-ind(i); % number of samples in the i-th group\n\n if (opts.nFlag==0)\n Ax(ind_i,1)=A(ind_i,:)* x(:,i);\n elseif (opts.nFlag==1)\n invNu=x(:,i)./nu; mu_invNu=mu * invNu;\n Ax(ind_i,1)=A(ind_i,:)*invNu -repmat(mu_invNu, m_i, 1);\n else\n Ax(ind_i,1)=A(ind_i,:)*x(:,i)-repmat(mu*x(:,i), m, 1);\n Ax(ind_i,1)=Ax./nu(ind_i,1);\n end\nend\n\n\n%% The main program\n% The Armijo Goldstein line search schemes\n\nif (opts.lFlag==0)\n \n lambda0=0;\n % a guess of the root\n \n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1/m; % the intial guess of the Lipschitz continuous gradient\n\n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,k);\n cp=c; ccp=zeros(1,k);\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; sc=c + beta* ccp;\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 % aa= - diag(y) * (A * s + sc)\n vec_sc=zeros(m,1);\n for i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n vec_sc(ind_i,1)=sc(i);\n end\n aa=- y.*(As+ vec_sc);\n\n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_s= sum(sum ( log( exp(-bb) + exp(aa-bb) ) + bb ) ) / m;\n\n % compute prob=[p_1;p_2;...;p_m]\n prob=1./( 1+ exp(aa) );\n\n % b= - diag(y) * (1 - prob)\n b= -y.*(1-prob) / m;\n\n gc=zeros(1,k); % the gradient of c\n for i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n gc(1,k)=sum(b(ind_i));\n end\n\n % compute g= AT b, the gradient of x\n for i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n\n if (opts.nFlag==0)\n tt =A(ind_i,:)'*b(ind_i,1);\n elseif (opts.nFlag==1)\n tt= A(ind_i,:)'*b(ind_i,1) - sum(b(ind_i,1)) * mu';\n tt=tt./nu(ind_i,1);\n else\n invNu=b(ind_i,1)./nu(ind_i,1);\n tt=A(ind_i,:)'*invNu - sum(invNu)*mu';\n end\n\n g(:,i)= tt;\n end\n\n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n cp=c;\n\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; c= sc- gc/L;\n\n % L1/Lq-norm regularized projection\n [x, lambda, zf_step]=ep21d(v, n, k, z, lambda0);\n lambda0=lambda;\n \n v=x-s; % the difference between the new approximate solution x\n % and the search point s\n\n % compute Ax: Ax_i= A_i * x_i\n for i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n m_i=ind(i+1)-ind(i); % number of samples in the i-th group\n\n if (opts.nFlag==0)\n Ax(ind_i,1)=A(ind_i,:)* x(:,i);\n elseif (opts.nFlag==1)\n invNu=x(:,i)./nu; mu_invNu=mu * invNu;\n Ax(ind_i,1)=A(ind_i,:)*invNu -repmat(mu_invNu, m_i, 1);\n else\n Ax(ind_i,1)=A(ind_i,:)*x(:,i)-repmat(mu*x(:,i), m, 1);\n Ax(ind_i,1)=Ax./nu(ind_i,1);\n end\n end\n\n % aa= - diag(y) * (A * x + c)\n vec_sc=zeros(m,1);\n for i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n vec_sc(ind_i,1)=c(i);\n end\n aa=- y.*(Ax+ vec_sc);\n\n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_x= sum(sum ( log( exp(-bb) + exp(aa-bb) ) + bb ) ) / m;\n\n r_sum=(norm(v,'fro')^2 + norm(c-sc,2)^2) / 2;\n l_sum=fun_x - fun_s - sum(sum(v.* g)) - (c-sc)* gc';\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 fun_x <= fun_s + + \n % + L/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 ValueL(iterStep)=L;\n\n xxp=x-xp; ccp=c-cp;\n\n funVal(iterStep)=fun_x;\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=norm(xxp,'fro');\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=norm(xp,'fro'); norm_xxp=norm(xxp,'fro');\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 end\nend\n\n%% Adaptive line search scheme\n\nif (opts.lFlag==1)\n \n lambda0=0;\n % a guess of the root\n \n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1/m; % the intial guess of the Lipschitz continuous gradient\n\n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,k);\n cp=c; ccp=zeros(1,k);\n % t is the upper bound of absolute value of x\n\n gamma=1;\n % we shall set the value of gamma = L,\n % and L is appropriate for the starting point\n\n for iterStep=1:opts.maxIter\n while (1)\n if (iterStep~=1)\n alpha= (-gamma+ sqrt(gamma*gamma + 4* L * gamma)) / (2*L);\n beta= (gamma - gamma* alphap) / (alphap * gamma + alphap* L * alpha);\n % beta is the coefficient for generating search point s\n\n s=x + beta* xxp; sc=c + beta* ccp;\n As=Ax + beta* (Ax-Axp);\n else\n alpha= (-1+ sqrt(5)) / 2; beta=0; \n s=x; sc= c; \n As=Ax;\n end\n\n % aa= - diag(y) * (A * s + sc)\n vec_sc=zeros(m,1);\n for i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n vec_sc(ind_i,1)=sc(i);\n end\n aa=- y.*(As+ vec_sc);\n\n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_s= sum(sum ( log( exp(-bb) + exp(aa-bb) ) + bb ) ) / m;\n\n % compute prob=[p_1;p_2;...;p_m]\n prob=1./( 1+ exp(aa) );\n\n % b= - diag(y) * (1 - prob)\n b= -y.*(1-prob) / m;\n\n gc=zeros(1,k); % the gradient of c\n for i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n gc(1,k)=sum(b(ind_i));\n end\n\n % compute g= AT b, the gradient of x\n for i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n\n if (opts.nFlag==0)\n tt =A(ind_i,:)'*b(ind_i,1);\n elseif (opts.nFlag==1)\n tt= A(ind_i,:)'*b(ind_i,1) - sum(b(ind_i,1)) * mu';\n tt=tt./nu(ind_i,1);\n else\n invNu=b(ind_i,1)./nu(ind_i,1);\n tt=A(ind_i,:)'*invNu - sum(invNu)*mu';\n end\n\n g(:,i)= tt;\n end\n\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; cnew= sc- gc/L;\n\n % projection\n [xnew, lambda, zf_step]=ep21d(v, n, k, z, lambda0);\n lambda0=lambda;\n\n v=xnew-s; % the difference between the new approximate solution x\n % and the search point s\n\n % compute Axnew = A *xnew: Ax_i= A_i * xnew_i\n for i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n m_i=ind(i+1)-ind(i); % number of samples in the i-th group\n\n if (opts.nFlag==0)\n Axnew(ind_i,1)=A(ind_i,:)* xnew(:,i);\n elseif (opts.nFlag==1)\n invNu=xnew(:,i)./nu; mu_invNu=mu * invNu;\n Axnew(ind_i,1)=A(ind_i,:)*invNu -repmat(mu_invNu, m_i, 1);\n else\n Axnew(ind_i,1)=A(ind_i,:)*xnew(:,i)-repmat(mu*xnew(:,i), m, 1);\n Axnew(ind_i,1)=Axnew./nu(ind_i,1);\n end\n end\n\n % aa= - diag(y) * (A * x + c)\n vec_sc=zeros(m,1);\n for i=1:k\n ind_i=(ind(i)+1):ind(i+1); % indices for the i-th group\n vec_sc(ind_i,1)=cnew(i);\n end\n aa=- y.*(Axnew+ vec_sc);\n\n % fun_x is the logistic loss at the new approximate solution\n % xnew\n bb=max(aa,0);\n fun_x= sum(sum ( log( exp(-bb) + exp(aa-bb) ) + bb ) ) / m;\n\n\n r_sum=(norm(v,'fro')^2 + norm(cnew-sc,2)^2) / 2;\n l_sum=fun_x - fun_s - sum(sum(v.* g)) - (cnew-sc)* gc';\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 fun_x <= fun_s + + \n % + L/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 gamma=L* alpha* alpha; alphap=alpha;\n % update gamma, and alphap\n\n ValueL(iterStep)=L;\n \n tao=L * r_sum / l_sum;\n if (tao >=5)\n L=L*0.8;\n end\n % decrease the value of L\n\n xp=x; Axp=Ax;\n x=xnew; Ax=Axnew;\n cp=c; c=cnew;\n % update x, t, c, and Ax\n \n xxp=x-xp; ccp=c-cp;\n\n funVal(iterStep)=fun_x;\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=norm(xxp,'fro');\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=norm(xp,'fro'); norm_xxp=norm(xxp,'fro');\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 end\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/L1Lq/L21C/mtLogisticC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7130192411730337}} {"text": "%Tristan Ursell\n%Relative Noise Transform\n%(c) November 2012\n%\n%Iout=relnoise(Iin,sz,sigma);\n%Iout=relnoise(Iin,sz,sigma,'field');\n%[Iout,Ivar]=relnoise(Iin,sz,sigma,...);\n%[Iout,Ivar,Imean]=relnoise(Iin,sz,sigma,...);\n%\n%Iin = the input image, of any numerical class.\n%\n%sz = (3 < sz < min(size(Iin))) is the size of the filter block used to\n%calculate means and variances. This value must be odd.\n%\n%sigma (sigma > 0) is the weighting parameter that defines the standard\n%deviation relative to the filter block's standard deviation around which\n%the center pixel will be Gaussian weighted. Setting sigma = 1 weights the\n%current pixel using the STD of the current filter block. Lower values\n%bring the current pixel closer to the mean, while high values are more\n%tolerant of variations. As sigma -> Inf, Iout = Iin.\n%\n%The field 'plot' will create an output plot comparing this transform to\n%the original image, a Gaussian blur with STD = sz/2, and median filter \n%with block size equal to sz. At first glance, this filter appears similar\n%to a median transform, but it does a better job of preserving local\n%intensity extrema. Comparison with the median filter requires the Image\n%Processing Toolbox, but the rest of the script does not.\n%\n%The field 'disk' or 'square' will choose between using a disk or square\n%filter block shape, where sz is the disk diameter or square side length.\n%The default is square.\n%\n%The field 'custom' may be followed by a user-defined logical matrix or\n%strel, e.g. relnoise(Iin,sz,sigma,'custom',strel('line',30,45)). In this\n%case 'sz' will be unused.\n%\n%Iout is the transformed output image.\n%\n%Ivar is the variance of the pixel intensities in the filter block at every\n%point in the image -- essentially the spatially varying variance of the\n%image.\n%\n%Imean is the mean smoothed image using the filter block, equivalent to a\n%convolution averaging filter with the specified neighborhood.\n%\n%see also: wiener2 filter2\n%\n%Example:\n%\n%Iin=imread('spot_test.tif');\n%\n%Iout=relnoise(Iin,3,0.5,'square','plot');\n% %OR\n%Iout=relnoise(Iin,3,0.5,'custom',strel('line',30,0),'plot');\n%\n%figure;\n%subplot(1,2,1)\n%imagesc(Iout-double(Iin))\n%title('What was removed from the original image.')\n%axis equal tight\n%box on\n%\n%subplot(1,2,2)\n%imagesc(abs(fftshift(fft(Iout-double(Iin)))))\n%title('FFT of difference between original and filtered images.')\n%axis equal tight\n%box on\n%\n\nfunction [varargout]=relnoise(Iin,sz,sigma,varargin)\n\n%Nans\nInan=isnan(Iin);\nif sum(Inan(:))>0\n error('Input matrix contains NaNs.')\nend\n\n%convert type\nIin=double(Iin);\n\n%check filter size\nif or(sz<1,sz>min(size(Iin)))\n error('The filter size is out of bounds.')\nend\n\nif mod(sz,2)~=1\n error('The filter size must be an odd integer.')\nend\n\n%parse field input\nf1=find(strcmp('plot',varargin),1);\nf2=find(strcmp('disk',varargin),1);\nf3=find(strcmp('custom',varargin),1);\n\n%choose plot option\nif ~isempty(f1)\n plotq=1;\nelse\n plotq=0;\nend\n\n%choose filter type\nif ~isempty(f3)\n hood_temp=varargin{f3+1};\n if strcmp(class(hood_temp),'strel')\n hood=hood_temp.getnhood;\n else\n hood=hood_temp;\n end\n \n sz=round(mean(size(hood)));\nelseif ~isempty(f2)\n %disk filter block\n Xdisk = ones(sz,1)*(-(sz-1)/2:(sz-1)/2);\n Ydisk = (-(sz-1)/2:(sz-1)/2)'*ones(1,sz);\n Zdisk = sqrt(Xdisk.^2 + Ydisk.^2);\n \n hood=zeros(sz,sz);\n hood(Zdisk<=(sz-1)/2)=1;\nelse\n %square filter block\n hood=ones(sz,sz);\nend\n\n%convert hood class\nhood=single(hood);\n\n%calcualte means and variances\nhood_sz=sum(hood(:));\n\n%perform convolultion and normalization\nImean0=conv2(Iin,hood,'same')/hood_sz;\nInorm=conv2(ones(size(Iin)),hood,'same')/hood_sz;\nImean=Imean0./Inorm;\nIvar=conv2(Iin.^2,hood,'same')./Inorm*1/hood_sz-Imean.^2;\n\n%compute weight matrix\nW=exp(-(Iin-Imean).^2./(2*sigma^2*Ivar));\n\n%correct for zero variance pixels\nW(Ivar==0)=0;\n\n%compute output image\nif sigma==0\n Iout=Imean;\nelse\n Iout=Iin.*W+(1-W).*Imean;\nend\n\n%handle outputs\nif nargout==1\n varargout{1}=Iout;\nelseif nargout==2\n varargout{1}=Iout;\n varargout{2}=Ivar;\nelseif nargout==3\n varargout{1}=Iout;\n varargout{2}=Ivar;\n varargout{3}=Imean;\nelseif nargout==0\nelse\n error('Incorrect number of output arguments.') \nend\n\n%plot comparisons\nif plotq==1 \n \n figure;\n subplot(2,2,1)\n imagesc(Iin)\n xlabel('X')\n ylabel('Y')\n box on\n axis equal tight\n title('Original Image')\n \n subplot(2,2,2)\n imagesc(Iout)\n xlabel('X')\n ylabel('Y')\n box on\n axis equal tight\n title(['Relative Noise Reduction (this filter), size = ' num2str(sz) ', sigma = ' num2str(sigma)])\n \n subplot(2,2,3)\n %look for image processing toolbox\n boxes=ver;\n gotit=strfind([boxes.Name],'Image Processing Toolbox');\n if ~isempty(gotit)\n Iout2=medfilt2(Iin,[sz,sz],'symmetric');\n else\n disp('Sorry, you do not have the Image Processing Toolbox.')\n disp('The medfilt2 comparison image cannot be generated.')\n disp('Disabling `plot` will stop this message.')\n Iout2=Imean;\n end\n imagesc(Iout2)\n xlabel('X')\n ylabel('Y')\n box on\n axis equal tight\n\n if ~isempty(gotit)\n title(['Median Filter of size ' num2str(sz)])\n else\n title(['Mean Filter of size ' num2str(sz)])\n end\n \n %construct Gaussian filter (without Image Processing Toolbox)\n sz2=round(3/2*sz);\n Xgauss = ones(sz2,1)*(-(sz2-1)/2:(sz2-1)/2);\n Ygauss = (-(sz2-1)/2:(sz2-1)/2)'*ones(1,sz2);\n Zgauss = exp(-(Xgauss.^2+Ygauss.^2)/(2*(sz/2)^2));\n Zgauss = Zgauss/sum(Zgauss(:));\n Iout3=conv2(Iin,Zgauss,'same');\n \n subplot(2,2,4)\n imagesc(Iout3)\n xlabel('X')\n ylabel('Y')\n box on\n axis equal tight\n title(['Gaussian Blur with STD = ' num2str(sz/2)])\n pause(0.1)\nend\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/35556-image-noise-reduction-by-local-statistics/relnoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7130192304907232}} {"text": "function [errRadians] = hyperSam(a, b)\n% HYPERSAM Computes the spectral angle error (in radians) between two vectors\n%\n% Usage\n% [errRadians] = hyperSam(a, b)\n% Inputs\n% a - Vector 1.\n% b - Vector 2.\n% Outputs\n% errRadians - angle between vectors a and b in radians\n\n[p,N] = size(a);\nerrRadians = zeros(1,N);\nfor k=1:N\n tmp = a(:,k);\n errRadians(k) = acos(dot(tmp, b)/ (norm(b) * norm(tmp)));\nend\nreturn;", "meta": {"author": "isaacgerg", "repo": "matlabHyperspectralToolbox", "sha": "26955b0abb442d06009c220980e974461e419bf8", "save_path": "github-repos/MATLAB/isaacgerg-matlabHyperspectralToolbox", "path": "github-repos/MATLAB/isaacgerg-matlabHyperspectralToolbox/matlabHyperspectralToolbox-26955b0abb442d06009c220980e974461e419bf8/hyperspectralToolbox/hyperSam.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7130192222438524}} {"text": "function x = project_exp(v)\n% PROJECT_EXP Project points onto the exponential cone.\n%\n% When v is a 1 x 3 vector, project_exp(v) is the projection\n% of v onto the exponential cone. When v is an n x 3 vector,\n% project_exp(v) projects each row of v onto the cone\n% in a vectorized fashion.\n%\n% For reference, the exponential cone and its dual are given by\n% Kexp = { (x,y,z) | ye^(x/y) <= z, y > 0 }\n% Kexp^* = { (u,v,w) | u < 0, -ue^(v/u) <= ew } cup { (0,v,w) | v,w >= 0 }\n\n r = v(:,1); s = v(:,2); t = v(:,3);\n x = nan(size(v));\n\n % v in cl(Kexp)\n idx = ( (s.*exp(r./s) <= t & s > 0) | (r <= 0 & s == 0 & t >= 0) );\n x(idx,:) = v(idx,:); \n\n % -v in Kexp^*\n idx = ( (-r < 0 & r.*exp(s./r) <= -exp(1).*t) | (-r == 0 & -s >= 0 & -t >= 0) );\n x(idx,:) = 0;\n\n % special case with analytical solution\n idx = (r < 0 & s < 0);\n x(idx,:) = v(idx,:);\n x(idx,2) = max(x(idx,2),0);\n x(idx,3) = max(x(idx,3),0);\n\n % minimize ||x - v||^2 subject to se^{r/s} = t via primal-dual Newton method\n % these components are computed serially, so much slower\n idx = find(isnan(x(:,1)));\n\n g = @(w) w(2)*exp(w(1)/w(2)) - w(3);\n gradg = @(w) [ exp(w(1)/w(2)); exp(w(1)/w(2))*(1 - w(1)/w(2)); -1 ];\n\n alpha = 0.001; beta = 0.5;\n\n for i = 1:length(idx)\n disp('newton')\n u = v(idx(i),:)';\n u(2) = max(u(2),1); u(3) = max(u(3),1);\n y = 1; % dual variable\n\n r = @(w,z) [ w - v(idx(i),:)' + z*gradg(w); g(w) ];\n\n for iter = 1:100\n KKT = [ eye(3)+y*hessg(u), gradg(u) ; gradg(u)', 0 ];\n z = KKT \\ -r(u,y);\n du = z(1:3);\n dy = z(4);\n\n % backtracking line search\n t = 1;\n ustep = u + t*du; ystep = y + t*dy;\n while ustep(2) < 0 || (norm(r(ustep, ystep)) > (1 - alpha*t)*norm(r(u, y)))\n t = beta*t;\n ustep = u + t*du; ystep = y + t*dy;\n end\n\n u = ustep; y = ystep;\n\n if abs(g(u)) < 1e-8 && norm(r(u,y)) <= 1e-8\n x(idx(i),:) = u;\n break;\n end\n end\n end\nend\n\nfunction h = hessg(w)\n r = w(1); s = w(2); t = w(2);\n h = exp(r/s)*[ 1/s, -r/s^2, 0;\n -r/s^2, r^2/s^3, 0;\n 0, 0, 0 ];\nend\n", "meta": {"author": "cvxgrp", "repo": "proximal", "sha": "736f2c48bdb1d8ac4fc325d529ea85be2a3d7f8b", "save_path": "github-repos/MATLAB/cvxgrp-proximal", "path": "github-repos/MATLAB/cvxgrp-proximal/proximal-736f2c48bdb1d8ac4fc325d529ea85be2a3d7f8b/matlab/project_exp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.7130192181897085}} {"text": "% Check whether a graph is regular, i.e. whether every node has the same degree.\n%\n% INPUTS: adjacency matrix, nxn\n% OUTPUTS: Boolean, 0 or 1\n%\n% Note: Defined for unweighted graphs only.\n% GB: last updated, Sep 23, 2012\n\nfunction S=isRegular(adj)\n\nS=false;\n\ndegs=sum(adj>0); % remove weights and sum columns\n\nif degs == degs(1)*ones(size(degs)); S = true; end", "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/isRegular.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206818021531, "lm_q2_score": 0.7905303260722198, "lm_q1q2_score": 0.712995650676335}} {"text": "function p_mendousse = mendousse(x, t, source_freq, p0, c0, rho0, BonA, alpha_0)\n%MENDOUSSE Compute Mendousse's solution for nonlinear wave propagation in viscous media. \n%\n% DESCRIPTION:\n% mendousse calculates the propagation of a monofrequency plane wave\n% source in a thermoviscous medium with absorption given by\n% alpha_0*f^2. The solution is taken from Eq. (264) in Chapter 4 of\n% Nonlinear acoustics by Hamilton and Blackstock (2008). The infinite\n% sum is adaptively truncated when the moving average of the previous\n% five sum terms is smaller than a predefined convergence percentage\n% (0.01 percent by default). \n%\n% USAGE:\n% p_mendousse = mendousse(x, t, source_freq, p0, c0, rho0, BonA, alpha_0)\n%\n% INPUTS:\n% x - position [m]\n% t - time [s]\n% source_freq - frequency of plane wave [Hz]\n% p0 - source pressure [Pa]\n% c0 - medium sound speed [m/s]\n% rho0 - medium density [kg/m^3]\n% BonA - nonlinearity parameter B/A\n% alpha_0 - absorption coefficient [dB/(MHz^2 cm)]\n%\n% OUTPUTS:\n% p_mendousse - calculated pressure field\n%\n% ABOUT:\n% author - Bradley Treeby\n% date - 21st February 2011\n% last update - 17th June 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% 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% stop the summation when the current term contributes less than this amount\nCONVERGENCE_PERCENTAGE = 0.01; \n\n% minimum number of sum terms to use\nMIN_NUM_SUM_TERMS = 20;\n\n% number of pressure values to use in the moving average\nMOVING_AV = 5;\n\n% calculate the mach number\nmach_num = p0/(rho0*c0^2);\n\n% calculate the nonlinearity coefficient\nbeta = 1 + BonA/2;\n\n% convert the absorption to nepers per meter\nalpha_0 = db2neper(alpha_0, 2);\n\n% calculate the absorption parameter\nalpha = alpha_0*(2*pi*source_freq)^2;\n\n% calculate the Goldberg number\ngoldberg_num = beta*mach_num*2*pi*source_freq/(c0*alpha);\n\n% preallocate output variable\np_mendousse = zeros(1, length(x));\n\n% calculate series\nfor loop_index = 1:length(x)\n \n % ---------------------------------------------------------------------\n % compute numerator summation\n % ---------------------------------------------------------------------\n \n % initialise loop variables\n p_term1 = 0; % pressure\n sum_term_contrib = 1; % percentage contribution of current sum term\n n = 1; % summation index variable\n p_prev = zeros(1, MOVING_AV); % moving average variable\n\n % loop the sum until it reaches an acceptable level of convergence\n while (sum_term_contrib > CONVERGENCE_PERCENTAGE) || (n < MIN_NUM_SUM_TERMS)\n\n % compute next sum term and add to the total\n p_term1 = p_term1 + (-1)^(n + 1) * n * besseli(n, goldberg_num/2) * exp(-n^2*alpha*x(loop_index)) * sin(n*2*pi*source_freq*t(loop_index)); \n \n % update moving average of the contribution of sum term in a fifo\n % paradigm\n p_prev = circshift(p_prev, [0, 1]);\n p_prev(1) = p_term1;\n sum_term_contrib = 100*abs((p_term1 - mean(p_prev))/p_term1);\n \n % update summation variable\n n = n + 1;\n\n end\n \n % ---------------------------------------------------------------------\n % compute denominator summation\n % ---------------------------------------------------------------------\n \n % initialise loop variables\n p_term2 = 0; % pressure\n sum_term_contrib = 1; % percentage contribution of current sum term\n n = 1; % summation index variable\n p_prev = zeros(1, MOVING_AV); % moving average variable\n\n % loop the sum until it reaches an acceptable level of convergence\n while (sum_term_contrib > CONVERGENCE_PERCENTAGE) || (n < MIN_NUM_SUM_TERMS)\n\n % compute next sum term and add to the total\n p_term2 = p_term2 + (-1)^(n) * besseli(n, goldberg_num/2) * exp(-n^2*alpha*x(loop_index)) * cos(n*2*pi*source_freq*t(loop_index)); \n \n % update moving average of the contribution of sum term in a fifo\n % paradigm\n p_prev = circshift(p_prev, [0, 1]);\n p_prev(1) = p_term2;\n sum_term_contrib = 100*abs((p_term2 - mean(p_prev))/p_term2);\n \n % update summation variable\n n = n + 1;\n\n end\n \n % ---------------------------------------------------------------------\n % apply scaling parameters and store the value of p\n % ---------------------------------------------------------------------\n \n % check if the numerator is zero\n if p_term1 ~= 0\n p_term1 = 4*p_term1./goldberg_num;\n else\n p_term1 = 0;\n end\n p_mendousse(loop_index) = p_term1 / (besseli(0, goldberg_num/2) + 2*p_term2);\n \nend\n\n% scale output by p0\np_mendousse = p0.*p_mendousse;", "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/mendousse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.7129956356635053}} {"text": "function [A,M] = assemblematrix3(node,elem,lumpflag)\n%% ASSEMBLEMATRIX3 matrix for diffusion and reaction\n%\n% [A,M] = ASSEMBLEMATRIX3(node,elem) return the stiffness matrix and the\n% mass matrix.\n%\n% [A,M] = ASSEMBLEMATRIX3(node,elem,1) return the stiffness matrix and the\n% lumped mass matrix. Note that in the output M is a vector not a matrix. A\n% sparse diagonal matrix using M as diaongal can be obtained by\n% spdiags(M,0,N,N);\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nN = size(node,1);\nA = sparse(N,N);\nM = sparse(N,N);\n\n%% Compute geometric quantities and gradient of local basis\n[Dphi,volume] = gradbasis3(node,elem);\n\n%% Assemble stiffness matrix\nfor i = 1:4\n for j = i:4\n Aij = dot(Dphi(:,:,i),Dphi(:,:,j),2).*volume;\n ii = double(elem(:,i));\n jj = double(elem(:,j));\n if (j==i)\n A = A + sparse(ii,jj,Aij,N,N);\n else\n A = A + sparse([ii;jj],[jj;ii],[Aij; Aij],N,N); \n end \n if (nargout > 1) && (~exist('lumpflag','var') || lumpflag == 0 )\n if (j==i)\n M = M + sparse(ii,jj,volume/10,N,N);\n else\n M = M + sparse([ii;jj],[jj;ii],[volume/20; volume/20],N,N); \n end \n end\n end\nend\n\n%% Assemble mass matrix by mass lumping\nif exist('lumpflag','var') && lumpflag==1 && nargout > 1\n M = accumarray(elem(:),[volume;volume;volume;volume]/4,[N,1]);\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/assemblematrix3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7129956334380024}} {"text": "function S = oblateSurfaceArea(elli, varargin)\n%OBLATESURFACEAREA Approximated surface area of an oblate ellipsoid.\n%\n% S = oblateSurfaceArea(R1,R2)\n%\n% Example\n% oblateSurfaceArea\n%\n% See also\n% geom3d, ellipsoidSurfaceArea, prolateSurfaceArea\n%\n\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2015-07-03, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2015 INRA - Cepia Software Platform.\n\n%% Parse input argument\n\nif size(elli, 2) == 7\n R1 = elli(:, 4);\n R2 = elli(:, 5);\n \nelseif size(elli, 2) == 1 && ~isempty(varargin)\n R1 = elli(:, 1);\n R2 = varargin{1};\nend\n\nassert(R1 < R2, 'First radius must be smaller than second radius'); \n\n% surface theorique d'un ellipsoide oblate \n% cf http://fr.wikipedia.org/wiki/Ellipso%C3%AFde_de_r%C3%A9volution\ne = sqrt(R2.^2 - R1.^2) ./ R2;\nS = 2 * pi * R2.^2 + pi * R1.^2 * log((1 + e) ./ (1 - e)) ./ e;\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_geom3d/geom3d/oblateSurfaceArea.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7129956310710768}} {"text": "% Chapter 3 - Complex Iterative Maps.\n% Program 3a - Julia Sets.\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% Plot the Julia set J(0,1.1) (Figure 3.1(d)).\nclear\nk=15;niter=2^k;\nx=zeros(1,niter);y=zeros(1,niter);\nx1=zeros(1,niter);y1=zeros(1,niter);\na=0;b=1.1;\nx(1)=real(0.5+sqrt(0.25-(a+1i*b)));\ny(1)=imag(0.5+sqrt(0.25-(a+1i*b)));\n% Check that the point is unstable.\nisunstable=2*abs(x(1)+1i*y(1))\n\nhold on\nfor n=1:niter\n x1=x(n);y1=y(n);\n u=sqrt((x1-a)^2+(y1-b)^2)/2;v=(x1-a)/2;\n u1=sqrt(u+v);v1=sqrt(u-v);\n x(n+1)=u1;y(n+1)=v1;\n if y(n)= freq_bins(j) & freq_in(:,i) < freq_bins(j+1);\n elseif j==length(freq_bins)\n freq_mask = freq_in(:,i) >= freq_bins(j-1) & freq_in(:,i) < freq_bins(j);\n else\n freq_mask = freq_in(:,i) >= freq_bins(j-1) & freq_in(:,i) < freq_bins(j+1);\n end\n x = level_in(freq_mask,i);\n y = level_out(freq_mask,i);\n validmask = x > -100 & y > -100 & ~isnan(x) & ~isnan(y) & ~isinf(x) & ~isinf(y);\n x = x(validmask);\n y = y(validmask);\n c = freq_color(j,:);\n if length(x) > 6\n p = polyfit(x,y,4);\n out_mean(j,:) = polyval(p,sample_levels);\n end\n scatter(x,y,20,c);\n if mod(j-1,2) == 0\n h(j) = plot(-90:10,polyval(p,-90:10),'Color',c);\n end\n end\n legend(h,num2str(round(freq_bins(2:2:end).')),'location','southeast');\n\n xlim([-100 10]);\n ylim([-100 10]);\n xlabel('Input / dB FS');\n ylabel('Output / dB FS');\n\n subplot(2,2,i+2);\n\n plot(log([50 16000]),[0 0],'k');\n hold on;\n\n level_color = hsv(length(sample_levels)).*0.8;\n\n h = [];\n for j=1:length(sample_levels)\n c = level_color(j,:);\n plot(log(freq_bins(1:end-1)),sample_levels(j).*ones(length(freq_bins)-1,1),'--','Color',c);\n h(j) = plot(log(freq_bins),out_mean(:,j),'-','Color',c);\n end\n\n xlim(log([50 16000]));\n ylim([-100 10]);\n xlabel('Frequency / Hz');\n ylabel('Levels / dB');\n set(gca,'xtick',log(freq_bins(2:2:end-1)));\n set(gca,'xticklabel',round(freq_bins(2:2:end-1)));\n legend(h,num2str(sample_levels.'),'location','southeast');\nend\n\nset(gcf,'PaperUnits','inches','PaperPosition',[0 0 8 8].*1.4);\nprint('-depsc2','-r300','inout.eps');\n", "meta": {"author": "m-r-s", "repo": "hearingaid-prototype", "sha": "973b4c8e793a0ac78e8d1e7bd40e518876fc3c83", "save_path": "github-repos/MATLAB/m-r-s-hearingaid-prototype", "path": "github-repos/MATLAB/m-r-s-hearingaid-prototype/hearingaid-prototype-973b4c8e793a0ac78e8d1e7bd40e518876fc3c83/tools/evaluate_inout.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.7129251662489321}} {"text": "function ex9bvp\n%EX9BVP Example 9 of the BVP tutorial.\n% This boundary value problem is the subject of Chapter 8 of \n% C.C. Lin and L.A. Segel, Mathematics Applied to Deterministic\n% Problems in the Natural Sciences, SIAM, Philadelphia, 1988. \n% The ODEs\n% \n% v' = (C - 1)/n\n% C' = (vC - min(x,1))/eta\n%\n% are solved on the interval [0, lambda]. The boundary conditions \n% are v(0) = 0, C(lambda) = 1, and continuity of v(x) and C(x) at \n% x = 1. Accordingly, this is a three-point BVP that must be \n% reformulated for solution with the two-point BVP solver BVP4C. \n% This reformulation involves introducing unknowns y_1(x) for v \n% and y_2(x) for C on the interval 0 <= x <= 1 and unknowns y_3(x) \n% for v and y_4(x) for C on 1 <= x <= lambda. A new independent \n% variable is introduced for the second interval, tau = \n% (x - 1)/(lambda - 1), so that it also ranges from 0 to 1. The \n% differential equations for the four unknowns are then solved\n% on the interval [0, 1]. The continuity conditions on v and C\n% become boundary conditions on the new unknowns. A plot of v(x)\n% and C(x) on [0, lambda] involves plotting the new unknowns over\n% the subintervals.\n%\n% The quantity of most interest is the emergent osmolarity Os =\n% 1/v(lambda). The parameters are related to another parameter\n% kappa by eta = lambda^2/(n*kappa^2). Lin and Segel develop an \n% approximate solution for Os valid for \"small\" n. Here the BVP is\n% solved for a range of kappa when lambda = 2 and n = 0.005. The\n% computed Os is compared to the approximation of Lin and Segel.\n\n% Copyright 1999, The MathWorks, Inc.\n\nn = 5e-2;\nlambda = 2;\n\noptions = []; % place holder\n\nsol = bvpinit(linspace(0,1,5),[1 1 1 1]);\n\nfprintf(' kappa computed Os approximate Os \\n')\nfor kappa = 2:5\n eta = lambda^2/(n*kappa^2);\n \n sol = bvp4c(@ex9ode,@ex9bc,sol,options,n,lambda,eta);\n \n K2 = lambda*sinh(kappa/lambda)/(kappa*cosh(kappa));\n approx = 1/(1 - K2);\n computed = 1/sol.y(3,end);\n fprintf(' %2i %10.3f %10.3f \\n',kappa,computed,approx);\nend\n\n% v and C are computed separately on 0 <= x <= 1 and 1 <= x <= lambda.\n% A change of independent variable is used for the second interval,\n% which must then be undone to obtain the corresponding mesh.\nx = [sol.x sol.x*(lambda-1)+1];\ny = [sol.y(1:2,:) sol.y(3:4,:)];\n\nclf reset\nplot(x,y(1,:),x,y(2,:),'--')\nlegend('v(x)','C(x)')\ntitle('A three-point BVP.')\nxlabel(['\\lambda = ',num2str(lambda),', \\kappa = ',num2str(kappa),'.'])\nylabel('v and C')\nshg\n\n% --------------------------------------------------------------------------\n\nfunction dydx = ex9ode(x,y,n,lambda,eta)\n%EX9ODE ODE function for Example 9 of the BVP tutorial.\ndydx = [ (y(2) - 1)/n\n (y(1)*y(2) - x)/eta \n (lambda - 1)*(y(4) - 1)/n\n (lambda - 1)*(y(3)*y(4) - 1)/eta ];\n\n% --------------------------------------------------------------------------\n\nfunction res = ex9bc(ya,yb,n,lambda,eta)\n%EX9BC Boundary conditions for Example 9 of the BVP tutorial.\nres = [ ya(1)\n yb(4) - 1\n yb(1) - ya(3)\n yb(2) - ya(4)];\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/ex9bvp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7128673906880839}} {"text": "function varargout = harris(varargin)\n% VL_HARRIS Harris corner strength\n% H = VL_HARRIS(I,SI) computes the Harris corner strength of the image I\n% at ``integration'' scale SI.\n%\n% The Harris strength [1] of a pixel is a statistic of the gradient\n% of the image integrated in a neighborhood of that pixel. This\n% neighborhood is a Gaussian window of variance SI.\n%\n% In computing the Harris corner strength, there is a second scale\n% parameter, the ``derivation'' scale SD, which is the variance of\n% the Gaussian kernel used to pre-smooth the image I before computing\n% its gradient. SI and SD are independent parameters and VL_HARRIS(I,SI)\n% assumes that I is already smoothed at level SD.\n%\n% VL_HARRIS(I,SI) uses Noble's variation [2] of the Harris score. If\n% SIGMAP and SIGMAM are respectively the biggest and smallest\n% eigenvalue of the structure tensor at a pixel, the score is given\n% by (SIGMAP*SIGMAM) / (SIGMAP+SIGMAM/2). Let GAMMA = SIGMAM/SIGMAP\n% the ratio between the eigenvalues, which measures the degree of\n% anisotropy of the tensor and is always comprised in the range\n% [0,1]. Noble's score can be decomposed in two factors: the biggest\n% eigenvalue SIGMAP and the number\n%\n% RHO = (2 GAMMA) / (GAMMA + 1).\n%\n% RHO is another measure of isotropy that has value one for a\n% symmetric tensor and and zero for maximally anisotropic tensor.\n% [H,DETAILS] = VL_HARRIS(I,SIGMA) returns the additional structure\n% DETAILS with the following fields:\n%\n% DETAILS.SIGMAP\n% DETAILS.RHO\n%\n% VL_HARRIS(I,SI,ALPHA) uses Harris' original score [1], defined to be\n% SIGMAP*SIGMAM - ALPHA*(SIGMAP+SIGMAM)^2. This can be decomposed in\n% the factors SIGMAP^2 (note the square) and\n%\n% RHO = GAMMA - ALPHA (1+GAMMA)^2.\n%\n% Note that RHO is equal to -ALPHA for a maximally anisotropic\n% tensor. Typically ALPHA=0.04 and this is what is used by\n% VL_HARRIS(I,SI,[]).\n%\n% REMARK. The gradient of the image I, used to compute the structure\n% tensor, is computed using central differencies. This means that a\n% function line [+1,-1,+1,...] has null Harris' score. This is\n% generally assumed to be a sampling artifact, and might be\n% avoided by oversampling the image.\n%\n% EXAMPLE::\n% To extacts Harris points from image I:\n% idx = vl_localmax( vl_harris( vl_imsmooth( I, sd ), si ) ) ;\n% [i,j] = ind2sub( size(I), idx )\n%\n% REFERENCES::\n% [1] C. Harris and M. Stephens, \"A combined corner and edge detector,\"\n% in Proceedings of The Fourth Alvey Vision Conference, pp. 147-151,\n% 1988.\n%\n% [2] J. A. Noble, \"Finding corners, \"Image Vision Computing, vol. 6,\n% no. 2, pp. 121-128, 1988.\n%\n% See also: VL_HELP().\n[varargout{1:nargout}] = vl_harris(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/harris.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7128673661670918}} {"text": "% -------------------------------------------------------------------------\n% runduffsr.m\n% Numerically solve the driven duffing oscillator with noise. Compute \n% the averaged signal and noise amplitude spectra for varing noise \n% strength. Plot signal-to-noise vs noise strength and time-series, phase\n% space, well occupation distributions, and amplitude spectra for four \n% chosen noise strengths.\n% Dependencies: duff.m and noise.m\n% -------------------------------------------------------------------------\n\nclear all\n\ntic % start timer\n\nglobal p w\n\n% -------------------------------------------------------------------------\n\nX0 = [0 0]'; % initial conditions\nt0 = 0; % initial time\ntf = 1000; % final time\ndt = 0.05; % time step\nT = (t0:dt:tf); % time vector\noptions = [];\n\nf = (1:length(T))/(length(T)*dt); % frequency\nf = f(1:(ceil(length(T)/2))); % first half of frequency axis\n\nwin = hann(length(T)); % hanning window\n\nwmax = 10; % noise cut-off frequency\nalpha = 0.5; % strength of non-linear term\nbeta = 1; % strength of linear term\ngam = 0.5; % damping strength\nA = 0.38; % driving amplitude\nw0 = 0.09; % driving frequency\n\nN = 1000; % number of terms in noise sum\n\nd = 0.05:0.05:2; % noise strength\n\n% noise strength values for plots\ndc = [0.1 0.5 1 2];\n\ndw0 = w0*0.25; % integration range (w0+/- 25%)\n\nM = 4; % number of terms in average (>= 2)\n\n% initialize arrays\nx = zeros(length(T),length(dc));\nv = zeros(length(T),length(dc));\nlc = zeros(1,length(dc));\n\nFd = zeros((1+length(T))/2,M);\nFdn = zeros((1+length(T))/2,M);\n\nSd = zeros((1+length(T))/2,length(d));\nSdn = zeros((1+length(T))/2,length(d));\n\nPd = zeros(1,length(d));\nPdn = zeros(1,length(d));\n\n% -------------------------------------------------------------------------\n\nfor l = 1:length(d) % loop over noise strength array\n \nn = d(l);\n\nfor j = 1:M % average amplitudes \n \np = unifrnd(0,2*pi,1,N); % random phases in noise\nw = unifrnd(0,wmax,1,N); % random frequencies in noise\n\n% numerically solve duffing oscillator\n[t,y]=ode23(@duff,T,X0,options,gam,alpha,beta,A,w0,n);\n\n% create x and v vectors at various noise strengths (d = 0.1,0.5,1.5,4)\n% and get index for plots\nif j == 1\n for i = 1:length(dc)\n if n == dc(i)\n x(:,i) = y(:,1);\n v(:,i) = y(:,2);\n lc(i) = l;\n break\n end\n end\nend\n\n% compute positive fft of windowed time-dependent signal and noise \n% amplitudes\nFdtemp = fft(win.*y(:,1))/length(t); % signal fft\nFdntemp = fft(sqrt(n)*win.*noise(t)')/length(t); % noise fft\n\nFd(:,j) = Fdtemp(1:(ceil(length(t)/2))); % positive half of signal fft\nFdn(:,j) = Fdntemp(1:(ceil(length(t)/2))); % positive half of noise frequency\n\nclear Fdtemp Fdntemp\n\nend\n\n% average frequency dependent signal and noise amplitude\nSd(:,l) = sum(abs(Fd'))/M; % averaged signal amplitude\nSdn(:,l) = sum(abs(Fdn'))/M; % averaged noise amplitude\n\ni = 1;\n\n% find signal and noise amplitude around driving frequency\nfor k = 1:length(f)\n if 2*pi*f(k) >= w0-dw0 && 2*pi*f(k) <= w0+dw0 \n fr(i) = 2*pi*f(k); % frequency\n fd(i) = Sd(k,l); % signal amplitude\n fdn(i) = Sdn(k,l); % noise amplitude\n i = i + 1; \n end\nend\n\n% integrate signal and noise amplitude around driving frequency\nPd(l) = trapz(fr,fd); % signal \"power\"\nPdn(l) = trapz(fr,fdn); % noise \"power\"\n\nclear fr fd fdn\n\nend\n\n% calculate and smooth snr (dB)\nSNR = smooth(10*log(Pd./Pdn),0.1);\n\n% -------------------------------------------------------------------------\n\nfigure(1) % plot snr vs noise strength\nplot(d,SNR,'-ob')\nxlabel('d'); ylabel('SNR (dB)');\n\n% plots for various noise strengths (d = 0.1,0.5,1.5,4)\nfigure(2) % plot time-series\nsubplot(4,1,1)\nplot(t,x(:,1))\nxlabel('t'); ylabel('x');\nsubplot(4,1,2)\nplot(t,x(:,2))\nxlabel('t'); ylabel('x');\nsubplot(4,1,3)\nplot(t,x(:,3))\nxlabel('t'); ylabel('x');\nsubplot(4,1,4)\nplot(t,x(:,4))\nxlabel('t'); ylabel('x');\n\nfigure(3) % plot phase-space\nsubplot(2,2,1)\nplot(x(:,1),v(:,1))\nxlabel('x'); ylabel('v');\nsubplot(2,2,2)\nplot(x(:,2),v(:,2))\nxlabel('x'); ylabel('v');\nsubplot(2,2,3)\nplot(x(:,3),v(:,3))\nxlabel('x'); ylabel('v');\nsubplot(2,2,4)\nplot(x(:,4),v(:,4))\nxlabel('x'); ylabel('v');\n\nfigure(4) % plot histogram of well distribution\nsubplot(2,2,1)\nhist(x(:,1),100)\nxlabel('x');\nsubplot(2,2,2)\nhist(x(:,2),100)\nxlabel('x');\nsubplot(2,2,3)\nhist(x(:,3),100)\nxlabel('x');\nsubplot(2,2,4)\nhist(x(:,4),100)\nxlabel('x');\n\nfigure(5) % plot noise subtracted amplitude spectra\nplot(2*pi*f,Sd(:,lc(1))-Sdn(:,lc(1)),2*pi*f,Sd(:,lc(2))-Sdn(:,lc(2)),...\n 2*pi*f,Sd(:,lc(3))-Sdn(:,lc(3)),2*pi*f,Sd(:,lc(4))-Sdn(:,lc(4)))\nlegend('d = 0.1','d = 0.6','d = 1.8','d = 2.4')\nxlabel('\\omega'); ylabel('|A|');\n\ntoc % end timer\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/35479-stochastic-resonance-in-the-duffing-oscillator-with-matlab/runduffsr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7128023858631268}} {"text": "function Amatrix=createDFTAmatrix(X,H);\n% function Amatrix=createDFTAmatrix(X,H);\n% Creates matrix of DFT-amplitudes for a signal X.\n% In each column is a spectrum (1:N/2+1), row indices are time-frame indices.\n% H is the analysis window. N is the frame length, 50% overlap is used.\n\n% Turn into column vector\nX=X(:);\nH=H(:);\nNx=length(X);\nN=length(H);\nM=floor(2*Nx/N-1);\nAmatrix=zeros(N/2+1,M);\nfor k=1:M\n index=(k-1)*N/2+1:(k+1)*N/2;\n F=abs(fft(X(index).*H'));\n Amatrix(:,k)=F(1:N/2+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/27311-noise-tracking-algorithm-for-single-microphone-speech-signals/createDFTAmatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.7879312031126511, "lm_q1q2_score": 0.7128023764164497}} {"text": "% Fig. W1 Web Appendix W8 Feedback Control of Dynamic Systems, 6e \n% Franklin, Powell, Emami\n%\n\nclear all;\nclose all;\n\nF=[0 1;0 0];\nG=[0;1];\nH=[1 0];\nJ=0;\nT=1;\n[Phi,Gam]=c2d(F,G,T);\nj=sqrt(-1);\nPc=[.78+.18*j;.78-.18*j];\nK=acker(Phi,Gam,Pc);\nPe=[.2+.2*j;.2-.2*j];\nL=acker(Phi',H',Pe)';\n[A,B,C,D]=dreg(Phi,Gam,H,J,K,L);\nA=Phi-Gam*K-L*H;\nB=L;\nC=K;\nD=0;\n[Ac,Bc,Cc,Dc]=series(A,B,C,D,Phi,Gam,H,J);\n[Acl,Bcl,Ccl,Dcl]=feedback(Ac,Bc,Cc,Dc,0,0,0,1);\ntf=30;\nN=tf/T+1;\ntd=0:1:tf;\nyd=dstep(Acl,Bcl,Ccl,Dcl,1,N);\naxis([0 30 0 1.5])\nplot(td,yd,'-',td,yd,'*'),\nxlabel('time (sec)')\nylabel('plant output y(t)')\ntitle('Fig. 8.20 Step response of the continuous and digital systems')\nnicegrid;\nhold on\n\n% use command structure from section 7.8\n\nNx=[1;0]; \nA2=[Phi -Gam*K;\n L*H Phi-L*H-Gam*K];\nB2=[Gam*K*Nx;Gam*K*Nx];\nC2=[1 0 0 0];\nD2=0;\ny2=dstep(A2,B2,C2,D2,1,N);\nplot(td,y2,'-',td,y2,'o')\ntext(6.5,.25,'o-----o-----o-----o Command structure from Fig 7.48(b)')\ntext(6.5,.45,'*-----*-----*-----* Command structure from Fig 7.15')\nhold off\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/26412-feedback-control-of-dynamic-systems-6th-edition-prentice-hall-2010/fig8_w1_webAppendixW8.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7128023714574735}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% GEOMETRIC ASIAN OPTION PRICER (RUN SCRIPT)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Descritpion: Script to Price Geometric Asian options in Levy Models using the PROJ method\n% Author: Justin Kirkby\n%\n% Reference: (1) An Efficient Transform Method For Asian Option Pricing, SIAM J. Financial Math., 2016\n% (2) Efficient Option Pricing by Frame Duality with the Fast Fourier Transform. \n% SIAM J. Financial Math (2015), Kirkby, J.L\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[folder, name, ext] = fileparts(which( mfilename('fullpath')));\ncd(folder);\naddpath('../RN_CHF')\naddpath('../Helper_Functions')\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Step 1) CHOOSE CONTRACT/GENERAL PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ncall = 1; %For call use 1 (else, its a put)\nS_0 = 100; %Initial price\nW = 100; %Strike %NOTE: no error handling in place for extreme values of W (increase grid if strike falls outside)\nr = 0.05; %Interest rate\nq = 0.00; %dividend yield\nT = 1; %Time (in years)\nM = 52; %Number of monitoring points\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Step 2) CHOOSE MODEL PARAMETERS (Levy Models)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nmodel = 1; %See Models Below (e.g. model 1 is Black Scholes), and choose specific params\nparams = {};\n\nif model == 1 %BSM (Black Scholes Merton)\n params.sigmaBSM = 0.15; %CHOOSE \n \nelseif model == 2 %CGMY\n params.C = 0.02; \n params.G = 5; \n params.MM = 15; \n params.Y = 1.2;\n\nelseif model == 3 %NIG\n params.alpha = 15;\n params.beta = -5;\n params.delta = 0.5;\n \nelseif model == 4 %MJD (Merton Jump Diffusion)\n params.sigma = 0.12;\n params.lam = 0.4;\n params.muj = -0.12;\n params.sigmaj = 0.18;\n \nelseif model == 5 %Kou Double Expo\n params.sigma = 0.15;\n params.lam = 3;\n params.p_up = 0.2;\n params.eta1 = 25;\n params.eta2 = 10;\n \nelseif model == 8 % Variance Gamma \n params.sigma = 0.2; \n params.nu = 0.85; \n params.theta = 0; \n\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Step 3) CHOOSE PROJ PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nUseCumulant = 1; %Set to 1 to use the cumulant base rule (Approach 1) to determine gridwidth, else used fixed witdth (Approach 2)\n\n%---------------------\n% APPROACH 1: Cumulant Based approach for grid width\n% (see \"Robust Option Pricing with Characteritics Functions and the BSpline Order of Density Projection\")\n%---------------------\nif UseCumulant ==1 %With cumulant based rule, choose N and Alpha (N = 2^(P+Pbar) based on second approach)\n logN = 8; %Uses N = 2^logN gridpoint \n L1 = 10; % determines grid witdth (usually set L1 = 8 to 15 for Levy)\n%---------------------\n% APPROACH 2: Manual GridWidth approach \n%--------------------- \nelse %Manually specify resolution and Pbar\n P = 6; % resolution is 2^P\n Pbar = 3; % Determines density truncation grid with, 2^Pbar \nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% PRICE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Note: rnCHF is the risk netural CHF, c1,c2,c4 are the cumulants\ndt = T/M;\nmodelInput = getModelInput(model, dt, r, q, params);\n\nif UseCumulant ==1 % Choose density truncation width based on cumulants\n alpha = getTruncationAlpha(T, L1, modelInput, model);\nelse % Manually supply density truncation width above\n logN = P + Pbar;\n alpha = 2^Pbar/2;\nend\nN = 2^logN; % grid roughly centered on [c1 - alph, c1 + alph]\n\ntic\nprice = PROJ_Geometric_Asian(N, alpha, S_0, M, W, call, T, r, q, modelInput.rnSYMB);\ntoc\n\n\nfprintf('Geometric Price: %.8f \\n', price)\n\ncompare_arithmetic = 1;\n\nif compare_arithmetic\n addpath('../Asian_Options')\n price_arith = PROJ_Asian( N,alpha,S_0,M,W,call,T,r,q, modelInput.rnCHF, modelInput.RNmu*dt);\n fprintf('Arithmetic Price: %.8f \\n', price_arith)\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/Geometric_Asian_Options/Script_GeometricAsianOptions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7126612050584058}} {"text": "function [H] = rigidbody(f);\n\n% RIGIDBODY creates the homogenous spatial transformation matrix\n% for a 6 parameter rigid-body transformation \n%\n% Use as\n% [H] = rigidbody(f)\n%\n% The transformation vector f should contain the \n% x-shift\n% y-shift\n% z-shift\n% followed by the\n% pitch (rotation around x-axis)\n% roll (rotation around y-axis)\n% yaw (rotation around z-axis)\n\n% Copyright (C) 2000-2005, Robert Oostenveld\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\n% $Log: rigidbody.m,v $\n% Revision 1.1 2009/01/30 04:02:11 arno\n% *** empty log message ***\n%\n% Revision 1.4 2006/04/13 10:37:38 roboos\n% added a ; to the end of a line\n%\n% Revision 1.3 2005/08/15 08:15:32 roboos\n% reimplemented the rotate function, which contained an error (the error is in the AIR technical reference)\n% changed all functions to be dependent on the rotate, translate and scale function\n% all functions now behave consistenly, which also means that they are not compleetly backward compatible w.r.t. the order of the rotations\n%\n% Revision 1.2 2004/05/19 09:57:07 roberto\n% added GPL copyright statement, added CVS log item\n%\n\n% compute the homogenous transformation matrix for the translation\nT = translate(f([1 2 3]));\n\n% compute the homogenous transformation matrix for the rotation\nR = rotate_new(f([4 5 6]));\n\n% compute the homogenous transformation matrix for the combination\nH = T*R;\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/eeglab13_4_4b/plugins/dipfit2.3/private/rigidbody.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7126612003856839}} {"text": "function [embedding_layer_state, hidden_layer_state, output_layer_state] = ...\n fprop(input_batch, word_embedding_weights, embed_to_hid_weights,...\n hid_to_output_weights, hid_bias, output_bias)\n% This method forward propagates through a neural network.\n% Inputs:\n% input_batch: The input data as a matrix of size numwords X batchsize where,\n% numwords is the number of words, batchsize is the number of data points.\n% So, if input_batch(i, j) = k then the ith word in data point j is word\n% index k of the vocabulary.\n%\n% word_embedding_weights: Word embedding as a matrix of size\n% vocab_size X numhid1, where vocab_size is the size of the vocabulary\n% numhid1 is the dimensionality of the embedding space.\n%\n% embed_to_hid_weights: Weights between the word embedding layer and hidden\n% layer as a matrix of size numhid1*numwords X numhid2, numhid2 is the\n% number of hidden units.\n%\n% hid_to_output_weights: Weights between the hidden layer and output softmax\n% unit as a matrix of size numhid2 X vocab_size\n%\n% hid_bias: Bias of the hidden layer as a matrix of size numhid2 X 1.\n%\n% output_bias: Bias of the output layer as a matrix of size vocab_size X 1.\n%\n% Outputs:\n% embedding_layer_state: State of units in the embedding layer as a matrix of\n% size numhid1*numwords X batchsize\n%\n% hidden_layer_state: State of units in the hidden layer as a matrix of size\n% numhid2 X batchsize\n%\n% output_layer_state: State of units in the output layer as a matrix of size\n% vocab_size X batchsize\n%\n\n[numwords, batchsize] = size(input_batch);\n[vocab_size, numhid1] = size(word_embedding_weights);\nnumhid2 = size(embed_to_hid_weights, 2);\n\n%% COMPUTE STATE OF WORD EMBEDDING LAYER.\n% Look up the inputs word indices in the word_embedding_weights matrix.\nembedding_layer_state = reshape(...\n word_embedding_weights(reshape(input_batch, 1, []),:)',...\n numhid1 * numwords, []);\n\n%% COMPUTE STATE OF HIDDEN LAYER.\n% Compute inputs to hidden units.\ninputs_to_hidden_units = embed_to_hid_weights' * embedding_layer_state + ...\n repmat(hid_bias, 1, batchsize);\n\n% Apply logistic activation function.\n% FILL IN CODE. Replace the line below by one of the options.\nhidden_layer_state = zeros(numhid2, batchsize);\n% Options\n% (a) hidden_layer_state = 1 ./ (1 + exp(inputs_to_hidden_units));\n% (b) hidden_layer_state = 1 ./ (1 - exp(-inputs_to_hidden_units));\nhidden_layer_state = 1 ./ (1 + exp(-inputs_to_hidden_units));\n% (d) hidden_layer_state = -1 ./ (1 + exp(-inputs_to_hidden_units));\n\n%% COMPUTE STATE OF OUTPUT LAYER.\n% Compute inputs to softmax.\n% FILL IN CODE. Replace the line below by one of the options.\ninputs_to_softmax = zeros(vocab_size, batchsize);\n% Options\ninputs_to_softmax = hid_to_output_weights' * hidden_layer_state + repmat(output_bias, 1, batchsize);\n% (b) inputs_to_softmax = hid_to_output_weights' * hidden_layer_state + repmat(output_bias, batchsize, 1);\n% (c) inputs_to_softmax = hidden_layer_state * hid_to_output_weights' + repmat(output_bias, 1, batchsize);\n% (d) inputs_to_softmax = hid_to_output_weights * hidden_layer_state + repmat(output_bias, batchsize, 1);\n\n% Subtract maximum.\n% Remember that adding or subtracting the same constant from each input to a\n% softmax unit does not affect the outputs. Here we are subtracting maximum to\n% make all inputs <= 0. This prevents overflows when computing their\n% exponents.\ninputs_to_softmax = inputs_to_softmax...\n - repmat(max(inputs_to_softmax), vocab_size, 1);\n\n% Compute exp.\noutput_layer_state = exp(inputs_to_softmax);\n\n% Normalize to get probability distribution.\noutput_layer_state = output_layer_state ./ repmat(...\n sum(output_layer_state, 1), vocab_size, 1);\n", "meta": {"author": "BradNeuberg", "repo": "hinton-coursera", "sha": "578b7310e17b4b072f66fe83b4e9460a4f83d8d6", "save_path": "github-repos/MATLAB/BradNeuberg-hinton-coursera", "path": "github-repos/MATLAB/BradNeuberg-hinton-coursera/hinton-coursera-578b7310e17b4b072f66fe83b4e9460a4f83d8d6/assignment2/fprop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7126611902126999}} {"text": "function checkdiff(problem, x, d)\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% This file is part of Manopt: www.manopt.org.\n% Original author: Nicolas Boumal, Dec. 30, 2012.\n% Contributors: \n% Change log: \n%\n% April 3, 2015 (NB):\n% Works with the new StoreDB class system.\n\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 ~canGetDirectionalDerivative(problem)\n error('It seems no directional derivatives were provided.'); \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 df0 = getDirectionalDerivative(problem, x, d, storedb, xkey);\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 i = 1 : length(h)\n y = problem.M.exp(x, d, h(i));\n ykey = storedb.getNewKey();\n value(i) = getCost(problem, y, storedb, ykey);\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 '(reference) line\\nover 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 % In a numerically reasonable neighborhood, the error should decrease\n % as the square of the stepsize, i.e., in loglog scale, the error\n % should have a slope of 2.\n window_len = 10;\n [range, poly] = identify_linear_piece(log10(h), log10(err), window_len);\n hold on;\n loglog(h(range), 10.^polyval(poly, log10(h(range))), ...\n 'r-', 'LineWidth', 3);\n hold off;\n \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 \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/tools/checkdiff.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7126086472326675}} {"text": "function y = reflect(x,minx,maxx)\n\n% function y = reflect(x,minx,maxx)\n% Reflect the values in matrix x about the scalar values minx and maxx.\n% Hence a vector x containing a long linearly increasing series\n% is converted into a waveform which ramps linearly up and down\n% between minx and maxx.\n% If x contains integers and minx and maxx are (integers + 0.5),\n% the ramps will have repeated max and min samples.\n%\n% Nick Kingsbury, Cambridge University, January 1999.\n\ny = x;\n\n% Reflect y in maxx.\nt = find(y > maxx);\ny(t) = 2*maxx - y(t);\n\n% Reflect y in minx.\nt = find(y < minx);\nwhile ~isempty(t)\n y(t) = 2*minx - y(t);\n \n % Repeat until no more values out of range.\n t = find(y > maxx);\n if ~isempty(t), y(t) = 2*maxx - y(t); end\n t = find(y < minx);\nend\n\nreturn;\n\n", "meta": {"author": "xingchenzhang", "repo": "VIFB", "sha": "7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa", "save_path": "github-repos/MATLAB/xingchenzhang-VIFB", "path": "github-repos/MATLAB/xingchenzhang-VIFB/VIFB-7a89c52b46cfe52dd4d93d4f93cf367a0ed3f8fa/methods/NSCT_SR/dtcwt_toolbox/reflect.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7126086430883624}} {"text": "function [U, S, V, info] = truncated_svd(A, p)\n% Returns an SVD decomposition of A truncated to rank p.\n%\n% function [U, S, V, info] = truncated_svd(A, p)\n%\n% Input: A real matrix A of size mxn and an integer p <= min(m, n).\n% Output: An orthonormal matrix U of size mxp, an orthonormal matrix Y of\n% size nxp and a diagonal matrix S of size pxp with nonnegative and\n% decreasing diagonal entries such that USV.' is the best rank p\n% approximation of A according to the Frobenius norm. All real.\n% This function produces an output akin to svds.\n% \n% The decomposition is obtained by maximizing\n% f(U, V) = .5*norm(U'*A*V, 'fro')^2\n% where U, V are orthonormal. Notice that f(U*Q, V*R) = f(U, V) for all\n% Q, R orthogonal pxp matrices. Hence, only the column spaces of U and V\n% matter and we may perform the optimization over a product of two\n% Grassmannian manifolds.\n%\n% It is easy to show that maximizing f is equivalent to minimizing g with\n% g(U, V) = min_S norm(U*S*V' - A, 'fro')^2,\n% which confirms that we are going for a best low-rank approximation of A.\n% \n% The inner workings of the Grassmann manifold use the built-in svd\n% function of Matlab but only for matrices of size mxp and nxp to\n% re-orthonormalize them.\n% \n% Notice that we are actually chasing a best fixed-rank approximation of a\n% matrix, which is best obtained by working directly over a manifold of\n% fixed-rank matrices. This is simply an example script to demonstrate some\n% functionalities of the toolbox.\n% \n% The code can be modified to accept a function handle for A(x) = A*x\n% instead of a matrix A, which is often useful. This would further require\n% a function handle At for the transpose of A, such that At(x) = A.'*x.\n\n% This file is part of Manopt and is copyrighted. See the license file.\n% \n% Main author: Nicolas Boumal, July 5, 2013\n% Contributors:\n% \n% Change log:\n% \n% Aug. 23, 2021 (XJ):\n% Added AD to compute the egrad and the ehess \n \n % Generate some random data to test the function if none is given.\n if ~exist('A', 'var') || isempty(A)\n A = randn(42, 60);\n end\n if ~exist('p', 'var') || isempty(p)\n p = 5;\n end\n \n % Retrieve the size of the problem and make sure the requested\n % approximation rank is at most the maximum possible rank.\n [m, n] = size(A);\n assert(p <= min(m, n), 'p must be smaller than the smallest dimension of A.');\n \n % Define the cost and its derivatives on the Grassmann manifold\n tuple.U = grassmannfactory(m, p);\n tuple.V = grassmannfactory(n, p);\n % All of the code will work just as well if we ignore the invariance\n % property of the cost function indicated above and thus place U and V\n % on the Stiefel manifold (orthonormal matrices) instead of the\n % Grassmann manifold. Working on Stiefel is expected to be slower\n % though, partly because de search space is higher dimensional and\n % partly because the optimizers are not isolated.\n % tuple.U = stiefelfactory(m, p);\n % tuple.V = stiefelfactory(n, p);\n M = productmanifold(tuple);\n \n % Define a problem structure, specifying the manifold M, the cost\n % function and its derivatives. Here, to demonstrate the rapid\n % prototyping capabilities of Manopt, we directly define the Euclidean\n % gradient and the Euclidean Hessian egrad and ehess instead of the\n % Riemannian gradient and Hessian grad and hess. Manopt will take care\n % of the conversion. This automatic conversion is usually not\n % computationally optimal though, because much of the computations\n % involved in obtaining the gradient could be reused to obtain the\n % Hessian. After the prototyping stage, when efficiency becomes\n % important, it makes sense to define grad and hess rather than egrad\n % an ehess, and to use the caching system (the store structure).\n problem.M = M;\n problem.cost = @cost;\n problem.egrad = @egrad;\n problem.ehess = @ehess;\n \n % The functions below make many redundant computations. This\n % performance hit can be alleviated by using the caching system.\n \n % Cost function\n function f = cost(X)\n U = X.U;\n V = X.V;\n f = -.5*norm(U'*A*V, 'fro')^2;\n end\n % Euclidean gradient of the cost function\n function g = egrad(X)\n U = X.U;\n V = X.V;\n AV = A*V;\n AtU = A'*U;\n g.U = -AV*(AV'*U);\n g.V = -AtU*(AtU'*V);\n end\n % Euclidean Hessian of the cost function\n function h = ehess(X, H)\n U = X.U;\n V = X.V;\n Udot = H.U;\n Vdot = H.V;\n AV = A*V;\n AtU = A'*U;\n AVdot = A*Vdot;\n AtUdot = A'*Udot;\n h.U = -(AVdot*AV'*U + AV*AVdot'*U + AV*AV'*Udot);\n h.V = -(AtUdot*AtU'*V + AtU*AtUdot'*V + AtU*AtU'*Vdot);\n end\n\n % An alternative way to compute the egrad and the ehess is to use \n % automatic differentiation provided in the deep learning toolbox \n % (slower). Notice that the function norm is not supported for AD so \n % far. Replace norm(...,'fro') with the backup function cnormsqfro \n % described in manoptADhelp\n % problem.cost = @cost_AD;\n % function f = cost_AD(X)\n % U = X.U;\n % V = X.V;\n % f = -.5*cnormsqfro(U'*A*V);\n % end\n % call manoptAD to prepare AD for the problem structure\n % problem = manoptAD(problem);\n \n % Execute some checks on the derivatives for early debugging.\n % These things can be commented out of course.\n % checkgradient(problem);\n % pause;\n % checkhessian(problem);\n % pause;\n \n % Issue a call to a solver. A random initial guess will be chosen and\n % default options are selected. Here, we specify a maximum trust\n % region radius (which in turn induces an initial trust region radius).\n % Note that this is not required: default values are used if we omit\n % this. The diameter of the manifold scales like sqrt(2*p), hence the\n % form of our (empirical) choice.\n options.Delta_bar = 4*sqrt(2*p);\n [X, Xcost, info] = trustregions(problem, [], options); %#ok\n U = X.U;\n V = X.V;\n \n % Finish the job by rotating U and V such that the middle matrix S can\n % be diagonal with nonnegative, decreasing entries. This requires a\n % small svd of size pxp.\n Spp = U'*A*V;\n [Upp, Spp, Vpp] = svd(Spp);\n U = U*Upp;\n S = Spp;\n V = V*Vpp;\n \n % For our information, Manopt can also compute the spectrum of the\n % Riemannian Hessian on the tangent space at (any) X. Computing the\n % spectrum at the solution gives us some idea of the conditioning of\n % the problem. If we were to implement a preconditioner for the\n % Hessian, this would also inform us on its performance.\n %\n % Notice that if the optimization is performed on a product of Stiefel\n % manifolds instead of a product of Grassmannians, the double\n % invariance under the orthogonal group O(p) will appear as twice\n % p*(p-1)/2, thus p*(p-1) zero eigenvalues in the spectrum of the\n % Hessian. This means that the minimizers are not isolated, which\n % typically hinders convergence of second order algorithms.\n if M.dim() < 512\n evs = hessianspectrum(problem, X);\n stairs(sort(evs));\n title(['Eigenvalues of the Hessian of the cost function ' ...\n 'at the solution']);\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/examples/truncated_svd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7126086384326449}} {"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\nnarginchk(2,3);\ncvx_optval = -sum_largest( -x, varargin{:} );\n\n% Copyright 2005-2016 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/functions/sum_smallest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7126086366161982}} {"text": "% Figure 3.30b Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%\n\nclf;\nnum=1;\na=5;\n\nzeta =1;\nden2=[1/(zeta*a) 1];\nden1=[1 2*zeta 1];\nden=conv(den1,den2);\nt=0:.1:8;\ny1=step(num,den,t);\n\nzeta =.7;\nden2=[1/(zeta*a) 1];\nden1=[1 2*zeta 1];\nden=conv(den1,den2);\ny2=step(num,den,t);\n\nzeta =.5;\nden2=[1/(zeta*a) 1];\nden1=[1 2*zeta 1];\nden=conv(den1,den2);\ny3=step(num,den,t);\n\naxis([0 5 .1 .9])\nplot(t,y1,'-',t,y2,'--',t,y3,'-.'),grid\ntitle('Fig. 3.30b Step response with extra pole, \\alpha= 5')\nxlabel('\\omega_n t')\nylabel('y(t)')\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig3_30b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7125794906517199}} {"text": "function fx = p11_fun ( n, x )\n\n%*****************************************************************************80\n%\n%% P11_FUN evaluates the integrand for problem 11.\n%\n% Discussion:\n%\n% S&S gives exact value as pi = 3.1415926535897932385...\n% S&S gives Laguerre(16) as 2.6652685196...\n% S&S gives EXP_TRANSFORM(16) as 2.3629036166... \n%\n% Integral:\n%\n% Integral ( 0 <= x < +oo ) 1/((1+x)*sqrt(x)) dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 29 July 2007\n%\n% Author:\n%\n% 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, integer N, the number of points.\n%\n% Input, real X(N), the evaluation points.\n%\n% Output, real FX(N), the function values.\n%\n for i = 1 : n\n if ( x(i) == 0.0 )\n fx(i) = 0.0;\n else\n fx(i) = 1.0 / ( ( 1.0 + x(i) ) * sqrt ( 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/laguerre_test_int/p11_fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7125794837710032}} {"text": "function [RCM1, RCM2, RCM3, RCM4, RCM5] = region_covariance(img, options)\n% Region covariance matrix (GCM) algorithm\n%\n% Inputs:\n% img image data\n% options options\n% Output:\n% RCM1 region covariance matrix of size 7x7 (RCM1) \n% pixel location, intensity, 1st&2nd-order gradient\n% RCM2 region covariance matrix of size 7x7 (RCM2)\n% pixel location, 1st&2nd-order gradient, and edge orientation\n% RCM3 region covariance matrix of size 6x6 (RCM3)\n% pixel location, and 1st&2nd-order gradient\n% RCM4 region covariance matrix of size 8x8 (RCM4) with\n% pixel location, intensity, 1st&2nd-order gradient, and \n% edge orientation\n% RCM5 region covariance matrix of size 5x5 (RCM5) with\n% intensity, 1st&2nd-order gradient (not appear in the paper)\n%\n%\n% References:\n% Yanwei Pang, Yuan Yuan, and Xuelong Li \n% 'Gabor-Based Region Covariance Matrices for Face Recognition'\n% IEEE Transactions on Circuits and Systems for Video Technology vol.18, no.7, 2008.\n%\n%\n% Created by H.Kasai on June 23, 2017\n\n\n symm = @(X) .5*(X+X');\n\n % check correct number of arguments\n if (nargin ~= 2) \n error('Please use the correct number of input arguments!')\n end\n \n % extract options\n if ~isfield(options, 'spd_projection')\n spd_projection = true;\n else\n spd_projection = options.spd_projection;\n end \n\n % check if the input image is grayscale\n if size(img,3) == 3 \n warning('The input RGB image is converted to grayscale!')\n img = rgb2gray(img);\n end\n \n % obtain image size\n [ysize, xsize] = size(img);\n num_of_pixels = ysize * xsize;\n\n % prepare array\n Feature_Mat = zeros(8, num_of_pixels);\n \n \n % calculate first-order and second-order derivatives\n img = double(img);\n [Ix, Iy] = gradient(img); % first order partials\n [Ixx, Ixy] = gradient(Ix); % second order partials\n [Iyx, Iyy] = gradient(Iy); % second order partials \n\n \n % calculate 9-dimensional feature vectior for every pixels\n pixel_cnt = 0;\n for y = 1 : ysize\n for x = 1 : xsize \n %fprintf('[%d %d] %d)\\n', y, x, pixel_cnt);\n pixel_cnt = pixel_cnt + 1;\n\n Feature_Mat(1, pixel_cnt) = x; \n Feature_Mat(2, pixel_cnt) = y; \n Feature_Mat(3, pixel_cnt) = img(y,x); \n \n Feature_Mat(4, pixel_cnt) = abs(Ix(y,x));\n Feature_Mat(5, pixel_cnt) = abs(Iy(y,x)); \n \n Feature_Mat(6, pixel_cnt) = abs(Ixx(y,x)); \n Feature_Mat(7, pixel_cnt) = abs(Iyy(y,x)); \n\n theta = atan(abs(Iy(y,x))/abs(Ix(y,x)));\n Feature_Mat(8, pixel_cnt) = theta; \n\n end\n end\n\n\n % calculate covariance matrix\n Feature_Mat_type1 = Feature_Mat;\n Feature_Mat_type1(8,:) = []; % remove orientation (theta)\n RCM1 = cov(Feature_Mat_type1'); % case for Eq.(5)\n \n Feature_Mat_type2 = Feature_Mat;\n Feature_Mat_type2(3,:) = []; % remove intensity\n RCM2 = cov(Feature_Mat_type2'); % case for Eq.(6)\n \n Feature_Mat_type3 = Feature_Mat;\n Feature_Mat_type3(8,:) = []; % remove edge orientation (theta) \n Feature_Mat_type3(3,:) = []; % remove intensity\n RCM3 = cov(Feature_Mat_type3'); % case for Eq.(8) \n \n RCM4 = cov(Feature_Mat'); % case for Eq.(9)\n \n Feature_Mat_type5 = Feature_Mat;\n Feature_Mat_type5(8,:) = []; % remove edge orientation (theta) \n Feature_Mat_type5(1:2,:) = []; % remove location \n RCM5 = cov(Feature_Mat_type5'); % additional case\n\n\n % project onto SPD if needed\n if spd_projection\n RCM1 = symm(spd_project(RCM1));\n RCM2 = symm(spd_project(RCM2));\n RCM3 = symm(spd_project(RCM3));\n RCM4 = symm(spd_project(RCM4));\n RCM5 = symm(spd_project(RCM5));\n end\n \nend\n\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/auxiliary/covariance_generator/region_covariance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7125200795059523}} {"text": "function [Z] = MCWNNM_ADMM( 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\nmNSig = min(NSig);\nW = (mNSig+eps) ./ (NSig+eps);\n\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;\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 %if error has changed sign,reduce the step size\n if ~same_sign(preverr,err1) && cstep >= MIN_CSTEP\n cstep=cstep * STEP_REDUCTIONFACTOR;\n end\n end\n \n pc = pc - cstep * sign(err1); % move closer to zero\n \n dt=ts+pc;\n if dt <= 0\n pc=ts+cstep;\n end\n if ~isempty(loop) && loop == 30\n cstep=cstep * STEP_REDUCTIONFACTOR;\n loop=0;\n end\n \nend\n\nfunction [pstep, pp] = take_pstep(MIN_PSTEP, pp, pstep, preverr, nit, err2)\n % calculate the parameters of p-value\n if isempty(MIN_PSTEP); return; end\n STEP_REDUCTIONFACTOR = 0.9;\n \n if nit>1\n %if error has changed sign,reduce the step size\n if ~same_sign(preverr,err2) && pstep>= MIN_PSTEP\n pstep=pstep * STEP_REDUCTIONFACTOR;\n end\n end\n \n pp = pp - pstep * sign(err2); % move closer to zero\nend\n\n\nfunction [sdk, sdp, sdc] = kcp_stdevs()\n % calculate standard deviations for k, c, and p values\n %kcp_stdevs.m A.Allmann\n %\n % calculat the parameters of p-value\n %calls itself with different parameters for different loops in programm\n \n % TODO: get rid of all these globals!!@!!Q#RQR@!#R$@!\n \n global p c tt pc pp \n global pk ts dk \n \n te=tt;\n p=pp;\n c=pc;\n dk=pk;\n \n %case1\n f1=((te+c)^(-p+1))/(-p+1);\n h1=((ts+c)^(-p+1))/(-p+1);\n s(1)=(1/dk)*(f1-h1);\n \n %case2\n f2=((te+c)^(-p));\n h2=((ts+c)^(-p));\n s(2)=f2-h2;\n \n %case3\n \n \n f3=(-(te+c)^(-p+1))*(((log(te+c))/(-p+1))-(1/((-p+1)^2)));\n h3=(-(ts+c)^(-p+1))*(((log(ts+c))/(-p+1))-(1/((-p+1)^2))); \n s(3)=f3-h3;\n \n %case4\n \n s(4)=s(2);\n \n %case5\n \n f5=((te+c)^(-p-1))/(p+1);\n h5=((ts+c)^(-p-1))/(p+1);\n s(5)=(-dk)*(p^2)*(f5-h5);\n \n %case6\n \n \n f6=((te+c)^(-p))*(((log(te+c))/(-p))-(1/(p^2)));\n h6=((ts+c)^(-p))*(((log(ts+c))/(-p))-(1/(p^2)));\n s(6)=(dk*p)*(f6-h6);\n \n %case7\n \n s(7)=s(3);\n \n %case8\n \n s(8)=s(6);\n \n %case9\n \n f10=((te+c)^(-p+1))*((log(te+c))^2)/(-p+1);\n f11=(2*((te+c)^(-p+1)))/((-p+1)^2);\n f12=(log(te+c))-(1/(-p+1));\n f9=f10-(f11*f12);\n \n h10=((ts+c)^(-p+1))*((log(ts+c))^2)/(-p+1);\n h11=(2*((ts+c)^(-p+1)))/((-p+1)^2);\n h12=(log(ts+c))-(1/(-p+1));\n h9=h10-(h11*h12);\n s(9)=(dk)*(f9-h9);\n \n \n %assign the values of s to the matrix A(i,j)\n %invert the matrix to calculate the standard deviation\n %for k,c,p .\n \n if nargout == 3\n A=[s(1) s(2) s(3); s(4) s(5) s(6); s(7) s(8) s(9)];\n\n A=inv(A);\n\n sdk=sqrt(A(1,1));\n sdc=sqrt(A(2,2));\n sdp=sqrt(A(3,3));\n \n elseif nargout == 2\n A=[s(1) s(3); s(3) s(9)];\n A=inv(A);\n sdk=sqrt(A(1,1));\n sdp=sqrt(A(2,2));\n else\n error('wrong number of output arguments');\n end\n \nend", "meta": {"author": "CelsoReyes", "repo": "zmap7", "sha": "3895fcb3ca3073608abe22ca71960eb082fd0d9a", "save_path": "github-repos/MATLAB/CelsoReyes-zmap7", "path": "github-repos/MATLAB/CelsoReyes-zmap7/zmap7-3895fcb3ca3073608abe22ca71960eb082fd0d9a/zmap_deprecated/ploop_c_and_p_calcs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7124417755268907}} {"text": "%% Ex. 2 For loop: Utility of the dummy index\n\nb = 3;\nfor k = 1:5\n b^k\nend\n%Output:\n% 3\n% 9\n% 27\n% 81\n% 243\n\n%Remark: The outputs are 3^1, 3^2, 3^3, 3^4, and 3^5. the value of \"k\" keeps changing as\n% we go through the loop", "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_2(basic_looping)/program2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.712401893849911}} {"text": "function [frq,cr] = v_cent2frq(c)\n%V_FRQ2ERB Convert Hertz to Cents frequency scale [C,CR]=(FRQ)\n%\tfrq = v_frq2mel(c) converts a vector of frequencies in cents\n%\tto the corresponding values in Hertz.\n% 100 cents corresponds to one semitone and 440Hz corresponds to 5700\n% cents.\n% The optional cr output gives the gradient in Hz/cent.\n%\n%\tThe relationship between cents and frq is given by:\n%\n%\tc = 1200 * log2(f/(440*(2^((3/12)-5)))\n%\n%\tReference:\n%\n% [1] Ellis, A.\n% On the Musical Scales of Various Nations\n% Journal of the Society of Arts, 1885, 485-527\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: v_cent2frq.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 p q\nif isempty(p)\n p=1200/log(2);\n q=5700-p*log(440);\nend\n% c = 1200*sign(frq).*log2(frq/(440*2^((3/12)-5)));\naf=(exp((abs(c)-q)/p));\nfrq=sign(c).*af;\ncr=af/p;\nif ~nargout\n plot(c,frq,'-x');\n ylabel(['Frequency (' v_yticksi 'Hz)']);\n xlabel(['Frequency (' v_xticksi 'Cents)']);\nend\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_cent2frq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.7124018877999844}} {"text": "% Maximize stopband attenuation of a lowpass IIR filter\n% \"Linear Programming Design of IIR Digital Filters with Arbitrary\n% Magnitude Functions\" by L.R. Rabiner, N.Y. Graham, and H.D. Helms\n% (figures are generated)\n%\n% Designs a lowpass IIR filter using spectral factorization method where we:\n% - minimize maximum stopband attenuation\n% - have a constraint on the maximum passband ripple\n%\n% minimize max |H(w)| for w in the stopband\n% s.t. 1/delta <= |H(w)| <= delta for w in the passband\n%\n% where we now have a rational frequency response function:\n%\n% H(w) = sum_{m=0}^{M-1} b_m exp{-jwm} / sum_{n=1}^{N-1} a_n exp{-jwn}\n%\n% We change variables via spectral factorization method and get:\n%\n% minimize max R(w) for w in the stopband\n% s.t. (1/delta)^2 <= R(w) <= delta^2 for w in the passband\n% R(w) >= 0 for all w\n%\n% where R(w) is the squared magnited of the frequency response\n% (and the Fourier transform of the autocorrelation coefficients r).\n% We represent R(w) = N_hat(w)/D_hat(w), where now R(w) is a rational\n% function since we deal with IIR filter (see the reference paper).\n%\n% Variables are coeffients of the numerator, denoted as c, and\n% denominator, denoted as d. delta is the allowed passband ripple.\n% This is a quasiconvex problem and can be solved using bisection.\n%\n% Written for CVX by Almir Mutapcic 02/02/06\n\n%*********************************************************************\n% user's filter specs (for a low-pass filter example)\n%*********************************************************************\n% number of coefficients for the IIR filter (including the zeroth one)\n% (also without loss of generality we can assume that d_0 = 1, which\n% is the zeroth coefficient of the autocorrelation denominator)\nM = 4; % nominator\nN = 4; % denominator\n\nwpass = 0.12*pi; % end of the passband\nwstop = 0.24*pi; % start of the stopband\ndelta = 1; % maximum passband ripple in dB (+/- around 0 dB)\n\n%*********************************************************************\n% create optimization parameters\n%*********************************************************************\n% rule-of-thumb discretization (from Cheney's Approx. Theory book)\nsample_order = 30;\nm = 15*(sample_order);\nw = linspace(0,pi,m)'; % omega\n\n% A's are matrices used to compute the power spectrum\nAnum = [ones(m,1) 2*cos(kron(w,[1:M-1]))];\nAden = [ones(m,1) 2*cos(kron(w,[1:N-1]))];\n\n% passband 0 <= w <= w_pass\nind = find((0 <= w) & (w <= wpass)); % passband\nAp_num = Anum(ind,:);\nAp_den = Aden(ind,:);\n\n% transition band is not constrained (w_pass <= w <= w_stop)\n\n% stopband (w_stop <= w)\nind = find((wstop <= w) & (w <= pi)); % stopband\nAs_num = Anum(ind,:);\nAs_den = Aden(ind,:);\n\n%********************************************************************\n% optimization\n%********************************************************************\n\n% use bisection (on the log of vars) to solve for the min stopband atten\nUs_top = 1e-0; % 0 dB\nUs_bot = 1e-6; % -60 dB (in original variables)\n\nwhile( 20*log10(Us_top/Us_bot) > 1)\n % try to find a feasible design for given specs\n Us_cur = sqrt(Us_top*Us_bot);\n \n % formulate and solve the magnitude design problem\n cvx_begin quiet\n variable c(M,1)\n variable d(N-1,1)\n\n % feasibility problem\n % passband constraints\n (Ap_num*c) <= (10^(+delta/20))^2*(Ap_den*[1;d]); % upper constr\n (Ap_num*c) >= (10^(-delta/20))^2*(Ap_den*[1;d]); % lower constr\n % stopband constraint\n (As_num*c) <= (Us_cur)*(As_den*[1;d]); % upper constr\n % nonnegative-real constraint\n Anum*c >= 0;\n Aden*[1;d] >= 0;\n cvx_end\n\n % bisection\n if ~any(isnan(c)) % feasible\n fprintf(1,'Problem is feasible for stopband atten = %3.2f dB\\n', ...\n 10*log10(Us_cur));\n Us_top = Us_cur;\n b = spectral_fact(c);\n a = spectral_fact([1;d]);\n else % not feasible\n fprintf(1,'Problem not feasible for stopband atten = %3.2f dB\\n', ...\n 10*log10(Us_cur));\n Us_bot = Us_cur;\n end\nend\n\n% display the max attenuation in the stopband (convert to original vars)\nfprintf(1,'\\nOptimum min stopband atten is between %3.2f and %3.2f dB.\\n',...\n 10*log10(Us_bot),10*log10(Us_top));\ndisp('Optimal IIR filter coefficients are: ')\ndisp('Numerator: '), b\ndisp('Denominator: '), a\n\n%*********************************************************************\n% plotting routines\n%*********************************************************************\n% frequency response of the designed filter, where j = sqrt(-1)\nH = ([exp(-j*kron(w,[0:M-1]))]*b)./([exp(-j*kron(w,[0:N-1]))]*a);\n\n% magnitude plot\nfigure(1)\nsubplot(2,1,1)\nplot(w,20*log10(abs(H)), ...\n [0 wpass],[delta delta],'r--', ...\n [0 wpass],[-delta -delta],'r--', ...\n [wstop pi],[10*log10(Us_top) 10*log10(Us_top)],'r--')\nxlabel('w')\nylabel('mag H(w) in dB')\naxis([0 pi -55 10]);\n\n% phase plot\nsubplot(2,1,2)\nplot(w,angle(H))\naxis([0,pi,-pi,pi])\nxlabel('w'), ylabel('phase H(w)')\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/examples/filter_design/iir_mag_design_lowpass_max_atten.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303732328411, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.7124018842532129}} {"text": "% Figure 3.35 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%script to generate Fig. 3.35\nclf;\nt=0:.05:10;\nk=1;\nki=0;\nnumCL=[k ki];\ndenCL=[1 3 2+k ki];\ny1=step(numCL,denCL,t);\nki=1;\nnumCL=[k ki];\ndenCL=[1 3 2+k ki];\ny2=step(numCL,denCL,t);\nk=10;\nki=5;\nnumCL=[k ki];\ndenCL=[1 3 2+k ki];\ny3=step(numCL,denCL,t);\naxis([0 10 0 1.2]);\nplot(t,y1,t,y2,t,y3);\ngrid;\nxlabel('Time (sec)');\nylabel('y(t)');\ntitle('Fig. 3.35 Transient responses');\naxis('normal');\ntext(2,.25,'K=1, K_I=0');\ntext(3,0.75,'K=1, K_I=1');\ntext(1.5,1.1,'K=10, K_I=5');\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig3_35.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7123398158243569}} {"text": "%% DNLS Example1\nclc\n% ODE System\n ode = @(t,z,p) [-p(1)*z(1) + 4; \n 2*z(1) - p(1)*z(2) + 5; \n -4*z(1) - 2*z(2)*z(3) - p(2)];\n\n% Initial Conditions\n z0 = [-1.5;1.25;1];\n\n% True Parameter Values\n p = [2.345;1.1];\n\n% Generate Fitting Data\n tm = 0:0.1:2; %measurement times\n odeInt = @(t,z) ode(t,z,p); %ODE function for ODE45\n[~,zm] = ode45(odeInt,tm,z0); %Solve ODEs\n\n% Starting Guess\n theta0 = [1;0.5];\n\n% Create OPTI Object\n Opt = opti('ode',ode,'data',tm,zm,'z0',z0,'theta0',theta0)\n\n% Solve\n[theta,fval,exitflag,info] = solve(Opt)\n\n% Plot the Solution\nplot(Opt)\n\n\n%% DNLS Example2\nclc\n% Indicate Initial Conditions to Solve for Using NaNs\n z0 = [-1.5;NaN;NaN];\n\n% Starting Guess [p;z0]\n theta0 = [1;0.5;0.5;0.5];\n\n% Create OPTI Object\n Opt = opti('ode',ode,'data',tm,zm,'z0',z0,'theta0',theta0)\n\n% Solve\n[theta,fval,exitflag,info] = solve(Opt)\n\n% Plot the Solution\nplot(Opt)\n\n%% Example 3\nclc\n\n% Add Bounds\n lb = [1.5;0;0.1;0.1];\n ub = [3.5;2;1.5;1.5];\n\n% Create OPTI Object\n Opt = opti('ode',ode,'data',tm,zm,'bounds',lb,ub,'z0',z0,'theta0',theta0)\n\n% Solve\n[theta,fval,exitflag,info] = solve(Opt)\n\n% Plot the Solution\nplot(Opt)\n\n%% DNLS Example4\nclc\n% Set Dynamic Options (specifying states of interest)\n dopts = optidynset('stateIndex',[2 3]);\n\n% Add to General OPTI Options\n opts = optiset('display','iter','dynamicOpts',dopts);\n\n% Index Measured Data\n zm23 = zm(:,[2 3]);\n\n% Create OPTI Object\n Opt = opti('ode',ode,'data',tm,zm23,'z0',z0,'theta0',theta0,'options',opts)\n\n% Solve\n[theta,fval,exitflag,info] = solve(Opt)\n\n% Plot the Solution\nplot(Opt)\n\n%% DNLS Example5\nclc\n% Initial Conditions\nz0 = [-1.5;1.25;1];\n\n% Measurement Times for each State\ntm2 = 0:0.1:2; %state 2\ntm3 = 0.2:0.2:2; %state 3\n\n% Solve ODEs and index Measurement Data\n[~,zm2] = ode45(odeInt,tm2,z0); zm2 = zm2(:,2);\n% Note 0 is required below just to match initial condition in this example\n[~,zm3] = ode45(odeInt,[0 tm3],z0); zm3 = zm3(2:end,3); %drop first point\n\n% Group measurements and time stamps in cell arrays\ntm_multi = {tm2;tm3};\nzm_multi = {zm2;zm3};\n\n% Indicate Initial Conditions to Solve for Using NaNs\n z0 = [-1.5;NaN;NaN];\n\n% Create OPTI Object\nOpt = opti('ode',ode,'data',tm_multi,zm_multi,'z0',z0,'theta0',theta0,'options',opts)\n\n% Solve\n[theta,fval,exitflag,info] = solve(Opt)\n\n% Plot the Solution\nplot(Opt)\n\n%% DNLS Example6\nclc\n% Initial Conditions\nz0 = [-1.5;1.25;1];\n\n% Measurement Times for each State\ntm1 = 0.5:0.1:2; %state 1\ntm2 = 1:0.1:2; %state 2\ntm3 = 0.2:0.2:2; %state 3\n\n% Solve ODEs and index Measurement Data\n% Note 0 is required below just to match initial condition in this example\n[~,zm1] = ode45(odeInt,[0 tm1],z0); zm1 = zm1((2:end),1);\n[~,zm2] = ode45(odeInt,[0 tm2],z0); zm2 = zm2((2:end),2);\n[~,zm3] = ode45(odeInt,[0 tm3],z0); zm3 = zm3((2:end),3);\n\n% Group measurements and time stamps in cell arrays\ntm_multi = {tm1;tm2;tm3};\nzm_multi = {zm1;zm2;zm3};\n\n% Indicate Initial Conditions to Solve for Using NaNs\n z0 = [NaN;NaN;NaN];\n \n% New Initial Guess Vector [p;z0];\n theta0 = [1;0.5;0.5;0.5;0.5];\n\n% Create OPTI Object\ndopts = optidynset('initialT',0);\nopts = optiset('display','iter','dynamicOpts',dopts);\nOpt = opti('ode',ode,'data',tm_multi,zm_multi,'z0',z0,'theta0',theta0,'options',opts)\n\n% Solve\n[theta,fval,exitflag,info] = solve(Opt)\n\n% Plot the Solution\nplot(Opt)\n\n\n%% DNLS Example7\nclc\n% Initial Conditions\nz0 = [-1.5;1.25;1];\n\n% Measurement Times for each State\ntm1 = 0.5:0.1:2; %state 1\ntm1b = 1:0.25:2; %state 1\ntm2 = 1:0.1:2; %state 2\ntm3 = 0.2:0.2:2; %state 3\n\n%ODE with modified parameters (representing a different run)\nodeIntB = @(t,z) ode(t,z,p*0.85); \n\n% Solve ODEs and index Measurement Data\n% Note 0 is required below just to match initial condition in this example\n[~,zm1] = ode45(odeInt,[0 tm1],z0); zm1 = zm1((2:end),1);\n[~,zm1b] = ode45(odeIntB,[0 tm1b],z0); zm1b = zm1b((2:end),1);\n[~,zm2] = ode45(odeInt,[0 tm2],z0); zm2 = zm2((2:end),2);\n[~,zm3] = ode45(odeInt,[0 tm3],z0); zm3 = zm3((2:end),3);\n[~,zm3b] = ode45(odeInt,[0 tm3],z0*0.75); zm3b = zm3b((2:end),3);\n\n% Group measurements and time stamps in cell arrays\ntm_multi = {[tm1 tm1b];tm2;[tm3 tm3]};\nzm_multi = {[zm1;zm1b];zm2;[zm3;zm3b]};\n\n% Indicate Initial Conditions to Solve for Using NaNs\n z0 = [NaN;NaN;NaN];\n \n% New Initial Guess Vector [p;z0];\n theta0 = [1;0.5;0.5;0.5;0.5];\n\n% Create OPTI Object\ndopts = optidynset('initialT',0);\nopts = optiset('display','iter','dynamicOpts',dopts);\nOpt = opti('ode',ode,'data',tm_multi,zm_multi,'z0',z0,'theta0',theta0,'options',opts)\n\n% Solve\n[theta,fval,exitflag,info] = solve(Opt)\n\n% Plot the Solution\nplot(Opt)\n\n\n%% DNLS Example8\nclc\n% Declare Symbolic Variables\nsyms p1 p2 z1 z2 z3\n% Symbolic ODE\nODE = [-p1*z1 + 4; \n 2*z1 - p1*z2 + 5; \n -4*z1 - 2*z2*z3 - p2];\n\n% Evaluate Jacobians\ndfdz_sym = jacobian(ODE,[z1 z2 z3])\ndfdp_sym = jacobian(ODE,[p1 p2])\n\n[dfdz,dfdp] = symDynJac(ode)\n\n\n% Analytical Derivative Expressions\n dfdz = @(t,z,p) [-p(1) 0, 0;\n 2, -p(1), 0;\n -4, -2*z(3), -2*z(2)];\n dfdp = @(t,z,p) [-z(1), 0;\n -z(2), 0;\n 0, -1];\n\n% Set Dynamic Options\n dopts = optidynset('dfdz',dfdz,'dfdp',dfdp,'sensitivity','User','initialT',0);\n\n% General OPTI Options\n opts = optiset('display','iter','derivCheck','on','dynamicOpts',dopts);\n\n% Create OPTI Object\n Opt = opti('ode',ode,'data',tm_multi,zm_multi,'z0',z0,'theta0',theta0,...\n 'options',opts)\n\n% Solve\n[theta,fval,exitflag,info] = solve(Opt)\n\n% Plot the Solution\nplot(Opt)\n\n\n%% DNLS Ex9\nclc\n%ODE to fit\node = @(t,z,p) p(1)*z(1)^2 - z(1)^3;\nz0 = 0.001; %ic\n\n%Generate measurement data\np = 1.5; %true parameter value\noi = @(t,z) ode(t,z,p); %ode integrator function\ntm = [0 65:70 80:1:90 100]*10; %measurement times\n[~,zm] = ode15s(oi,tm,z0); %measurements\n\n% Starting Guess\ntheta0 = 1;\n\n%Build OPTI Object\ndopts = optidynset('sensitivity','none');\nopts1 = optiset('display','iter','iterfun',@optiplotlogfval,'dynamicOpts',dopts);\nopts2 = optiset('display','iter','iterfun',@optiplotlogfval);\n\n% Create OPTI Objects\nOptNoDer = opti('ode',ode,'data',tm,zm,'z0',z0,'theta0',theta0,'options',opts1)\nOptWDer = opti('ode',ode,'data',tm,zm,'z0',z0,'theta0',theta0,'options',opts2)\n\n% Solve\n[theta,fval,exitflag,info] = solve(OptNoDer)\n[theta,fval,exitflag,info] = solve(OptWDer)\n\n% Plot the Solution\nsubplot(121)\nplot(OptNoDer); title('No Sensitivity');\nsubplot(122)\nplot(OptWDer); title('With Sensitivity');\n\n%% DNS Ex9b\nclc\n% Partial Derivatives\ndfdz = @(t,z,p) 2*p(1)*z(1) - 3*z(1)^2;\ndfdp = @(t,z,p) z(1)^2;\n\n% Set Dynamic Options\ndopts = optidynset('dfdz',dfdz,'dfdp',dfdp,'integrator','ode15s',...\n 'sensitivity','User');\n\n% General OPTI Options\nopts = optiset('display','iter','derivCheck','on','dynamicOpts',dopts);\n\n% Create OPTI Object\nOpt = opti('ode',ode,'data',tm,zm,'z0',z0,'theta0',theta0,'options',opts)\n\n% Solve\n[theta,fval,exitflag,info] = solve(Opt)\n\n% Plot\nplot(Opt)\n\n\n%% DNS Ex9c\nclc\n% Set Dynamic Options\ndopts = optidynset('integrator','ode15s','sensitivity','None');\n\n% General OPTI Options\nopts = optiset('solver','nomad','display','iter','dynamicOpts',dopts);\n\n% Create OPTI Object\nOpt = opti('ode',ode,'data',tm,zm,'bounds',0.5,2.5,'z0',z0,'theta0',theta0,'options',opts)\n\n% Solve\n[theta,fval,exitflag,info] = solve(Opt)", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/ThirdPartyToolbox/OptiToolbox/Test Problems/Development/dnls_examples.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7122105128094668}} {"text": "function v = barywts(n)\n%BARYWTS Barycentric weights for Chebyshev points of 2nd kind.\n% BARYWTS(N) returns the N barycentric weights for polynomial interpolation on\n% a Chebyshev grid of the 2nd kind. The weights are normalised so that they\n% have infinity norm equal to 1 and the final entry is positive.\n%\n% See also BARY, CHEBPTS. \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% See Thm. 5.2 of Trefethen, Approximation Theory and Approximation Practice, \n% SIAM, 2013 for more information.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nif ( n == 0 ) % Special case (no points)\n v = [];\nelseif ( n == 1 ) % Special case (single point)\n v = 1;\nelse % General case\n v = [ones(n-1,1) ; .5]; % Note v(end) is positive.\n v(end-1:-2:1) = -1; \n v(1) = .5*v(1);\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/@chebtech2/barywts.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7122104905874799}} {"text": "% Driver script for solving the 2D Poisson equation on curvilinear domains\nGlobals2D;\n\n% Polynomial order used for approximation \nN = 6;\n\n% Read in Mesh\n[Nv, VX, VY, K, EToV] = MeshReaderGambitBC2D('circA01.neu');\n\n% Initialize solver and construct grid and metric\nStartUp2D;\n\n% hard coded for all Dirichlet boundaries to be on cylinder\n[k,f] = find(BCType==Dirichlet);\nif(~isempty(k))\n cylfaces = [k,f];\n curved = sort(unique(k)); straight = setdiff(1:K, curved);\n MakeCylinder2D(cylfaces, 1, 0, 0);\nend\n\n% choose order to integrate exactly\nNint = ceil(2*N/2);\n\n% build cubature nodes for all elements\nCubatureOrder = 2*(Nint+1); cub = CubatureVolumeMesh2D(CubatureOrder);\n \n% build Gauss node data for all element faces\nNGauss = (Nint+1); gauss = GaussFaceMesh2D(NGauss);\n \n% build weak Poisson operator matrices\n[A, M] = CurvedPoissonIPDG2D();\nAbc = CurvedPoissonIPDGbc2D();\n\n% set up right hand side\nf = (-2*pi^2-1)*sin(pi*x).*sin(pi*y); \n\n% set up boundary condition \nubc = zeros(gauss.NGauss*Nfaces*K,1);\nxbc = gauss.x(gauss.mapD); ybc = gauss.y(gauss.mapD);\nubc(gauss.mapD) = sin(pi*xbc).*sin(pi*ybc);\nxbc = gauss.x(gauss.mapN); ybc = gauss.y(gauss.mapN);\nubc(gauss.mapN) = ...\n gauss.nx(gauss.mapN).*(pi*cos(pi*xbc).*sin(pi*ybc)) + ...\n gauss.ny(gauss.mapN).*(pi*sin(pi*xbc).*cos(pi*ybc));\n\nubc = Abc*ubc;\n\n% solve linear system\nsolvec = (A+M)\\(M*(-f(:)) + ubc);\nu = reshape(solvec, Np, K);\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/Codes2D/CurvedPoissonIPDGDriver2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.712185805794341}} {"text": "function f = lnDiffCumGaussian(u, uprime)\n\n% LNDIFFCUMGAUSSIAN Log of the difference between two cumulative Gaussians.\n% FORMAT\n% DESC computes the logarithm of the difference between two\n% cumulative Gaussian distributions.\n% ARG u1 : the argument of the first (positive) cumulative\n% Gaussian.\n% ARG u2 : the argument of the second (negative) cumulative\n% Gaussian.\n% RETURN f : where f = log(cumGaussian(u1) - cumGaussian(u2)).\n%\n% SEEALSO : cumGaussian, gaussOverDiffCumGaussian, lnCumGaussian\n%\n% COPYRIGHT : Neil D. Lawrence, 2005, 2006\n\n% NDLUTIL\n\nf = log(gaussOverDiffCumGaussian(u, uprime, 1)+1e-300) ...\n + .5*u.*u + .5*log(2*pi);\nf=-f;\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ndlutil/lnDiffCumGaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850110816422, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7121858047712133}} {"text": "% Construction of a bilinearly blended Coons surface \n% \n \n% D.M. Spink \n% Copyright (c) 2000. \n \n% Boundary curve 1 \npnts = [ 0.0 3.0 4.5 6.5 8.0 10.0; \n 0.0 0.0 0.0 0.0 0.0 0.0; \n 2.0 2.0 7.0 4.0 7.0 9.0]; \ncrv1 = nrbmak(pnts, [0 0 0 1/3 0.5 2/3 1 1 1]); \n \n% Boundary curve 2 \npnts= [ 0.0 3.0 5.0 8.0 10.0; \n 10.0 10.0 10.0 10.0 10.0; \n 3.0 5.0 8.0 6.0 10.0]; \ncrv2 = nrbmak(pnts, [0 0 0 1/3 2/3 1 1 1]); \n \n% Boundary curve 3 \npnts= [ 0.0 0.0 0.0 0.0; \n 0.0 3.0 8.0 10.0; \n 2.0 0.0 5.0 3.0]; \ncrv3 = nrbmak(pnts, [0 0 0 0.5 1 1 1]); \n \n% Boundary curve 4 \npnts= [ 10.0 10.0 10.0 10.0 10.0; \n 0.0 3.0 5.0 8.0 10.0; \n 9.0 7.0 7.0 10.0 10.0]; \ncrv4 = nrbmak(pnts, [0 0 0 0.25 0.75 1 1 1]); \n \nsrf = nrbcoons(crv1, crv2, crv3, crv4); \n \n% Draw the surface \nnrbplot(srf,[20 20]); \ntitle('Construction of a bilinearly blended Coons surface.'); \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/26390-nurbs-toolbox-by-d-m-spink/nurbs_toolbox/democoons.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480346, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.7121857956340614}} {"text": "function g = p26_g ( n, x )\n\n%*****************************************************************************80\n%\n%% P26_G evaluates the gradient for problem 26.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 January 2001\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 jroot = 5;\n k = 500;\n fi = k;\n dfidx1 = 0.0;\n dfidx2 = 0.0;\n\n for j = 1 : jroot * jroot\n\n j1 = mod ( j-1, jroot ) + 1;\n a1 = -32 + j1 * 16;\n\n j2 = ( j - 1 ) / jroot;\n a2 = -32 + j2 * 16;\n\n fj = ( j + ( x(1) - a1 )^6 + ( x(2) - a2 )^6 );\n\n fi = fi + 1.0 / fj;\n\n dfidx1 = dfidx1 - ( 1.0 / fj^2 ) * 6.0 * ( x(1) - a1 )^5;\n dfidx2 = dfidx2 - ( 1.0 / fj^2 ) * 6.0 * ( x(2) - a2 )^5;\n\n end\n\n g(1) = - ( 1.0 / fi^2 ) * dfidx1;\n g(2) = - ( 1.0 / fi^2 ) * dfidx2;\n\n return\nend\n", "meta": {"author": "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/p26_g.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.7121500691381661}} {"text": "%% DEMOSLOPE Short demonstration of slopes\n%\n\n%% Some sample applications of the Hessian toolbox\n% Hessians implement second order automatic differentiation in forward mode, which is\n% conveniently to implement using the Matlab operator concept.\n%\n% For a demonstration of the slope toolbox, intervals are wide; therefore, output \n% is switched to infimum/supremum representation (see demointval):\n \nsetround(0) % set rounding to nearest\nformat compact short infsup\n \n%% Slope expansions\n% In order to use slope expansions, the expansion range and expansion \n% point (interval) need to be identified and values have to be assigned. \n% This is performed by the function \"slopeinit\", for example \n \nu = slopeinit( [1;2] , infsup([1;2],[1.1;2.1]) )\n \n%% \n% The length (number of rows) is the number \n% of independent variables, in the example above two. Slopes are always \n% of type intval. For definition and use of slopes cf. Neumaier's book\n% on interval analysis.\n \n%% Computing with slopes \n% Automatic slope expansion is performed by operations with slope variables. \n% For example, \n \nx = slopeinit(3.5,midrad(3.5,1e-4)); \ny = exp(3*x-sqrt(x))\n \n%%\n% evaluates the expression using slopes with expansion point 3.5 and expansion\n% interval 3.5+/-1e-4. \n%\n% There is access to the center value, the range and \n% the slope of y:\n \ny.c\ny.r\ny.s\n \n%%\n% When evaluating the expression for another argument, e.g. a vector argument,\n% use the same statement as before with new values.\n \nxs = [2;3]; \nx = slopeinit(xs,midrad(xs,1e-4)); \ny = exp(3*x-sqrt(x))\n\n%% Graphical illustration of slopes\n% There is a simple graphic to demonstrate the behaviour of slope expansions for \n% one-dimensional functions. The routine \"slopeplot\" assumes a function\n% in one variable which can be evaluated for vectors, the expansion\n% point and the expansion interval.\n% For example, \n \nformat short\nslopeplot('(x-2).*exp(x)-sqrt(abs(x))',1,infsup(1,2))\n \n%%\n% shows a best possible upper slope, but an underestimated lower slope.\n\n%% Non-differentiable functions\n% Functions to be handled by slopes need not be differentiable. \n% An example is sqrt(abs(x)). Consider \n \nslopeplot('sqrt(abs(x))',-2,infsup(-1,1))\n \n%% \n% The slope is best possible, but the grid is not fine enough to catch the\n% extreme point at zero. For some 10000 grid points the picture looks\n% as follows:\n \nslopeplot('sqrt(abs(x))',-2,infsup(-1,1),[],10000)\n \n%% Computation of the Gamma function with slopes\n% Consider the following example in one unknown. \n% According to Stirling's formula it is for u -> inf, \n% \n% 1 1 139 571 \n% Gamma(u) ~ C * ( 1 + --- + ----- - ------- - --------- + ... ) \n% 12u 2 3 4 \n% 288u 51840u 2488320u \n% with \n%\n% -u u-0.5 \n% C = e u sqrt(2*pi) . \n% \n% The following function evaluates Stirling's formula. It is also \n% suited for vector input. \n% \n% \n% function y = g(u) \n% C = exp(-u) .* ( u.^(u-0.5) ) * sqrt(2.0*pi) ; \n% v = (((( -571.0/2488320.0 ./ u - 139.0/51840.0 ) ./ u ... \n% + 1.0/288.0) ./ u ) + 1.0/12.0 ) ./ u + 1.0; \n% y = C .* v; \n% \n% A corresponding inline function is\n\nformat long e\ng = @(u) ( ( exp(-u) .* ( u.^(u-0.5) ) * sqrt(2.0*pi) ) .* ...\n ( (((( -571.0/2488320.0 ./ u - 139.0/51840.0 ) ./ u ... \n + 1.0/288.0) ./ u ) + 1.0/12.0 ) ./ u + 1.0 ) )\nu = [ 3.5 61 5 ]\ng(u)\n \n%% Computation of the range of the function g\n% Next calculate the range of the function g within \n% a certain interval. This can be performed, for example, by straightforward \n% interval evluation (naive interval arithmetic) \n\nformat long\nX = infsup(4.1,4.2); \nY = g(X)\n\n%%\n% or by slopes:\n \nxs = 4.1; \nX = infsup(4.1,4.2); \nYs = g(slopeinit(xs,X))\n \n%%\n% The range computed by the slope expansion is better by a factor 2 than \n% naive interval arithmetic and less than 20 % overestimation of the true range:\n \ndiam(Y)\ndiam(Ys.r)\ng(4.2)-g(4.1)\n\n%%\n% Note that Y or Ys.r is an inclusion of the range of g; for an inclusion \n% of the range of the Gamma function an error\n% term has to be added.\n\n%% Slopes in several unknowns\n% Automatic slope expansion with several unknowns works the same way. \n% Consider the following example by Broyden. \n% \n% .5*sin(x1*x2) - x2/(4*pi) - x1/2 = 0 \n% (1-1/(4*pi))*(exp(2*x1)-exp(1)) + exp(1)*x2/pi - 2*exp(1)*x1 ) = 0 \n% \n% with initial approximation [ .6 ; 3 ] and one solution [ .5 ; pi ]. \n% The following function evaluates Broyden's function. \n% \n% function y = f1(x) \n% y = x; \n% y(1) = .5*sin(x(1)*x(2)) - x(2)/(4*pi) - x(1)/2; \n% y(2) = (1-1/(4*pi))*(exp(2*x(1))-exp(1)) + exp(1)*x(2)/pi - 2*exp(1)*x(1); \n% \n% The first statement is for efficiency. It is generally better to fix the size \n% of an array before assigning values to the components. An inline function\n% is as follows (cf. demogradient): \n\nf = @(x) ( [ .5*sin(x(1)*x(2)) - x(2)/(4*pi) - x(1)/2 ; ...\n (1-1/(4*pi))*(exp(2*x(1))-exp(1)) + exp(1)*x(2)/pi - 2*exp(1)*x(1) ] ) \n\n%% Solution of a nonlinear system\n% The nonlinear system defined by Broyden's function can solved by Newton's procedure \n% as follows (cf. demogradient):\n \nx = gradientinit([ .6 ; 3 ]);\nfor i=1:5\n y = f1(x);\n x = x - y.dx\\y.x;\nend\nx\n \n%% \n% For simplicity, we omitted the stopping criterion. \n% Here, y.dx is the Jacobian, y.x the function value at x.x, and -y.dx\\y.x \n% is the correction obtained by solution of a linear system. \n \n%% Verified solution of a nonlinear system \n% For verified solution of the nonlinear system, we need a correct definition \n% of the function, see demogradient: \n% \n% function y = f(x) \n% y = x;\n% c1 = typeadj( 1 , typeof(x) );\n% cpi = typeadj( midrad(3.14159265358979323,1e-16) , typeof(x) );\n% y(1) = .5*sin(x(1)*x(2)) - x(2)/(4*cpi) - x(1)/2;\n% y(2) = (1-1/(4*cpi))*(exp(2*x(1))-exp(c1)) + exp(c1)*x(2)/cpi - 2*exp(c1)*x(1);\n% \n% This code is implemented in the function demotest.m .\n\n%% Verified solution using verifynlss \n% The nonlinear system defined by Broyden's function can be \n% solved with verification and using slopes by: \n \ny = verifynlss('demotest',[ .6 ; 3 ],'s')\n \n%%\n% The first parameter gives the name of the function, in this case \"demotest\", \n% such that \"demotest(x)\" evaluates the function at \"x\". \n% For the last parameter being 's', slopes are used, otherwise gradients (the default). \n% \n% We used slopes. However, the inclusion of the error with respect to an approximate\n% is computed; therefore, the results for gradient and slope inclusion are identical.\n% Note that use of gradients guarantees uniqueness of the zero within the computed\n% interval, use of slope does not. \n \n%% Nonlinear systems with uncertain parameters \n% Next we artificially introduce an interval parameter of large diameter\n% in Broyden's function: \n% \n% function y = demotest(x,radius) \n% y = x; \n% if nargin==1 \n% radius = 1e-15; \n% end\n% cPi = typeadj( midrad(3.141592653589793,radius) , typeof(x) ); \n% y(1) = .5*sin(x(1)*x(2)) - x(2)/(4*cPi) - x(1)/2; \n% y(2) = (1-1/(4*cPi))*(exp(2*x(1))-exp(1)) + exp(1)*x(2)/cPi - 2*exp(1)*x(1); \n% \n% This is to show that the range of applicability is larger for slopes than\n% for gradients. For radius .04, both gradient expansion and slope expansion \n% compute an inclusion (the extra parameter is passed to demotest): \n\nradius = 4e-2; y1 = verifynlss('demotest',[ .6 ; 3 ],'g',[],radius)\nradius = 4e-2; y2 = verifynlss('demotest',[ .6 ; 3 ],'s',[],radius)\n \n%%\n% The inclusion using slopes is better by 10 to 20 % in radius:\n\n[ rad(y1) rad(y2) ]\n\n%% A demo nonlinear function with large uncertainty\n% Finally, we enlarge the radius of the parameter cPi to 0.05 and try to \n% calculate an inclusion:\n \nradius = 5e-2; y1 = verifynlss('demotest',[ .6 ; 3 ],'g',[],radius)\nradius = 5e-2; y2 = verifynlss('demotest',[ .6 ; 3 ],'s',[],radius)\n \n%%\n% Now, only the slope expansion is able to compute an inclusion. \n \n%% Enjoy INTLAB\n% INTLAB was designed and written by S.M. Rump, head of the Institute for Reliable Computing,\n% Hamburg University of Technology. Suggestions are always welcome to rump (at) tuhh.de\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/demos/dslope.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.7121500664375632}} {"text": "function Xd = Pendulum_Cart_Dynamics_Forced(X,F,P_Dyn)\n% Xd = Pendulum_Cart_Dynamics_Forced(X,F,P_Dyn)\n%\n% FUNCTION:\n% This function is used to compute the dynamics of the pendulum cart\n% system. The inputs are the system state, actuator force, and paramters.\n% \n% INPUTS:\n%\n% X = [4 x N] state matrix: [x;v;th;w]\n% F = [1 x N] actuator force (applied horizontally to cart)\n% P_Dyn = a parameter struct with fields:\n% M = cart mass\n% m = bob mass\n% L = pendulum length\n% g = gravitational acceleration\n%\n% OUTPUTS:\n% dX = [4 x N] derivative of the state matrix [dx;dv;dth;dw]\n%\n% NOTES:\n% The equations of motion are found using a cartesian force balance for\n% each rigid body\n%\n% The cart is modelled as a point mass, and the pendulum is modelled as a\n% point mass at the end of a slender rod. There is no friction in the\n% system. \n%\n% Parts of the derivation are shown below in comments. This code has been\n% partially optimized, so some of the comments show intermediate steps\n% that were bypassed.\n%\n\n%Define Parameters\nm = P_Dyn.m; %Pendulum point mass\nM = P_Dyn.M; %Cart mass\nL = P_Dyn.L; %Pendulum length (to point mass)\ng = P_Dyn.g; %Gravity\n\n%Define input states:\n% % x = X(1); %Horizontal position of the cart\nv = X(2,:); %Horizontal velocity of the cart\nth = X(3,:); %Angle of the pendulum: 0 = straight up, pi = straight down\nw = X(4,:); %Angular rate of the pendulum\n\n%Evaluate sines and cosines\nSin = -sin(th);\nCos = -cos(th);\nOne = ones(size(Sin));\n\n%\"Constant terms\"\n% % App_Forces = [...\n% % -F;\n% % M*g;\n% % -m*L*w^2*Sin;\n% % m*g + m*L*w^2*Cos];\n\n% % %Matrix for of coeffieients: \n% % % Coeff * [Tension; Normal; Trans. Acc; Rot Acc] =\n% % % Applied_Forces( X0, Y0, X1, Y1 )\n% % Coeff = [...\n% % sin(th) 0 -M 0;\n% % -cos(th) 1 0 0;\n% % -sin(th) 0 -m -m*L*cos(th);\n% % cos(th) 0 0 -m*L*sin(th)];\n\n% Analytic Inverse of Coeff via Mathematica:\nDet = m*L*(M*Cos.^2 + (m+M)*Sin.^2);\ninv_Det = 1./Det; \n% % Adj = [...\n% % m^2*L*Sin 0 -m*M*L*Sin m*M*L*Cos;\n% % m^2*L*Sin*Cos 1 -m*M*L*Sin*Cos m*M*L*Cos^2;\n% % -m*L \t0 -m*L*Sin^2 m*L*Cos*Sin;\n% % m*Cos \t0 -M*Cos -(M+m)*Sin];\n\n% % Inv = inv_Det*Adj;\n% % UnKnowns = Inv*App_Forces; %Solve linear system of equations\n\n% % % % Tension = Unknowns(1);\n% % % % Normal = UnKnowns(2);\n% % vd = UnKnowns(3);\n% % wd = UnKnowns(4);\n\n%Unknowns (By Hand)\n% % UnKnowns = inv_Det*[...\n% % %-F* M*g* -m*L*w^2*Sin* (m*g + m*L*w^2*Cos)*\n% % -F*m^2*L*Sin + 0 + m*L*w^2*Sin*m*M*L*Sin + (m*g + m*L*w^2*Cos)*m*M*L*Cos ; %Tension\n% % -F*m^2*L*Sin*Cos + M*g + m*L*w^2*Sin*m*M*L*Sin*Cos + (m*g + m*L*w^2*Cos)*m*M*L*Cos^2 ; %Normal Force\n% % F*m*L + 0 + m*L*w^2*Sin*m*L*Sin^2 + (m*g + m*L*w^2*Cos)*m*L*Cos*Sin ; %Translational acceleration\n% % -F*m*Cos + 0 + m*L*w^2*Sin*M*Cos + -(m*g + m*L*w^2*Cos)*(M+m)*Sin ]; %Angular Acceleration\n\n%Broken Out UnKnowns (By Hand)\nvd = (F*m*L + 0 + m*L*w.^2.*Sin*m*L.*Sin.^2 + (m*g*One + m*L*w.^2.*Cos).*m*L.*Cos.*Sin).*inv_Det;%Translational acceleration\nwd = (-F.*m.*Cos + 0 + m*L*w.^2.*Sin.*M.*Cos + -(m*g*One + m*L*w.^2.*Cos)*(M+m).*Sin).*inv_Det;%Angular Acceleration\n\n%Defined derivatives:\nxd = v;\nthd = w;\n\n%Express as a vector\nXd = [xd;vd;thd;wd];\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/PendulumCart_SwingUp/Piecewise_Linear_Soln/Pendulum_Cart_Dynamics_Forced.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7121500607012359}} {"text": "% Figure 10.59 Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%\n% fig10_59.m is a script for disk read/write head control design\n% the design is based on 1/s^2 with robustness\n% with respect to a resonance of damping zeta = z at wm.\n% the design calls for a single lead selected to maximize wc\n% the compensator has a second order roll-off filter\n% the resonance is 'gain stabilized' with GM \n% the phase margin is set by alpha = a\n% the time is scaled to milliseconds\nwm= 5*pi\n% input the nominal plant with a gain of 1.\nnumGo=1;\nz=.05;\nGM = 4;\na=0.1;\ndenGo= [1 0 0];\nsysGo=tf(numGo,denGo);\n% input the plant with the resonance\nnumG= [1/(50*pi) 1];\ndenG=[1/(25*pi^2) 1/(50*pi) 1 0 0];\nsysG=tf(numG,denG);\n% Define the design constant\nA = ((a*2*z)/(GM))^.333;\n% PM >50; we have selected alpha = a = 0.1\nTinv= A*wm*sqrt(a);\nT=1/Tinv;\nwc = A*wm\n% K = wc^2;\nK= wc^2;\n% Input the lead compensation\nnumD =K*sqrt(a)*[T 1];\ndenD = [a*T 1];\nsysD=tf(numD,denD);\n% Now design the roll-off filter\nw1=wm*sqrt(A/sqrt(a));\n% Design the roll-off damping\nz1=.3 ;\nnumF=1;\ndenF=[1/w1^2 2*z1/w1 1];\nsysF=tf(numF,denF);\n% now compute the entire compensation\nsysDc=sysD*sysF;\nsysOLo=sysD*sysGo;\nsysOL=sysDc*sysG;\nclf;\n% bode(sysOLo);\n% hold on\nw=logspace(-1,2);\n[mag,ph]=bode(sysOL,w); \nmagdb=20*log10(mag(:,:));\nmagdb1=[magdb; zeros(size(magdb))];\nsubplot(211);\nsemilogx(w,magdb1);\ngrid on;\ntitle('Fig. 10.59 Disk drive control with gain-stabilized resonance and roll-off filter');\nxlabel('\\omega (rad/sec)');\nylabel('Magnitude (db)');\n\nsubplot(212);\nsemilogx(w,[ph(:,:); -180*ones(size(ph(:,:)))]);\ngrid on;\nxlabel('\\omega (rad/sec)');\nylabel('Phase (deg)');\n[Gm,Pm,Wcg,Wcp] = margin(mag,ph,w)", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig10_59.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7120918801899966}} {"text": "function pAzPts=polAzEquidistRefChange(pAzPts,latLonRefOld,latLonRefNew,a,f,algorithm,desAngSpan)\n%%POLAZEQUIDISTREFCHANGE Points given in polar azimuthal equidistant\n% coordinates are defined with respect to a particular reference location\n% on the surface of the reference ellipsoid or sphere. Here, given one\n% set of polar azimuthal equidistant coordinates, obtain the coordinates\n% when the reference points has been changed. This can be useful for\n% expressing rays traced from one sensor in the coordinate system of\n% another sensor.\n%\n%INPUTS: pAzPts A 2XN set of the [ground distance; heading] points, with the\n% 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 pAzPts should be converted.\n% a The semi-major axis of the reference ellipsoid (in meters).\n% If this argument is omitted or an empty matrix is passed,\n% the value in Constants.WGS84SemiMajorAxis is used.\n% f The flattening factor of the reference ellipsoid. If this\n% argument is omitted or an empty matrix is passed, the value\n% in Constants.WGS84Flattening is used.\n% algorithm If f is not zero, then this parameter is not used. If f=0,\n% then this parameter selects the algorithm to use. Possible\n% values are:\n% 0 (The default if omitted or an empty matrix is used) Use a\n% formula specific for the transformation on a sphere.\n% 1 Call the polarAzEquidistProj2Ellipse function and then the\n% ellips2PolarAzEquidistProj function.\n% desAngSpan A 2X1 range of angular values [min Val;max Val] in which it\n% is desired that the converted azimuthal values should\n% attempt to be kept (by adding or subtracing either 0 or 2*pi\n% [but not a multiple thereof] to the converted value to get\n% it as close as possible to the span). If omitted or an empty\n% matrix is passed, no attempt is made to keep the azimuth\n% within any particular bounds.\n%\n%OUTPUTS: pAzPts A 2XN (or 3XN) set of [ground distance;heading;(height)]\n% points in polar azimuthal equidistant coordinates taken\n% with respect to latLonRefNew.\n%\n%If f is 0 and algorithm=0, then the coordinate system change is occurring\n%on a sphere and a direct conversion is used. Otherwise, this function just\n%calls polarAzEquidistProj2Ellipse to convert the points into latitude and\n%longitude coordinates and then uses ellips2PolarAzEquidistProj to convert\n%them into polar azimuthal equidistant coordinates with a different\n%reference point.\n%\n%EXAMPLE 1:\n%This example shows that the relative error of this conversion is on the\n%order of finite precision limitatios when compared to simply using the\n%desired alternate reference point from the start.\n% latLonPt=[deg2rad([20.631756;-155.551818;10]),deg2rad([21.295516;-158.002386;20])];\n% latLonRef1=deg2rad([20.906029;-157.078918]);\n% latLonRef2=deg2rad([35;-125]);\n% pAzPts1=ellips2PolarAzEquidistProj(latLonPt,latLonRef1);\n% pAzPts2=ellips2PolarAzEquidistProj(latLonPt,latLonRef2);\n% pAzPtsConv=polAzEquidistRefChange(pAzPts1,latLonRef1,latLonRef2);\n% RelErr=max(max(abs((pAzPtsConv-pAzPts2)./pAzPts2)))\n%\n%EXAMPLE 2:\n%This example generates a number of random values and then computes the\n%error in the conversion compared to directly converting it. The maximum\n%relative error magnitude is displayed and is reasonable given the\n%scale of the distances across the surface of the Earth and finite\n%precision limits.\n% rE=Constants.WGS84MeanRadius;\n% numMCRuns=10e3;\n% maxDiff=0;\n% for curRun=1:numMCRuns\n% latLonRef1=[UniformD.rand(1,[-pi/2;pi/2]);\n% UniformD.rand(1,[-pi;pi])];\n% latLonRef2=[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% \n% pAzPts1=ellips2PolarAzEquidistProj(latLonPt,latLonRef1,rE,0);\n% pAzPts2=ellips2PolarAzEquidistProj(latLonPt,latLonRef2,rE,0);\n% pAzConv=polAzEquidistRefChange(pAzPts1,latLonRef1,latLonRef2,rE,0);\n% \n% diffVal=(pAzPts2-pAzConv);\n% diffVal(2)=wrapRange(diffVal(2),-pi,pi);\n% diffVal=diffVal./pAzPts2;%Make a relative error.\n% maxDiff=max(maxDiff,norm(diffVal));\n% end\n% maxDiff\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<7)\n desAngSpan=[];\nend\n\nif(nargin<6||isempty(algorithm))\n algorithm=0;\nend\n\nif(nargin<5||isempty(f))\n f=Constants.WGS84Flattening;\nend\n\nif(nargin<4||isempty(a))\n a=Constants.WGS84SemiMajorAxis;\nend\n\nif(algorithm~=0&&algorithm~=1)\n error('Unknown algorithm specified.')\nend\n\nif(f==0&&algorithm==0)\n [azStart,azEnd]=greatCircleAzimuth(latLonRefOld,latLonRefNew);\n azOffset1=pi/2-azStart;\n azOffset2=pi/2-azEnd;\n lambdaDelta=greatCircleDistance(latLonRefOld,latLonRefNew,1);\n \n %Transform into the system with both sensors on the equator.\n pAzPts(2,:)=pAzPts(2,:)+azOffset1;\n \n p=pAzPts(1,:);\n Az=pAzPts(2,:);\n rE=a;\n pAzPts(1:2,:)=[rE.*acos(cos(p./rE).*cos(lambdaDelta)+sin(p./rE).*sin(Az).*sin(lambdaDelta));\n atan2(sin(p./rE).*cos(lambdaDelta).*sin(Az)-cos(p./rE).*sin(lambdaDelta),sin(p./rE).*cos(Az))];\n \n %Convert back to the global coordinate system.\n pAzPts(2,:)=pAzPts(2,:)-azOffset2; \nelse\n convLatLon=polarAzEquidistProj2Ellipse(pAzPts,latLonRefOld,a,f);\n pAzPts=ellips2PolarAzEquidistProj(convLatLon,latLonRefNew,a,f);\nend\n\nif(~isempty(desAngSpan))\n N=size(pAzPts,2);\n \n minVal=desAngSpan(1);\n maxVal=desAngSpan(2);\n\n for k=1:N\n curAz=pAzPts(2,k);\n\n if(minVal>curAz)\n %See if adding 2*pi places it closer to the span.\n azTest=curAz+2*pi;\n offsetOld=minVal-curAz;\n elseif(maxVal min\n% by a semi-smooth Newton method\n%\n% u = minL1Tikhonov(f, gamma, A)\n%\n%\n% Reference:\n% Clason, Jin, Kunisch\n% A semismooth Newton method for L^1 data fitting with automatic choice of regularization parameters and noise calibration\n% SIAM Journal on Scientific Computing, 2010\n%\n\n% written by M. Storath\n% $Date: 2012/10/29 01:19:08 $\t$Revision: 0.1 $\n\n%%-------------------------------------------------------------------------\n% init\nm = numel(f);\nmaxit = [];\ninit = [];\nflag = 0;\nif exist('opts', 'var')\n if isfield(opts, 'mat')\n AAT = opts.mat;\n end\n if isfield(opts, 'maxit')\n maxit = opts.maxit;\n end\n if isfield(opts, 'init')\n init = opts.init;\n end\n if isfield(opts, 'L')\n L = opts.L;\n end\nend\nif ~exist('AAT', 'var')\n AAT = A * A';\nend\nif ~isa(A, 'linop') && ~exist('L', 'var')\n L = spconvmatrix([-1, 2, -1], m);\nend\n\n% diagonal idx \ndiagidx = eye(m) == 1;\n\n% standard parameters (see Clason, Jin, Kunisch 2010)\niMax = 20; %(iMax higher than standard)\nc = 1e9;\nbeta = 1;\nq = 0.2;\n\n% init variables\np = zeros(m,1);\npos = p;\nneg = p;\nalpha = 2 * gamma;\n\n%deactivate warnings temporaily\nwarning off;\n\n%%-------------------------------------------------------------------------\n% main program\nwhile beta > 1e-16\n pOld = p;\n \n % precompute matrices\n if ~isa(A, 'linop')\n M = (1/alpha) * AAT + beta * L;\n diagM = M(diagidx);\n end\n \n % newton step\n for k = 1:iMax\n % compute active sets\n posNew = p > +1;\n negNew = p < -1;\n comb = posNew | negNew;\n \n % solve linear equation\n \n b = f(:) + c * (posNew - negNew);\n if isa(A, 'linop')\n M = @(x) reshape(AAT * (x / alpha), m, 1) + beta * conv(x(:), [-1; 2; -1], 'same') + c * comb .* x;\n [p, flag] = cgs(M, b, [], maxit, [], [], init);\n else\n M(diagidx) = diagM + c * comb;\n p = M \\ b;\n end\n \n % if active sets did not change, break\n if ~(any(posNew - pos) || any(negNew - neg))\n break;\n end\n \n % set new active sets\n pos = posNew;\n neg = negNew;\n end\n \n if (k == iMax) && any(abs(p)>2)\n p = pOld;\n break;\n end\n \n % decrease beta\n beta = beta * q;\nend\n\n% restore primal variable\nu = A' * (p / alpha);\n\n% reactivate warnings\nwarning on;", "meta": {"author": "mstorath", "repo": "Pottslab", "sha": "53571378ef2f60b1104fc8dacc1d8f03427987a9", "save_path": "github-repos/MATLAB/mstorath-Pottslab", "path": "github-repos/MATLAB/mstorath-Pottslab/Pottslab-53571378ef2f60b1104fc8dacc1d8f03427987a9/Tikhonov/minL1Tikhonov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.7119464801166806}} {"text": "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: finds coefficients of cubic spline interpolant\n%\n% INPUTs: (p1,p2): interpolating mediary points\n%\n% Author: Nick Battista\n% Date: February 23, 2018\n% Institution: TCNJ\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction interp_Function_Coeffs(p1,p2)\n\n%\n% Set up MATRIX for linear system of cubic interpolant\n%\nmat1 = [1 0 0 0 0 0 0 0 0 0 0 0];\nmat2 = [0 1 0 0 0 0 0 0 0 0 0 0];\nmat3 = [0 0 1 0 0 0 0 0 0 0 0 0];\nmat4 = [1 p1 p1^2 p1^3 -1 -p1 -p1^2 -p1^3 0 0 0 0];\n\nmat5 = [0 1 2*p1 3*p1^2 0 -1 -2*p1 -3*p1^2 0 0 0 0];\nmat6 = [0 0 2 6*p1 0 0 -2 -6*p1 0 0 0 0];\nmat7 = [0 0 0 0 1 p2 p2^2 p2^3 -1 -p2 -p2^2 -p2^3];\nmat8 = [0 0 0 0 0 1 2*p2 3*p2^2 0 -1 -2*p2 -3*p2^2];\n\nmat9 = [0 0 0 0 0 0 2 6*p2 0 0 -2 -6*p2];\nmat10= [0 0 0 0 0 0 0 0 1 1 1 1];\nmat11= [0 0 0 0 0 0 0 0 0 1 2 3];\nmat12= [0 0 0 0 0 0 0 0 0 0 2 6];\n\nmat = [mat1; mat2; mat3; mat4; mat5; mat6; mat7; mat8; mat9; mat10; mat11; mat12];\n\n%\n% RHS of Linear System for cubic interpolant\n%\nrhs = [0 0 0 0 0 0 0 0 0 1 0 0]';\n\n%\n% Give coefficients\n%\ncoeffs = mat\\rhs\n\n\n%------------------------------------\n% Plot Interpolation Polynomial\n% (and its derivatives)\n%------------------------------------\n\n%Plotting t-Values\nds = 0.005;\nt = 0:ds:1;\nt2=t/2;\n\n%Plot Attributes\nms = 20;\n\n%\n% PLOT: interpolating function, g(t)\nfigure(1)\nfor i=1:length(t)\n plot(t2(i),g(coeffs,t(i),p1,p2),'.','MarkerSize',ms); hold on;\nend\nxlabel('t');\nylabel('g(t)');\nset(gca,'FontSize',18)\n\n%\n% PLOT: interpolating function's derivative, dg(t)/dt\nfigure(2)\nfor i=1:length(t)\n plot(t2(i),gP(coeffs,t(i),p1,p2),'.','MarkerSize',ms); hold on;\nend\nxlabel('t');\nylabel('dg/dt');\nset(gca,'FontSize',18)\n\n%\n% PLOT: interpolating function's 2nd derivative, d^2g(t)/dt^2\nfigure(3)\nfor i=1:length(t)\n plot(t2(i),gPP(coeffs,t(i),p1,p2),'.','MarkerSize',ms); hold on;\nend\nxlabel('t');\nylabel('d^2g/dt^2');\nset(gca,'FontSize',18)\n\n\n\n%\n% Store coefficients for plotting\n%\n% vec = []; \n% for i=1:12\n% vec = [vec coeffs(i)];\n% end\n\n%strName = 'coeffs_Vec';\n%print_Matrix_To_Txt_File(coeffs,strName);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION prints matrix to file\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction print_Matrix_To_Txt_File(a,strName)\n\nnameTxt = [strName '.txt'];\n\nfid = fopen(nameTxt, 'wt'); % Open for writing\nfor i=1:size(a,1)\n fprintf(fid, '%.14f ', a(i,:));\n fprintf(fid, '\\n');\nend\nfclose(fid);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: evaluate interpolating polynomial\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = g(coeffs,x,p1,p2)\n\nif x<=p1\n val = coeffs(1) + coeffs(2)*x + coeffs(3)*x^2 + coeffs(4)*x^3;\nelseif x<=p2\n val = coeffs(5) + coeffs(6)*x + coeffs(7)*x^2 + coeffs(8)*x^3;\nelse\n val = coeffs(9) + coeffs(10)*x + coeffs(11)*x^2 + coeffs(12)*x^3;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: evaluate interpolating polynomial 1st derivative\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = gP(coeffs,x,p1,p2)\n\nif x<=p1\n val = coeffs(2) + 2*coeffs(3)*x + 3*coeffs(4)*x^2;\nelseif x<=p2\n val = coeffs(6) + 2*coeffs(7)*x + 3*coeffs(8)*x^2;\nelse\n val = coeffs(10) + 2*coeffs(11)*x + 3*coeffs(12)*x^2;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% FUNCTION: evaluate interpolating polynomial 2nd derivative\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction val = gPP(coeffs,x,p1,p2)\n\nif x<=p1\n val = 2*coeffs(3) + 6*coeffs(4)*x;\nelseif x<=p2\n val = 2*coeffs(7) + 6*coeffs(8)*x;\nelse\n val = 2*coeffs(11) + 6*coeffs(12)*x;\nend\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/Examples/Example_Concentration_Dynamics/Moving_Cylinders_64/interp_Function_Coeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.7119464755875454}} {"text": "function R = xyz2R(xyz)\n%DESCRIPTION: given a point on earth retrun the rotation matrix with:\n% - fist lien directed to loacal east\n% - second line directed as north\n% - third line directed as local up\n[phi, lam] = cart2geod(xyz(1), xyz(2), xyz(3));\n\n %rotation matrix from global to local reference system\n R = [-sin(lam) cos(lam) 0;\n -sin(phi)*cos(lam) -sin(phi)*sin(lam) cos(phi);\n +cos(phi)*cos(lam) +cos(phi)*sin(lam) sin(phi)];\nend\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/xyz2R.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9504109770159682, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.7119407100865369}} {"text": "function [ax,ci,cen,ub,lb,S,e,lam,Fm,Fc,F,pval, msb] = conf_region(X,varargin)\n% :Usage:\n% ::\n%\n% [ax,ci,cen,ub,lb,S,e,lam,Fm,Fc,F,pval, msb] = conf_region(X,[doplot])\n%\n% alternative conf region multivariate based on Johnson & Wichern, 4th ed., p. 236\n% 2D (3D)\n%\n% :Outputs:\n%\n% **ax:**\n% axes of confidence region, scaled to be half-length of confidence hyperellipsoid\n%\n% **ci:**\n% length of axes of conf region (diagonal matrix), axes in reverse order of importance\n% as in ouput of eig\n%\n% **cen:**\n% center of region (means of variables)\n%\n% **ub:**\n% upper boundary coordinates for region, rows are dims (vars), cols index coordinates\n% last coordinate is on axis of greatest variation (\"reverse order\"), from output of eig\n%\n% **lb:**\n% lower boundary coordinates\n% to plot, try: plot(ub(1,:),ub(2,:),'bo'); hold on; plot(lb(1,:),lb(2,:),'ro')\n%\n% **S:**\n% covariance matrix\n%\n% **e:**\n% eigenvectors\n%\n% **lam:**\n% eigenvalues\n%\n% **Fm:**\n% degrees of freedom multiplier, p(n-1) / n(n-p)\n%\n% **Fc:**\n% critical F value based on alpha level\n%\n% **F:**\n% F value for test - probably not quite right\n%\n% **pval:**\n% p value for test - probably not quite right\n%\n% :To plot:\n% Either enter 1 or color as a 2nd argument, or do it yourself:\n% ::\n%\n% [ax,ci,cen,ub,lb,S,e,lam] = conf_region(X);\n% b = pinv([X(:,1) ones(size(X,1),1)] ) * X(:,2);\n% theta = atan(b(1)) - pi/2;\n% [h,h2] = plot_ellipse(cen(1),cen(2),theta,ci(1,1),ci(2,2));\n%\n% There is also an example for rendering individual subject conf regions\n%\n% :Examples:\n% ::\n%\n% N = 250;\n% X = mvnrnd([1 2], [1 .6; .6 1], N);\n% [ax,ci,cen,ub,lb,S,e,lam] = conf_region(X);\n% b = pinv([X(:,1) ones(size(X,1),1)] ) * X(:,2);\n% theta = atan(b(1)) - pi/2;\n% %create_figure('test');\n% [h,h2] = plot_ellipse(cen(1),cen(2),theta,ci(1,1),ci(2,2));\n%\n% % plot standard deviation - for boostrapping, or for individual cases\n% [h,h2] = plot_ellipse(cen(1),cen(2),theta,ci(1,1)*sqrt(N),ci(2,2)*sqrt(N));\n%\n% :Example: Render individual subject conf regions\n% ::\n%\n% X = x(wh, [3 1]);\n% dfe = size(X, 1) - size(X, 2); % df\n% alph = .1; % .1 for 90%, .05 for 95%\n% tcrit = tinv(1 - alph, dfe); \n% ci = ((lam) .^ .5) .* tcrit;\n% b = pinv([X(:,1) ones(size(X,1),1)] ) * X(:,2);\n% theta = atan(b(1)) - pi/2;\n% [h,h2] = plot_ellipse(cen(1),cen(2),theta,ci(1,1),ci(2,2));\n%\n% set(h, 'Color', 'k', 'LineWidth', 1);\n% set(h2, 'FaceColor', [.5 1 0]);\n\n\n\ndoplot = 0;\nif length(varargin) > 0, doplot = varargin{1}; end\n\n% -----------------------------------------------------\n% * determine multivariate standard deviation matrix S\n% -----------------------------------------------------\n\n% center\nXs = X - repmat(mean(X),size(X,1),1);\n\n% covariance matrix S\nS = (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\nd = Xs * inv(S) * Xs';\nd = diag(d); % what do the off-diagonals signify?\n\n% -----------------------------------------------------\n% * get critical F and coefficient of mult. for axes\n% -----------------------------------------------------\np = size(X,2); \nn = size(X,1);\nFm = (p * (n - 1)) ./ (n * (n - p));\na = .95; % alpha\nFc = finv(a,p,n - p); % critical F\ncoef = sqrt(Fm .* Fc);\n\n[e,lam] = eig(S);\n\n% -----------------------------------------------------\n% * get F and p-values \n% ratio of squared distances (mahal?) between to within\n% -----------------------------------------------------\nmsb = pdist([mean(X); zeros(1,size(X,2))]); % .^ 2;\nmsw = sum(d) ./ (n-p);\nF = msb / msw;\npval = 1 - fcdf(F,p,n-p); % - this is wrong I think. do nonparam.\n\n% nonparametric\nniter = 1000;dnull = [];\nsignv = sign(randn(size(X,1),niter));\nfor i = 1:niter\n xtmp = X .* repmat(signv(:,i),1,size(X,2));\n dnull(i) = pdist([mean(xtmp); zeros(1,size(X,2))]);\nend\npval = sum(msb <= dnull) ./ length(dnull);\n\n\n% -----------------------------------------------------\n% * confidence interval, in units - mult by axes.\n% -----------------------------------------------------\nci = ((lam) .^ .5 .* coef);\nax = e * ci;\n\ncen = mean(X)';\nlb = repmat(cen,1,size(e,2)) - (e * ci);\nub = repmat(cen,1,size(e,2)) + (e * ci);\n\n\nif doplot\n % 2-d plot\n\n % degrees or slope to angle in radians\n %ang = corrcoef(X); ang = ang(1,2);\n %theta = acos(ang-(pi/2));\n %pi * ang / 180\n\n b = pinv([X(:,1) ones(size(X,1),1)] ) * X(:,2);\n theta = atan(b(1)) - pi/2;\n [h,h2] = plot_ellipse(cen(1),cen(2),theta,ci(1,1),ci(2,2));\n set(h,'Color',[1 1 1],'LineWidth',.5);\n \n if length(doplot) == 3 , set(h2,'FaceColor',doplot); end\n if ischar(doplot), set(h2,'FaceColor',doplot(1)); end\n \n drawnow\nend\n\n\nreturn\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Visualization_functions/conf_region.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533032291501, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7119129623061078}} {"text": "function [s,c,r,t]=v_atan2sc(y,x)\n%V_ATAN2SC sin and cosine of atan(y/x) [S,C,R,T]=(Y,X)\n%\n% Outputs:\n% s sin(t) where tan(t) = y/x\n% c cos(t) where tan(t) = y/x\n% r sqrt(x^2 + y^2)\n% t arctan of y/x\n%\n% Note y and x can be arrays but must be the same size. The outputs will\n% all be the same size as y.\n\n% Copyright (C) Mike Brookes 2007\n% Version: $Id: v_atan2sc.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\nsz=size(y);\ns=zeros(sz);\nc=NaN(sz);\nr=zeros(sz);\nt=NaN(sz);\nm=y==0;\nif any(m(:)) % handle case when y=0 and possibly x=0 also\n t(m)=(x(m)<0);\n c(m)=1-2*t(m);\n r(m)=abs(x(m));\n t(m)=t(m)*pi;\nend\nm=abs(y)>abs(x) & isnan(c);\nif any(m(:))\n q = x(m)./y(m);\n u = sqrt(1+q.^2).*sign(y(m)); % avoids underflow even if x and y are very small\n s(m) = 1./u;\n c(m) = s(m).*q;\n r(m) = y(m).*u;\nend\nm=isnan(c);\nif any(m(:))\n q = y(m)./x(m);\n u = sqrt(1+q.^2).*sign(x(m));\n c(m) = 1./u;\n s(m) = c(m).*q;\n r(m) = x(m).*u;\nend\nm=isnan(t);\nif nargout>3 && any(m(:))\n t(m)=atan2(s(m),c(m));\nend", "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_atan2sc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8128673178375734, "lm_q1q2_score": 0.7118986228979036}} {"text": "function [ add, mul, sub ] = setfld2 ( dummy )\n\n%*****************************************************************************80\n%\n%% SETFLD2 sets up arithmetic tables for the finite field of order 2.\n%\n% Discussion:\n%\n% SETFLD2 sets up addition, multiplication, and subtraction tables\n% for the finite field of order 2.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 March 2003\n%\n% Author:\n%\n% Original FORTRAN77 version by Paul Bratley, Bennett Fox, Harald Niederreiter.\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, integer DUMMY, a dummy argument.\n%\n% Output, integer ADD(2,2), MUL(2,2), SUB(2,2), the addition, \n% multiplication, and subtraction tables, mod 2.\n%\n q = 2;\n\n p = 2;\n\n for i = 0 : 1\n for j = 0 : 1\n add(i+1,j+1) = mod ( i + j, p );\n end\n end\n\n for i = 0 : 1\n for j = 0 : 1\n mul(i+1,j+1) = mod ( i * j, p );\n end\n end\n\n for i = 0 : 1\n for j = 0 : 1\n sub(add(i+1,j+1)+1, i+1) = j;\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/niederreiter2/setfld2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7118986156421142}} {"text": "function [ y, m, d, f ] = jed_to_ymdf_julian2 ( jed )\n\n%*****************************************************************************80\n%\n%% JED_TO_YMDF_JULIAN2 converts a JED to a Julian YMDF date.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 10 March 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real JED, the Julian Ephemeris Date.\n%\n% Output, integer Y, M, D, real F, the YMDF date.\n%\n\n%\n% Check the input.\n%\n ierror = jed_check ( jed );\n\n if ( ierror ~= 0 )\n y = -1;\n m = -1;\n d = -1;\n f = -1.0;\n return\n end\n\n j = floor ( jed + 0.5 );\n f = ( jed + 0.5 ) - j;\n\n jd = floor ( ( j + 1524 - 122.1 ) / 365.25 );\n je = floor ( 365.25 * jd );\n jg = floor ( ( j + 1524 - je ) / 30.6001 );\n%\n% Now compute D, M and Y.\n%\n d = j + 1524 - je - floor ( 30.6001 * jg );\n\n if ( jg <= 13 )\n m = jg - 1;\n else\n m = jg - 13;\n end\n\n if ( 2 < m )\n y = jd - 4716;\n else\n y = jd - 4715;\n end\n%\n% Any year before 1 AD must be moved one year further back, since\n% this calendar does not include a year 0.\n%\n y = y_astronomical_to_common ( y );\n\n return\nend\n", "meta": {"author": "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/jed_to_ymdf_julian2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639067, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.7118986136569891}} {"text": "function [tcorr,rho,X_ECEF] = get_rho(tR_RAW,pseudorange,Eph,X_receiver)\n%GET_RHO Calculation of distance in ECEF system between\n%\t satellite and receiver at time tR_RAW given the\n%\t ephemeris Eph.\n\n%Kai Borre 04-01-96\n%Copyright (c) by Kai Borre\n%$Revision: 1.0 $ $Date: 1997/09/23 $\n\n% Initial assigment of constants\nvlight = 299792458;\t % vacuum speed of light in m/s\nOmegae = 7.292115147e-5;\t % rotation rate of the earth in rad/s\n\n%signal sended time=signal received time-signal transmission time\ntx_RAW = tR_RAW-pseudorange/vlight;\n\n%time correction acording to system time\ntoc = Eph(21);\n dt = check_t(tx_RAW-toc);\n tcorr = (Eph(2)*dt + Eph(20))*dt + Eph(19);\n tx_GPS = tx_RAW-tcorr;\n dt = check_t(tx_GPS-toc);\n tcorr = (Eph(2)*dt + Eph(20))*dt + Eph(19);\n tx_GPS = tx_RAW-tcorr; \n\n% satellite position \nX = satpos(tx_GPS, Eph);\n\n%geometric range\nrho = norm(X-X_receiver(1:3));\n\n%satellite coordinates into inertial coordinate system\nomegatau = Omegae*rho/vlight;\nR3 = [ cos(omegatau) sin(omegatau) 0;\n -sin(omegatau) cos(omegatau) 0;\n 0\t 0\t 1];\nX_ECEF = R3*X;\n\n%geometric range acording to inertial coordinate system\nrho = norm(X_ECEF-X_receiver(1:3));\n%%%%%%%%% end get_rho.m %%%%%%%%%\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/example/gps_spp_test/easysuite/get_rho.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966702001757, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.7118526087917252}} {"text": "function [ val ] = check_dominance(vec1, vec2)\n% This procedure checks the dominance of two vectors,\n% where the vectors are in the form [obj,cv]\n% The non-domnination check will work like this --\n% 1 if vec1 dominates vec2\n% -1 if vec2 dominates vec1\n% 0 if both vec1 and vec2 are non-dominated\n%\n% Please note: Vectorization on this function may not be too\n% efficient as it operates on only two vectors, and couple of\n% variables.\n\n% split the obj and cv values \nobj1 = vec1(1:end-1);\ncv1 = vec1(end);\nobj2 = vec2(1:end-1);\ncv2 = vec2(end);\n\nif(cv1 < 0 && cv2 < 0)\n if(cv1 > cv2)\n val = 1 ;\n return ;\n elseif(cv1 < cv2)\n val = -1 ;\n return ;\n else\n val = 0;\n return ;\n end\nelse\n if(cv1 < 0 && cv2 == 0)\n val = -1 ;\n return ;\n elseif(cv1 == 0 && cv2 < 0)\n val = 1 ;\n return ;\n else\n if(any(obj1 < obj2) && ~(any(obj1 > obj2)))\n val = 1 ;\n elseif(~(any(obj1 < obj2)) && any(obj1 > obj2)) \n val = -1 ;\n else\n val = 0 ;\n return ;\n end\n end\nend\n% end of check_dominance\nend\n", "meta": {"author": "chudur-budur", "repo": "nsga2-matlab", "sha": "58c2ca3729c1c871dcd3bda310693f19cf181a9e", "save_path": "github-repos/MATLAB/chudur-budur-nsga2-matlab", "path": "github-repos/MATLAB/chudur-budur-nsga2-matlab/nsga2-matlab-58c2ca3729c1c871dcd3bda310693f19cf181a9e/check_dominance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7118317896099751}} {"text": "function f=involute(f,dim);\n%INVOLUTE Involution \n% Usage: finv=involute(f);\n% finv=involute(f,dim);\n%\n% `involute(f)` will return the involution of *f*.\n%\n% `involute(f,dim)` will return the involution of *f* along dimension *dim*.\n% This can for instance be used to calculate the 2D involution::\n%\n% f=involute(f,1);\n% f=involute(f,2);\n%\n% The involution *finv* of *f* is given by::\n%\n% finv(l+1)=conj(f(mod(-l,L)+1));\n%\n% for $l=0,\\ldots,L-1$.\n%\n% The relation between conjugation, Fourier transformation and involution\n% is expressed by::\n%\n% conj(dft(f)) == dft(involute(f))\n%\n% for all signals *f*. The inverse discrete Fourier transform can be\n% expressed by::\n%\n% idft(f) == conj(involute(dft(f)));\n%\n% See also: dft, pconv\n\n% Assert correct input.\n\n% AUTHOR : Peter L. Søndergaard\n% TESTING: TEST_INVOLUTE\n% REFERENCE: OK\n\ncomplainif_argnonotinrange(nargin,1,2,mfilename);\n\nif nargin==1\n dim=[];\nend;\n\nL=[];\n[f,L,Ls,W,dim,permutedsize,order]=assert_sigreshape_pre(f,L,dim,'INVOLUTE');\n\n% This is where the calculation is performed.\n% The reshape(...,size(f) ensures that f will keep its\n% original shape if it is multidimensional.\nf=reshape(conj([f(1,:); ...\n\t flipud(f(2:L,:))]),size(f));\n\nf=assert_sigreshape_post(f,dim,permutedsize,order);\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/fourier/involute.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7118317802749003}} {"text": "function indx = whichInterval(dom, x, direction)\n%WHICHINTERVAL Determine which interval a point lies in.\n% INDX = WHICHINTERVAL(DOM, X) returns a matrix of size(X) whos j,k entry is a\n% positive integer denoting which subinterval of the domain DOM (which should\n% be a sorted real-valued vector) the real part of the point X(j,k) is\n% positioned. INDX(j,k) = -/+INF if X(j,k) < DOM(1) or X(j,k) > DOM(end),\n% respectively.\n% \n% WHICHINTERVAL(DOM, X, DIRECTION) determines which interval those points in X\n% which lie on the breakpoints of DOM should be counted in. DIRECTION = -1\n% (the default) places such points in the interval to the left, whilst\n% DIRECTION = 1 places them to the right.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nnumInts = numel(dom) - 1;\nxReal = real(x);\nindx = NaN(size(x));\n\n% Points to the left of the domain:\nindx(xReal < dom(1)) = -inf;\n\n% Deal with the points that lie on breakpoints:\nif ( nargin > 2 && direction > 0 )\n mygt = @(x, y) x >= y;\n mylt = @(x, y) x < y;\nelse\n mygt = @(x, y) x > y;\n mylt = @(x, y) x <= y;\nend\n\nindx(xReal == dom(1)) = 1;\n% Points within the domain:\nfor j = 1:numInts\n indx( mygt(xReal, dom(j)) & mylt(xReal, dom(j+1)) ) = j;\nend\nindx(xReal == dom(end)) = numInts;\n\n% Points to the right of the domain:\nindx(xReal > dom(end)) = inf;\n\nend\n", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@chebfun/whichInterval.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.8519528038477825, "lm_q1q2_score": 0.7117925559635327}} {"text": "function inside = quad_contains_point_2d ( q, p )\n\n%*****************************************************************************80\n%\n%% QUAD_CONTAINS_POINT_2D finds if a point is inside a convex quadrilateral in 2D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real Q(2,4), the vertices of the quadrilateral.\n%\n% Input, real P(2,1), the point to be checked.\n%\n% Output, logical INSIDE, is TRUE if the point is in the quadrilateral.\n%\n\n%\n% This will only handle convex quadrilaterals.\n%\n inside = 0;\n\n angle_1 = angle_rad_2d ( q(1:2,1), q(1:2,2), q(1:2,3) );\n angle_2 = angle_rad_2d ( q(1:2,1), q(1:2,2), p(1:2,1) );\n\n if ( angle_1 < angle_2 )\n return\n end\n\n angle_1 = angle_rad_2d ( q(1:2,2), q(1:2,3), q(1:2,4) );\n angle_2 = angle_rad_2d ( q(1:2,2), q(1:2,3), p(1:2,1) );\n\n if ( angle_1 < angle_2 )\n return\n end\n\n angle_1 = angle_rad_2d ( q(1:2,3), q(1:2,4), q(1:2,1) );\n angle_2 = angle_rad_2d ( q(1:2,3), q(1:2,4), p(1:2,1) );\n\n if ( angle_1 < angle_2 )\n return\n end\n\n angle_1 = angle_rad_2d ( q(1:2,4), q(1:2,1), q(1:2,2) );\n angle_2 = angle_rad_2d ( q(1:2,4), q(1:2,1), p(1:2,1) );\n\n if ( angle_1 < angle_2 )\n return\n end\n\n inside = 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/geometry/quad_contains_point_2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8354835411997896, "lm_q1q2_score": 0.7117925376424956}} {"text": "function [ n_data, a, b, fx ] = binomial_values ( n_data )\n\n%*****************************************************************************80\n%\n%% BINOMIAL_VALUES returns some values of the binomial coefficients.\n%\n% Discussion:\n%\n% The formula for the binomial coefficient is\n%\n% C(N,K) = N! / ( K! * (N-K)! )\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Binomial[n,k]\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% 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 A, B, the arguments of the function.\n%\n% Output, integer FX, the value of the function.\n%\n n_max = 20;\n\n a_vec = [ ...\n 1, 6, 6, 6, 15, ...\n 15, 15, 15, 15, 15, ...\n 15, 25, 25, 25, 25, ...\n 25, 25, 25, 25, 25 ];\n\n b_vec = [ ...\n 0, 1, 3, 5, 1, ...\n 3, 5, 7, 9, 11, ...\n 13, 1, 3, 5, 7, ...\n 9, 11, 13, 15, 17 ];\n\n fx_vec = [ ...\n 1, ...\n 6, ...\n 20, ...\n 6, ...\n 15, ...\n 455, ...\n 3003, ...\n 6435, ...\n 5005, ...\n 1365, ...\n 105, ...\n 25, ...\n 2300, ...\n 53130, ...\n 480700, ...\n 2042975, ...\n 4457400, ...\n 5200300, ...\n 3268760, ...\n 1081575 ];\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;\n b = 0;\n fx = 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/test_values/binomial_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7117925341525965}} {"text": "function fx = annulus ( n, x )\n\n%*****************************************************************************80\n%\n%% ANNULUS evaluates the annulus function.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 December 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of points.\n%\n% Input, real X(N,2), the point coordinates.\n%\n% Output, real FX(N), the function values.\n%\n fx = zeros ( n, 1 );\n\n c1 = 0.25 * ones ( n, 2 );\n r1 = 0.5 * ones ( n, 1 );\n\n c2 = 0.0 * ones ( n, 2 );\n r2 = 1.0 * ones ( n, 1 );\n\n a = ( sqrt ( sum ( ( x - c1 ) .* ( x - c1 ), 2 ) ) ) - r1;\n b = r2 - ( sqrt ( sum ( ( x - c2 ) .* ( x - c2 ), 2 ) ) );\n\n fx = a .* b;\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/shoreline/annulus.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.711778099889992}} {"text": "function [x, counter] = conjugate_gradient(K, P, tol)\n % 共轭梯度法对方程进行求解\n\n % 默认精度\n if nargin == 2\n tol = 1e-5;\n end\n\n [m, n] = size(K);\n [p, q] = size(P);\n\n % 初始化\n x = sparse(zeros(m,1));\n\n % 根据P初始化 r0 and d\n r0 = P;\n d = P;\n % 计数器\n counter = 0; \n\n % 如果成立,直接返回\n if sqrt(r0'*r0) < tol;\n return;\n end\n \n v = K * d;\n % 计算步长\n w = r0' * r0 / (d' * v);\n % 更新 x\n x = x + w * d;\n % 计算剩余的\n r1 = r0 - w * v;\n counter = counter + 1;\n\n while sqrt(r1'*r1) > tol\n P = r1' * r1 / (r0' * r0);\n % 更新搜索方向\n d = r1 + P * d;\n r0 = r1;\n v = K * d;\n % 计算步长\n w = r0' * r0 / (d' * v);\n x = x + w * d;\n r1 = r0 - w * v;\n counter = counter + 1;\n end\n", "meta": {"author": "Meelfy", "repo": "FEM", "sha": "0de70230af2aad240d9a5c74463a6b4a23cac53d", "save_path": "github-repos/MATLAB/Meelfy-FEM", "path": "github-repos/MATLAB/Meelfy-FEM/FEM-0de70230af2aad240d9a5c74463a6b4a23cac53d/src/utils/conjugateGradient.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7117432405070033}} {"text": "function [xMid,fMid,exitCode]=bisectionRootFind(f,xSpan,AbsTol,maxIter)\n%%BISECTIONROOTFIND Given two points that are of different signs\n% surrounding the root of a scalar funding, find the root of the\n% function via a bisection search.\n%\n%INPUTS: f The handle to the function whose root is desired. The function\n% is called as f(x), where x is a scalar value.\n% xSpan A 2X1 or 1X2 vector such that\n% sign(f(xSpan(1)))~=sign(f(xSpan(2)))\n% AbsTol The absolute tolerance on the value of f for converence. The\n% default if omitted or an empty matrix is passed is eps().\n% maxIter The maximum number of bisections to perform. The default if\n% omitted or an empty matrix is passed is 100.\n%\n%OUTPUTS: xMid The point found that is the value of the approximate zero.\n% fMid The value of the function at xMid.\n% exitCode A value indicating how the function terminated. Possible\n% values are:\n% 0 Either AbsTol was satisfied or the bounds on the value\n% xMid went below finite precision constraints.\n% 1 The maximum number of iterations occurred.\n%\n%The bisection algorithm is straightforward: Assuming that only a single\n%root is surrounded by xSpan, one evaluates the point at the middle of the\n%interval. One then discards the point in xSpan having the same sign as the\n%point in the middle of the interval. That gives a new interval and the\n%process continues until convergence. The method is discussed in [1].\n%\n%EXAMPLE:\n% f=@(x)(x.^2-4);\n% xSpan=[0;5];\n% [xMid,fMid,exitCode]=bisectionRootFind(f,xSpan)\n%In this example convergence is to the exact root, xMid=2.\n%\n%REFERENCES:\n%[1] Weisstein, Eric W. \"Bisection.\" From MathWorld--A Wolfram Web\n% Resource. http://mathworld.wolfram.com/Bisection.html\n%\n%July 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n \nif(nargin<4||isempty(maxIter))\n maxIter=100;\nend\n\nif(nargin<3||isempty(AbsTol))\n AbsTol=eps(); \nend\n \nxLeft=xSpan(1);\nxRight=xSpan(2);\n \nfLeft=f(xLeft);\nfRight=f(xRight);\n\nif(sign(fLeft)==sign(fRight))\n error('bisectionRootFind:NoChange','There is no sign change in the initial set. ');\nend\n\nxMid=xRight;\nfMid=fRight;\n \nexitCode=1;\nfor curIter=1:maxIter\n xMid=(xLeft+xRight)/2;\n fMid=f(xMid);\n\n if(abs(fMid).\n%\n% Reference: \n%\tR. Gonzalez, J. Giribet, and H. Patiño. NaveGo: a \n% simulation framework for low-cost integrated navigation systems, \n% Journal of Control Engineering and Applied Informatics}, vol. 17, \n% issue 2, pp. 110-120, 2015. Inverse process of Eq. 15.\n%\n% Version: 003\n% Date: 2019/01/16\n% Author: Rodrigo Gonzalez \n% URL: https://github.com/rodralez/navego \n\nlat = llh_org(1);\nlon = llh_org(2);\n\necef_org = llh2ecef(llh_org)';\n\nslat = sin(lat);\nclat = cos(lat);\nslon = sin(lon);\nclon = cos(lon);\n\nR = [ -slat*clon -slat*slon clat; ...\n -slon clon 0; ... \n -clat*clon -clat*slon -slat];\n\n[MAX, N] = size(ecef);\nned = zeros(MAX, N);\n\nfor i=1:MAX\n \n ned_t = R * (ecef(i, :)' - ecef_org) ;\n ned (i, :) = ned_t';\nend\n", "meta": {"author": "rodralez", "repo": "NaveGo", "sha": "3de9a74ab1597be13255d4649892e68aeff9a8b7", "save_path": "github-repos/MATLAB/rodralez-NaveGo", "path": "github-repos/MATLAB/rodralez-NaveGo/NaveGo-3de9a74ab1597be13255d4649892e68aeff9a8b7/conversions/ecef2ned.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7117336822542298}} {"text": "function [km3] = gal2km3(gal)\n% Convert volume from US liquid gallons to cubic kilometers. \n% Chad Greene 2012\nkm3 = gal*3.785411784e-12;", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35258-unit-converters/unit_converters/gal2km3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.711733677558099}} {"text": "function varargout = entropy(varargin)\n%ENTROPY\n%\n% y = ENTROPY(x)\n%\n% Computes/declares concave entropy -sum(x.*log(x))\n%\n% Implemented as evalutation based nonlinear operator. Hence, the concavity\n% of this function is exploited to perform convexity analysis and rigorous\n% modelling.\n%\n% See also CROSSENTROPY, KULLBACKLEIBLER.\n\nswitch class(varargin{1})\n\n case 'double'\n x = varargin{1};\n % Safe version with defined negative values (helps fmincon when\n % outside feasible region)\n if any(x<=0)\n z = abs(x);z(z==0)=1;\n y = z.*log(z);\n y(x==0) = 0;\n y(x<0) = 3*(x(x<0)-1).^2-3;\n varargout{1} = -sum(y);\n else\n varargout{1} = -sum(x.*log(x));\n end\n\n case {'sdpvar','ndsdpvar'}\n \n varargin{1} = reshape(varargin{1},[],1);\n varargout{1} = yalmip('define',mfilename,varargin{1}); \n\n case 'char'\n\n X = varargin{3};\n F = (X >= 0);\n\n operator = struct('convexity','concave','monotonicity','none','definiteness','none','model','callback');\n operator.range = [-inf exp(-1)*length(X)];\n operator.domain = [0 inf];\n operator.bounds = @bounds;\n operator.convexhull = @convexhull;\n operator.derivative = @derivative;\n varargout{1} = F;\n varargout{2} = operator;\n varargout{3} = X;\n\n otherwise\n error('SDPVAR/ENTROPY called with CHAR argument?');\nend\n\nfunction df = derivative(x)\nx(x<=0)=eps;\ndf = (-1-log(x));\n\nfunction [L, U] = bounds(xL,xU)\n\nt = find(xL==0);\nu = find(xL<0);\nxL(t)=1;\nLU = [-xL.*log(xL) -xU.*log(xU)];\nLU(t,1)=0;\nxL(t) = 0;\nL = min(LU,[],2);\nU = max(LU,[],2);\nU((xL < exp(-1)) & (xU > exp(-1))) = exp(-1);\nL = sum(L);\nU = sum(U);\n\n\nfunction [Ax, Ay, b] = convexhull(xL,xU)\n\nif length(xL)==1\n xM = (xU+xL)/2;\n f1 = entropy(xL);\n f2 = entropy(xM);\n f3 = entropy(xU); \n df1 = derivative(xL);\n df2 = derivative(xM);\n df3 = derivative(xU);\n [Ax,Ay,b] = convexhullConcave(xL,xM,xU,f1,f2,f3,df1,df2,df3);\n\nelseif length(xL)==2\n x1 = [xL(1);xL(2)];\n x2 = [xU(1);xL(2)];\n x3 = [xL(1);xU(2)];\n x4 = [xU(1);xU(2)];\n x5 = (xL+xU)/2;\n \n f1 = entropy(x1);\n f2 = entropy(x2);\n f3 = entropy(x3);\n f4 = entropy(x4);\n f5 = entropy(x5);\n \n df1 = derivative(x1);\n df2 = derivative(x2);\n df3 = derivative(x3);\n df4 = derivative(x4);\n df5 = derivative(x5);\n \n [Ax,Ay,b] = convexhullConcave2D(x1,f1,df1,x2,f2,df2,x3,f3,df3,x4,f4,df4,x5,f5,df5);\nelse\n Ax = [];\n Ay = [];\n b = [];\nend", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/YALMIP/operators/entropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7116937392024693}} {"text": "function [a,t]=rotqr2ax(q)\n%ROTQR2AX converts a real quaternion to the corresponding rotation axis and angle\n% Inputs: \n%\n% Q(4,1) real-valued quaternion (with magnitude = 1)\n%\n% Outputs:\n%\n% A(3,1) Unit vector in the direction of the rotation axis.\n% T Rotation angle in radians (in range 0 to 2pi)\n%\n% In the quaternion representation of a rotation, and q(1) = cos(t/2) \n% where t is the angle of rotation in the range 0 to 2pi\n% and q(2:4)/sin(t/2) is a unit vector lying along the axis of rotation\n% a positive rotation about [0 0 1] takes the X axis towards the Y axis.\n% \n% Copyright (C) Mike Brookes 2007\n% Version: $Id: rotqr2ax.m,v 1.2 2007/11/21 12:42:36 dmb Exp $\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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\na=q(2:4);\nm=sqrt(a'*a);\nt=2*atan2(m,q(1)); % avoids problems if unnormalized\nif m>0\n a=a/m;\nelse\n a=[0 0 1]';\nend\n ", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/rotqr2ax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.711693734536091}} {"text": "function epitrochoid(r1,r2,len)\n%animation of EPITROCHOID\n%epitrochoid(r1,r2,len);\n%r1=radius of fixed circle on which smaller circle rolls\n%r2=radius of rolling circle \n%len=line connected to centre of rolling circle\n%example: epitrochoid(1,0.25,0.5);\n% epitrochoid(1,0.25,1);\n%this code also trace epicycloid\n%when r2=len then it becomes epicycloid\n%example for epicycloid: epitrochoid(1,0.25,0.25); \n%always keep r1>r2\nif nargin==0\n r1=1; %radius of fixed circle on which smaller circle rolls\n r2=0.25; %radius of rolling circle \n len=0.5; %line connected to centre of rolling circle \nend\nn=0; \ndtheta=pi/20; %increase in angle per iteration \nroughx=[]; %variable to trace trochoid \nroughy=[]; %variable to trace trochoid \nupto=2*pi*r1/r2+dtheta; %rotate upto\nt=linspace(0,2*pi,75);\n\n[x,y]=pol2cart(t,r2);\nh1=patch(x,y,'r');%draw rolling circle\n\n\n[phil,rl]=cart2pol([-len 0],[0 0]);\nh2=line(0,0);%draw line connected to centre of rolling circle\n\n[x_fix,y_fix]=pol2cart(t,r1);\nline(x_fix,y_fix);%draw fixed circle,only once because it is fixed\n\naxis equal\naxis(r1*[-2 2 -2 2]) %fix axis\n\nwhile n>robot=load_robot('example','3RRR');\n% >>T=directkinematics_3RRR_numerical(robot, [pi/2 pi/4 -pi/2])\n%\n% Author: Arturo Gil. Universidad Miguel Hernandez de Elche. \n% email: arturo.gil@umh.es date: 20/01/2014\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\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 .\n\nfunction T=direct_kinematics_3RRR_numerical(robot, theta, randomize, threshold, max_iter)\n\nglobal xQ yQ xR yR b1 b2 b3 a1 a2 a3 h\nclose all\nL=3; % basic mechanism length\n%position of the fixed points xQ, yQ, xR, yR\nxQ=L; yQ=0; xR=L/2; yR=L;\n\n% Geometry\nb1=1; b2=1; b3=1; a1=1; a2=1;a3=1; % m\n%end effector is a triangle of side h\nh=0.5; %m\n\n%check convergence parameters\nif ~exist('threshold','var')\n threshold=0.01;\nend\n\nif ~exist('max_iter','var')\n max_iter=50;\nend\n\n%randomize solutions\nif ~exist('randomize','var')\n randomize=0;\nend\n\n\n%input parameters for the direct kinematics\nth1=theta(1);%1.9948;\nth2=theta(2);%3.2869;\nth3=theta(3);%-1.3998;\n\ntheta = [th1 th2 th3];\n\n%initial beta, different solutions may be found, depending on the \n%starting values for the parameters beta\n% beta = [xA yA Phi phi1 phi2 phi3]\nbeta=[0.0 0.0 -pi/4 0 0 0]';\n\n%randomize solution\nif randomize\n beta = beta + randn(1,6)';\nend\n\n%the vector y is the vector of values that the Gamma equations should have\n%in this case, they should be all null\n% Gamma=[Gamma1, Gamma2, Gamma3..., Gamma6];\ny=[0 0 0 0 0 0]';\n\nfs=[];\n\nfor i=1:max_iter, \n f=compute_gamma_values(beta,theta);\n J=compute_jacobian_beta(beta,theta);\n \n delta=inv(J'*J)*J'*(y-f);\n \n %update beta\n beta = beta + delta; \n \n sumofsqes=(y-f)'*(y-f);\n fs=[fs sumofsqes];\n \n if sumofsqes < threshold \n fprintf('\\ndirect_kinematics_3RRR::Solution found in %d iterations',i);\n fprintf('\\nPlease note that only ONE possible solution is returned');\n break;\n end\nend\n\n%check whether the algorithm converged in less than max_iter steps\nif i==max_iter\n fprintf('ERROR:: direct_kinematics_3RRR::Could not converge in %d iterations',i);\nend\n\nfprintf('FINAL VALUE of Gamma function');\nf\n\nfprintf('FINAL VALUE of sumof squares');\nsumofsqes\n\n%build solution from the beta parameters.\nT=eye(4);\nT(1,4)=beta(1);\nT(2,4)=beta(2);\nT(1,1)=cos(beta(3));\nT(2,1)=sin(beta(3));\nT(1,2)=-sin(beta(3));\nT(2,2)=cos(beta(3));\n\n\n%draw the given solution\n%q=[th1 phi1 th2 phi2 th3 phi3]\nq=[th1 beta(4) th2 beta(5) th3 beta(6)];\ndrawrobot3d(robot, q), pause(2);\n\nfigure, plot(fs), title('Sum of squares vs. iteration step')\n\n\n\n\n%compute the gamma functions, each function fi corresponds to a loop closing\n%equation in the 3RRR mechanism, given the current estimates of beta\n%the theta (theta1, theta2, theta3) may be considered here as constants,\n%since they are known values for the direct kinematic solution\nfunction f=compute_gamma_values(beta, theta)\n\nglobal xQ yQ xR yR b1 b2 b3 a1 a2 a3 h\n\n%just assign the values to some variables, so that the equations are easier\n%to read\nxA=beta(1);\nyA=beta(2);\nPhi=beta(3);\nphi1=beta(4);\nphi2=beta(5);\nphi3=beta(6);\n\n%known values of the direct kinematic problems\nth1=theta(1);\nth2=theta(2);\nth3=theta(3);\n\n%Loop closing equations for the 3RRR mechanism\nf1=eval('xA-a1*cos(th1)-b1*cos(th1+phi1)');\nf2=eval('yA-a1*sin(th1)-b1*sin(th1+phi1)');\nf3=eval('xA-xQ-a2*cos(th2)-b2*cos(th2+phi2)+h*cos(Phi)');\nf4=eval('yA-yQ-a2*sin(th2)-b2*sin(th2+phi2)+h*sin(Phi)');\nf5=eval('xA-xR-a3*cos(th3)-b3*cos(th3+phi3)+h*cos(Phi+pi/3)');\nf6=eval('yA-yR-a3*sin(th3)-b3*sin(th3+phi3)+h*sin(Phi+pi/3)');\n\n%form vector with values,\n%note that the f functions are the loop closing equations that should be \n%equal to zero\nf=[f1 f2 f3 f4 f5 f6]';\n\n\n%Compute Jacobian with respect to beta parameters\n%xA yA Phi, ph1, ph2, ph3\nfunction J=compute_jacobian_beta(beta, theta)\n\nglobal xQ yQ xR yR b1 b2 b3 a1 a2 a3 h\n\n%just assign the values to some variables, so that the equations are easier\n%to read\n%xA=beta(1);\n%yA=beta(2);\nPhi=beta(3);\nph1=beta(4);\nph2=beta(5);\nph3=beta(6);\n\n%known values of the direct kinematic problems\nth1=theta(1);\nth2=theta(2);\nth3=theta(3);\n\n%Compute Jacobian\n%Gamma1 with respect to xA yA Phi, ph1, ph2, ph3\nJ11=1;\nJ12=0;\nJ13=0;\nJ14=b1*sin(th1+ph1);\nJ15=0;\nJ16=0;\n\n%Gamma2 with respect to xA yA Phi, ph1, ph2, ph3\nJ21=0;\nJ22=1;\nJ23=0;\nJ24=-b1*cos(th1+ph1);\nJ25=0;\nJ26=0;\n \n%Gamma3 with respect to xA yA Phi, ph1, ph2, ph3\nJ31=1;\nJ32=0;\nJ33=-h*sin(Phi);\nJ34=0;\nJ35=b2*sin(th2+ph2);\nJ36=0;\n\n%Gamma4 with respect to xA yA Phi, ph1, ph2, ph3\nJ41=0;\nJ42=1;\nJ43=h*cos(Phi);\nJ44=0;\nJ45=-b2*cos(th2+ph2);\nJ46=0;\n\n%Gamma5 with respect to xA yA Phi, ph1, ph2, ph3\nJ51=1;\nJ52=0;\nJ53=-h*sin(Phi+pi/3);\nJ54=0;\nJ55=0;\nJ56=b3*sin(th3+ph3);\n \n%Gamma6 with respect to xA yA Phi, ph1, ph2, ph3\nJ61=0;\nJ62=1;\nJ63=h*cos(Phi+pi/3);\nJ64=0;\nJ65=0;\nJ66=-b3*cos(th3+ph3);\n\nJ=[J11 J12 J13 J14 J15 J16;\n J21 J22 J23 J24 J25 J26;\n J31 J32 J33 J34 J35 J36;\n J41 J42 J43 J44 J45 J46;\n J51 J52 J53 J54 J55 J56;\n J61 J62 J63 J64 J65 J66];\n \n\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/robots/example/3RRR/direct_kinematics_3RRR_numerical.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.7114815761573177}} {"text": "function z = entropy(x)\n% Compute entropy z=H(x) of a discrete variable x.\n% Input:\n% x: a integer vectors \n% Output:\n% z: entropy z=H(x)\n% Written by Mo Chen (sth4nth@gmail.com).\nn = numel(x);\n[~,~,x] = unique(x);\nPx = accumarray(x, 1)/n;\nHx = -dot(Px,log2(Px));\nz = max(0,Hx);", "meta": {"author": "PRML", "repo": "PRMLT", "sha": "baac49f643db6b39e75307d3b21307b32b29a7a9", "save_path": "github-repos/MATLAB/PRML-PRMLT", "path": "github-repos/MATLAB/PRML-PRMLT/PRMLT-baac49f643db6b39e75307d3b21307b32b29a7a9/chapter01/entropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.711471934561263}} {"text": "function [x, c, funVal, ValueL]=mcLogisticC(A, y, z, opts)\n%\n%%\n% Function mcLeastR:\n% Logistic Loss for Multi-class (task) Learning\n% with the (group) L2/L1-norm Constraint\n%\n%% Problem\n%\n% min - sum_{il} weight_{il} log( p_{il} ) \n% s.t. sum_j ||x^j||_q <=z\n%\n% p_{il}= 1 / (1+ exp(-y_i (x_i' * a_i + c_l) ) ) denotes the probability\n% weight_{il} is the weight for the i-th sample in the l-th classifier\n% is a m x k matrix\n% c_l is the intercept for the l-th classfier, and is a 1xk vector\n% x_i denotes the i-th column of x\n% x^j denotes the j-th row of x\n% a_i' denotes the i-th row of A\n%\n% y_i (either 1 or -1) is the response\n%\n% In this implementation, we assume weight_{il}=1/(mk)\n%\n% When y are of binary values (1 and -1), this problem is the\n% multi-class classificaiton problem, which learns the projection\n% matrix x, by sharing information across k classification tasks (with the\n% Lq/L1-norm Regularization)\n%\n% For the case that the multi tasks have separate data\n% matrix, please refer to the functions:\n% mtLeastR and mtLogisticR.\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 m x k)\n% z - L_1/L_q norm regularization parameter (z >=0)\n% opts- Optional inputs (default value: opts=[])\n%\n%% Output parameters:\n% x- The obtained weight of size n x k\n% c- The obtained intercept if size 1 x k\n% funVal- Function value during iterations\n%\n%% Copyright (C) 2009-2010 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 February 19, 2010.\n%\n%% Related papers\n%\n% [1] Jun Liu, Shuiwang Ji, and Jieping Ye, Multi-Task Feature Learning\n% Via Efficient L2,1-Norm Minimization, UAI, 2009\n%\n% [2] Jun Liu, Lei Yuan, Songcan Chen and Jieping Ye, Multi-Task Feature Learning\n% Via Efficient L2,1-Norm Minimization, Technical Report ASU, 2009.\n%\n%% Related functions:\n%\n% sll_opts, initFactor, pathSolutionLeast\n% mcLeastR, mcLeastC, mcLogisticR, ep21d\n%\n%%\n\n%% Verify and initialize the parameters\n%%\nif (nargin <3)\n error('\\n Inputs: A, y and z should be specified!\\n');\nend\n\n[m,n]=size(A);\n\nk=size(y,2);\n\nif (size(y,1) ~=m)\n error('\\n Check the length of y!\\n');\nend\n\nif (z<=0)\n error('\\n z should be positive!\\n');\nend\n\nopts=sll_opts(opts); % run sll_opts to set default values (flags)\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\n%% Group Property\n\n% Initialize q\nif (~isfield(opts,'q'))\n q=2; opts.q=2;\nelse\n q=opts.q;\n if (q~=2)\n error('\\n The current program only supports q=2');\n end\nend\n\n\n%% Starting point initialization\n\n% % % compute AT y\n% % if (opts.nFlag==0)\n% % ATy =A'* y;\n% % elseif (opts.nFlag==1)\n% % ATy= A'* y - mu' * sum(y, 1); ATy=ATy./repmat(nu, 1, k);\n% % else\n% % invNu=y./repmat(nu, 1, k); ATy=A'*invNu-mu' * sum(invNu, 1);\n% % end\n\n\np_flag=(y==1); % the indices of the postive samples\nm1=sum(p_flag,1); % the total number of the positive samples\nm2=m-m1; % the total number of the negative samples\n% m1 and m2 are 1 x k vectors\n\n% initialize a starting point\nif opts.init==2\n x=zeros(n,k); c=zeros(1,k);\nelse\n if isfield(opts,'x0')\n x=opts.x0;\n if ( size(x,1)~=n && size(x,2)~=k )\n error('\\n Check the input .x0');\n end\n else\n x=zeros(n,k);\n end\n \n if isfield(opts,'c0')\n c=opts.c0;\n \n if ( length(c)~=k )\n error('\\n Check the input .c0');\n end\n else\n c=log(m1./m2);\n end\nend\n\n% compute Ax= A * x\nif (opts.nFlag==0)\n Ax=A* x;\nelseif (opts.nFlag==1)\n invNu=x./repmat(nu, 1, k); 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./repmat(nu, 1, k);\nend\n\n%% The main program\n\n%% The Armijo Goldstein line search schemes\n\nif (opts.lFlag==0)\n \n lambda0=0;\n % a guess of the root\n \n bFlag=0; % this flag tests whether the gradient step only changes a little\n \n L=1/(m*k); % the intial guess of the Lipschitz continuous gradient\n \n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,k);\n cp=c; ccp=zeros(1,k);\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; sc=c + beta* ccp;\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 % aa= - diag(y) * (A * s + sc)\n aa=- y.*(As+ repmat(sc,m,1));\n \n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_s= sum(sum ( log( exp(-bb) + exp(aa-bb) ) + bb ) ) / (m * k);\n \n % compute prob=[p_1;p_2;...;p_m]\n prob=1./( 1+ exp(aa) );\n \n % b= - diag(y) * (1 - prob)\n b= -y.*(1-prob) / (m * k);\n \n gc=sum(b); % the gradient of c\n \n % compute g= AT b, the gradient of x\n if (opts.nFlag==0)\n g=A'*b;\n elseif (opts.nFlag==1)\n g= A'* b - mu' * sum(b, 1); g=g./repmat(nu, 1, k);\n else\n invNu=b./repmat(nu, 1, k); g=A'*invNu-mu' * sum(invNu, 1);\n end\n \n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n cp=c;\n \n while (1)\n % let s walk in a step in the antigradient of s to get v\n % and then do the Lq/L1-norm regularized projection\n v=s-g/L; c= sc- gc/L;\n \n % Lq/L1-norm regularized projection\n [x, lambda, zf_step]=ep21d(v, n, k, z, lambda0);\n lambda0=lambda;\n \n v=x-s; % the difference between the new approximate solution x\n % and the search point s\n \n % compute Ax= A * x\n if (opts.nFlag==0)\n Ax=A* x;\n elseif (opts.nFlag==1)\n invNu=x./repmat(nu, 1, k); 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./repmat(nu, 1, k);\n end\n \n % aa= - diag(y) * (A * x + c)\n aa=- y.*(Ax+ repmat(c,m,1));\n \n % fun_x is the logistic loss at the new approximate solution\n bb=max(aa,0);\n fun_x= sum(sum ( log( exp(-bb) + exp(aa-bb) ) + bb ) ) / (m * k);\n \n r_sum=(norm(v,'fro')^2 + norm(c-sc,2)^2) / 2;\n l_sum=fun_x - fun_s - sum(sum(v.* g)) - (c-sc)* gc';\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 fun_x <= fun_s + + \n % + L/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 ValueL(iterStep)=L;\n % store values for L\n \n xxp=x-xp; ccp=c-cp;\n \n funVal(iterStep)=fun_x;\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=norm(xxp,'fro');\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=norm(xp,'fro'); norm_xxp=norm(xxp,'fro');\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 end\nend\n\n%% adpative line search\n\nif (opts.lFlag==1)\n \n lambda0=0;\n % a guess of the root\n \n bFlag=0; % this flag tests whether the gradient step only changes a little\n \n L=1/(m*k); % the intial guess of the Lipschitz continuous gradient\n \n gamma=1;\n % we shall set the value of gamma = L,\n % and L is appropriate for the starting point\n \n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,k);\n cp=c; ccp=zeros(1,k);\n \n for iterStep=1:opts.maxIter \n while (1) \n if (iterStep~=1)\n alpha= (-gamma+ sqrt(gamma*gamma + 4* L * gamma)) / (2*L);\n beta= (gamma - gamma* alphap) / (alphap * gamma + alphap* L * alpha);\n % beta is the coefficient for generating search point s\n \n s=x + beta* xxp; sc=c + beta* ccp;\n As=Ax + beta* (Ax-Axp);\n else\n alpha= (-1+ sqrt(5)) / 2; beta=0; \n s=x; sc= c; \n As=Ax;\n end\n \n % aa= - diag(y) * (A * s + sc)\n aa=- y.*(As+ repmat(sc,m,1));\n \n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_s= sum(sum ( log( exp(-bb) + exp(aa-bb) ) + bb ) ) / (m * k);\n \n % compute prob=[p_1;p_2;...;p_m]\n prob=1./( 1+ exp(aa) );\n \n % b= - diag(y) * (1 - prob)\n b= -y.*(1-prob) / (m * k);\n \n gc=sum(b); % the gradient of c\n \n % compute g= AT b, the gradient of x\n if (opts.nFlag==0)\n g=A'*b;\n elseif (opts.nFlag==1)\n g= A'* b - mu' * sum(b, 1); g=g./repmat(nu, 1, k);\n else\n invNu=b./repmat(nu, 1, k); g=A'*invNu-mu' * sum(invNu, 1);\n end\n \n % let s walk in a step in the antigradient of s to get v\n % and then do the Lq/L1-norm regularized projection\n v=s-g/L; cnew= sc- gc/L;\n \n % projection\n [xnew, lambda, zf_step]=ep21d(v, n, k, z, lambda0);\n lambda0=lambda;\n \n v=xnew-s; % the difference between the new approximate solution x\n % and the search point s\n \n % compute A * xnew\n if (opts.nFlag==0)\n Axnew=A* xnew;\n elseif (opts.nFlag==1)\n invNu=xnew./nu; mu_invNu=mu * invNu;\n Axnew=A*invNu -repmat(mu_invNu, m, 1);\n else\n Axnew=A*xnew-repmat(mu*xnew, m, 1); Axnew=Axnew./nu;\n end\n \n % aa= - diag(y) * (A * x + c)\n aa=- y.*(Axnew+ repmat(cnew,m,1));\n \n % fun_x is the logistic loss at the new approximate solution\n bb=max(aa,0);\n fun_x= sum(sum ( log( exp(-bb) + exp(aa-bb) ) + bb ) ) / (m * k);\n \n r_sum=(norm(v,'fro')^2 + norm(cnew-sc,2)^2) / 2;\n l_sum=fun_x - fun_s - sum(sum(v.* g)) - (cnew-sc)* gc';\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 fun_x <= fun_s + + \n % + L/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 gamma=L* alpha* alpha; alphap=alpha;\n % update gamma, and alphap\n\n ValueL(iterStep)=L;\n % store values for L\n\n tao=L * r_sum / l_sum;\n if (tao >=5)\n L=L*0.8;\n end\n % decrease the value of L\n\n xp=x; Axp=Ax;\n x=xnew; Ax=Axnew; \n cp=c; c=cnew;\n % update x and Ax with xnew and Axnew\n \n xxp=x-xp; ccp=c-cp;\n \n funVal(iterStep)=fun_x;\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=norm(xxp,'fro');\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=norm(xp,'fro'); norm_xxp=norm(xxp,'fro');\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 end\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/L1Lq/L21C/mcLogisticC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7114337670058307}} {"text": "function A = ambiguityfunction(f,g)\n%AMBIGUITYFUNCTION Ambiguity function\n% Usage: A = ambiguityfunction(f);\n% A = ambiguityfunction(f,g);\n%\n% Input parameters:\n% f,g : Input vector(s).\n%\n% Output parameters:\n% A : ambiguity function\n%\n% `ambiguityfunction(f)` computes the (symmetric) ambiguity function of f.\n% The ambiguity function is computed as the two-dimensional Fourier transform\n% of the Wigner-Ville distribution |wignervilledist|.\n%\n% **WARNING**: The quadratic time-frequency distributions are highly\n% redundant. For an input vector of length L, the quadratic time-frequency\n% distribution will be a $L \\times L$ matrix.\n\n% AUTHOR: Jordy van Velthoven\n% TESTING: TEST_AMBIGUITYFUNCTION\n% REFERENCE: REF_AMBIGUITYFUNCTION\n\nupfname = upper(mfilename);\ncomplainif_notenoughargs(nargin, 1, upfname);\ncomplainif_toomanyargs(nargin, 2, upfname);\n\n[f,~,W]=comp_sigreshape_pre(f,upfname);\n\nif W>1\n error('%s: Only one-dimensional vectors can be processed.',upfname); \nend\n\nif (nargin == 1)\n if isreal(f)\n z1 = comp_fftanalytic(f);\n else\n z1 = f;\n end\n z2 = z1;\n\nelseif (nargin == 2)\n [g,~,W]=comp_sigreshape_pre(g,upfname);\n if W>1\n error('%s: Only one-dimensional vectors can be processed.',upfname); \n end\n\n if ~all(size(f)==size(g))\n \terror('%s: f and g must have the same length.', upfname);\n end;\n\n if xor(isreal(f), isreal(g))\n error('%s: One input is real, the other one must be real too. ',...\n upfname);\n end\n\n if isreal(f) || isreal(g)\n z1 = comp_fftanalytic(f);\n z2 = comp_fftanalytic(g);\n else\n z1 = f;\n z2 = g;\n end;\nend\n\nR = comp_instcorrmat(z1, z2);\n\nA = fftshift(fft2(fft(R)));\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/quadratic/ambiguityfunction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.711377838105645}} {"text": "function [ h, m, s ] = frac_to_hms ( f )\n\n%*****************************************************************************80\n%\n%% FRAC_TO_HMS converts a fractional day into hours, minutes, seconds.\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% Parameters:\n%\n% Input, real F, a day fraction between 0.0 and 1.0.\n%\n% Output, integer H, M, S, the equivalent hours, minutes\n% and seconds.\n%\n f2 = f;\n\n f2 = 24.0 * f2;\n h = floor ( f2 );\n f2 = f2 - h;\n\n f2 = 60.0 * f2;\n m = floor ( f2 );\n f2 = f2 - m;\n\n f2 = 60.0 * f2;\n s = floor ( f2 );\n f2 = f2 - 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/calpak/frac_to_hms.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.711334742546555}} {"text": "function [B,L,var,fac,E] = FA(X,s)\n% FA Factor analysis (principal factoring technique)\n%\n% The reason to favour this method opposite to maximum likelihood \n% (Statistics toolbox) is no distributional assumptions. In comparison to\n% SPSS program, this provides the same results. We expect identical\n% numerical solution, especially advantage of singular value decomposition.\n% Initial estimates of communalities are set as squared multiple\n% correlations. In iteration process (convergence criterium 0.001, limit\n% for iteration 75), communalities are set to one if Heywood case occurs. \n% The loadings are rotated (normalized varimax rotation, convergence \n% criterium 0.00001, iteration limit 35). Estimate of rotated factors is\n% based on regression approach.\n% \n% [B,L,var,fac,E] = FA(X,s)\n%\n% Inputs: \n% X is the data matrix (columns as variables, X must have more\n% than one row and more than one column).\n%\n% s is the number of extracted factors (if this parameter is\n% not included, number is chosen by principal component \n% criterion with eigenvalues greater than or equal to one).\n%\n% Results: \n% B is the matrix of factor loadings (unrotated), last column\n% of matrix B indicates an extraction estimate of \n% communalities.\n%\n% L is the varimax rotated loadings matrix.\n%\n% var describes the variability proportions, last item is\n% the cumulative variance proportion.\n%\n% fac is the matrix of factors.\n% \n% E is the matrix of specific variances.\n%\n% Example: From the data containing temperature, relative humidity, wind\n% speed, radiation, NO/NO2 ratio and ozone gained in boundary layer\n% [B,L,var] = FA(X,3)\n% The number of factors extracted: 3\n% Factorial number of iterations: 14\n% Rotational number of iterations: 5\n%\n% B =\n% -0.962 0.145 0.088 0.954\n% 0.964 -0.065 -0.230 0.986\n% -0.551 0.189 0.061 0.343\n% -0.557 0.422 -0.444 0.685\n% 0.718 0.649 0.238 0.994\n% -0.975 -0.077 0.081 0.963\n%\n% L =\n% -0.850 -0.308 -0.370\n% 0.913 0.322 0.220\n% -0.516 -0.087 -0.262\n% -0.291 -0.083 -0.771\n% 0.297 0.948 0.087\n% -0.807 -0.495 -0.258\n%\n% var =\n% 0.441 0.226 0.154 0.821\n%\n% The biggest values of rotated loadings points dependence of tempetature,\n% relative humidity, wind speed and ozone in the first factor and NO/NO2 \n% ratio with ozone in another.\n%\n% Communalities show the biggest relation of NO/NO2 ratio to the others. Be\n% careful, variances need not be in decreasing order.\n%\n% For citation ensue following format: Malec L., Skacel F., Trujillo-Ortiz\n% A.(2007). FA: Factor analysis by principal factoring. A MATLAB file. \n% [WWW document]. URL http://www.mathworks.com/matlabcentral/fileexchange/\n% loadFile.do?objectId=14115\n%\n% Golub G. H., Van Loan C. F.: Matrix Computations. The Johns Hopkins\n% University Press, Baltimore 1996.\n% Harman H. H.: Modern Factor Analysis. The University of Chicago Press,\n% Chicago 1976.\n% Krzanowski W. J.: Principles of Multivariate Analysis. Oxford University\n% Press, Oxford 2003.\n%\n% Copyright. February 26, 2007.\n\n\n[m,n] = size(X);\n\nif nargin==2 && n=1;\n s = sum(f);\nend\n\nfprintf ('The number of factors extracted: %.i\\n', s);\n\n% Communality estimation by coefficients of multiple correlation.\nc = ones(n,1) - 1 ./ diag(R \\ diag(ones(n,1)));\ng = [];\n\n% Iteration cycle which maximizes factors correlations.\nfor k = 1:75\n [U,D,V] = svd(R - diag(diag(R)) + diag(c),0);\n N = V * sqrt(D(:,1:s));\n p = c;\n c = sum(N.^2,2);\n g = [g find(c>1)']; % Heywood case in communality estimates.\n c(g) = 1;\n if max(abs(c - p))<0.001\n break\n end\nend\n\nfprintf ('Factorial number of iterations: %.i\\n', k);\n\n% Evaluation of factor loadings and communalities estimations.\nB = [N c];\n\n% Normalization of factor loadings.\nh = sqrt(c);\nN = N ./ repmat(h,1,s);\n\n% Initial choice of eigenvalues and loadings labelling.\nL = N;\nz = 0;\n\n% Iteration cycle maximizing variance of individual columns.\nfor l = 1:35\n [A,S,M] = svd(N' * (n * L.^3 - L * diag(sum(L.^2))),0);\n L = N * A * M';\n b = z;\n z = sum(diag(S));\n if abs(z - b)<0.00001\n break\n end \nend\n\nfprintf ('Rotational number of iterations: %.i\\n', l);\n\n% Unnormalization of factor loadings.\nL = L .* repmat(h,1,s);\n\n% Factors computation by regression and variance proportions.\nt = sum(L.^2) / n;\nvar = [t sum(t)];\nfac = X * (R \\ diag(ones(n,1))) * L;\n\n% Evaluation of given factor model variance specific matrix. \nr = diag(R) - sum(L.^2,2);\nE = R - L * L' - diag(r);\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/14115-fa/FA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7113159981869149}} {"text": "function x = log_series_cdf_inv ( cdf, a )\n\n%*****************************************************************************80\n%\n%% LOG_SERIES_CDF_INV inverts the Logarithmic Series CDF.\n%\n% Discussion:\n%\n% Simple summation is used. The only protection against an\n% infinite loop caused by roundoff is that X cannot be larger\n% than 1000.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 December 1999\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real CDF, the value of the CDF.\n%\n% Input, real A, the parameter of the PDF.\n% 0.0 < A < 1.0.\n%\n% Output, real X, the argument of the CDF for which\n% CDF(X-1) <= CDF <= CDF(X).\n%\n xmax = 1000;\n\n if ( cdf < 0.0 | 1.0 < cdf )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LOG_SERIES_CDF_INV - Fatal error!\\n' );\n fprintf ( 1, ' CDF < 0 or 1 < CDF.\\n' );\n error ( 'LOG_SERIES_CDF_INV - Fatal error!' );\n end\n\n cdf2 = 0.0;\n x = 1;\n\n while ( cdf2 < cdf & x < xmax )\n\n if ( x == 1 )\n pdf = - a / log ( 1.0 - a );\n else\n pdf = ( x - 1 ) * a * pdf / x;\n end\n\n cdf2 = cdf2 + pdf;\n\n x = x + 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/prob/log_series_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7113159929997115}} {"text": "%PCA Principal component analysis (PCA or MCA on overall covariance matrix)\n% \n% [W,FRAC] = PCA(A,N)\n% [W,N] = PCA(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 PCA mapping\n% FRAC or N Fraction of variance or number of dimensions retained.\n%\n% DESCRIPTION\n% This routine performs a principal component analysis (PCA) or minor\n% component analysis (MCA) on the overall covariance matrix (weighted\n% by the class prior probabilities). It finds a rotation of the dataset A to \n% an N-dimensional linear subspace such that at least (for PCA) or at most \n% (for MCA) a fraction FRAC of the total variance is preserved.\n%\n% PCA is applied when N (or FRAC) >= 0; MCA when N (or FRAC) < 0. If N is \n% given (abs(N) >= 1), FRAC is optimised. If FRAC is given (abs(FRAC) < 1), \n% N is optimised. \n%\n% Objects in a new dataset B can be mapped by B*W, W*B or by A*PCA([],N)*B.\n% Default (N = inf): the features are decorrelated and ordered, but no \n% feature reduction is performed.\n%\n% ALTERNATIVE\n%\n% V = PCA(A,0)\n% \n% Returns the cumulative fraction of the explained variance. V(N) is the \n% cumulative fraction of the explained variance by using N eigenvectors.\n%\n% Use KLM for a principal component analysis on the mean class covariance.\n% Use FISHERM for optimizing the linear class separability (LDA).\n% \n% SEE ALSO\n% MAPPINGS, DATASETS, PCLDC, KLLDC, KLM, FISHERM\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: pca.m,v 1.2 2006/03/08 22:06:58 duin Exp $\n\nfunction [w,truefrac] = pca (varargin)\n\n\tprtrace(mfilename);\n\n\t[w,truefrac] = pcaklm(mfilename,varargin{:});\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/pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7113159909134651}} {"text": "function G = curl(F) \n%CURL Numerical surface curl.\n% G = CURL(F) returns the numerical surface curl of the SPHEREFUNV F.\n% This only makes mathematical sense for a tangential vector field. \n%\n% See also SPHEREFUNV/DIVERGENCE, SPHEREFUN/GRADIENT, SPHEREFUNV/VORTICITY.\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% Empty check.\nif ( isempty(F) )\n G = spherefunv;\n return\nend\n\nFc = F.components;\n\n% The following derivatives are all tangential derivatives.\n\n% First component: d/dy(fz) - d/dz(fy)\ngx = diff(Fc{3}, 2) - diff(Fc{2}, 3);\n\n% Second component: d/dz(fx) - d/dx(fz)\ngy = diff(Fc{1}, 3) - diff(Fc{3}, 1);\n\n% Third component: d/dx(fy) - d/dy(fx)\ngz = diff(Fc{2}, 1) - diff(Fc{1}, 2);\n\nG = spherefunv(gx,gy,gz);\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/@spherefunv/curl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750400464602, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.7112756730803536}} {"text": "function varargout = sltensor_svd(T, n)\n%SLTENSOR_SVD Performs a Higher-Order SVD on a Tensor\n%\n% $ Syntax $\n% - [S, U1, U2, ...] = sltensor_svd(T)\n% - [S, U1, U2, ...] = sltensor_svd(T, n)\n% - [S, Us] = sltensor_svd(...)\n%\n% $ Description $\n% - [S, U1, U2, ...] = sltensor_svd(T) Performs a Higher Order Singular Value\n% Decomposition to a Tensor T. In the output arguments, S is the core\n% tensor, U1, U2, ... are the singular vector matrices of mode 1, 2,...\n%\n% - [S, U1, U2, ...] = sltensor_svd(T, n) Here n specifies the order of the\n% tensor T, n should be not less than ndims(T). If n > ndims(T) is just\n% regarded as a tensor of dimensions d1xd2x...x1. \n%\n% - [S, Us] = sltensor_svd(...) where all mode matrices are returned to Us,\n% which is an 1 x n cell array, with each cell containing a mode matrix.\n% \n% $ History $\n% - Created by Dahua Lin on Dec 17th, 2005\n%\n\n%% parse and verify the arguments\nslchknargs(nargin, 1);\nn0 = ndims(T);\nif nargin == 1\n n = n0;\nelse\n if n < n0;\n error('sltoolbox:invalidarg', ...\n 'The order %d is too small', n);\n end\nend\nif nargout > 2 && nargout ~= n+1\n error('sltoolbox:invalidnargout', ...\n 'The number of outputs is not valid');\nend\n\n%% compute\n\nUs = cell(n, 1);\nS = T;\nfor i = 1 : n0\n M = sltensor_unfold(T, i);\n [d1, d2] = size(M);\n if d1 < d2\n [V, D, U] = svd(M', 0);\n else\n [U, D, V] = svd(M, 0);\n end\n slignorevars(D, V);\n clear D V;\n \n Us{i} = U;\n S = sltensor_multiply(S, U', i);\nend\nif n > n0\n for i = n0+1 : n\n Us{i} = 1;\n end\nend\n\n%% output\nvarargout{1} = S;\nif nargout == 2\n varargout{2} = Us;\nelse\n varargout(2:n+1) = Us;\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/tensor/sltensor_svd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7111764296902444}} {"text": "function fem1d_adaptive ( )\n\n%*****************************************************************************80\n%\n%% MAIN is the main program for FEM1D_ADAPTIVE.\n%\n% Discussion:\n%\n% FEM1D_ADAPTIVE solves a 1D problem using an adaptive finite element method.\n%\n% The equation to be treated is:\n%\n% -d/dx ( P(x) * dU(x)/dx ) + Q(x) * U(x) = F(x)\n%\n% by the finite-element method using piecewise linear basis\n% functions.\n%\n% An adaptive method is used to try to reduce the maximum\n% error by refining the mesh in certain places.\n%\n% Here U is an unknown scalar function of X defined on the\n% interval [XL,XR], and P, Q and F are given functions of X.\n%\n% The values of U at XL and XR are also specified.\n%\n% The interval [XL,XR] is \"meshed\" with N+1 points,\n%\n% XN(0) = XL, XN(1) = XL+H, XN(2) = XL+2*H, ..., XN(N) = XR.\n%\n% This creates N subintervals, with interval I having endpoints \n% XN(I-1) and XN(I).\n%\n% The algorithm tries to guarantee a certain amount\n% of accuracy by examining the current solution, estimating the error\n% in each subinterval, and, if necessary, subdividing one or more\n% subintervals and repeating the calculation.\n%\n% We can think of the adaptive part of the algorithm as a refined\n% problem. The program re-solves the problem on the pair of\n% intervals J and J+1, which extend from node J-1 to node J+1.\n% The values of U that were just computed at nodes J-1 and J+1\n% will be used as the boundary values for this refined problem.\n% The intervals J and J+1 will each be evenly divided into NY\n% smaller subintervals. This boundary value problem is solved,\n% and the derivatives of the original and refined solutions are\n% then compared to get an estimate of the error.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% real ADIAG(NU).\n% ADIAG(I) is the \"diagonal\" coefficient of the I-th\n% equation in the linear system. That is, ADIAG(I) is\n% the coefficient of the I-th unknown in the I-th equation.\n%\n% real ALEFT(NU).\n% ALEFT(I) is the \"left hand\" coefficient of the I-th\n% equation in the linear system. That is, ALEFT(I) is the\n% coefficient of the (I-1)-th unknown in the I-th equation.\n% There is no value in ALEFT(1), since the first equation\n% does not refer to a \"0-th\" unknown.\n%\n% real ARITE(NU).\n% ARITE(I) is the \"right hand\" coefficient of the I-th\n% equation in the linear system. ARITE(I) is the coefficient\n% of the (I+1)-th unknown in the I-th equation. There is\n% no value in ARITE(NU) because the NU-th equation does not\n% refer to an \"NU+1\"-th unknown.\n%\n% real ETA(N).\n% ETA(I) is the error estimate for interval I. It is computed\n% as the sum of two quantities, one associated with the left\n% and one with the right node of the interval.\n%\n% real F(NU).\n% ASSEMBLE stores into F the right hand side of the linear\n% equations.\n% SOLVE replaces those values of F by the solution of the\n% linear equations.\n%\n% real FY(M).\n% FY is the right hand side of the linear system of the refined\n% problem.\n%\n% real H(N)\n% H(I) is the length of subinterval I. This code uses\n% equal spacing for all the subintervals.\n%\n% real HY(M).\n% HY(I) is the length of subinterval I in the refined problem.\n%\n% integer IBC.\n% IBC declares what the boundary conditions are.\n% 1, at the left endpoint, U has the value UL,\n% at the right endpoint, U' has the value UR.\n% 2, at the left endpoint, U' has the value UL,\n% at the right endpoint, U has the value UR.\n% 3, at the left endpoint, U has the value UL,\n% and at the right endpoint, U has the value UR.\n% 4, at the left endpoint, U' has the value UL,\n% at the right endpoint U' has the value UR.\n%\n% integer IBCY.\n% IBCY declares the boundary conditions for the refined problem\n% which should always be that the value of U is specified at\n% both the left and right endpoints. This corresponds to a\n% value of IBCY = 3.\n%\n% integer INDX(0:N).\n% For a node I, INDX(I) is the index of the unknown\n% associated with node I.\n% If INDX(I) is equal to -1, then no unknown is associated\n% with the node, because a boundary condition fixing the\n% value of U has been applied at the node instead.\n% Unknowns are numbered beginning with 1.\n% If IBC is 2 or 4, then there is an unknown value of U\n% at node 0, which will be unknown number 1. Otherwise,\n% unknown number 1 will be associated with node 1.\n% If IBC is 1 or 4, then there is an unknown value of U\n% at node N, which will be unknown N or N+1,\n% depending on whether there was an unknown at node 0.\n%\n% integer INDY(0:M).\n% INDY(I) records the index of the unknown associated with\n% node I for the refined problem.\n%\n% integer JADD(N).\n% JADD(I) is 1 if the error estimates show that interval I\n% should be subdivided.\n%\n% integer KOUNT, the number of adaptive steps that have been taken.\n%\n% integer M.\n% M is the number of subintervals used in the refined problem.\n% M is equal to NY for computations centered at node 0 or node N,\n% and otherwise, M is equal to 2*NY.\n%\n% integer N\n% The number of subintervals into which the interval\n% [XL,XR] is broken.\n%\n% integer NL.\n% The number of basis functions used in a single\n% subinterval. (NL-1) is the degree of the polynomials\n% used. For this code, NL is fixed at 2, meaning that\n% piecewise linear functions are used as the basis.\n%\n% integer NMAX, the maximum number of unknowns that can be handled.\n%\n% integer NODE(NL,N).\n% For each subinterval I:\n% NODE(1,I) is the number of the left node, and\n% NODE(2,I) is the number of the right node.\n%\n% integer NODEY(NL,M).\n% NODEY performs the same function for the refined problem that\n% NODE performs for the full problem, recording the node numbers\n% associated with a particular subinterval.\n%\n% integer NQUAD\n% The number of quadrature points used in a subinterval.\n%\n% integer NU.\n% NU is the number of unknowns in the linear system.\n% Depending on the value of IBC, there will be N-1,\n% N, or N+1 unknown values, which are the coefficients\n% of basis functions.\n%\n% integer NUY.\n% The number of unknowns in the refined problem.\n%\n% integer NY.\n% NY is the number of subintervals into which a given interval\n% will be subdivided, before solving the refined probelm.\n%\n% integer PROBLEM, chooses the problem to be solved.\n% The user must choose this value by setting it in routine GETPRB.\n% * 1, u = x, p = 1, q = 0, f = 0, ibc = 3, ul = 0, ur = 1.\n% The program should find the solution exactly, and the\n% adaptive code should find that there is no reason to\n% subdivide any interval.\n% * 2, u = x*x, p = 1, q = 0, f = -2, ibc = 3, ul = 0, ur = 1.\n% This problem should find the solution exactly, and\n% the adaptive code should again find there is nothing\n% to do.\n% *3, u = sin(pi*x/2), p = 1, q = 0, ibc = 3, f = 0.25*pi*pi*sin(pi*x/2), \n% ul = 0, ur = 1.\n% *4, u = cos(pi*x/2), p = 1, q = 0, ibc = 3, f = 0.25*pi*pi*cos(pi*x/2), \n% ul = 1, ur = 0.\n% *5: u = x**(beta+2)/((beta+2)*(beta+1)), p = 1, q = 1, ibc = 3, \n% f = -x**beta + (x**(beta+2))/((beta+2)*(beta+1)),\n% ul = 0, ur = 1/((beta+2)*(beta+1))\n% (beta must be greater than -2, and not equal to -1)\n% *6: u = atan((x-0.5)/alpha), p = 1, q = 0, ibc = 3, \n% f = 2*alpha*(x-0.5) / (alpha^2 + (x-0.5)^2) ^2,\n% ul = u(0), ur = u(1)\n%\n% integer STATUS, reports status of subdivision.\n% 0, a new subdivision was carried out.\n% 1, no more subdivisions are needed.\n% -1, no more subdivisions can be carried out.\n%\n% real TOL.\n% A tolerance that is used to determine whether the estimated\n% error in an interval is so large that it should be subdivided\n% and the problem solved again.\n%\n% real UL.\n% If IBC is 1 or 3, UL is the value that U is required\n% to have at X = XL.\n% If IBC is 2 or 4, UL is the value that U' is required\n% to have at X = XL.\n%\n% real UR.\n% If IBC is 2 or 3, UR is the value that U is required\n% to have at X = XR.\n% If IBC is 1 or 4, UR is the value that U' is required\n% to have at X = XR.\n%\n% real WQUAD(NQUAD).\n% WQUAD(I) is the weight associated with the I-th point\n% of an NQUAD point Gaussian quadrature rule.\n%\n% real XL.\n% XL is the left endpoint of the interval over which the\n% differential equation is being solved.\n%\n% real XN(0:N).\n% XN(I) is the location of the I-th node. XN(0) is XL,\n% and XN(N) is XR.\n%\n% real XQUAD(NQUAD,NMAX), the I-th quadrature point\n% in interval J.\n%\n% real XQUADY(NQUAD,NMAY ), the I-th quadrature point\n% in subinterval J of the refined problem.\n%\n% real XR.\n% XR is the right endpoint of the interval over which the\n% differential equation is being solved.\n%\n% Workspace, double precision XT(0:NMAX), used to compute a new\n% set of nodes.\n%\n% real YN(0:M).\n% YN(I) is the location of the I-th node in the refined\n% problem.\n%\n nl = 2;\n nmax = 30;\n nquad = 2;\n\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM1D_ADAPTIVE\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Solve the two-point boundary value problem:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' -d/dx ( P(x) * dU(x)/dx ) + Q(x) * U(x) = F(x)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'on the interval [0,1], specifying the value\\n' );\n fprintf ( 1, 'of U at each endpoint.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'The number of basis functions per element is %d\\n', nl );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'The number of quadrature points per element is %d\\n', nquad );\n\n problem = get_problem ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Problem index = %d\\n', problem );\n fprintf ( 1, '\\n' );\n\n if ( problem == 1 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"Linear\" problem:\\n' );\n fprintf ( 1, ' (No refinement needed)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' U(X) = X\\n' );\n fprintf ( 1, ' P(X) = 1.0\\n' );\n fprintf ( 1, ' Q(X) = 0.0\\n' );\n fprintf ( 1, ' F(X) = 0.0\\n' );\n fprintf ( 1, ' IBC = 3\\n' );\n fprintf ( 1, ' UL = 0.0\\n' );\n fprintf ( 1, ' UR = 1.0\\n' );\n\n elseif ( problem == 2 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"Quadratic\" problem:\\n' );\n fprintf ( 1, ' (No refinement needed)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' U(X) = X*X\\n' );\n fprintf ( 1, ' P(X) = 1.0\\n' );\n fprintf ( 1, ' Q(X) = 0.0\\n' );\n fprintf ( 1, ' F(X) = -2.0\\n' );\n fprintf ( 1, ' IBC = 3\\n' );\n fprintf ( 1, ' UL = 0.0\\n' );\n fprintf ( 1, ' UR = 1.0\\n' );\n\n elseif ( problem == 3 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"SINE\" problem:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' U(X) = SIN(PI*X/2)\\n' );\n fprintf ( 1, ' P(X) = 1.0\\n' );\n fprintf ( 1, ' Q(X) = 0.0\\n' );\n fprintf ( 1, ' F(X) = PI*PI*SIN(PI*X/2)/4\\n' );\n fprintf ( 1, ' IBC = 3\\n' );\n fprintf ( 1, ' UL = 0.0\\n' );\n fprintf ( 1, ' UR = 1.0\\n' );\n\n elseif ( problem == 4 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"COSINE\" problem:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' U(X) = COS(PI*X/2)\\n' );\n fprintf ( 1, ' P(X) = 1.0\\n' );\n fprintf ( 1, ' Q(X) = 0.0\\n' );\n fprintf ( 1, ' F(X) = PI*PI*COS(PI*X/2)/4\\n' );\n fprintf ( 1, ' IBC = 3\\n' );\n fprintf ( 1, ' UL = 0.0\\n' );\n fprintf ( 1, ' UR = 1.0\\n' );\n\n elseif ( problem == 5 )\n\n beta = get_beta ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"RHEINBOLDT\" problem:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' U(X) = X**(B+2)/((B+2)*(B+1))\\n' );\n fprintf ( 1, ' P(X) = 1.0\\n' );\n fprintf ( 1, ' Q(X) = 1.0\\n' );\n fprintf ( 1, ' F(X) = -X**B+(X**B+2))/((B+2)*(B+1))\\n' );\n fprintf ( 1, ' IBC = 3\\n' );\n fprintf ( 1, ' UL = 0.0\\n' );\n fprintf ( 1, ' UR = 1/((B+2)*(B+1))\\n' );\n fprintf ( 1, ' B = %f\\n', beta );\n\n elseif ( problem == 6 )\n\n alpha = get_alpha ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"ARCTAN\" problem:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' U(X) = ATAN((X-0.5)/A)\\n' );\n fprintf ( 1, ' P(X) = 1.0\\n' );\n fprintf ( 1, ' Q(X) = 0.0\\n' );\n fprintf ( 1, ' F(X) = 2*A*(X-0.5)/(A^2+(X-0.5)^2)^2\\n' );\n fprintf ( 1, ' IBC = 3\\n' );\n fprintf ( 1, ' UL = ATAN(-0.5/A)\\n' );\n fprintf ( 1, ' UR = ATAN( 0.5/A)\\n' );\n fprintf ( 1, ' A = %f\\n', alpha );\n\n end\n%\n% Start out with just 4 subintervals.\n%\n n = 4;\n%\n% Initialize values that define the problem.\n%\n [ ibc, tol, ul, ur, xl, xn, xr ] = init ( n );\n%\n% Start the iteration counter off at 0.\n%\n kount = 0;\n%\n% Begin the next iteration.\n%\n while ( 1 )\n\n kount = kount + 1;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Begin new iteration with %d nodes.\\n', n );\n fprintf ( 1, '\\n' );\n%\n% Solve the regular problem.\n%\n [ u, h, nu ] = solvex ( ibc, kount, n, nl, nmax, ul, ur, xn );\n%\n% Solve N subproblems to get the error estimators.\n%\n eta = solvey ( u, h, n, nu, ul, ur, xn );\n%\n% Examine the error estimators, and see how many intervals should\n% be subdivided.\n%\n [ n, xn, status ] = subdiv ( eta, kount, n, nmax, tol, xn );\n\n if ( status ~= 0 )\n break\n end\n\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM1D_ADAPTIVE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction [ adiag, aleft, arite, f ] = assemble ( h, n, indx, node, nu, nl, ...\n nquad, nmax, ul, ur, wquad, xn, xquad )\n\n%*****************************************************************************80\n%\n%% ASSEMBLE assembles the global matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, real H(N)\n% H(I) is the length of subinterval I. This code uses\n% equal spacing for all the subintervals.\n%\n% Input, integer N\n% The number of subintervals into which the interval\n% [XL,XR] is broken.\n%\n% Input, integer INDX(0:N).\n% For a node I, INDX(I) is the index of the unknown\n% associated with node I.\n% If INDX(I) is equal to -1, then no unknown is associated\n% with the node, because a boundary condition fixing the\n% value of U has been applied at the node instead.\n% Unknowns are numbered beginning with 1.\n% If IBC is 2 or 4, then there is an unknown value of U\n% at node 0, which will be unknown number 1. Otherwise,\n% unknown number 1 will be associated with node 1.\n% If IBC is 1 or 4, then there is an unknown value of U\n% at node N, which will be unknown N or N+1,\n% depending on whether there was an unknown at node 0.\n%\n% Input, integer NODE(NL,N).\n% For each subinterval I:\n% NODE(1,I) is the number of the left node, and\n% NODE(2,I) is the number of the right node.\n%\n% Input, integer NU.\n% NU is the number of unknowns in the linear system.\n% Depending on the value of IBC, there will be N-1,\n% N, or N+1 unknown values, which are the coefficients\n% of basis functions.\n%\n% Input, integer NL.\n% The number of basis functions used in a single\n% subinterval. (NL-1) is the degree of the polynomials\n% used. For this code, NL is fixed at 2, meaning that\n% piecewise linear functions are used as the basis.\n%\n% Input, integer NQUAD\n% The number of quadrature points used in a subinterval.\n%\n% Input, integer NMAX, the maximum number of unknowns that can be handled.\n%\n% Input, real UL.\n% If IBC is 1 or 3, UL is the value that U is required\n% to have at X = XL.\n% If IBC is 2 or 4, UL is the value that U' is required\n% to have at X = XL.\n%\n% Input, real UR.\n% If IBC is 2 or 3, UR is the value that U is required\n% to have at X = XR.\n% If IBC is 1 or 4, UR is the value that U' is required\n% to have at X = XR.\n%\n% Input, real WQUAD(NQUAD).\n% WQUAD(I) is the weight associated with the I-th point\n% of an NQUAD point Gaussian quadrature rule.\n%\n% Input, real XN(0:N).\n% XN(I) is the location of the I-th node. XN(0) is XL,\n% and XN(N) is XR.\n%\n% Input, real XQUAD(NQUAD,NMAX), the I-th quadrature point\n% in interval J.\n%\n% Output, real ADIAG(NU).\n% ADIAG(I) is the \"diagonal\" coefficient of the I-th\n% equation in the linear system. That is, ADIAG(I) is\n% the coefficient of the I-th unknown in the I-th equation.\n%\n% Output, real ALEFT(NU).\n% ALEFT(I) is the \"left hand\" coefficient of the I-th\n% equation in the linear system. That is, ALEFT(I) is the\n% coefficient of the (I-1)-th unknown in the I-th equation.\n% There is no value in ALEFT(1), since the first equation\n% does not refer to a \"0-th\" unknown.\n%\n% Output, real ARITE(NU).\n% ARITE(I) is the \"right hand\" coefficient of the I-th\n% equation in the linear system. ARITE(I) is the coefficient\n% of the (I+1)-th unknown in the I-th equation. There is\n% no value in ARITE(NU) because the NU-th equation does not\n% refer to an \"NU+1\"-th unknown.\n%\n% Output, real F(NU).\n% ASSEMBLE stores into F the right hand side of the linear\n% equations.\n% SOLVE replaces those values of F by the solution of the\n% linear equations.\n%\n\n%\n% Zero out the entries.\n%\n f(1:nu) = 0.0;\n aleft(1:nu) = 0.0;\n arite(1:nu) = 0.0;\n adiag(1:nu) = 0.0;\n%\n% For each interval,\n%\n for ie = 1 : n\n\n he = h(ie);\n xleft = xn(node(1,ie)+1);\n xrite = xn(node(2,ie)+1);\n%\n% For each quadrature point in the interval,\n%\n for iq = 1 : nquad\n\n xquade = xquad(iq,ie);\n wquade = wquad(iq);\n%\n% Pick a basis function which defines the equation,\n%\n for il = 1 : nl\n\n ig = node(il,ie);\n iu = indx(ig+1);\n\n if ( 0 < iu )\n\n [ phii, phiix ] = phi ( il, xquade, xleft, xrite );\n f(iu) = f(iu) + he * wquade * ff ( xquade ) * phii;\n%\n% Take care of boundary conditions specifying the value of U'.\n%\n if ( ig == 0 )\n x = 0.0;\n f(iu) = f(iu) - pp ( x ) * ul;\n elseif ( ig == n )\n x = 1.0;\n f(iu) = f(iu) + pp ( x ) * ur;\n end\n%\n% Pick a basis function which defines the coefficient\n% being computed.\n%\n for jl = 1 : nl\n\n jg = node(jl,ie);\n ju = indx(jg+1);\n [ phij, phijx ] = phi ( jl, xquade, xleft, xrite );\n\n aij = he * wquade * ...\n ( pp ( xquade ) * phiix * phijx ...\n + qq ( xquade ) * phii * phij );\n%\n% Decide where the coefficient is to be added.\n%\n if ( ju <= 0 )\n \n if ( jg == 0 )\n f(iu) = f(iu) - aij * ul;\n elseif ( jg == n )\n f(iu) = f(iu) - aij * ur;\n end\n\n elseif ( iu == ju )\n adiag(iu) = adiag(iu) + aij;\n elseif ( ju < iu )\n aleft(iu) = aleft(iu) + aij;\n else\n arite(iu) = arite(iu) + aij;\n end\n\n end\n end\n end\n end\n end\n\n return\nend\nfunction value = ff ( x )\n\n%*****************************************************************************80\n%\n%% FF evaluates the function F in the differential equation.\n%\n% Discussion:\n%\n% This is the function F(X) that appears on the right hand\n% side of the equation:\n%\n% -d/dx ( P(x) * dU(x)/dx ) + Q(x) * U(x) = F(x)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of F(X).\n%\n\n%\n% Find out which problem we're working on.\n%\n problem = get_problem ( );\n\n if ( problem == 1 )\n\n value = 0.0;\n\n elseif ( problem == 2 )\n\n value = -2.0 * x;\n\n elseif ( problem == 3 )\n\n value = 0.25 * pi^2 * sin ( 0.5 * pi * x );\n\n elseif ( problem == 4 )\n\n value = 0.25 * pi^2 * cos ( 0.5 * pi * x );\n\n elseif ( problem == 5 )\n\n beta = get_beta ( );\n\n value = - ( x^beta ) + ( x^( beta + 2.0 ) ) ...\n / ( ( beta + 2.0 ) * ( beta + 1.0 ) );\n\n elseif ( problem == 6 )\n\n alpha = get_alpha ( );\n\n value = 2.0 * alpha * ( x - 0.5 ) ...\n / ( alpha^2 + ( x - 0.5 )^2 )^2;\n\n end\n\n return\nend\nfunction [ h, indx, node, nu, wquad, xquad ] = geometry ( ibc, n, nl, nmax, ...\n nquad, xn )\n\n%*****************************************************************************80\n%\n%% GEOMETRY sets up some of the geometric information for the problem. \n%\n% Discussion:\n%\n% Note, however, that the location of the nodes\n% is done outside of this routine, and, in fact, before this\n% routine is called.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, integer IBC.\n% IBC declares what the boundary conditions are.\n% 1, at the left endpoint, U has the value UL,\n% at the right endpoint, U' has the value UR.\n% 2, at the left endpoint, U' has the value UL,\n% at the right endpoint, U has the value UR.\n% 3, at the left endpoint, U has the value UL,\n% and at the right endpoint, U has the value UR.\n% 4, at the left endpoint, U' has the value UL,\n% at the right endpoint U' has the value UR.\n%\n% Input, integer N\n% The number of subintervals into which the interval\n% [XL,XR] is broken.\n%\n% Input, integer NL.\n% The number of basis functions used in a single\n% subinterval. (NL-1) is the degree of the polynomials\n% used. For this code, NL is fixed at 2, meaning that\n% piecewise linear functions are used as the basis.\n%\n% Input, integer NMAX, the maximum number of unknowns that can be handled.\n%\n% Input, integer NQUAD\n% The number of quadrature points used in a subinterval.\n%\n% Input, real XN(0:N).\n% XN(I) is the location of the I-th node. XN(0) is XL,\n% and XN(N) is XR.\n%\n% Output, real H(N)\n% H(I) is the length of subinterval I. This code uses\n% equal spacing for all the subintervals.\n%\n% Output, integer INDX(0:N).\n% For a node I, INDX(I) is the index of the unknown\n% associated with node I.\n% If INDX(I) is equal to -1, then no unknown is associated\n% with the node, because a boundary condition fixing the\n% value of U has been applied at the node instead.\n% Unknowns are numbered beginning with 1.\n% If IBC is 2 or 4, then there is an unknown value of U\n% at node 0, which will be unknown number 1. Otherwise,\n% unknown number 1 will be associated with node 1.\n% If IBC is 1 or 4, then there is an unknown value of U\n% at node N, which will be unknown N or N+1,\n% depending on whether there was an unknown at node 0.\n%\n% Output, integer NODE(NL,N).\n% For each subinterval I:\n% NODE(1,I) is the number of the left node, and\n% NODE(2,I) is the number of the right node.\n%\n% Output, integer NU.\n% NU is the number of unknowns in the linear system.\n% Depending on the value of IBC, there will be N-1,\n% N, or N+1 unknown values, which are the coefficients\n% of basis functions.\n%\n% Output, real WQUAD(NQUAD).\n% WQUAD(I) is the weight associated with the I-th point\n% of an NQUAD point Gaussian quadrature rule.\n%\n% Output, real XQUAD(NQUAD,NMAX), the I-th quadrature point\n% in interval J.\n%\n\n%\n% Store in NODE the fact that interval I has node I-1\n% as its left endpoint, and node I as its right endpoint.\n%\n for i = 1 : n\n node(1,i) = i-1;\n node(2,i) = i;\n end\n%\n% For every node that is associated with an unknown, we\n% record the number of the unknown in INDX.\n%\n nu = 0;\n\n for i = 0 : n\n\n if ( i == 0 & ( ibc == 1 | ibc == 3 ) )\n indx(i+1) = -1;\n elseif ( i == n & ( ibc == 2 | ibc == 3 ) )\n indx(i+1) = -1;\n else\n nu = nu + 1;\n indx(i+1) = nu;\n end\n\n end\n%\n% We compute the width of each interval.\n%\n for i = 1 : n\n igl = node(1,i);\n igr = node(2,i);\n h(i) = xn(igr+1) - xn(igl+1);\n end\n%\n% We compute the location of the quadrature points in each\n% interval.\n%\n for i = 1 : n\n\n xl = xn(node(1,i)+1);\n xr = xn(node(2,i)+1);\n\n if ( nquad == 1 )\n xquad(1,i) = 0.5 * ( xl + xr );\n elseif ( nquad == 2 )\n alfa = -0.577350;\n xquad(1,i) = ( ( 1.0 - alfa ) * xl ...\n + ( 1.0 + alfa ) * xr ) ...\n / 2.0;\n alfa = +0.577350;\n xquad(2,i) = ( ( 1.0 - alfa ) * xl ...\n + ( 1.0 + alfa ) * xr ) ...\n / 2.0;\n elseif ( nquad == 3 )\n alfa = -0.774597;\n xquad(1,i) = ( ( 1.0 - alfa ) * xl ...\n + ( 1.0 + alfa ) * xr ) ...\n / 2.0;\n xquad(2,i) = 0.5 * ( xl + xr );\n alfa = +0.774597;\n xquad(3,i) = ( ( 1.0 - alfa ) * xl ...\n + ( 1.0 + alfa ) * xr ) ...\n / 2.0;\n end\n\n end\n%\n% Store the weights for the quadrature rule.\n%\n if ( nquad == 1 )\n wquad(1) = 1.0;\n elseif ( nquad == 2 )\n wquad(1) = 0.5;\n wquad(2) = 0.5;\n elseif ( nquad == 3 )\n wquad(1) = 4.0 / 9.0;\n wquad(2) = 5.0 / 18.0;\n wquad(3) = 4.0 / 9.0;\n end\n\n return\nend\nfunction alpha = get_alpha ( )\n\n%*****************************************************************************80\n%\n%% GET_ALPHA returns the value of ALPHA, for use by problem 6.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Output, real ALPHA, the value of ALPHA.\n%\n alpha = 0.01;\n\n return\nend\nfunction beta = get_beta ( )\n\n%*****************************************************************************80\n%\n%% GET_BETA returns the value of BETA, for use by problem 5.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 February 2014\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Output, real BETA, the value of BETA.\n%\n beta = -0.9;\n\n return\nend\nfunction problem = get_problem ( )\n\n%*****************************************************************************80\n%\n%% GETPRB returns the value of the current problem number.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Output, integer PROBLEM, the index of the problem.\n%\n problem = 6;\n\n return\nend\nfunction [ ibc, tol, ul, ur, xl, xn, xr ] = init ( n )\n\n%*****************************************************************************80\n%\n%% INIT initializes some parameters that define the problem.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, integer N\n% The number of subintervals into which the interval\n% [XL,XR] is broken.\n%\n% Output, integer IBC.\n% IBC declares what the boundary conditions are.\n% 1, at the left endpoint, U has the value UL,\n% at the right endpoint, U' has the value UR.\n% 2, at the left endpoint, U' has the value UL,\n% at the right endpoint, U has the value UR.\n% 3, at the left endpoint, U has the value UL,\n% and at the right endpoint, U has the value UR.\n% 4, at the left endpoint, U' has the value UL,\n% at the right endpoint U' has the value UR.\n%\n% Output, real TOL.\n% A tolerance that is used to determine whether the estimated\n% error in an interval is so large that it should be subdivided\n% and the problem solved again.\n%\n% Output, real UL.\n% If IBC is 1 or 3, UL is the value that U is required\n% to have at X = XL.\n% If IBC is 2 or 4, UL is the value that U' is required\n% to have at X = XL.\n%\n% Output, real UR.\n% If IBC is 2 or 3, UR is the value that U is required\n% to have at X = XR.\n% If IBC is 1 or 4, UR is the value that U' is required\n% to have at X = XR.\n%\n% Output, real XL.\n% XL is the left endpoint of the interval over which the\n% differential equation is being solved.\n%\n% Output, real XN(0:N).\n% XN(I) is the location of the I-th node. XN(0) is XL,\n% and XN(N) is XR.\n%\n% Output, real XR.\n% XR is the right endpoint of the interval over which the\n% differential equation is being solved.\n%\n tol = 0.01;\n%\n% Find out which problem we're working on.\n%\n problem = get_problem ( );\n%\n% Set the boundary conditions for the problem, and\n% print out its title.\n%\n if ( problem == 1 )\n\n ibc = 3;\n ul = 0.0;\n ur = 1.0;\n xl = 0.0;\n xr = 1.0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Exact solution is U = X\\n' );\n\n elseif ( problem == 2 )\n\n ibc = 3;\n ul = 0.0;\n ur = 1.0;\n xl = 0.0;\n xr = 1.0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Exact solution is U = X*X\\n' );\n\n elseif ( problem == 3 )\n\n ibc = 3;\n ul = 0.0;\n ur = 1.0;\n xl = 0.0;\n xr = 1.0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Exact solution is U = SIN(PI*X/2)\\n' );\n\n elseif ( problem == 4 )\n\n ibc = 3;\n ul = 1.0;\n ur = 0.0;\n xl = 0.0;\n xr = 1.0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Exact solution is U = COS(PI*X/2)\\n' );\n\n elseif ( problem == 5 )\n\n ibc = 3;\n beta = get_beta ( 'DUMMY' );\n ul = 0.0;\n ur = 1.0 / ( ( beta + 2.0 ) * ( beta + 1.0 ) );\n xl = 0.0;\n xr = 1.0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Rheinboldt problem\\n' );\n\n elseif ( problem == 6 )\n\n ibc = 3;\n alpha = get_alpha ( );\n xl = 0.0;\n xr = 1.0;\n ul = uexact ( xl );\n ur = uexact ( xr );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Arctangent problem\\n' );\n\n end\n%\n% The nodes are defined here, and not in the geometry routine.\n% This is because each new iteration chooses the location\n% of the new nodes in a special way.\n%\n for i = 0 : n\n xn(i+1) = ( ( n - i ) * xl ...\n + ( i ) * xr ) ...\n / ( n );\n end\n\n fprintf ( 1, 'The equation is to be solved for\\n' );\n fprintf ( 1, 'X greater than %f\\n', xl );\n fprintf ( 1, ' and less than %f\\n', xr );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'The boundary conditions are:\\n' );\n fprintf ( 1, '\\n' );\n\n if ( ibc == 1 | ibc == 3 )\n fprintf ( 1, ' At X = XL, U = %f\\n', ul );\n else\n fprintf ( 1, ' At X = XL, U'' = %f\\n', ul );\n end\n\n if ( ibc == 2 | ibc == 3 )\n fprintf ( 1, ' At X = XR, U = %f\\n', ur );\n else\n fprintf ( 1, ' At X = XR, U'' %f\\n= ', ur );\n end\n\n return\nend\nfunction output ( f, ibc, indx, n, nu, ul, ur, xn )\n\n%*****************************************************************************80\n%\n%% OUTPUT prints out the computed solution.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, real F(NU).\n% ASSEMBLE stores into F the right hand side of the linear\n% equations.\n% SOLVE replaces those values of F by the solution of the\n% linear equations.\n%\n% Input, integer IBC.\n% IBC declares what the boundary conditions are.\n% 1, at the left endpoint, U has the value UL,\n% at the right endpoint, U' has the value UR.\n% 2, at the left endpoint, U' has the value UL,\n% at the right endpoint, U has the value UR.\n% 3, at the left endpoint, U has the value UL,\n% and at the right endpoint, U has the value UR.\n% 4, at the left endpoint, U' has the value UL,\n% at the right endpoint U' has the value UR.\n%\n% Input, integer INDX(0:N).\n% For a node I, INDX(I) is the index of the unknown\n% associated with node I.\n% If INDX(I) is equal to -1, then no unknown is associated\n% with the node, because a boundary condition fixing the\n% value of U has been applied at the node instead.\n% Unknowns are numbered beginning with 1.\n% If IBC is 2 or 4, then there is an unknown value of U\n% at node 0, which will be unknown number 1. Otherwise,\n% unknown number 1 will be associated with node 1.\n% If IBC is 1 or 4, then there is an unknown value of U\n% at node N, which will be unknown N or N+1,\n% depending on whether there was an unknown at node 0.\n%\n% Input, integer N\n% The number of subintervals into which the interval\n% [XL,XR] is broken.\n%\n% Input, integer NU.\n% NU is the number of unknowns in the linear system.\n% Depending on the value of IBC, there will be N-1,\n% N, or N+1 unknown values, which are the coefficients\n% of basis functions.\n%\n% Input, real UL.\n% If IBC is 1 or 3, UL is the value that U is required\n% to have at X = XL.\n% If IBC is 2 or 4, UL is the value that U' is required\n% to have at X = XL.\n%\n% Input, real UR.\n% If IBC is 2 or 3, UR is the value that U is required\n% to have at X = XR.\n% If IBC is 1 or 4, UR is the value that U' is required\n% to have at X = XR.\n%\n% Input, real XN(0:N).\n% XN(I) is the location of the I-th node. XN(0) is XL,\n% and XN(N) is XR.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Node X(I) U(X(I)) Uexact Error\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 0 : n\n\n if ( i == 0 )\n\n if ( ibc == 1 | ibc == 3 )\n u = ul;\n else\n u = f(indx(i+1));\n end\n\n elseif ( i == n )\n\n if ( ibc == 2 | ibc == 3 )\n u = ur;\n else\n u = f(indx(i+1));\n end\n\n else\n\n u = f(indx(i+1));\n\n end\n\n uex = uexact ( xn(i+1) );\n error = u - uex;\n\n fprintf ( 1, ' %4d %12f %12f %12f %12f\\n', i, xn(i+1), u, uex, error );\n\n end\n\n return\nend\nfunction [ phii, phiix ] = phi ( il, x, xleft, xrite )\n\n%*****************************************************************************80\n%\n%% PHI evaluates a linear basis function and its derivative.\n%\n% Discussion:\n%\n% The functions are evaluated at a point X in an interval. In any\n% interval, there are just two basis functions. The first\n% basis function is a line which is 1 at the left endpoint\n% and 0 at the right. The second basis function is 0 at\n% the left endpoint and 1 at the right.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, integer IL, the local index of the basis function.\n%\n% Input, real X, the evaluation point.\n%\n% Input, real XLEFT, XRITE, the endpoints of the interval.\n%\n% Output, real PHII, PHIIX, the value of the basis function\n% and its derivative.\n%\n if ( xleft <= x & x <= xrite )\n\n if ( il == 1 )\n phii = ( xrite - x ) / ( xrite - xleft );\n phiix = -1.0 / ( xrite - xleft );\n else\n phii = ( x - xleft ) / ( xrite - xleft );\n phiix = 1.0 / ( xrite - xleft );\n end\n%\n% If X is outside of the interval, then the basis function\n% is always zero.\n%\n else\n phii = 0.0;\n phiix = 0.0;\n end\n\n return\nend\nfunction value = pp ( x )\n\n%*****************************************************************************80\n%\n%% PP evaluates the function P in the differential equation.\n%\n% Discussion:\n%\n% The function P(X) occurs in the differential equation:\n%\n% -d/dx ( P(x) * dU(x)/dx ) + Q(x) * U(x) = F(x)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of P(X).\n%\n\n%\n% Find out which problem we're working on.\n%\n problem = get_problem ( );\n\n if ( problem == 1 )\n value = 1.0;\n elseif ( problem == 2 )\n value = 1.0;\n elseif ( problem == 3 )\n value = 1.0;\n elseif ( problem == 4 )\n value = 1.0;\n elseif ( problem == 5 )\n value = 1.0;\n elseif ( problem == 6 )\n value = 1.0;\n end\n\n return\nend\nfunction prsys ( adiag, aleft, arite, f, nu )\n\n%*****************************************************************************80\n%\n%% PRSYS prints out the tridiagonal linear system.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, real ADIAG(NU).\n% ADIAG(I) is the \"diagonal\" coefficient of the I-th\n% equation in the linear system. That is, ADIAG(I) is\n% the coefficient of the I-th unknown in the I-th equation.\n%\n% Input, real ALEFT(NU).\n% ALEFT(I) is the \"left hand\" coefficient of the I-th\n% equation in the linear system. That is, ALEFT(I) is the\n% coefficient of the (I-1)-th unknown in the I-th equation.\n% There is no value in ALEFT(1), since the first equation\n% does not refer to a \"0-th\" unknown.\n%\n% Input, real ARITE(NU).\n% ARITE(I) is the \"right hand\" coefficient of the I-th\n% equation in the linear system. ARITE(I) is the coefficient\n% of the (I+1)-th unknown in the I-th equation. There is\n% no value in ARITE(NU) because the NU-th equation does not\n% refer to an \"NU+1\"-th unknown.\n%\n% Input, real F(NU).\n% ASSEMBLE stores into F the right hand side of the linear\n% equations.\n% SOLVE replaces those values of F by the solution of the\n% linear equations.\n%\n% integer NU.\n% NU is the number of unknowns in the linear system.\n% Depending on the value of IBC, there will be N-1,\n% N, or N+1 unknown values, which are the coefficients\n% of basis functions.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Printout of tridiagonal linear system:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Equation A-Left A-Diag A-Rite RHS\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : nu\n if ( i == 1 )\n fprintf ( 1, '%3d %12f %12f %12f\\n', ...\n i, adiag(i), arite(i), f(i) );\n elseif ( i < nu )\n fprintf ( 1, '%3d %12f %12f %12f %12f\\n', ...\n i, aleft(i), adiag(i), arite(i), f(i) );\n else\n fprintf ( 1, '%3d %12f %12f %12f\\n', ...\n i, aleft(i), adiag(i), f(i) );\n end\n end\n\n return\nend\nfunction value = qq ( x )\n\n%*****************************************************************************80\n%\n%% QQ evaluates the function Q in the differential equation.\n%\n% Discussion:\n%\n% The function Q(X) occurs in the differential equation:\n%\n% -d/dx ( P(x) * dU(x)/dx ) + Q(x) * U(x) = F(x)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of Q(X).\n%\n\n%\n% Find out which problem we're working on.\n%\n problem = get_problem ( );\n\n if ( problem == 1 )\n value = 0.0;\n elseif ( problem == 2 )\n value = 0.0;\n elseif ( problem == 3 )\n value = 0.0;\n elseif ( problem == 4 )\n value = 0.0;\n elseif ( problem == 5 )\n value = 1.0;\n elseif ( problem == 6 )\n value = 0.0;\n end\n\n return\nend\nfunction u = solve ( adiag, aleft, arite, f, nu )\n\n%*****************************************************************************80\n%\n%% SOLVE solves a tridiagonal matrix system of the form A*x = b.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, real ADIAG(NU), ALEFT(NU), ARITE(NU).\n% the diagonal, left and right entries of the equations.\n%\n% Input, real F(NU), the right hand side of the linear system.\n%\n% Input, INTEGER NU, the number of equations to be solved.\n%\n% Output, real U(NU), the solution of the linear system.\n%\n\n%\n% Handle the special case of a single equation.\n%\n if ( nu == 1 )\n\n u(1) = f(1) / adiag(1);\n%\n% The general case, when NU is greater than 1.\n%\n else\n\n arite(1) = arite(1) / adiag(1);\n for i = 2 : nu-1\n adiag(i) = adiag(i) - aleft(i) * arite(i-1);\n arite(i) = arite(i) / adiag(i);\n end\n adiag(nu) = adiag(nu) - aleft(nu) * arite(nu-1);\n\n u(1) = f(1) / adiag(1);\n for i = 2 : nu\n u(i) = ( f(i) - aleft(i) * u(i-1) ) / adiag(i);\n end\n\n for i = nu-1 : -1 : 1\n u(i) = u(i) - arite(i) * u(i+1);\n end\n\n end\n\n return\nend\nfunction [ u, h, nu ] = solvex ( ibc, kount, n, nl, nmax, ul, ur, xn )\n\n%*****************************************************************************80\n%\n%% SOLVEX discretizes and solves a differential equation given the nodes.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, integer IBC.\n% IBC declares what the boundary conditions are.\n% 1, at the left endpoint, U has the value UL,\n% at the right endpoint, U' has the value UR.\n% 2, at the left endpoint, U' has the value UL,\n% at the right endpoint, U has the value UR.\n% 3, at the left endpoint, U has the value UL,\n% and at the right endpoint, U has the value UR.\n% 4, at the left endpoint, U' has the value UL,\n% at the right endpoint U' has the value UR.\n%\n% Input, integer KOUNT, the number of adaptive steps that have been taken.\n%\n% Input, integer N\n% The number of subintervals into which the interval\n% [XL,XR] is broken.\n%\n% Input, integer NL.\n% The number of basis functions used in a single\n% subinterval. (NL-1) is the degree of the polynomials\n% used. For this code, NL is fixed at 2, meaning that\n% piecewise linear functions are used as the basis.\n%\n% Input, integer NMAX, the maximum number of unknowns that can be handled.\n%\n% Input, real UL.\n% If IBC is 1 or 3, UL is the value that U is required\n% to have at X = XL.\n% If IBC is 2 or 4, UL is the value that U' is required\n% to have at X = XL.\n%\n% Input, real UR.\n% If IBC is 2 or 3, UR is the value that U is required\n% to have at X = XR.\n% If IBC is 1 or 4, UR is the value that U' is required\n% to have at X = XR.\n%\n% Input, real XN(0:N).\n% XN(I) is the location of the I-th node. XN(0) is XL,\n% and XN(N) is XR.\n%\n% Output, real U(NU), the finite element coefficients of the\n% solution of the differential equation.\n%\n% Output, real H(N)\n% H(I) is the length of subinterval I. This code uses\n% equal spacing for all the subintervals.\n%\n% Output, integer NU.\n% NU is the number of unknowns in the linear system.\n% Depending on the value of IBC, there will be N-1,\n% N, or N+1 unknown values, which are the coefficients\n% of basis functions.\n%\n% Local parameters:\n%\n% Local, real ADIAG(NU).\n% ADIAG(I) is the \"diagonal\" coefficient of the I-th\n% equation in the linear system. That is, ADIAG(I) is\n% the coefficient of the I-th unknown in the I-th equation.\n%\n% Local, real ALEFT(NU).\n% ALEFT(I) is the \"left hand\" coefficient of the I-th\n% equation in the linear system. That is, ALEFT(I) is the\n% coefficient of the (I-1)-th unknown in the I-th equation.\n% There is no value in ALEFT(1), since the first equation\n% does not refer to a \"0-th\" unknown.\n%\n% Local, real ARITE(NU).\n% ARITE(I) is the \"right hand\" coefficient of the I-th\n% equation in the linear system. ARITE(I) is the coefficient\n% of the (I+1)-th unknown in the I-th equation. There is\n% no value in ARITE(NU) because the NU-th equation does not\n% refer to an \"NU+1\"-th unknown.\n%\n% Local, integer INDX(0:N).\n% For a node I, INDX(I) is the index of the unknown\n% associated with node I.\n% If INDX(I) is equal to -1, then no unknown is associated\n% with the node, because a boundary condition fixing the\n% value of U has been applied at the node instead.\n% Unknowns are numbered beginning with 1.\n% If IBC is 2 or 4, then there is an unknown value of U\n% at node 0, which will be unknown number 1. Otherwise,\n% unknown number 1 will be associated with node 1.\n% If IBC is 1 or 4, then there is an unknown value of U\n% at node N, which will be unknown N or N+1,\n% depending on whether there was an unknown at node 0.\n%\n% Local, integer NODE(NL,N).\n% For each subinterval I:\n% NODE(1,I) is the number of the left node, and\n% NODE(2,I) is the number of the right node.\n%\n% Local, integer NQUAD\n% The number of quadrature points used in a subinterval.\n%\n% Local, real WQUAD(NQUAD).\n% WQUAD(I) is the weight associated with the I-th point\n% of an NQUAD point Gaussian quadrature rule.\n%\n% Local, real XQUAD(NQUAD,NMAX), the I-th quadrature point\n% in interval J.\n%\n nquad = 2;\n%\n% Given a set of N nodes (where N increases on each iteration),\n% compute the other geometric information.\n%\n [ h, indx, node, nu, wquad, xquad ] = geometry ( ibc, n, nl, nmax, nquad, xn );\n%\n% Assemble the linear system.\n%\n [ adiag, aleft, arite, f ] = assemble ( h, n, indx, node, nu, nl, ...\n nquad, nmax, ul, ur, wquad, xn, xquad );\n%\n% Print out the linear system, just once.\n%\n if ( kount == 1 )\n prsys ( adiag, aleft, arite, f, nu );\n end\n%\n% Solve the linear system.\n%\n u = solve ( adiag, aleft, arite, f, nu );\n%\n% Print out the solution.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Basic solution\\n' );\n\n output ( u, ibc, indx, n, nu, ul, ur, xn );\n\n return\nend\nfunction eta = solvey ( u, h, n, nu, ul, ur, xn )\n\n%*****************************************************************************80\n%\n%% SOLVEY computes error estimators for a finite element solution.\n%\n% Discussion:\n%\n% SOLVEY accepts information about the solution of a finite element\n% problem on a grid of nodes with coordinates XN. It then starts\n% at node 0, and for each node, computes two \"error estimators\",\n% one for the left, and one for the right interval associated with the\n% node. These estimators are found by solving a finite element problem\n% over the two intervals, using the known values of the original\n% solution as boundary data, and using a mesh that is \"slightly\"\n% refined over the original one.\n%\n% Note that the computations at the 0-th and N-th nodes only involve\n% a single interval.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, real U(NU), the finite element representation of the\n% solution of the current problem.\n%\n% Input, real H(N)\n% H(I) is the length of subinterval I. This code uses\n% equal spacing for all the subintervals.\n%\n% Input, integer N\n% The number of subintervals into which the interval\n% [XL,XR] is broken.\n%\n% Input, integer NU.\n% NU is the number of unknowns in the linear system.\n% Depending on the value of IBC, there will be N-1,\n% N, or N+1 unknown values, which are the coefficients\n% of basis functions.\n%\n% Input, real UL.\n% If IBC is 1 or 3, UL is the value that U is required\n% to have at X = XL.\n% If IBC is 2 or 4, UL is the value that U' is required\n% to have at X = XL.\n%\n% Input, real UR.\n% If IBC is 2 or 3, UR is the value that U is required\n% to have at X = XR.\n% If IBC is 1 or 4, UR is the value that U' is required\n% to have at X = XR.\n%\n% Input, real XN(0:N).\n% XN(I) is the location of the I-th node. XN(0) is XL,\n% and XN(N) is XR.\n%\n% Output, real ETA(N).\n% ETA(I) is the error estimate for interval I. It is computed\n% as the sum of two quantities, one associated with the left\n% and one with the right node of the interval.\n%\n nl = 2;\n ny = 2;\n nquad = 2;\n nmay = 2 * ny;\n%\n% Initialize the error estimators to zero.\n%\n eta(1:n) = 0.0;\n%\n% Set the boundary conditions for each subproblem to be\n% known values of U at the left and right.\n%\n%\n% For each node, subdivide its left and right hand intervals\n% into NY subintervals.\n%\n% Set up and solve the differential equation again on this\n% smaller region.\n%\n% The 0-th and N-th nodes are special cases.\n%\n ibcy = 3;\n\n for j = 0 : n\n\n if ( j == 0 )\n m = ny;\n jlo = j;\n jmid = j + 1;\n jhi = j + 1;\n elseif ( j == n )\n m = ny;\n jlo = j - 1;\n jmid = j;\n jhi = j;\n else\n m = 2 * ny;\n jlo = j - 1;\n jmid = j;\n jhi = j + 1;\n end\n%\n% Set the location of the nodes in the subintervals.\n%\n yl = xn(jlo+1);\n ym = xn(jmid+1);\n yr = xn(jhi+1);\n\n for i = 0 : ny\n yn(i+1) = ( ( ny - i ) * yl ...\n + ( i ) * ym ) ...\n / ( ny );\n end\n\n for i = ny+1 : m\n yn(i+1) = ( ( m - i ) * ym ...\n + ( i - ny ) * yr ) ...\n / ( m - ny );\n end\n%\n% Set up the geometry of the sub-problem.\n%\n [ hy, indy, nodey, nuy, wquad, xquady ] = geometry ( ibcy, m, nl, ...\n nmay, nquad, yn );\n%\n% Set the boundary values for the sub-problem.\n%\n if ( j <= 1 )\n uly = ul;\n else\n uly = u(j-1);\n end\n\n if ( n - 1 <= j )\n ury = ur;\n else\n ury = u(j+1);\n end\n%\n% Assemble the matrix for the sub-problem.\n%\n [ adiag, aleft, arite, fy ] = assemble ( hy, m, indy, nodey, nuy, nl, ...\n nquad, nmay, uly, ury, wquad, yn, xquady );\n%\n% Solve the system.\n%\n uy = solve ( adiag, aleft, arite, fy, nuy );\n%\n% Compute the weighted sum of the squares of the differences\n% of the original computed slope and the refined computed slopes.\n%\n% Calculation for left interval.\n%\n if ( 1 <= j )\n\n if ( j <= 1 )\n uleft = ul;\n urite = u(1);\n elseif ( j == n )\n uleft = u(j-1);\n urite = ur;\n else\n uleft = u(j-1);\n urite = u(j);\n end\n\n uprime = ( urite - uleft ) / h(j);\n\n total = 0.0;\n for i = 1 : ny\n\n yl = yn(i-1+1);\n yr = yn(i+1);\n\n if ( i == 1 )\n vlval = uly;\n vrval = uy(i);\n elseif ( i == m )\n vlval = uy(i-1);\n vrval = ury;\n else\n vlval = uy(i-1);\n vrval = uy(i);\n end\n\n vprime = ( vrval - vlval ) / hy(i);\n\n ulval = ( real ( ny - i + 1 ) * uleft ...\n + real ( i - 1 ) * urite ) ...\n / real ( ny );\n\n urval = ( real ( ny - i ) * uleft ...\n + real ( i ) * urite ) ...\n / real ( ny );\n%\n% Compute the integral of\n%\n% p(x)*(u'(x)-v'(x))^2 + q(x)*(u(x)-v(x))^2\n%\n for k = 1 : nquad\n\n y = xquady(k,i);\n\n uval = ( ( yl - y ) * urval ...\n + ( y - yr ) * ulval ) ...\n / ( yl - yr );\n\n vval = ( ( yl - y ) * vrval ...\n + ( y - yr ) * vlval ) ...\n / ( yl - yr );\n\n total = total + 0.5 * wquad(k) * hy(i) * ...\n ( pp ( y ) * ( uprime - vprime )^2 ...\n + qq ( y ) * ( uval - vval )^2 );\n\n end\n\n end\n\n eta(j) = eta(j) + 0.5 * sqrt ( total );\n\n end\n%\n% Calculation for right interval.\n%\n if ( j <= n - 1 )\n\n if ( j == 0 )\n uleft = ul;\n urite = u(j+1);\n elseif ( n - 1 <= j )\n uleft = u(j);\n urite = ur;\n else\n uleft = u(j);\n urite = u(j+1);\n end\n\n uprime = ( urite - uleft ) / h(j+1);\n\n total = 0.0;\n for i = m+1-ny : m\n\n yl = yn(i);\n yr = yn(i+1);\n\n if ( i == 1 )\n vlval = uly;\n vrval = uy(i);\n elseif ( i == m )\n vlval = uy(i-1);\n vrval = ury;\n else\n vlval = uy(i-1);\n vrval = uy(i);\n end\n\n vprime = ( vrval - vlval ) / hy(i);\n\n ulval = ( ( m - i + 1 ) * uleft ...\n + ( ny - m + i - 1 ) * urite ) ...\n / ( ny );\n\n urval = ( ( m - i ) * uleft ...\n + ( ny - m + i ) * urite ) ...\n / ( ny );\n%\n% Compute the integral of\n%\n% p(x)*(u'(x)-v'(x))^2 + q(x)*(u(x)-v(x))^2\n%\n for k = 1 : nquad\n\n y = xquady(k,i);\n\n uval = ( ( yl - y ) * urval ...\n + ( y - yr ) * ulval ) ...\n / ( yl - yr );\n\n vval = ( ( yl - y ) * vrval ...\n + ( y - yr ) * vlval ) ...\n / ( yl - yr );\n \n total = total + 0.5 * wquad(k) * hy(i) * ...\n ( pp ( y ) * ( uprime - vprime )^2 ...\n + qq ( y ) * ( uval - vval )^2 );\n\n end\n\n end\n\n eta(j+1) = eta(j+1) + 0.5 * sqrt ( total );\n\n end\n\n end\n%\n% Print out the error estimators.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ETA\\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : n\n fprintf ( 1, ' %12f\\n', eta(j) );\n end\n\n return\nend\nfunction [ n, xn, status ] = subdiv ( eta, kount, n, nmax, tol, xn )\n\n%*****************************************************************************80\n%\n%% SUBDIV decides which intervals should be subdivided.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 November 2006\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Parameters:\n%\n% Input, real ETA(N).\n% ETA(I) is the error estimate for interval I. It is computed\n% as the sum of two quantities, one associated with the left\n% and one with the right node of the interval.\n%\n% Input, integer KOUNT, the number of adaptive steps that have been taken.\n%\n% Input, integer N\n% The number of subintervals into which the interval\n% [XL,XR] is broken. \n%\n% Input, integer NMAX, the maximum number of unknowns that can be handled.\n%\n% Input, real TOL.\n% A tolerance that is used to determine whether the estimated\n% error in an interval is so large that it should be subdivided\n% and the problem solved again.\n%\n% Input, real XN(0:N).\n% XN(I) is the location of the I-th node. XN(0) is XL,\n% and XN(N) is XR.\n%\n% Output, integer N, the updated number of nodes.\n%\n% Output, real XN(0:N), the updated nodes.\n%\n% Output, integer STATUS, reports status of subdivision.\n% 0, a new subdivision was carried out.\n% 1, no more subdivisions are needed.\n% -1, no more subdivisions can be carried out.\n%\n% Local Parameters:\n%\n% Local, integer JADD(N).\n% JADD(I) is 1 if the error estimates show that interval I\n% should be subdivided.\n%\n status = 0;\n%\n% Add up the ETA's, and get their average.\n%\n ave = sum ( eta(1:n) ) / n;\n%\n% Look for intervals whose ETA value is relatively large,\n% and note in JADD that these intervals should be subdivided.\n%\n k = 0;\n temp = max ( 1.2 * ave + 0.00001, tol^2 / n );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'Tolerance = %f\\n', temp );\n fprintf ( 1, '\\n' );\n\n for j = 1 : n\n\n if ( temp < eta(j) )\n k = k + 1;\n jadd(j) = 1;\n fprintf ( 1, 'Subdivide interval %d\\n', j );\n else\n jadd(j) = 0;\n end\n\n end\n%\n% If no subdivisions needed, we're done.\n%\n if ( k <= 0 )\n fprintf ( 1, 'Success on step %d\\n', kount );\n status = 1;\n return\n end\n%\n% See if we're about to go over our limit.\n%\n if ( nmax < n + k )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'The iterations did not reach their goal.\\n' );\n fprintf ( 1, 'The next value of N is %d\\n', n + k );\n fprintf ( 1, 'which exceeds NMAX = %d\\n', nmax );\n status = -1;\n return\n end\n%\n% Insert new nodes where needed.\n%\n k = 0;\n xt(1) = xn(1);\n for j = 1 : n\n\n if ( 0 < jadd(j) )\n xt(j+k+1) = 0.5 * ( xn(j+1) + xn(j) );\n k = k + 1;\n end\n\n xt(j+k+1) = xn(j+1);\n\n end\n%\n% Update the value of N, and copy the new nodes into XN.\n%\n n = n + k;\n\n xn(1:n+1) = xt(1:n+1);\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\nfunction value = uexact ( x )\n\n%*****************************************************************************80\n%\n%% UEXACT returns the value of the exact solution at any point X.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 November 2006\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n%\n% Output, real VALUE, the value of the exact solution at X.\n%\n\n%\n% Find out which problem we're working on.\n%\n problem = get_problem ( );\n\n if ( problem == 1 )\n value = x;\n elseif ( problem == 2 )\n value = x^2;\n elseif ( problem == 3 )\n value = sin ( pi * x / 2.0 );\n elseif ( problem == 4 )\n value = cos ( pi * x / 2.0 );\n elseif ( problem == 5 )\n beta = get_beta ( );\n value = ( x^( beta + 2.0 ) ) ...\n / ( ( beta + 2.0 ) * ( beta + 1.0 ) );\n elseif ( problem == 6 )\n alpha = get_alpha ( );\n value = atan ( ( x - 0.5 ) / alpha );\n else\n value = 0.0;\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/fem1d_adaptive/fem1d_adaptive.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7111659250071317}} {"text": "function [ x, w ] = rule03 ( n )\n\n%*****************************************************************************80\n%\n%% RULE03 returns the rule of degree 3.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 July 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This 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 N, the number of nodes.\n%\n% Output, real X(2,N), the coordinates of the nodes.\n%\n% Output, real W(N), the weights.\n%\n xs = [ ...\n -.5773502691896256,0.5773502691896260, ...\n 0.5773502691896256,-.5773502691896260 ];\n ys = [ ...\n -.5773502691896260,-.5773502691896256, ...\n 0.5773502691896260,0.5773502691896256 ];\n ws = [ ...\n 0.7071067811865476,0.7071067811865476, ...\n 0.7071067811865476,0.7071067811865476 ];\n\n x(1,1:n) = xs(1:n);\n x(2,1:n) = ys(1:n);\n w(1:n) = ws(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/square_arbq_rule/rule03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7111659144695399}} {"text": "function rotMat = matRad_getRotationMatrix(gantryAngle,couchAngle,system)\n% matRad function to return the rotation / transformation matrix \n% for gantry and/or couch rotation. The Rotation matrix stands for a (1)\n% counter-clockwise, (2) active rotation in the patient coordinate system\n% that is performed on a (4) column vector (by premultiplying the matrix). \n% Per change of one of these directions a matrix transpose of the returned \n% matrix is required.\n% \n% \n% call\n% rotMat = matRad_getRotationMatrix(gantryAngle,couchAngle,type,system)\n%\n% input\n% gantryAngle: beam/gantry angle\n% couchAngle: couch angle \n%\n% system: optional coordinate system the transformation matrix is\n% requested for. So far, only the default option 'LPS' is\n% supported (right handed system).\n%\n% output\n% rotMat: 3x3 matrix that performs an active rotation around the \n% patient system origin via rotMat * x\n%\n% References\n% https://en.wikipedia.org/wiki/Rotation_matrix (2017, Mar 1)\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright 2015 the matRad development team. \n% \n% This file is part of the matRad project. It is subject to the license \n% terms in the LICENSE file found in the top-level directory of this \n% distribution and at https://github.com/e0404/matRad/LICENSES.txt. No part \n% of the matRad project, including this file, may be copied, modified, \n% propagated, or distributed except according to the terms contained in the \n% LICENSE file.\n%\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% Parse arguments\n%We need at least two and max 3 input arguments\nnarginchk(2,3);\n\n% Coordinate System (only LPS so far)\nif nargin < 3\n system = 'LPS';\nend\n\n%% Set Up requested Rotation Matrix\nswitch system\n case 'LPS'\n %The LPS system is right-handed, gantry rotates counter-clockwise \n %around z and couch rotates counter-clockwise around y\n \n %active, counter-clockwise rotation Matrix for Gantry around z \n %with pre-multiplication of the matrix (R*x)\n %Note: Gantry rotation is physically an active rotation of a beam \n %vector around the target / isocenterin the patient coordinate\n %system\n R_Gantry = [cosd(gantryAngle) -sind(gantryAngle) 0; ...\n sind(gantryAngle) cosd(gantryAngle) 0; ...\n 0 0 1];\n \n %active, counter-clockwise rotation for couch around y\n %with pre-multiplication of the matrix (R*x)\n %Note: Couch rotation is physically a passive rotation of the \n %patient system around the beam target point / isocenter\n R_Couch = [cosd(couchAngle) 0 sind(couchAngle); ...\n 0 1 0; ...\n -sind(couchAngle) 0 cosd(couchAngle)];\n otherwise\n error('matRad only supports LPS system so far');\nend\n\nrotMat = R_Couch*R_Gantry;\n\nend\n\n", "meta": {"author": "e0404", "repo": "matRad", "sha": "0a03aee5ef4a100dbc4bef8927db41b59f44946e", "save_path": "github-repos/MATLAB/e0404-matRad", "path": "github-repos/MATLAB/e0404-matRad/matRad-0a03aee5ef4a100dbc4bef8927db41b59f44946e/matRad_getRotationMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757596, "lm_q2_score": 0.7634837743174789, "lm_q1q2_score": 0.7111565148129315}} {"text": "function utmp = IEC_MANN(Nx,Ny,Nz,delta,UHub,HubHt,IECturbC)\n%%INITIALISATION\n\n% definition of constants\ntwopi=2*pi;\n%constants and derived parameters from IEC\ngamma = 3.9; %IEC, (B.12)\nalpha = 0.2; %IEC, sect. 6.3.1.2\n\n%set delta1 according to guidelines (chap.6)\nif HubHt<=60,\n delta1=0.7*HubHt;\nelse\n delta1=42;\nend;\n\n%IEC, Table 1, p.22\nif IECturbC == 'A',\n Iref=0.16;\nelseif IECturbC == 'B',\n Iref=0.14; \nelseif IECturbC == 'C',\n Iref=0.12;\nelse\n error('IECturbC can be equal to A,B or C;adjust the input value')\nend;\n\n%IEC, sect. 6.3.1.3\nb=5.6;\nsigma1=Iref*(0.75*UHub+b);\nsigma2=0.7*sigma1;\nsigma3=0.5*sigma1;\n%derived constants\nl=0.8*delta1; %IEC, (B.12)\nsigmaiso=0.55*sigma1; %IEC, (B.12)\n\nCij2=zeros(3,3,Nx,Ny,Nz);\nikx=cat(2,-Nx/2:-1,1:Nx/2-1);\n[x y z]=ndgrid(ikx,1:Ny,1:Nz);\nk1=(x)*l/(Nx*delta)*twopi;\nk2=(y-Ny/2)*l/(Ny*delta)*twopi;\nk3=(z-Nz/2)*l/(Nz*delta)*twopi;\nkabs=sqrt(k1.^2+k2.^2+k3.^2);\nbeta= gamma./(kabs.^(2/3).*real(pfq([1/3 17/6],4/3,-kabs.^(-2))));\nk03=k3+beta.*k1;\nk0abs=sqrt(k1.^2+k2.^2+k03.^2);\nEk0=1.453*k0abs.^4./(1+k0abs.^2).^(17/6);\nC1=beta.*k1.^2.*( k0abs.^2 - 2*k03.^2 + beta.*k1.*k03 )./( kabs.^2.*( k1.^2 + k2.^2 ));\nC2=k2.*k0abs.^2./ (exp( (3/2).*log( k1.^2 + k2.^2 ) )) .* atan2( beta.*k1.* sqrt( k1.^2 + k2.^2 ) ,( k0abs.^2 - k03.*k1.*beta));\nxhsi1=C1 - k2.*C2./k1;\nxhsi2=k2.*C1./k1 + C2;\nCC=sigmaiso*sqrt(twopi*pi*l^3.*Ek0./(Nx*Ny*Nz*delta^3.*k0abs.^4));\nCij2(1,1,1:size(k1,1),:,:)= CC.*( k2.*xhsi1);\nCij2(1,2,1:size(k1,1),:,:)= CC.*( k3 - k1.*xhsi1 + beta.*k1);\nCij2(1,3,1:size(k1,1),:,:)= CC.*( -k2);\nCij2(2,1,1:size(k1,1),:,:)= CC.*( k2.*xhsi2 - k3 - beta.*k1);\nCij2(2,2,1:size(k1,1),:,:)= CC.*( -k1.*xhsi2);\nCij2(2,3,1:size(k1,1),:,:)= CC.*( k1);\nCij2(3,1,1:size(k1,1),:,:)= CC.*( k0abs.^2.*k2 ./ (kabs.^2));\nCij2(3,2,1:size(k1,1),:,:)= CC.*( -k0abs.^2.*k1 ./ (kabs.^2));\n%Cij2(isnan(Cij2))=0;\n%% FOURIER COEFFICIENTS\nn=complex(normrnd(0,1,[3 1 Nx Ny Nz]),normrnd(0,1,[3 1 Nx Ny Nz]));\nH = reshape(mtimesx(Cij2,n,'speed'),[],Nx,Ny,Nz);\n%% TIME SERIES\nu(1,:,:,:)=real(fftn(fftshift(H(1,:,:,:))));\nu(2,:,:,:)=real(fftn(fftshift(H(2,:,:,:))));\nu(3,:,:,:)=real(fftn(fftshift(H(3,:,:,:))));\n\nstdDv=zeros(Ny*Nz,3);\nstdDv(:,1)=reshape(std(u(1,:,:,:)),Ny*Nz,1); % Standard deviation for u-component\nstdDv(:,2)=reshape(std(u(2,:,:,:)),Ny*Nz,1); % Standard deviation for v-component\nstdDv(:,3)=reshape(std(u(3,:,:,:)),Ny*Nz,1); % Standard deviation for w-component\n\n% Introduction of a Corrective Factor SF in order to adjust the statistics\n% as advised by the OC4 project DTUs report\n\nsf=zeros(Ny*Nz,3);\nsf(:,1)=sqrt(sigma1^2./(stdDv(:,1).^2));\nsf(:,2)=sqrt((sigma2)^2./(stdDv(:,2).^2));\nsf(:,3)=sqrt((sigma3)^2./(stdDv(:,3).^2));\n\nutmp=zeros(3,Nx,Ny,Nz);\nfor i=1:length(sf),\n for j=1:Ny,\n for k=1:Nz, \n utmp(1,:,j,k)=sf(i,1).*u(1,:,j,k);\n utmp(2,:,j,k)=sf(i,2).*u(2,:,j,k);\n utmp(3,:,j,k)=sf(i,3).*u(3,:,j,k);\n end;\n end;\nend;\nfor i=1:Nz,\n thisZ=HubHt-(Nz*delta)/2+1.*i*(Nz*delta)/(Nz-1);\n profile=UHub*(thisZ/HubHt)^alpha;\n utmp(1,:,:,i)=(utmp(1,:,:,i)+profile); \nend;\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/35722-3d-turbulent-wind-field-by-means-of-the-mann-model/IEC_MANN.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7111565004296524}} {"text": "%%% Projection onto constrained force space + Constraint Stabilization\n\n% Course: Robotic Manipulation and Mobility\n% Advisor: Dr. V. Krovi\n% \n% Homework Number: MIDTERM\n% \n% Names: Sourish Chakravarty \n% \tHrishi Lalit Shah\n\n\nfunction [dX]= ROBO_midterm_f3(t,X)\n\nglobal l1 lc1 m1 j1 tau1 l2 lc2 m2 j2 tau2 g Lambda2 omega zeta\n\nth1=X(1);\nx2=X(2);\ny2=X(3);\nth2=X(4);\n\nth1d= X(5);\nx2d=X(6);\ny2d=X(7);\nth2d= X(8);\n%%%%%%%%%%%%%%%%%%%%%%% CREATING IMPORTANT MATRICES IN THE GOVERNING EQUATION\ns1=sin(th1);\ns2=sin(th2);\nc1=cos(th1);\nc2=cos(th2);\n\n%%%% Element - 1\nM1= [j1+m1*(lc1^2)];\nE1= [1,-1];\nG1= [m1*lc1*c1*g];\n% B11 = [-l1*s1, l1*c1];\n% B12 = [-m1*lc1*c1];\n\n%%%% Element - 2\nM2= [m2, 0, 0;\n 0, m2, 0;\n 0, 0, j2];\nE2= [ 0; 0; 1];\nG2= [0; m2*g; 0];\n% B21= [-1, 0;\n% 0, -1;\n% -lc2*s2, lc2*c2];\n% B22= [0, -m2, 0]'; \n\n%%%% Constraints\nC= [x2-l1*c1-lc2*c2;\n y2-l1*s1-lc2*s2];\nA= [l1*s1, 1, 0, lc2*s2;\n -l1*c1, 0, 1, -lc2*c2];% Jacobian of constraint matrix\nAd = [l1*c1*th1d, 0, 0, lc2*c2*th2d;\n l1*s1*th1d, 0, 0, lc2*s2*th2d]; % Derivative of matrix A\nS = [1, 0;\n -l1*s1, -lc2*s2;\n l1*c1, lc2*c2;\n 0, 1]; % Null space of A or Feasible Motion \nSd = [0, 0;\n -l1*c1*th1d, -lc2*c2*th2d;\n -l1*s1*th1d, -lc2*s2*th2d;\n 0, 0]; % Derivative of S matrix \n\n%%%%%%%%%%%%%%%%%%%%%%% PROJECTION ONTO CONSTRAINED FORCE SPACE USING\n%%%%%%%%%%%%%%%%%%%%%%% CONSTRAINT STABILIZATION\nM=[M1, zeros(1,3);\n zeros(3,1), M2];\nE=[E1;\n zeros(3,1),E2];\nG= [G1;G2];\nT =[tau1; tau2];\nV=zeros(4,1);\n\nQd = [th1d, x2d, y2d, th2d]';\n\nt1= inv([M, A';\n A, zeros(2,2)]); % since m=2;\n% size(Ad)\n% size(2*zeta*A)\n% size((Ad+2*zeta*A)*Qd)\n% size((omega^2)*C)\nt2= [E*T-V-G; -(Ad+2*zeta*A)*Qd-(omega^2)*C];%%% Applying constraint stabilization\nt3= t1*t2;\n\ndX(1:4,1)= [th1d,x2d,y2d,th2d]';\ndX(5:8,1)= t3(1:4);\nlam = t3(5:end);\nLambda2 = [Lambda2;lam];%%% Passing instaneous values of Lagrange multipliers back to main function\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/24246-dynamic-control-of-two-link-manipulator-with-redundant-coordinates/2 Link Dynamic Control/Code/ROBO_f3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.7111523871082239}} {"text": "function u = poisson(varargin)\n%POISSON Poisson solver in the unit ball with Dirichlet or Neumann\n% boundary conditions.\n% U = POISSON(F, BC, M, N, P) is the solution to the Poisson equation in\n% the unit ball with right-hand side F and Dirichlet boundary data\n% U(1,lambda,theta) = @(lambda,theta) BC(lambda, theta). It uses a\n% discretization size of M x N x P.\n%\n% U = POISSON(F, BC, M) is the same as POISSON(F, BC, M, M, M).\n%\n% U = POISSON(F, BC, M, N, P, 'neumann') is the solution to the Poisson \n% equation with right-hand side F and Neuamnn boundary data U(1,lambda,theta) = \n% @(lambda,theta) BC(lambda, theta). It uses a discretization size of M x N x P. \n%\n% U = POISSON(F, BC, M, 'neumann') is the same as POISSON(F, BC, M, M, M, 'neumann').\n%\n% Also see HELMHOLTZ.\n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Call Helmholtz command with zero frequency: \nu = helmholtz(varargin{1}, 0, varargin{2:end});\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@ballfun/poisson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7111523686504707}} {"text": "% Exact solution of Riemann problem; plot adapted to Osher scheme\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\n\ntend = n*dt\t\t\t% Exact time\n\np3 = p34*pright; alpha = (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 (1-(p34*pright/pleft)^((gamma-1)/(2*gamma)));\nc2 = sqrt(gamma*p3/rho2);\n\nspos = 0.5 + ...\t\t% Shock position\n tend*cright*sqrt((gamma-1)/(2*gamma) + (gamma+1)/(2*gamma)*p34) + tend*uright;\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\n\nxx = 0:0.002:1;\t\t\t% Preallocation\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\trhoexact(i) = rho2;\n uexact(i) = u2+uright; \tcexact(i) = sqrt(gamma*pexact(i)/rhoexact(i));\n machexact(i) = uexact(i)/cexact(i);\n elseif xx(i) <= spos\n pexact(i) = p3; \trhoexact(i) = rho3;\n uexact(i) = u2+uright; cexact(i) = sqrt(gamma*pexact(i)/rhoexact(i));\n machexact(i) = uexact(i)/cexact(i);\n else\n pexact(i) = pright; \trhoexact(i) = rhoright;\n uexact(i) = uright; \tcexact(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),\t\tplot(xx,pexact,'-');\nsubplot(2,3,4),\t\tplot(xx,machexact,'-');\nsubplot(2,3,5),\t\tenthexact = (gamma/(gamma-1))*pexact./rhoexact;\n\t\t\tplot(xx,enthexact,'-');\nsubplot(2,3,6),\t\tplot(xx,entroexact,'-');\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/cfdbook/chap10.3457/Riemann_Osher.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7111411429100851}} {"text": "function geometry_test0235 ( )\n\n%*****************************************************************************80\n%\n%% TEST0235 tests DMS_TO_RADIANS, RADIANS_TO_DMS.\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, 'TEST0235\\n' );\n fprintf ( 1, ' DMS_TO_RADIANS converts an angle from\\n' );\n fprintf ( 1, ' degrees/minutes/seconds to radians;\\n' );\n fprintf ( 1, ' RADIANS_TO_DEGREES converts an angle from radians\\n' );\n fprintf ( 1, ' to degrees/minutes/seconds;\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Radians DMS Radians\\n' );\n fprintf ( 1, '\\n' );\n\n for i = -2 : 15\n angle_rad = pi * i / 7.0;\n [ angle_deg, angle_min, angle_sec ] = radians_to_dms ( angle_rad );\n angle_rad2 = dms_to_radians ( angle_deg, angle_min, angle_sec );\n fprintf ( 1, ' %10f %4d %3d %3d %10f\\n', ...\n angle_rad, angle_deg, angle_min, angle_sec, angle_rad2 );\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_test0235.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7110372731696801}} {"text": "function [LMSout,blms,Rsq]=LMSpol(y,p,x)\n%Syntax: [LMSout,blms,Rsq]=LMSpol(y,p,x)\n%_______________________________________\n%\n% Calculates the Least Median of Squares (LMS) polynomial regression\n% parameters and output. It searches all the possible combinations\n% of points and makes the intercept adjustment for every combination.\n%\n% LMSout is the LMS estimated values vector.\n% blms is the LMS [intercept slopes] vector.\n% Rsq is the R-squared.\n% y is the vector of the dependent variable.\n% p is the order of the polynomial.\n% x is the vector of the independent variable.\n%\n% Reference:\n% Rousseeuw PJ, Leroy AM (1987): Robust regression and outlier detection. Wiley.\n%\n%\n% Alexandros Leontitsis\n% Institute of Mathematics and Statistics\n% University of Kent at Canterbury\n% Canterbury\n% Kent, CT2 7NF\n% U.K.\n%\n% University e-mail: al10@ukc.ac.uk (until December 2002)\n% Lifetime e-mail: leoaleq@yahoo.com\n% Homepage: http://www.geocities.com/CapeCanaveral/Lab/1421\n%\n% Sep 3, 2001.\n\nif nargin<1 | isempty(y)==1\n error('Not enough input arguments.');\nelse\n % y must be a column vector\n y=y(:);\n % n is the length of the data set\n n=length(y);\nend\n\nif nargin<2 | isempty(p)==1\n % If p is omitted give it the value of 1\n p=1;\nelse\n % p must be a scalar\n if sum(size(p))>2\n error('p must be a scalar.');\n end \n % p must be a non-negative integrer\n if round(p)-p~=0 | p<0\n error('p must be a non-negative integrer');\n end\nend\n\nif nargin<3 | isempty(x)==1\n % If x is omitted give it the values 1:n\n x=(1:n)';\nelse\n % x must be a column vector\n x=x(:);\n % x and y must have the same length\n if n~=size(x,1)\n error('x and y must have the same length.');\n end\nend\n\nif n<=p\n error('The ploynomial order is too large for the data set.');\nend\n\n% Prepare the matrix X for regression.\nfor i=1:p\n X(:,i)=x.^i;\nend\n\n% Perform the LMS regression\n[LMSout, blms, Rsq]=LMSreg(y,X);\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/801-lms-toolbox/LMSpol.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7109123011427353}} {"text": "function [afixed,sqnorm,Qahat,Z] = lambda_routine1 (afloat,Qahat,ncands,fidlog)\n%LAMBDA1: Integer ambiguity estimation using LAMBDA (extended version)\n%\n% This routine performs an integer ambiguity estimation using the\n% LAMBDA-method, as developed by the Delft University of Technology,\n% Mathematical Geodesy and Positioning.\n%\n% This version (lambda1) is intended to be used mainly for research.\n% It has more options than the original code, such as output of\n% intermediate results, optional number of candidates to be returned\n% and so on. If you are not interested in these options, you can use\n% \"lambda2\"\n%\n% Input arguments:\n% afloat: Float ambiguities (\\hat{a}, must be a column!)\n% Qahat : Variance/covariance matrix of ambiguities (Q_\\hat{a})\n% ncands: Number of candidates to be returned (default 2)\n% fidlog: File-id for intermediate results (default 0, no output)\n%\n% Output arguments:\n% afixed: Estimated integers\n% sqnorm: Distance between candidates and float ambiguity vector\n% Qzhat : Decorrelated variance/covariance matrix\n% Z : Transformation matrix\n\n% ----------------------------------------------------------------------\n% File.....: lambda1.m\n% Date.....: 19-MAY-1999\n% Version..: 2.0b\n% Author...: Peter Joosten\n% Mathematical Geodesy and Positioning\n% Delft University of Technology\n% ----------------------------------------------------------------------\n\n% ----------------------------------------------------------------------\n% Initialise\n% ----------------------------------------------------------------------\n\nif nargin < 3; ncands = 2; end;\nif nargin < 4; fidlog = 0; end;\n\nn = size (Qahat,1);\nafixed = zeros(n,ncands);\nsqnorm = zeros(1,ncands);\n\nif fidlog ~= 0;\n if fidlog == 1; clc; end;\n fprintf (fidlog, '\\n');\n fprintf (fidlog, ' -----------------------------------------------------------------------\\n');\n fprintf (fidlog, ' \"LAMBDA\" - Least Squares Ambiguity Decorrelation Adjustment \\n');\n fprintf (fidlog, ' Rel. 2.0b d.d. 19 MAY 1999 \\n');\n fprintf (fidlog, ' (c) Department of Mathematical Geodesy and Positioning (MGP) \\n');\n fprintf (fidlog, ' Faculty of Civil Engineering and Geosciences \\n');\n fprintf (fidlog, ' Delft University of Technology, The Netherlands \\n');\n fprintf (fidlog, ' -----------------------------------------------------------------------\\n');\n fprintf (fidlog, '\\n');\nend;\n\n% ----------------------------------------------------------------------\n% Display the input-arguments\n% ----------------------------------------------------------------------\n\nwritemat (fidlog,'Original float ambiguities',afloat);\nwritemat (fidlog,'Original variance/covariance matrix (Qahat)',Qahat);\nwritemat (fidlog,'Number of candidates requested',ncands);\n\n% ----------------------------------------------------------------------\n% --- Perform tests on the input, these tests are rather extensive ---\n% --- and can be switched off (by commenting-out) if necessary ---\n% --- Tests: Is the Q-matrix symmetric? ---\n% --- Is the Q-matrix positive-definite? ---\n% --- Do the Q-matrix and ambiguity-vector have identical ---\n% --- dimensions? ---\n% --- Is the ambiguity vector a column? ---\n% ----------------------------------------------------------------------\n\nif ~isequal(Qahat-Qahat'<1E-12,ones(size(Qahat)));\n error ('Variance/covariance matrix is not symmetric!');\nend;\n\nif sum(eig(Qahat)>0) ~= size(Qahat,1);\n error ('Variance/covariance matrix is not positive definite!');\nend;\n\nif length(afloat) ~= size(Qahat,1);\n error (['Variance/covariance matrix and vector of ambiguities do not have' ...\n\t ' identical dimensions!']);\nend;\n\nif size(afloat,2) ~= 1;\n error ('Ambiguity-vector should be a column-vector');\nend;\n\n% ----------------------------------------------------------------------\n% Make estimates in 'a' between -1 and +1 by subtracting an\n% integer number, store the increments in 'incr' (= shift the centre\n% of the ellipsoid over the grid by an integer translation)\n% ----------------------------------------------------------------------\n\nincr = afloat - rem(afloat,1);\nafloat = rem(afloat,1);\nwritemat (fidlog,'shifted ambiguities - increments',[afloat incr]);\n\n% ----------------------------------------------------------------------\n% Compute the Z-transformation based on L and D of Q, ambiguities\n% are transformed according to \\hat{z} = Z^T\\hat{a}, Q is transformed\n% according to Q_\\hat{z} = Z^T * Q_\\hat{a} * Z\n% ----------------------------------------------------------------------\n\n[Qz,Z,L,D,z] = decorrel (Qahat,afloat);\n\nwritemat (fidlog,'Decorrelated Q-matrix',Qz);\nwritemat (fidlog,'Transformation matrix (Z)',Z);\nwritemat (fidlog,'L-matrix, as used in ''search''',L);\nwritemat (fidlog,'D-matrix, as used in ''search''',D);\nwritemat (fidlog,'Transformed reduced ambiguities',z);\n\n% ----------------------------------------------------------------------\n% If the number of requested candidates is no more than \"n+1\", with \"n\"\n% the dimension of Q_\\hat(a), we can compute a suitable Chi^2 such that\n% we have the requested number of candidates at minimum; use an eps\n% to make sure the candidates are inside the ellipsoid and not exactly\n% on the border.\n%\n% If the requested number of canditates is larger, we have to \"guess\"\n% the volume of the search-space, it can not be guarenteed the requested\n% number of canditates will actually be found.\n% ----------------------------------------------------------------------\n\nChi2 = chistart (D,L,afloat,ncands);\nwritemat (fidlog,'Chi-squared, size of the search-ellipsoid',Chi2);\n\n% ----------------------------------------------------------------------\n% Find the requested number of candidates (search)\n% ----------------------------------------------------------------------\n\n[afixed,sqnorm,ierr] = lsearch (afloat,L,D,Chi2,ncands);\n\nif ierr == 1;\n fprintf (1,'Warning: Not enough candidates were found!!\\n');\n fprintf (1,' Requested number.: %2d\\n',ncands);\nend;\n\nwritemat (fidlog,'Fixed transformed ''reduced'' ambiguities',afixed);\nwritemat (fidlog,'Corresponding squared norms',sqnorm);\n\n% ----------------------------------------------------------------------\n% Finally, perform the back-transformation and add the increments\n% ----------------------------------------------------------------------\n\nafixed = (afixed' * inv(Z))';\nafixed = round(afixed + repmat(incr,1,ncands));\nwritemat (fidlog,'Final fixed ambiguities',afixed);\n\n% ----------------------------------------------------------------------\n% End of routine: lambda1\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/positioning/lambda/lambda_v2/lambda_routine1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88242786954645, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.7109122961607721}} {"text": "function [ n_data, n, x, fx ] = w_polynomial_values ( n_data )\n\n%*****************************************************************************80\n%\n%% W_POLYNOMIAL_VALUES returns values of Chebyshev polynomials W(n,x).\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% u = Sqrt[(x+1)/2],\n% ChebyshevU[2*n,u]\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% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, integer N, the order of the function.\n%\n% Output, real X, the point where the function is evaluated.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 13;\n\n fx_vec = [ ...\n 1.000000000000000E+00, ...\n 2.600000000000000E+00, ...\n 3.160000000000000E+00, ...\n 2.456000000000000E+00, ...\n 0.769600000000000E+00, ...\n -1.224640000000000E+00, ...\n -2.729024000000000E+00, ...\n -3.141798400000000E+00, ...\n -2.297853440000000E+00, ...\n -0.534767104000000E+00, ...\n 1.442226073600000E+00, ...\n 2.842328821760000E+00, ...\n 3.105500041216000E+00 ];\n\n n_vec = [ ...\n 0, 1, 2, ...\n 3, 4, 5, ...\n 6, 7, 8, ...\n 9, 10, 11, ...\n 12 ];\n\n x_vec = [ ...\n 0.8E+00, ... \n 0.8E+00, ...\n 0.8E+00, ...\n 0.8E+00, ...\n 0.8E+00, ...\n 0.8E+00, ...\n 0.8E+00, ...\n 0.8E+00, ...\n 0.8E+00, ...\n 0.8E+00, ...\n 0.8E+00, ...\n 0.8E+00, ...\n 0.8E+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 x = 0.0;\n fx = 0.0;\n else\n n = n_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/chebyshev_polynomial/w_polynomial_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7108768432787311}} {"text": "function bti_test03 ( )\n\n%*****************************************************************************80\n%\n%% BTI_TEST03 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_TEST03\\n' );\n fprintf ( 1, ' Test BURGERS_TIME_INVISCID\\n' );\n\n method = 3;\n nx = 81;\n nt = 200;\n t_max = 2.0;\n bc = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Method: 3, Lax Friedrichs.\\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 ( 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, inviscid, initial expansion, Lax Friedrichs' )\n\n filename = 'bti_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_inviscid/bti_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.7108768177468734}} {"text": "function chi = RoadInclination_Arkustangens(z_I_Ground_m,rx_I_IAji_m,ry_I_IAji_m,phiz_IK_rad)\n%% Computation of Road Angles from Street Profile in Inertial Frame\n% Input parameters:\n% phiz_IK_rad [rad] Euler-Angle around z-Axis from Inertial Reference Frame I to Vehicle Fixed Reference Frame K\n% rx_I_IAji_m [m] Track x-Position [x1 x2 x3 x4] [1x4]\n% ry_I_IAji_m [m] Track y-Position [y1 y2 y3 y4] [1x4]\n% z_I_Ground_m [m] Input Vector with z-Profile of Street in Inertial Coordinate System at the Axle Locations [z1 z2 z3 z4] [3x4]\n% Output parameters:\n% chi_rad [rad] Approximated Cardan Angles from Inertial Reference Frame to Road Fixed Reference Frame [chi_x chi_y Psi] [3x1]\n\n\n%% Computation of Road Angles\n\n% Distances [dxl dxr dyf dyr] between suspension hardpoints\ndxl=sqrt( (rx_I_IAji_m(1)-rx_I_IAji_m(3)).^2 + (ry_I_IAji_m(1)-ry_I_IAji_m(3)).^2 );\ndxr=sqrt( (rx_I_IAji_m(2)-rx_I_IAji_m(4)).^2 + (ry_I_IAji_m(2)-ry_I_IAji_m(4)).^2 );\ndyf=sqrt( (rx_I_IAji_m(1)-rx_I_IAji_m(2)).^2 + (ry_I_IAji_m(1)-ry_I_IAji_m(2)).^2 );\ndyr=sqrt( (rx_I_IAji_m(3)-rx_I_IAji_m(4)).^2 + (ry_I_IAji_m(3)-ry_I_IAji_m(4)).^2 );\n\n% Inclination Angle in x-direction for negative z-road-profile\nchi_y = -atan( 0.5*((z_I_Ground_m(1)+z_I_Ground_m(2))-(z_I_Ground_m(3)+z_I_Ground_m(4)))/(0.5*(dxl+dxr)) );\n% Inclination Angle in y-direction for negative z-road-profile\nchi_x = -atan( 0.5*((z_I_Ground_m(1)+z_I_Ground_m(3))-(z_I_Ground_m(2)+z_I_Ground_m(4)))/(0.5*(dyf+dyr)) );\n\n%% Output Parameters\nchi = [chi_x;chi_y;phiz_IK_rad];\n\nend\n", "meta": {"author": "TUMFTM", "repo": "sim_vehicle_dynamics", "sha": "df2ae95dbeb6f8e4591f31ee378acac8e812f358", "save_path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics", "path": "github-repos/MATLAB/TUMFTM-sim_vehicle_dynamics/sim_vehicle_dynamics-df2ae95dbeb6f8e4591f31ee378acac8e812f358/vehicle_model/vehicledynamics/src/RoadInclination_Arkustangens.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9603611608990299, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.7108346985869228}} {"text": "function [Dlambda,volume,elemSign] = gradbasis3(node,elem)\n%% GRADBASIS3 gradient of barycentric basis in 3-D.\n%\n% [Dlambda,volume,elemSign] = gradbasis3(node,elem) compute gradient of\n% barycentric basis and volume of tetrahedron. The array volume is NT by 1\n% and volume(t) is the volume of the t-th tetrahedron. Dlambda(1:NT, 1:3,\n% 1:4) the first index is the label of tetrahedron, the second is the x-y-z\n% coordinate, and the last one is the label of four indices of a tet. For\n% example, Dlambda(t,:,1) is the gradient of lambda of the 1st index of the\n% t-th tet. The elemSign array taking values 1 or -1 records the\n% sign of the signed volume.\n% \n% See also gradbasis, gradu, gradu3\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details. \n\nNT = size(elem,1);\nface = uint32([elem(:,[2 4 3]);elem(:,[1 3 4]);elem(:,[1 4 2]);elem(:,[1 2 3])]);\nv12 = node(face(:,2),:)-node(face(:,1),:);\nv13 = node(face(:,3),:)-node(face(:,1),:);\nnormal = mycross(v12,v13,2);\nv12 = v12(3*NT+1:4*NT,:); \nv13 = v13(3*NT+1:4*NT,:);\nv14 = node(elem(:,4),:)-node(elem(:,1),:);\nvolume = dot(mycross(v12,v13,2),v14,2)/6;\nDlambda = zeros(NT,3,4);\nDlambda(1:NT,:,1) = normal(1:NT,:)./[6*volume, 6*volume, 6*volume];\nDlambda(1:NT,:,2) = normal(NT+1:2*NT,:)./[6*volume, 6*volume, 6*volume];\nDlambda(1:NT,:,3) = normal(2*NT+1:3*NT,:)./[6*volume, 6*volume, 6*volume];\nDlambda(1:NT,:,4) = normal(3*NT+1:4*NT,:)./[6*volume, 6*volume, 6*volume];\n\n% When the tetrahedron is not positive orientated, we reverse the sign of\n% the volume. The sign of Dlambda is always right since signed volume is\n% used in the computation. \nidx = (volume<0); \nvolume(idx,:) = -volume(idx,:);\nelemSign = ones(NT,1);\nelemSign(idx) = -1;", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/gradbasis3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7108223021720819}} {"text": "clear all; close all; clc;\n\nt=linspace(0,10,1000);\nx=sin(t)+3*cos(t/3)+4*sin(t/4);\n\nplot(t,x,'b');\ngrid on;\nxlabel('time(s)'); ylabel('x(t)');\nhold on;\n\nTs=0.1;\nnum_of_space=10/Ts;\n\nt_DT=linspace(0,9,num_of_space);\nx_DT=sin(t_DT)+3*cos(t_DT/3)+4*sin(t_DT/4);\n% alpha=1;\nalpha=t_DT(2)-t_DT(1);\n for ii=1:1:length(t_DT)\n if x_DT(ii)>=0\n rectangle('Position',[t_DT(ii),0,alpha,x_DT(ii)*(1/alpha)],'EdgeColor','r'); \n else\n rectangle('Position',[t_DT(ii),1*x_DT(ii)*(1/alpha),alpha,abs(x_DT(ii)*(1/alpha))],'EdgeColor','r'); \n end\n \n end\n \n\n% axis([-1 11 -0.5 2.5])\n\n% stem(t_DT,x_DT)", "meta": {"author": "angeloyeo", "repo": "gongdols", "sha": "7be9fbd988dec6edab1dc881cb22d63e6f69398d", "save_path": "github-repos/MATLAB/angeloyeo-gongdols", "path": "github-repos/MATLAB/angeloyeo-gongdols/gongdols-7be9fbd988dec6edab1dc881cb22d63e6f69398d/신호처리일반/Why_need_Convolution_Analog.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7107827220441261}} {"text": "function varargout = gmm(varargin)\n% Vl_GMM Learn a Gaussian Mixture Model using EM\n% [MEANS, COVARIANCES, PRIORS] = VL_GMM(X, NUMCLUSTERS) fits a GMM with\n% NUMCLUSTERS components to the data X. Each column of X represent a\n% sample point. X may be either SINGLE or DOUBLE. MEANS, COVARIANCES, and\n% PRIORS are respectively the means, the diagonal covariances, and\n% the prior probabilities of the Guassian modes. MEANS and COVARIANCES\n% have the same number of rows as X and NUMCLUSTERS columns with one\n% column per mode. PRIORS is a row vector with NUMCLUSTER entries\n% summing to one.\n%\n% [MEANS, COVARIANCES, PRIORS, LL] = VL_GMM(...) returns the\n% loglikelihood (LL) of the model as well.\n%\n% [MEANS, COVARIANCES, PRIORS, LL, POSTERIORS] = VL_GMM(...) returns\n% the posterior probabilities POSTERIORS of the Gaussian modes given\n% each data point. The POSTERIORS matrix has NUMCLUSTERS rows and\n% NUMDATA columns.\n%\n% VL_GMM() supports different initialization and optimization\n% methods. Specifically, the following options are supported:\n%\n% Verbose::\n% Increase the verbosity level (may be specified multiple times).\n%\n% Initialization:: RAND\n% RAND initializes the means as random data poitns and the\n% covaraince matrices as the covariance of X. CUSTOM allow\n% specifying the initial means, covariances, and prior\n% probabilities.\n%\n% InitMeans:: none\n% Specify the initial means (size(X,1)-by-NUMCLUSTERS matrix).\n%\n% InitPriors:: none\n% Specify the initial weights (a vector of dimension NUMCLUSTER).\n%\n% InitCovariances:: none\n% Specify the initial diagonal covariance matrices\n%\n% NumRepetitions:: 1\n% Number of times to restart EM. The solution with maximum\n% loglikelihood is returned.\n%\n% CovarianceBound:: 10e-6\n% Set the lower bound on the diagonal covariance values.\n% The bound can be either a scalar or a vector with one\n% entry per dimension. Using null bounds is possible, but\n% may yield degenerate solutions, including NaNs.\n%\n% Example::\n% VL_GMM(X, 10, 'verbose', 'MaxNumIterations', 20) learns a\n% mixture of ten Gaussians using at most twenty iterations of the\n% algorithm.\n%\n% See also: GMMs, VL_KMEANS(), VL_HELP().\n[varargout{1:nargout}] = vl_gmm(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/gmm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7107827154700257}} {"text": "function linpack_s_test05 ( )\n\n%*****************************************************************************80\n%\n%% TEST05 tests SGBFA and SGBSL.\n%\n% Discussion:\n%\n% The problem solved here is a larger version of this one:\n%\n% Matrix A is ( 2 -1 0 0 0) right hand side B is (1)\n% (-1 2 -1 0 0) (0)\n% ( 0 -1 2 -1 0) (0)\n% ( 0 0 -1 2 -1) (0)\n% ( 0 0 0 -1 2) (1)\n%\n%\n% Solution is (1)\n% (1)\n% (1)\n% (1)\n% (1)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 June 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Local Parameters:\n%\n% N is the number of equations.\n%\n% ML is the number of subdiagonals,\n% MU the number of superdiagonals.\n%\n% LDA is the leading dimension of the array used to store the\n% matrix, which must be at least 2*ML+MU+1.\n%\n n = 10;\n ml = 1;\n mu = 1;\n lda = 2*ml+mu+1;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST05\\n' );\n fprintf ( 1, ' For a general banded matrix,\\n' );\n fprintf ( 1, ' SGBFA factors the matrix,\\n' );\n fprintf ( 1, ' SGBSL solves a factored linear system.\\n' );\n fprintf ( 1, ' The matrix size is N = %d\\n', n );\n%\n% Set the right hand side B.\n%\n b(1) = 1.0;\n b(2:n-1) = 0.0;\n b(n) = 1.0;\n%\n% Force B to be a column vector.\n%\n b = b';\n%\n% Set the matrix A.\n%\n m = ml + mu + 1;\n fprintf ( 1, ' The bandwidth of the matrix is %d\\n', m );\n\n for j = 1 : n\n a(m-1,j) = -1.0;\n a(m,j) = 2.0;\n a(m+1,j) = -1.0;\n end\n%\n% Call SGBFA to factor the matrix A.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Factor the matrix.\\n' );\n\n [ a, ipivot, info ] = sgbfa ( a, lda, n, ml, mu );\n\n if ( info ~= 0 )\n fprintf ( 1, ' Error! SGBFA returns INFO = %d\\n', info );\n return\n end\n%\n% Call SGBSL to solve the linear system. The solution\n% is returned in B, that is, it overwrites the right hand side.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Solve the linear system.\\n' );\n\n job = 0;\n b = sgbsl ( a, lda, n, ml, mu, ipivot, b, job );\n%\n% Print the results.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The first and last 5 entries of the solution:\\n' );\n fprintf ( 1, ' (All should be 1):\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n if ( i <= 5 | n-5 < i ) \n fprintf ( 1, ' %6d %14f\\n', i, b(i) );\n end\n if ( i == 5 )\n fprintf ( 1, ' ...... ..............\\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/linpack_s/linpack_s_test05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7107688625297677}} {"text": "function [wts,cfreqs] = gammatone_matrix(nfft, sr, nfilts, width, minfreq, maxfreq, maxlen)\n% [wts,cfreqa] = fft2gammatonemx(nfft, sr, nfilts, width, minfreq, maxfreq, maxlen)\n% Generate a matrix of weights to combine FFT bins into\n% Gammatone bins. nfft defines the source FFT size at\n% sampling rate sr. Optional nfilts specifies the number of\n% output bands required (default 64), and width is the\n% constant width of each band in Bark (default 1).\n% minfreq, maxfreq specify range covered in Hz (100, sr/2).\n% While wts has nfft columns, the second half are all zero. \n% Hence, aud spectrum is\n% fft2gammatonemx(nfft,sr)*abs(fft(xincols,nfft));\n% maxlen truncates the rows to this many bins.\n% cfreqs returns the actual center frequencies of each\n% gammatone band in Hz.\n%\n% 2004-09-05 Dan Ellis dpwe@ee.columbia.edu based on rastamat/audspec.m\n% Last updated: $Date: 2009/02/22 02:29:25 $\n\nif nargin < 2; sr = 16000; end\nif nargin < 3; nfilts = 64; end\nif nargin < 4; width = 0.5; end\nif nargin < 5; minfreq = 50; end\nif nargin < 6; maxfreq = sr/2; end\nif nargin < 7; maxlen = nfft/2; end\n\nwts = zeros(nfilts, nfft);\n\n% after Slaney's MakeERBFilters\nEarQ = 9.26449;\nminBW = 24.7;\norder = 1;\n\ncfreqs = -(EarQ*minBW) + exp((1:nfilts)'*(-log(maxfreq + EarQ*minBW) + ...\n log(minfreq + EarQ*minBW))/nfilts) * (maxfreq + EarQ*minBW);\ncfreqs = flipud(cfreqs);\n\nGTord = 4;\n\nucirc = exp(j*2*pi*[0:(nfft/2)]/nfft);\n\njustpoles = 0;\n\nfor i = 1:nfilts\n cf = cfreqs(i);\n ERB = width*((cf/EarQ).^order + minBW^order).^(1/order);\n B = 1.019*2*pi*ERB;\n r = exp(-B/sr);\n theta = 2*pi*cf/sr;\n pole = r*exp(j*theta);\n\n if justpoles == 1\n % point on unit circle of maximum gain, from differentiating magnitude\n cosomegamax = (1+r*r)/(2*r)*cos(theta);\n if abs(cosomegamax) > 1\n if theta < pi/2; omegamax = 0; \n else omegamax = pi; end\n else\n omegamax = acos(cosomegamax);\n end\n center = exp(j*omegamax);\n gain = abs((pole-center).*(pole'-center)).^GTord;\n wts(i,1:(nfft/2+1)) = gain * (abs((pole-ucirc).*(pole'- ...\n ucirc)).^-GTord);\n else\n % poles and zeros, following Malcolm's MakeERBFilter\n T = 1/sr;\n A11 = -(2*T*cos(2*cf*pi*T)./exp(B*T) + 2*sqrt(3+2^1.5)*T*sin(2* ...\n cf*pi*T)./exp(B*T))/2; \n A12 = -(2*T*cos(2*cf*pi*T)./exp(B*T) - 2*sqrt(3+2^1.5)*T*sin(2* ...\n cf*pi*T)./exp(B*T))/2;\n A13 = -(2*T*cos(2*cf*pi*T)./exp(B*T) + 2*sqrt(3-2^1.5)*T*sin(2* ...\n cf*pi*T)./exp(B*T))/2; \n A14 = -(2*T*cos(2*cf*pi*T)./exp(B*T) - 2*sqrt(3-2^1.5)*T*sin(2* ...\n cf*pi*T)./exp(B*T))/2; \n zros = -[A11 A12 A13 A14]/T;\n \n gain(i) = abs((-2*exp(4*j*cf*pi*T)*T + ...\n 2*exp(-(B*T) + 2*j*cf*pi*T).*T.* ...\n (cos(2*cf*pi*T) - sqrt(3 - 2^(3/2))* ...\n sin(2*cf*pi*T))) .* ...\n (-2*exp(4*j*cf*pi*T)*T + ...\n 2*exp(-(B*T) + 2*j*cf*pi*T).*T.* ...\n (cos(2*cf*pi*T) + sqrt(3 - 2^(3/2)) * ...\n sin(2*cf*pi*T))).* ...\n (-2*exp(4*j*cf*pi*T)*T + ...\n 2*exp(-(B*T) + 2*j*cf*pi*T).*T.* ...\n (cos(2*cf*pi*T) - ...\n sqrt(3 + 2^(3/2))*sin(2*cf*pi*T))) .* ...\n (-2*exp(4*j*cf*pi*T)*T + 2*exp(-(B*T) + 2*j*cf*pi*T).*T.* ...\n (cos(2*cf*pi*T) + sqrt(3 + 2^(3/2))*sin(2*cf*pi*T))) ./ ...\n (-2 ./ exp(2*B*T) - 2*exp(4*j*cf*pi*T) + ...\n 2*(1 + exp(4*j*cf*pi*T))./exp(B*T)).^4);\n wts(i,1:(nfft/2+1)) = ((T^4)/gain(i)) ...\n * abs(ucirc-zros(1)).*abs(ucirc-zros(2))...\n .*abs(ucirc-zros(3)).*abs(ucirc-zros(4))...\n .*(abs((pole-ucirc).*(pole'-ucirc)).^-GTord);\n end\nend\n\nwts = wts(:,1:maxlen);", "meta": {"author": "jtkim-kaist", "repo": "VAD", "sha": "a1e0b1299fcf22eb7654b2906a67184c73b37faa", "save_path": "github-repos/MATLAB/jtkim-kaist-VAD", "path": "github-repos/MATLAB/jtkim-kaist-VAD/VAD-a1e0b1299fcf22eb7654b2906a67184c73b37faa/lib/matlab/refVAD/vad-master/mfiles/gammatone_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357702, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7107392262059868}} {"text": "function co = convexification(varargin)\n%CONVEXIFICATION Compute the convexification of a polygon.\n%\n% CO = convexification(H)\n% Creates convexification from support function. Support function is\n% supposed to be uniformly distributed over [0 2pi].\n%\n% CO = convexification(POLYGON)\n% Computes support function of the polygon, then the corresponding\n% convexification.\n%\n% CO = convexification(POLYGON, N)\n% Uses N points for convexification computation. Note that the number of\n% points of CO can be lower than N.\n% \n% CAUTION: The result will be valid only for convex polygons.\n%\n% See also \n% polygons2d, supportFunction \n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2005-01-12\n% Copyright 2005-2022 INRA - Cepia Software Platform\n\nif ~isempty(varargin)>0\n var = varargin{1};\n if size(var, 2)==1\n h = var;\n else\n poly = var;\n N = 128;\n if length(varargin)>1\n N = varargin{2};\n end\n h = supportFunction(poly, N);\n end\nelse\n error('not enough input arguments');\nend\n\nN = length(h);\nu = (0:2*pi/N:2*pi*(1-1/N))';\nv = [cos(u) sin(u)].*[h h];\n\ni1 = 1:N;\ni2 = [2:N 1];\ni3 = [3:N 1 2];\n\ncirc = zeros(N, 4);\nfor i=1:N\n circ(i, 1:4) = createDirectedCircle(v(i1(i),:), v(i2(i),:), v(i3(i), :));\nend\n\n% remove non direct-oriented circles\ncirc = circ(circ(:,4)==0, :);\n\n% keep only circles seen several times\ndp = diff(circ(:,1:2));\ndp = sum(dp.*dp, 2);\nind1 = [1; find(dp<1e-10)+1];\ncirc = circ(ind1, :);\n\n% keep only one instance of each circle\ndp = diff(circ(:,1:2));\ndp = sum(dp.*dp, 2);\nind = [1; find(dp>1e-10)+1];\nco = 2*circ(ind, 1:2);\n\n% eventually remove the last point if it is the same as the first one\nif distancePoints(co(1,:), co(end, :))<1e-10 && size(co, 1)>1\n co = co(1:end-1,:);\nend\n\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/convexification.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7107137037674547}} {"text": "function [F_N, Y_N] = leastSquaresSHT(N, F, dirs, basisType, weights)\n%LEASTSQUARESSHT Spherical harmonic transform of F using least-squares\n%\n% N: maximum order of transform\n% F: the spherical function evaluated at K directions 'dirs'\n% if F is a KxM matrix then the transform is applied to each column\n% of F, and returns the coefficients at each column of F_N\n% respectively\n% dirs: [azimuth1 inclination1; ...; azimuthK inclinationK] angles in \n% rads for each evaluation point, where inclination is the polar \n% angle from zenith: inclination = pi/2-elevation\n% basisType: 'complex' or 'real' spherical harmonics\n% weights: vector of K weights for each direction, for weighted\n% least-squares\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Archontis Politis, 10/10/2013, updated 7/2/2015\n% archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n % compute the harmonic coefficients\n Y_N = getSH(N, dirs, basisType);\n Npoints = size(dirs,1);\n \n % non-weighted case for uniform arrangements\n if nargin<5 || ~exist('weights','var') || isempty(weights)\n \n % perform transform in the least squares sense\n F_N = pinv(Y_N)*F;\n else\n \n % perform weighted least-squares transform\n F_N = (Y_N'*diag(weights)*Y_N) \\ (Y_N'*diag(weights) * F);\n end \n \n\nend\n", "meta": {"author": "polarch", "repo": "Spherical-Harmonic-Transform", "sha": "ef8a69aedbaf467e2fccb50c810564d747ce3409", "save_path": "github-repos/MATLAB/polarch-Spherical-Harmonic-Transform", "path": "github-repos/MATLAB/polarch-Spherical-Harmonic-Transform/Spherical-Harmonic-Transform-ef8a69aedbaf467e2fccb50c810564d747ce3409/leastSquaresSHT.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7107136999182917}} {"text": "function [X, funVal, ValueL]=LeastR(A, Y, z, opts)\n%\n%%\n% Function LeastR\n% Least Squares Loss with the L1-norm Regularization\n%\n%% Problem\n%\n% min 1/2 || A x - y||^2 + 1/2 rsL2 * ||x||_2^2 + z * ||x||_1\n%\n% By default, rsL2=0.\n% When rsL2 is nonzero, this corresponds to the well-know elastic net.\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 - L_1 norm regularization parameter (z >=0)\n% opts- Optional inputs (default value: opts=[])\n%\n%% Output parameters:\n% x- Solution\n% funVal- Function value during iterations\n%\n%% Copyright (C) 2009-2010 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 February 18, 2010.\n%\n%% Related papers\n%\n% [1] Jun Liu and Jieping Ye, Efficient Euclidean Projections\n% in Linear Time, ICML 2009.\n%\n% [2] Jun Liu and Jieping Ye, Sparse Learning with Efficient Euclidean\n% Projections onto the L1 Ball, Technical Report ASU, 2008.\n%\n%% Related functions\n% \n% sll_opts, initFactor, pathSolutionLeast\n% LeastC, nnLeastR, nnLeastC, \n%\n%%\n\n%% Verify and initialize the parameters\n%%\n\n% Verify the number of input parameters\nif (nargin <3)\n error('\\n Inputs: A, y and z should be specified!\\n');\nelseif (nargin==3)\n opts=[];\nend\n\n% Get the size of the matrix A\n[m,n]=size(A);% m -- sample size,n -- feature dimension%******************************\nk=size(Y,2);\n%sigma=diag(diag(rand(k)));\nsigma=opts.sigma;\n% Verify the length of y\nif(size(Y,1) ~=m)%********************************\n%if (length(y) ~=m)\n error('\\n Check the length of y!\\n');\nend\n\n% Verify the value of z\nif (z<0)\n error('\\n z should be nonnegative!\\n');\nend\n\n% run sll_opts to set default values (flags)\nopts=sll_opts(opts);\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%% Starting point initialization\n\n% compute AT y\nif (opts.nFlag==0)\n ATY=A'*Y; %A-->mxn;y-->mxk****************************\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\n\n% L2 norm regularization\nif isfield(opts,'rsL2')\n rsL2=opts.rsL2;\n if (rsL2<0)\n error('\\n opts.rsL2 should be nonnegative!');\n end\nelse\n rsL2=0;\nend\n\n% L1 norm regularization\nif (opts.rFlag==0)\n lambda=z;\nelse % z here is the scaling factor lying in [0,1]\n if (z<0 || z>1)\n error('\\n opts.rFlag=1, and z should be in [0,1]');\n end\n\n lambda_max=max(abs(ATy));\n lambda=z*lambda_max;\n\n rsL2=rsL2*lambda_max; % the input rsL2 is a ratio of lambda_max\nend\n\n% initialize a starting point\nif opts.init==2\n X=zeros(n,k);%*************************************\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) % If .init=0, we set x=ratio*x by \"initFactor\"\n % Please refer to the function initFactor for detail\n\n x_norm=sum(abs(X(:))); x_2norm=trace(X'*X);%*****************************corresponding to L1norm,Fnorm\n if x_norm>=1e-6\n ratio=initFactorqiao(x_norm, AX, Y, lambda,'LeastR', rsL2, x_2norm);\n X=ratio*X; AX=ratio*AX;\n end\nend\n\n%% The main program\n\n%% The Armijo Goldstein line search scheme + accelearted gradient descent\nif (opts.mFlag==0 && opts.lFlag==0)\n \n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1 + rsL2;\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,k);\n\n % alphap and alpha are used for computing the weight in forming search point\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 + rsL2 * S*inv(sigma);%************************** +rsL2*s*inv(sigma)\n\n % copy x and Ax to xp and Axp\n Xp=X; AXp=AX;\n\n while (1)\n % let s walk in a step in the antigradient of s to get v\n % and then do the l1-norm regularized projection\n V=S-G/L;\n\n % L1-norm regularized projection\n X=sign(V).*max(abs(V)-lambda / L,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=trace(V'*V); l_sum=trace(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 - rsL2) * ||v||_2^2\n if(l_sum <= r_sum * (L-rsL2))\n break;\n else\n L=max(2*L, l_sum/r_sum + rsL2);\n % fprintf('\\n L=%5.6f',L);\n end\n end\n\n ValueL(iterStep)=L;\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 funVal(iterStep)=trace(AXY'* AXY)/2 + rsL2/2 * trace(X'*X) + sum(abs(X(:))) * lambda;\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 end\nend\n\n%% Reformulated problem + Nemirovski's scheme\n\n% .mFlag=1, and .lFlag=0\n% refomulate the problem as the constrained convex optimization\n% problem, and then apply Armijo Goldstein line search scheme\n\n% Problem:\n% min 1/2 || A x - y||^2 + 1/2 rsL2 * ||x||_2^2 + z * t' * 1\n% s.t. |x| <= t\n\nif(opts.mFlag==1 && opts.lFlag==0) \n \n bFlag=0; % this flag tests whether the gradient step only changes a little\n \n L=1 + rsL2;\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 t=abs(x); tp=t; \n % t is the upper bound of absolute value of x\n\n % alphap and alpha are used for computing the weight in forming search point\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; s_t= t + beta * (t -tp);\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 + rsL2 * s;\n\n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n tp=t;\n\n while (1)\n % let s walk in a step in the antigradient of s to get v\n % and then do the l1-norm regularized projection\n \n u=s-g/L;\n v= s_t - lambda / L;\n \n % projection\n [x, t]=ep1R(u, v, n);\n\n v=x-s; % the difference between the new approximate solution x\n % and the search point s\n \n v_t=t-s_t;\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 + v_t'*v_t; l_sum=Av'*Av + v'*v * rsL2;\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 + rsL2 * ||v||_2^2\n % <= L * (||v||_2^2 + ||v_t|| _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 ValueL(iterStep)=L;\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 funVal(iterStep)=Axy'* Axy/2 + rsL2/2 * x'*x + sum(t) * lambda;\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 + norm(t-tp)^2);\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=sqrt(xp'*xp + tp'*tp); norm_xxp=sqrt(xxp'*xxp+ norm(t-tp)^2);\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 end\n \nend\n\n\n%% adaptive line search\n\n% .mFlag=1, and .lFlag=1\n% refomulate the problem as the constrained convex optimization\n% problem, and then apply adaptive line search scheme\n\n% Problem:\n% min 1/2 || A x - y||^2 + 1/2 rsL2 * ||x||_2^2 + z * t' * 1\n% s.t. |x| <= t\n\nif(opts.mFlag==1 && opts.lFlag==1)\n \n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1 + rsL2;\n % We assume that the maximum eigenvalue of A'A is over 1\n \n gamma=1;\n % we shall set the value of gamma = L,\n % where L is appropriate for the starting point\n\n xp=x; Axp=Ax;\n % store x and Ax\n xxp=zeros(n,1);\n % the difference of x and xp \n t=abs(x); tp=t;\n % t is the upper bound of absolute value of x\n \n % compute AT Ax\n if (opts.nFlag==0)\n ATAx=A'*Ax;\n elseif (opts.nFlag==1)\n ATAx=A'*Ax - sum(Ax) * mu'; ATAx=ATAx./nu;\n else\n invNu=Ax./nu; ATAx=A'*invNu-sum(invNu)*mu';\n end\n \n % We begin the adaptive line search in the following\n %\n % Note that, in the line search, L and beta are changing\n \n for iterStep=1:opts.maxIter\n\n ATAxp=ATAx;\n % store ATAx to ATAxp\n\n if (iterStep~=1)\n % compute AT Ax\n if (opts.nFlag==0)\n ATAx=A'*Ax;\n elseif (opts.nFlag==1)\n ATAx=A'*Ax - sum(Ax) * mu'; ATAx=ATAx./nu;\n else\n invNu=Ax./nu; ATAx=A'*invNu-sum(invNu)*mu';\n end\n end\n\n %--------- Line Search for L begins\n while (1)\n if (iterStep~=1)\n alpha= (-gamma+ sqrt(gamma*gamma + 4* L * gamma)) / (2*L);\n beta= (gamma - gamma* alphap) / (alphap * gamma + alphap* L * alpha);\n % beta is the coefficient for generating search point s\n\n s=x + beta* xxp; s_t= t + beta * (t -tp);\n As=Ax + beta* (Ax-Axp);\n ATAs=ATAx + beta * (ATAx- ATAxp);\n % compute the search point s, A * s, and A' * A * s\n else\n alpha= (-1+ sqrt(5)) / 2;\n beta=0; s=x; s_t=t; As=Ax; ATAs=ATAx;\n end\n\n g=ATAs-ATy + rsL2 * s;\n % compute the gradient g\n \n % let s walk in a step in the antigradient of s \n u=s-g/L;\n v= s_t - lambda / L;\n\n % projection\n [xnew, tnew]=ep1R(u,v,n);\n\n v=xnew-s; % the difference between the new approximate solution x\n % and the search point s\n v_t=tnew-s_t;\n \n % compute A xnew\n if (opts.nFlag==0)\n Axnew=A* xnew;\n elseif (opts.nFlag==1)\n invNu=xnew./nu; mu_invNu=mu * invNu;\n Axnew=A*invNu -repmat(mu_invNu, m, 1);\n else\n Axnew=A*xnew-repmat(mu*xnew, m, 1); Axnew=Axnew./nu;\n end\n\n Av=Axnew -As;\n r_sum=v'*v + v_t'*v_t; l_sum=Av'*Av + v'*v * rsL2;\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 + rsL2 * ||v||_2^2\n % <= L * (||v||_2^2 + ||v_t|| _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 %--------- Line Search for L ends\n\n gamma=L* alpha* alpha; alphap=alpha;\n % update gamma, and alphap\n \n ValueL(iterStep)=L;\n\n tao=L * r_sum / l_sum;\n if (tao >=5)\n L=L*0.8;\n end\n % decrease the value of L\n\n xp=x; x=xnew; xxp=x-xp;\n Axp=Ax; Ax=Axnew;\n % update x and Ax with xnew and Axnew \n tp=t; t=tnew;\n % update tp and t \n \n Axy=Ax-y;\n funVal(iterStep)=Axy' * Axy/2 + rsL2/2 * x'*x + lambda * sum(t);\n % compute function value\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+ norm(t-tp)^2);\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=sqrt(xp'*xp + tp'*tp); norm_xxp=sqrt(xxp'*xxp+ norm(t-tp)^2);\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 end\nend\n\n\n%%\nif(opts.mFlag==0 && opts.lFlag==1)\n error('\\n The function does not support opts.mFlag=0 & opts.lFlag=1!');\nend", "meta": {"author": "zzstefan", "repo": "BrainNetClass", "sha": "556cda9516429a964100e1ac0bace4258194b4a1", "save_path": "github-repos/MATLAB/zzstefan-BrainNetClass", "path": "github-repos/MATLAB/zzstefan-BrainNetClass/BrainNetClass-556cda9516429a964100e1ac0bace4258194b4a1/Toolbox/SLEP_package_4.1/SLEP/functions/L1/L1R/LeastRqiao.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.7106514522474904}} {"text": "function f = olsmatrix(X,mode)\n\n% function f = olsmatrix(X,mode)\n%\n% is samples x parameters\n% (optional) is\n% 0 means normal operation\n% 1 means use inv instead of \\ and omit unit-length normalization.\n% the point of this mode is to reduce memory usage (i think).\n% default: 0.\n%\n% what we want to do is to perform OLS regression using \n% and obtain the parameter estimates. this is accomplished\n% by inv(X'*X)*X'*y = f*y where y is the data (samples x cases).\n%\n% what this function does is to return which has dimensions\n% parameters x samples. \n%\n% to ensure well-conditioning, we unit-length normalize each column\n% of before doing the inv.m operation. also, we actually use\n% left-slash (\\), which apparently is equivalent to inv.m but faster\n% and more accurate (see code for details). if you pass as 1,\n% we omit the normalization and use the inv method instead of the \\ method.\n%\n% also, in the case that one or more regressors in are all zero, then\n% without special handling, then this case will result in warnings and\n% NaN results. what we do is to explicitly ensure that all-zero regressors\n% are ignored and that there are all-zero rows for these regressors \n% in . this makes it such that the weights estimated for these \n% regressors are simply zero.\n%\n% see also olsmatrix2.m.\n%\n% history:\n% 2011/06/27 - explicitly ignore 0\n% 2011/03/29 - mode 1 now omits unit length normalization.\n% 2011/03/28 - add input.\n% 2010/08/05: now, we do not try to detect weird cases with low variance.\n% instead, we just blindly unit-length normalize each column.\n\n% input\nif ~exist('mode','var') || isempty(mode)\n mode = 0;\nend\n\n% check\nassert(all(~isnan(X(:))));\n\n% deal with degenerate regressors\ngood = ~all(X==0,1);\n\n% initialize result\nf = zeros(size(X,2),size(X,1));\n\n% do it\nswitch mode\ncase 0\n [X,len] = unitlength(X(:,good),1,[],0);\n temp = diag(1./len)*((X'*X)\\X'); % hm, suggested by M-Lint\ncase 1\n temp = inv(X(:,good)'*X(:,good))*X(:,good)';\nend\n\n% return\nif any(good)\n f(good,:) = temp;\nend\n", "meta": {"author": "qMRLab", "repo": "qMRLab", "sha": "036ff20b47e939877f746940a969494b55911636", "save_path": "github-repos/MATLAB/qMRLab-qMRLab", "path": "github-repos/MATLAB/qMRLab-qMRLab/qMRLab-036ff20b47e939877f746940a969494b55911636/External/knkutils/olsmatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021531, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.7106514411874253}} {"text": "%TROTX SE(3) rotation about X axis\n%\n% T = TROTX(THETA) is a homogeneous transformation (4x4) representing a rotation \n% of THETA radians about the x-axis.\n%\n% T = TROTX(THETA, 'deg') as above but THETA is in degrees.\n%\n% Notes::\n% - Translational component is zero.\n%\n% See also rotx, troty, trotz, trot2, SE3.Rx.\n\n%## 3d rotation\n\n% Copyright (C) 1993-2019 Peter I. Corke\n%\n% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).\n% \n% Permission is hereby granted, free of charge, to any person obtaining a copy\n% of this software and associated documentation files (the \"Software\"), to deal\n% in the Software without restriction, including without limitation the rights\n% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n% of the Software, and to permit persons to whom the Software is furnished to do\n% so, subject to the following conditions:\n%\n% The above copyright notice and this permission notice shall be included in all\n% copies or substantial portions of the Software.\n%\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n%\n% https://github.com/petercorke/spatial-math\n\nfunction T = trotx(t, varargin)\n\tT = [rotx(t, varargin{:}) [0 0 0]'; 0 0 0 1];\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/trotx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.7106514410189438}} {"text": "function anorm = update_gbound(anorm,alpha,beta,j)\n%UPDATE_GBOUND Update Gerscgorin estimate of 2-norm \n% ANORM = UPDATE_GBOUND(ANORM,ALPHA,BETA,J) updates the Gersgorin bound\n% for the tridiagonal in the Lanczos process after the J'th step.\n% Applies Gerscgorins circles to T_K'*T_k instead of T_k itself\n% since this gives a tighter bound.\n\nif j==1 % Apply Gerscgorin circles to T_k'*T_k to estimate || A ||_2\n i=j; \n % scale to avoid overflow\n scale = max(abs(alpha(i)),abs(beta(i+1)));\n alpha(i) = alpha(i)/scale;\n beta(i) = beta(i)/scale;\n anorm = 1.01*scale*sqrt(alpha(i)^2+beta(i+1)^2 + abs(alpha(i)*beta(i+1)));\nelseif j==2\n i=1;\n % scale to avoid overflow\n scale = max(max(abs(alpha(1:2)),max(abs(beta(2:3)))));\n alpha(1:2) = alpha(1:2)/scale;\n beta(2:3) = beta(2:3)/scale;\n \n anorm = max(anorm, scale*sqrt(alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1) + alpha(i+1)*beta(i+1)) + ...\n abs(beta(i+1)*beta(i+2))));\n i=2;\n anorm = max(anorm,scale*sqrt(abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...\n beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1))) );\nelseif j==3\n % scale to avoid overflow\n scale = max(max(abs(alpha(1:3)),max(abs(beta(2:4)))));\n alpha(1:3) = alpha(1:3)/scale;\n beta(2:4) = beta(2:4)/scale;\n i=2;\n anorm = max(anorm,scale*sqrt(abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...\n beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1) + alpha(i+1)*beta(i+1)) + ...\n abs(beta(i+1)*beta(i+2))) );\n i=3;\n anorm = max(anorm,scale*sqrt(abs(beta(i)*beta(i-1)) + ...\n abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...\n beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1))) );\nelse\n % scale to avoid overflow\n % scale = max(max(abs(alpha(j-2:j)),max(abs(beta(j-2:j+1)))));\n % alpha(j-2:j) = alpha(j-2:j)/scale;\n % beta(j-2:j+1) = beta(j-2:j+1)/scale;\n \n % Avoid scaling, which is slow. At j>3 the estimate is usually quite good\n % so just make sure that anorm is not made infinite by overflow.\n i = j-1;\n anorm1 = sqrt(abs(beta(i)*beta(i-1)) + ...\n abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...\n beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1) + alpha(i+1)*beta(i+1)) + ...\n abs(beta(i+1)*beta(i+2)));\n if isfinite(anorm1)\n anorm = max(anorm,anorm1);\n end\n i = j;\n anorm1 = sqrt(abs(beta(i)*beta(i-1)) + ...\n abs(beta(i)*alpha(i-1) + alpha(i)*beta(i)) + ...\n beta(i)^2+alpha(i)^2+beta(i+1)^2 + ...\n abs(alpha(i)*beta(i+1)));\n if isfinite(anorm1)\n anorm = max(anorm,anorm1);\n end\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/mc/SVP/private/update_gbound.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.7106514408504626}} {"text": "%% Simulating Iron Ore Prices\n% This example demonstrates calibrating an geomtric brownian motion & \n% mean reverting stochastic model from historical data of iron ore prices.\n% The model is then used to simulate the prices into the future using\n% the Stochastic Differential Equation Simulation engine in Econometrics\n% Toolbox.\n% \n%% Import Historical Data\n% Data is saved as a excel file based on historical iron ore prices from\n% May 10, 2012 to June 22, 2012\n% http://www.indexmundi.com/commodities/?commodity=iron-ore&months=240¤cy=aud\n\n% Database Version\nimportirondb\ndates = data.Month;\nDate = datenum(dates,'yyyy-mm-dd HH:MM:SS.FFF');\nS = data.Price;\n\n% Excel\n% [data,txt] = xlsread('ironoremonthly.xlsx');\n% dates = txt(3:end,1);\n% Date = datenum(dates,'dd/mm/yyyy');\n% S = data(:,1);\nSR = S(2:end)./S(1:end-1) - 1;\n%% The Models\n% Return Model (gbm)\n% The returns based model used for simulation Iron Orce Prices is geometric\n% brownian motion. It can be described as:\n%\n% $$ dX_t = \\mu(t)X_t dt + D(t,X_t)V(t)dW_t $$\n%\n% $$ \\mu = \\textrm{ Instantaneous Rate of Return} $$\n%\n% $$ \\sigma = \\textrm { Volatility Rate} $$\n%\n% Mean Reversion Model (hwv)\n% The mean reversion model used for simulating the Iron Ore prices is an Ornstein-Uhlenbeck\n% brownian motion with mean reverting drift. This model is fit to the prices\n% iron ore prices. The discrete-time equation of this model can be written as,\n%\n% $$ \\Delta x_t = \\alpha(\\mu - x_t)\\Delta t + \\sigma dz_t, \\textrm{ where } dz_t \\sim N(0, \\sqrt\\Delta_t) $$\n%\n% $$ \\alpha = \\textrm{ Mean Reversion Rate}$$\n%\n% $$ \\mu = \\textrm{ Mean level} $$\n%\n% $$ \\sigma = \\textrm { Volatility } $$\n\n%% Calibrate Parameters\n\nmodelsel = 'gbm'; %hwv - mean reverting, %gbm - based on returns\nstartdate = '2010-08-01';\ni = find(datenum(startdate,'yyyy-mm-dd') == Date);\nS2 = S(i:end);\nDate2 = Date(i:end);\nSR2 = SR(i+1:end);\n\nswitch modelsel\n case 'gbm'\n dt = 1;\n sigma = std(SR2);\n mu = mean(SR2);\n model = gbm(mu,sigma,'StartState', S(end));\n case 'hwv'\n % hwv - mean reversion model\n % The reversion rate and mean level can be calculated from the coefficients\n % of a linear fit between the prices and their first difference scaled\n % by the time interval parameter. All quantities are specified on an annual\n % scale.\n regressors = [ones(length(S2) - 1, 1) S2(1:end-1)];\n [coefficients, intervals, residuals] = regress(diff(S2), regressors);\n dt = 1;\n speed = -coefficients(2)/dt;\n level = -coefficients(1)/coefficients(2);\n sigma = std(residuals)/sqrt(dt);\n model = hwv(speed,level,sigma, 'StartState', S(end));\nend\n\n\n\n\n\n%% Monte-Carlo Simulation\n% The model defined above can be simulated with the simulate method of the\n% SDE object to generate multiple log price paths. These are exponentiated\n% to compute the simulated natural gas prices. The plot below shows 1000\n% paths simulated daily, 8 years into the future.\n\nNTrials = 1000;\nyears = 8;\nann = 12;\nNSteps = years*ann;\n\ntic\nXsim = simulate(model, NSteps, 'NTrials', NTrials, 'DeltaTime', dt);\nXsim = squeeze(Xsim); % Remove redundant dimension\ntoc\n\nSsim = Xsim;\nSYear = Ssim(13:12:end,:);\n\n% Visualize first 20 prices of 1000 paths\nplot(Date, S, Date(end)+(0:30:(years*ann+1)*30-1), Ssim(:,1:100));\ndatetick; xlabel('Date'); ylabel('Iron Ore Price $US/tonne');\ntitle('Historical & Simulated Iron Ore Prices')\n%% Save Model\n% The calibrated model is saved in a MAT-file for later use.\n\nsave ironoremodel model dt\n\n%% Visual Analysis of Simulated Price Paths\n% Instead of plotting a number of paths at once, we can plot longer single paths\n% against the observed historical data to visually validate the simulated\n% paths. This can serve as a final sanity check.\n\npath = 15;\nfigure\nplot(Date, S, 'b', Date(end)+(0:30:NSteps*30), Ssim(:,path), 'r');\ntitle(['Historical & Simulated Prices, Path ' int2str(path)]);\ndatetick('x','keeplimits');\nxlabel('Date'); ylabel('Iron Ore Price $US/tonne');\n%% Histogram results of price paths at the end of each year\n\nfigure\n\nfor i = 1:years\n subplot(years/2,2,i)\n SsimM = mean(Ssim(i*12+1,:));\n hist(Ssim(i*12,:),20)\n hold on\n hm = plot(SsimM,0,'ro');\n title(['Year: ',num2str(i),' of Iron Ore Prices'])\n xlabel(['Iron Ore Price: Mean =',num2str(round(100*(SsimM))/100)])\n zlabel('Simulation Count')\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/39257-mining-economics-with-matlab/ironoreprice_script.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7106514394471592}} {"text": "function surfacedata = ellipsoidsurface\n\na = 9;\nb = 3;\nc = 1;\n\na2 = a*a;\na4 = a2*a2;\nb2 = b*b;\nb4 = b2*b2;\nc2 = c*c;\nc4 = c2*c2;\n\nsurfacedata = struct('phi',@phi,'gradient', @gradient, 'unitoutnormal',...\n @unitoutnormal, 'project', @project, 'initmesh',@initmesh, 'meancurvature', @meancurvature, ...\n 'u',@u, 'f',@f,'gra_u',@gra_u);\n\n\nfunction [node, elem] = initmesh\nM = load('meshdata/ellipsoid3394.mat');\nnode = M.node;\nelem = M.elem;\nend\n\n\nfunction z = phi(p)\n% level set function\n\nx = p(:,1); y = p(:,2); z = p(:,3);\nz = x.^2/a2 + y.^2/b2 + z.^2/c2 - 1.0;\nend\n\n\nfunction n = unitoutnormal(p)\n% \nn = gradient(p);\nl = sqrt(sum(n.^2,2));\nn = n./repmat(l,1,3);\nend\n\nfunction n = gradient(p)\n% gradient of phi\n\nx = p(:,1); y = p(:,2); z = p(:,3);\nn = [2*x/a2, 2*y/b2, 2*z/c2];\nend\n\nfunction [node,dist] = project(p)\n% projection function \n\ns = sign(phi(p));\n\nnode = p;\n\nnormalAtNode = gradient(node);\nvalueAtNode = phi(node);\nnode = node - valueAtNode*ones(1,3).*normalAtNode./(dot(normalAtNode,normalAtNode,2)*ones(1,3));\n\nvector = (-s)*ones(1,3).*(node - p);\n\nd = s.*sqrt(dot(vector,vector,2));\n\nnormalAtNode = gradient(node);\n\nnode = p - d*ones(1,3).*normalAtNode./(sqrt(dot(normalAtNode,normalAtNode,2))*ones(1,3));\n\nvalueAtNode = phi(node);\n\nnormalAtNode = gradient(node);\n\nvector = (-s)*ones(1,3).*(node - p);\n\nd = s.*sqrt(dot(vector,vector,2));\n\n\ne1 = normalAtNode./(sqrt(dot(normalAtNode, normalAtNode,2))*ones(1,3))-vector./(sqrt(dot(vector,vector,2))*ones(1,3));\nerror=sqrt(valueAtNode.^2./(dot(normalAtNode, normalAtNode,2))+dot(e1,e1,2));\n\nk=1;\nwhile max(abs(error)) > 1e-6 && k<200\n \n k=k+1;\n \n node = node - valueAtNode*ones(1,3).*normalAtNode./(dot(normalAtNode,normalAtNode,2)*ones(1,3));\n \n vector = -s*ones(1,3).*(node - p);\n d = s.*sqrt(dot(vector,vector,2));\n normalAtNode = gradient(node);\n \n node = p - d*ones(1,3).*normalAtNode./(sqrt(dot(normalAtNode,normalAtNode,2))*ones(1,3));\n \n valueAtNode = phi(node);\n \n normalAtNode = gradient(node);\n \n vector = (-s)*ones(1,3).*(node - p);\n \n d = s.*sqrt(dot(vector,vector,2));\n e1 = normalAtNode./(sqrt(dot(normalAtNode, normalAtNode,2))*ones(1,3))-vector./(sqrt(dot(vector,vector,2))*ones(1,3));\n error=sqrt(valueAtNode.^2./(dot(normalAtNode, normalAtNode,2))+dot(e1,e1,2)); \nend\n\nif nargout == 2\n dist = d;\nend\nend\n\n\nfunction mc = meancurvature(p)\n\nx = p(:,1); y = p(:,2); z = p(:,3);\nx2 = x.^2; y2 = y.^2; z2 = z.^2;\n\n\ns1 = c4*a2*y2 + b4*a2*z2 + c4*b2*x2 + a4*b2*z2 + b4*c2*x2 + a4*c2*y2;\ns2 = b4*c4*x2 + a4*c4*y2 + a4*b4*z2;\ns3 = x2/a4+y2/b4+z2/c4;\n\nmc = 0.5* s1./(s2.*sqrt(s3));\nend\n\n\nfunction z = f(p)\np = project(p);\nx = p(:,1); y = p(:,2); z = p(:,3);\nx2 = x.^2; y2 = y.^2; z2 = z.^2;\nd1 = c4*y2 + b4*z2;\nd2 = c2*y2 + b2*z2;\nd3 = b4*c2 + c4*b2;\nd4 = c4 * b4 * (d2 * a4 + d1 * a2 + x2 * d3);\nd5 = (a4 * d1 + b4 * c4 * x2);\nz = a2*( d4.*x.*cos(x) + a2*d1.*d5.*sin(x)) ./ d5.^2;\nend\n\nfunction z = u(p) \n% exact solution\np = project(p);\nz =sin(p(:,1));\nend\n\nfunction z = gra_u(p) \n\np = project(p);\nx = p(:,1); y = p(:,2); z = p(:,3);\nx2 = x.^2; y2 = y.^2; z2 = z.^2;\n\nd1 = x2/a4 + y2/b4 + z2/c4 ;\n\nz1 = (1 - x2 ./(a4*d1));\nz2 = -x.*y./(a2*b2*d1);\nz3 = -x.*z./(a2*c2*d1);\nz = cos(x)*ones(1,3).*[z1,z2,z3];\nend\n\nend\n\n\n\n\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/mesh/surfacemesh/ellipsoidsurface.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.7106325979507826}} {"text": "function err = getL2error3ND2(node,elem,exactE,Eh,markedElem)\n%% GETL2ERROR3ND2 L2 norm of the quadratic (1st type) Nedelec edge element.\n% \n% error = getL23errorND2(node,elem,exactE,Eh,markedElem);\n%\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details. \n\n%% Sort elem to ascend ordering\nelem = sort(elem,2);\n\n%% Construct Data Structure\n[Dlambda,volume] = gradbasis3(node,elem);\n% elem2dof\n[elem2edge,edge] = dof3edge(elem);\n[elem2face,face] = dof3face(elem);\nNT = size(elem,1); NE = size(edge,1); NF = size(face,1);\nelem2dof = [elem2edge elem2edge+NE elem2face+2*NE elem2face+2*NE+NF];\n% local indices \nlocBasesIdx = [1 2 0; 1 3 0; 1 4 0; 2 3 0; 2 4 0; 3 4 0; ... % phi\n 1 2 0; 1 3 0; 1 4 0; 2 3 0; 2 4 0; 3 4 0; ... % psi\n 3 2 4; 3 1 4; 2 1 4; 2 1 3; ...\n 4 2 3; 4 1 3; 4 1 2; 3 1 2]; % chi\n%% Compute square of the L2 error\nerr = zeros(NT,1);\n[lambda,w] = quadpts3(4); % quadrature order is 4\nnQuad = size(lambda,1);\nfor p = 1:nQuad\n % quadrature points in the x-y-z coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ... \n + lambda(p,3)*node(elem(:,3),:) ... \n + lambda(p,4)*node(elem(:,4),:);\n Ep = exactE(pxy);\n Ehp = zeros(NT,3);\n % compute Ehp at quadrature points\n for k = 1:20\n k1 = locBasesIdx(k,1); \n k2 = locBasesIdx(k,2); \n k3 = locBasesIdx(k,3);\n % evaluate basis at quadrature points\n if k<=6\n % phi_k = lambda_{k1}Dlambda_{k2} - lambda_{k2}Dlambda_{k1};\n basis_k = (lambda(p,k1)*Dlambda(:,:,k2) ...\n -lambda(p,k2)*Dlambda(:,:,k1));\n elseif k<=12\n % phi_k = lambda_{k1}Dlambda_{k2} + lambda_{k2}Dlambda_{k1};\n basis_k = (lambda(p,k1)*Dlambda(:,:,k2) ...\n +lambda(p,k2)*Dlambda(:,:,k1));\n else\n % chi_k = lambda_{k1}phi_{k2,k3}; \n basis_k = lambda(p,k1)*(lambda(p,k2)*Dlambda(:,:,k3) ...\n -lambda(p,k3)*Dlambda(:,:,k2));\n end\n Ehp = Ehp + repmat(Eh(elem2dof(:,k)),1,3).*basis_k;\n end\n err = err + w(p)*volume.*sum((Ep - Ehp).^2,2);\nend\n% modify the error\nerr(isnan(err)) = 0; % remove the singular part\nif (nargin == 5) && ~isempty(markedElem)\n err = err(markedElem); % L2 error on some marked region\nend\nerr = sqrt(sum(err));\n%% TODO add example in M-lint", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/getL2error3ND2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.710621088322947}} {"text": "%% Ex. 7 More complicated use of loop and index\n\n\nb = [2 5 7 4 9 8 3];\nc = [2 3 5 7];\nsum1 = 0;\nfor k = 1:4\n sum1 = sum1+b(c(k));\nend\nsum1\n%Output:\n% 24\n% Remark: This program performs the summation of\n% sum1 = b(c(1))+b(c(2))+b(c(3))+b(c(4))\n% = b(2)+b(3)+b(5)+b(7)\n% = 5+7+9+3\n% = 24", "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_2(basic_looping)/program7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.7106210728047834}} {"text": "% This script estimates the prior of a hedge fund return and processes extreme views on CVaR \n% according to Entropy Pooling\n% This script complements the article\n%\t\"Fully Flexible Extreme Views\"\n%\tby A. Meucci, D. Ardia, S. Keel\n%\tavailable at www.ssrn.com\n% The most recent version of this code is available at\n% MATLAB Central - File Exchange\n\n% IMPORTANT - This script is about the methodology, not the input data, which has been modified\n\nclear; clc; close all;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Fetch data\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nload pseudodata;\n\nxi = 100 * cell2mat(data(:, 2));\nn = length(xi);\n\n% bandwith\nbw = kernelbw(xi);\n\n% weights\nlambda = log(2) / (n / 2);\nwi = exp(-lambda * (n - (n:-1:1)'));\nwi = flipud(wi) / sum(wi);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Prior market model\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% kernel density\nmarket = [];\nmarket.mu = mean(xi);\nmarket.pdf = @(x) kernelpdf(x, xi, bw, wi);\nmarket.cdf = @(x) kernelcdf(x, xi, bw, wi);\nmarket.inv = @(x) kernelinv(x, xi, bw, wi);\nmarket.VaR95 = market.inv(0.05);\nmarket.CVaR95 = quadgk(@(x) (x .* market.pdf(x)), -100, market.VaR95) / 0.05;\n\n\n% numerical (Gauss-Hermite grid) prior \nload ghq1000.mat % load mesh of GH zeros \ntmp = (ghqx-min(ghqx))/(max(ghqx)-min(ghqx)); % rescale GH zeros so they belong to [0,1]\nepsilon = 1e-10;\nLower = market.inv(epsilon);\nUpper = market.inv(1-epsilon);\nX = Lower + tmp * (Upper-Lower); % rescale mesh\n\np = integrateSubIntervals(X, market.cdf);\np = normalizeProb(p);\nJ = length(X); \n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Entropy posterior from extreme view on mean and CVaR\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nview = [];\nview.mu = mean(xi) - 1.0; \nview.CVaR95 = market.CVaR95 - 1.0; \n\n% Netwton Raphson\ns = []; \nidx = cumsum(p) <= 0.05 ;\ns(1) = sum(idx);\n[p_, KLdiv] = optimizeEntropy(p, idx', 0.05, [ones(1, J); X'; (idx .* X)'], [1; view.mu; 0.05 * view.CVaR95]);\n%[p_, KLdiv] = optimizeEntropy(p, [idx'; (idx .* X)'], [0.05; 0.05 * view.CVaR95], [ones(1, J); X'], [1; view.mu]);\n\ndoStop = 0;\ni = 1;\nwhile ~doStop\n i = i + 1;\n\n idx = [ones(1, s(i-1)), zeros(1, J - s(i-1))]';\n [dummy, KLdiv_s] = optimizeEntropy(p, idx', 0.05, [ones(1, J); X'; (idx .* X)'], [1; view.mu; 0.05 * view.CVaR95]);\n %[dummy, KLdiv_s] = optimizeEntropy(p, [idx'; (idx .* X)'], [0.05; 0.05 * view.CVaR95], [ones(1, J); X'], [1; view.mu]);\n \n idx = [ones(1, s(i-1) + 1), zeros(1, J - s(i-1) - 1)]';\n [dummy, KLdiv_s1] = optimizeEntropy(p, idx', 0.05, [ones(1, J); X'; (idx .* X)'], [1; view.mu; 0.05 * view.CVaR95]);\n %[dummy, KLdiv_s1] = optimizeEntropy(p, [idx'; (idx .* X)'], [0.05; 0.05 * view.CVaR95], [ones(1, J); X'], [1; view.mu]);\n \n idx = [ones(1, s(i-1) + 2), zeros(1, J - s(i-1) - 2)]';\n [dummy, KLdiv_s2] = optimizeEntropy(p, idx', 0.05, [ones(1, J); X'; (idx .* X)'], [1; view.mu; 0.05 * view.CVaR95]);\n %[dummy, KLdiv_s2] = optimizeEntropy(p, [idx'; (idx .* X)'], [0.05; 0.05 * view.CVaR95], [ones(1, J); X'], [1; view.mu]);\n\n % first difference\n DE = KLdiv_s1 - KLdiv_s;\n % second difference\n D2E = KLdiv_s2 - 2 * KLdiv_s1 + KLdiv_s;\n % optimal s\n s = [s; round( s(i-1) - (DE / D2E) )]; \n\n tmp = [];\n idx = [ones(1, s(i)), zeros(1, J - s(i))]';\n [tmp.p_, tmp.KLdiv] = optimizeEntropy(p, idx', 0.05, [ones(1, J); X'; (idx .* X)'], [1; view.mu; 0.05 * view.CVaR95]);\n %[tmp.p_, tmp.KLdiv] = optimizeEntropy(p, [idx'; (idx .* X)'], [0.05; 0.05 * view.CVaR95], [ones(1, J); X'], [1; view.mu]);\n p_ = [p_, tmp.p_]; \n KLdiv = [KLdiv; tmp.KLdiv]; %#ok<*AGROW>\n \n % if change in KLdiv less than one percent, stop\n if abs((KLdiv(i) - KLdiv(i-1)) / KLdiv(i-1)) < 0.01 \n doStop = 1;\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Display results\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfigure;\nplot(X, p, 'b', 'LineWidth', 1.5);\nhold on;\nplot(X, p_(:, end), 'r', 'LineWidth', 1.5);\nhold on; plot(market.mu, 0.0, 'o', 'Color', 'Blue', 'MarkerSize', 8, 'MarkerFaceColor', 'Blue'); \nhold on; plot(market.CVaR95, 0.0, '^', 'Color', 'Blue', 'MarkerSize', 8, 'MarkerFaceColor', 'Blue'); \nhold on; plot(view.mu, 0.0, 'o', 'Color', 'Red', 'MarkerSize', 8, 'MarkerFaceColor', 'Red'); \nhold on; plot(view.CVaR95, 0.0, '^', 'Color', 'Red', 'MarkerSize', 8, 'MarkerFaceColor', 'Red'); \ngrid on;\nxlabel('Returns [%]');\nh = legend('Prior', 'Posterior');\nset(h, 'FontSize', 8);\nset(gca, 'YTickLabel', '');\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/26478-fully-flexible-extreme-views/FullyFlexibleExtremeViews/S_Case_Study.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.7106210663937346}} {"text": "function [On,Wr] = reorder_mod(W,M)\n%REORDER_MOD Reorder connectivity matrix by modular structure\n%\n% On = reorder_mod(W,M);\n% [On Wr] = reorder_mod(W,M);\n%\n% This function reorders the connectivity matrix by modular structure and\n% may consequently be useful in visualization of modular structure.\n%\n% Inputs:\n% W, connectivity matrix (binary/weighted undirected/directed)\n% M, module affiliation vector\n%\n% Outputs:\n% On, new node order\n% Wr, reordered connectivity matrix\n%\n%\n% Used in: Rubinov and Sporns (2011) NeuroImage; Zingg et al. (2014) Cell.\n%\n%\n% 2011, Mika Rubinov, UNSW/U Cambridge\n\n% Modification History:\n% Mar 2011: Original\n%\tJan 2015: Improved behavior for directed networks\n\n%#ok<*ASGLU>\n%#ok<*AGROW>\n\nW = W+eps;\n[u,dum,M] = unique(M); %make consecutive;\nn = numel(M); %number of nodes\nm = numel(u); %number of modules\n\nNm=zeros(1,m); %number of nodes in modules\nKnm_o=zeros(n,m); %node-to-module out-degree\nKnm_i=zeros(n,m); %node-to-module in-degree\nfor i=1:m\n Nm(i)=nnz(M==i);\n Knm_o(:,i)=sum(W(:,M==i),2);\n Knm_i(:,i)=sum(W(M==i,:),1);\nend\nKnm=(Knm_o+Knm_i)/2;\n\nWm=zeros(m);\nfor u=1:m\n for v=1:m\n Wm(u,v)=sum(sum(W(M==u,M==v)));\n end\nend\nBm=(Wm+Wm.')./(2*(Nm.'*Nm));\n% Km_o=sum(Wm,2);\n% Km_i=sum(Wm,1);\n% Bm_oi=Wm-Km_o*Km_i/sum(sum(Wm));\n% Bm=(Bm_oi+Bm_oi.')/2;\n\n%1. Arrange densely connected modules together\n[I,J,bv]=find(tril(Bm,-1)); \t%symmetrized intermodular connectivity values\n[~,ord]=sort(bv,'descend'); %sort by greatest relative connectivity\nI=I(ord);\nJ=J(ord);\nOm=[I(1) J(1)]; %new module order\n\nSi=true(size(I));\nSj=true(size(J));\nSi(I==I(1) | I==J(1))=0;\nSj(J==I(1) | J==J(1))=0;\n\nwhile length(Om)0;\n logicAngle=(a1\n %Create edge array\n ee=ee';\n ee=ee(:);\n EE=reshape(E(:,ee)',2,numel(ee)*size(E,1)/2)';\n varargout{2}=EE;\nend\nif nargout>2\n %Create angles for edge array\n AE=reshape(A',1,numel(A))';\n varargout{3}=AE;\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/dihedralAngles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7105273970944053}} {"text": "function[c]=materncfun(al,ga)\n%MATERNCFUN Returns the normalization or C-function for a Matern process.\n%\n% MATERNCFUN is a low-level function used in the JMATERN package.\n%\n% MATERNCFUN(ALPHA) returns the Matern C-function defined in Eqn. (44) of\n% Lilly et al. (2017).\n%\n% MATERNCFUN(ALPHA,GAMMA) returns C-function for the two-parameter \n% generalized Matern process. See MATERNSPEC for details.\n%\n% Usage: c=materncfun(alpha);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2015--2020 J.M. Lilly --- type 'help jlab_license' for details\n \n%c=frac(1,2*pi)*frac(gamma(1/2)*gamma(alpha-1/2),gamma(alpha));\nif nargin==1\n if al>1/2\n c=frac(1,2*sqrt(pi))*frac(gamma(al-1/2),gamma(al));\n else\n c=frac(2.^(abs(al-1/2)-abs(al)),sqrt(2*pi)).*...\n frac(gamma(abs(al-1/2)),gamma(abs(al)));\n end\nelse\n c=frac(1,2*pi*ga).*beta(frac(1,2*ga),frac(1,ga).*(al-1/2));\nend\n%Verified that these two forms are the same for al>1/2\n%al1=[1/2:.01:10]';\n%gamma1=[0:.01:10]';\n%[al,gamma]=meshgrid(al1,gamma1);\n%c=materncfun(al,gamma);\n%jpcolor(al1,gamma1,log10(c)),caxis([-1 0])", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jmatern/materncfun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7105273883386727}} {"text": "\n% p(y_n) = N(y_n | C*x_n, R)\n% p(x_n | x_(n-1)) = N(x_n | A*x_(n-1), Q)\n%\n% [x, Covx, logp] = kalman_filter_step(x, Covx, y, A, Q, C, R, 1)\n%\n% [x, Covx, logp] = kalman_filter_step(x, Covx, y, A, Q, C, inv(chol(R,'lower')), 2)\n\n% Last modified 2011-10-19\n% Copyright (c) Jaakko Luttinen (jaakko.luttinen@aalto.fi)\n\nfunction [x, Covx, logp] = kalman_filter_step(x, Covx, y, A, Q, C, R, method)\n\n% Prediction step\nx = A*x;\nCovx = A*Covx*A' + Q;\n\n% Update step\nswitch method\n case 1\n \n % Standard update step (if length(y) <= length(x))\n y = y - C*x;\n S = C*Covx*C' + R;\n L = chol(S, 'lower');\n K = linsolve_tril(L, C*Covx); %(Covx * C') / S;\n v = linsolve_tril(L, y);\n if nargout >= 3\n logp = gaussian_logpdf(v'*v, ...\n 0, ...\n 0, ...\n logdet_chol(L), ...\n length(y));\n end\n x = x + K'*v;\n Covx = Covx - K'*K; % K*C*Covx;\n\n case 2\n % Update step in lower-dimensional space of X\n \n invL_R = R;\n Lx = chol(Covx, 'lower');\n Z = invL_R * C * Lx;\n L = chol(speye(size(Lx)) + Z'*Z, 'lower');\n v_y = y - C*x;\n v_x = C'*(invL_R'*(invL_R*y)) + linsolve_lchol(Lx,x);\n Z = linsolve_tril(L, Lx');\n Covx = Z'*Z;\n x = Covx * v_x;\n \n if nargout >= 3\n v = invL_R' * (invL_R*v_y); % R \\ (y - C*x)\n logp = gaussian_logpdf(v'*v_y - v'*C*Covx*C'*v, ...\n 0, ...\n 0, ...\n logdet_chol(L) - logdet_chol(invL_R), ...\n length(y));\n end\n \n \n% $$$ invR = R;\n% $$$ S = Covx * C';\n% $$$ K = Covx + S*invR*S';\n% $$$ L = chol(K, 'lower');\n% $$$ Z = L \\ Covx;\n% $$$ if nargout >= 3\n% $$$ % Compute marginal likelihood term\n% $$$ end\n% $$$ x = Z' * linsolve_tril(L, S*(invR*y) + x);\n% $$$ Covx = Z'*Z;\n \nend\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/signal_processing/kalman_filter_step.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.7105273865875261}} {"text": "classdef logistic_regression\n% This file defines logistic regression (binary classifier) problem class\n%\n% Inputs:\n% x_train train data matrix of x of size dxn.\n% y_train train data vector of y of size 1xn.\n% x_test test data matrix of x of size dxn.\n% y_test test data vector of y of size 1xn.\n% lambda l2-regularized parameter. \n% Output:\n% Problem problem instance. \n%\n%\n% The problem of interest is defined as\n%\n% min f(w) = 1/n * sum_i^n f_i(w), \n% where \n% f_i(w) = log(1 + exp(-y_i' .* (w'*x_i))) + lambda/2 * w^2.\n%\n% \"w\" is the model parameter of size d vector.\n%\n%\n% This file is part of GDLibrary and SGDLibrary.\n%\n% Created by H.Kasai on Feb. 17, 2016\n% Modified by H.Kasai on March 23, 2018\n\n\n properties\n name; \n dim;\n samples;\n lambda;\n classes; \n hessain_w_independent;\n d;\n n_train;\n n_test;\n x_train;\n y_train;\n x_test;\n y_test;\n x_norm;\n x; \n end\n \n methods\n function obj = logistic_regression(x_train, y_train, x_test, y_test, varargin) \n \n obj.x_train = x_train;\n obj.y_train = y_train;\n obj.x_test = x_test;\n obj.y_test = y_test; \n\n if nargin < 5\n obj.lambda = 0.1;\n else\n obj.lambda = varargin{1};\n end\n\n obj.d = size(obj.x_train, 1);\n obj.n_train = length(y_train);\n obj.n_test = length(y_test); \n obj.name = 'logistic_regression'; \n obj.dim = obj.d;\n obj.samples = obj.n_train;\n obj.lambda = obj.lambda;\n obj.classes = 2; \n obj.hessain_w_independent = false;\n obj.x_norm = sum(obj.x_train.^2,1);\n obj.x = obj.x_train;\n end\n\n function f = cost(obj, w)\n %f_old = sum(log(1+exp(-y_train.*(w'*x_train)))/n_train,2)+ lambda * (w'*w) / 2; %is replaced below \n % becasuse log(sigmoid(a)) = log(1/(1+exp(-a))) = log1 - log(1+exp(-a)) = -log(1+exp(-a)).\n %f = -sum(log(sigmoid(y_train.*(w'*x_train)))/n_train,2) + lambda * (w'*w) / 2;\n\n % Commented out below due to avoid '-Inf' values of g by HK on 2017/12/5\n % f = -sum(log(sigmoid(y_train.*(w'*x_train))),2)/n_train + lambda * (w'*w) / 2;\n\n % The above is replaced with below by HK on 2017/12/5\n sigmod_result = sigmoid(obj.y_train.*(w'*obj.x_train));\n sigmod_result = sigmod_result + (sigmod_result0.5;\n class2_idx = p<=0.5; \n p(class1_idx) = 1;\n p(class2_idx) = -1; \n\n end\n\n function a = accuracy(obj, y_pred)\n\n a = sum(y_pred == obj.y_test) / obj.n_test; \n\n end\n\n function w_opt = calc_solution(obj, maxiter, method)\n\n if nargin < 3\n method = 'lbfgs';\n end \n\n options.max_iter = maxiter;\n options.verbose = true;\n options.tol_optgap = 1.0e-24;\n options.tol_gnorm = 1.0e-16;\n options.step_alg = 'backtracking';\n\n if strcmp(method, 'sd')\n [w_opt,~] = sd(obj, options);\n elseif strcmp(method, 'cg')\n [w_opt,~] = ncg(obj, options);\n elseif strcmp(method, 'newton')\n options.sub_mode = 'INEXACT'; \n options.step_alg = 'non-backtracking'; \n [w_opt,~] = newton(obj, options);\n else \n options.step_alg = 'backtracking'; \n options.mem_size = 5;\n [w_opt,~] = lbfgs(obj, options); \n end\n end\n\n\n %% for NIM\n function [labels, samples] = get_partial_samples(obj, indices)\n samples = obj.x_train(:,indices);\n labels = obj.y_train(indices);\n end\n\n function [s] = phi_prime(obj, w, indices)\n e = exp(-1.0 * obj.y_train(indices)' .* (obj.x_train(:,indices)'*w));\n s = e ./ (1.0+e); \n end\n\n function [ss] = phi_double_prime(obj, w, indices)\n e = exp(-1.0 * obj.y_train(indices)' .* (obj.x_train(:,indices)'*w));\n s = e ./ (1.0+e); \n ss = s .* (1.0 - s);\n end\n\n\n %% for Sub-sampled Newton\n function h = diag_based_hess(obj, w, indices, square_hess_diag)\n X = obj.x_train(:,indices)';\n h = X' * diag(square_hess_diag) * X / length(indices) + obj.lambda * eye(obj.d);\n end \n\n function square_hess_diag = calc_square_hess_diag(obj, w, indices)\n %hess_diag = 1./(1+exp(Y.*(X*w)))./(1+exp(-Y.*(X*w)));\n Xw = obj.x_train(:,indices)'*w;\n y = obj.y_train(indices)';\n yXw = y .* Xw;\n square_hess_diag = 1./(1+exp(yXw))./(1+exp(-yXw));\n end \n\n end\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/problem/logistic_regression.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7104298344837591}} {"text": "% This function computes the entropy of a label set. \n\n% Copyright (C) 2012 Quan Wang , \n% Signal Analysis and Machine Perception Laboratory, \n% Department of Electrical, Computer, and Systems Engineering, \n% Rensselaer Polytechnic Institute, Troy, NY 12180, USA\n% \n% You are free to use this software for academic purposes if you cite our paper: \n% Q. Wang, Y. Ou, A.A. Julius, K.L. Boyer, M.J. Kim, \n% Tracking tetrahymena pyriformis cells using decision trees, \n% in: 2012 International Conference on Pattern Recognition, Tsukuba Science City, Japan.\n% \n% For commercial use, please contact the authors. \n\nfunction label_ent=getEntropy(label)\n\n% label: one label vector\n% label_ent: resulting entropy\n\nn1=sum(1-label);\nn2=sum(label);\nif n1+n2==0\n label_ent=0;\n return;\nend\np1=n1/(n1+n2);\np2=n2/(n1+n2);\nif p1==0\n label_ent=-p2*log(p2);\n return;\nelseif p2==0\n label_ent=-p1*log(p1);\n return;\nend\nlabel_ent=-p1*log(p1)-p2*log(p2);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/39110-binary-decision-tree/binary_decision_tree_v1.0/code/getEntropy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7104298319569964}} {"text": "function x=v_randvec(n,m,c,w,mode)\n%V_RANDVEC Generate real or complex GMM/lognormal random vectors X=(N,M,C,W,MODE)\n% generates a random matrix of size (|n|,p) where p is the maximum\n% dimension of M or C (see note below about row versus column vectors)\n% Inputs: N is the number of points to generate\n% M(K,P) is the mean vectors (one row per mixture)\n% C(K,P) are diagonal covariances (one row per mixture)\n% or C(P,P,K) are full covariance matrices (one per mixture)\n% W(K) are the mixture weights (or omit if all mixtures have equal weight)\n% MODE character string specifying options:\n% g = real gaussian [default]\n% c = complex gaussian\n% l = lognormal\n%\n% Outputs: X(N,P) is the output data\n%\n% Note this routine generates row vectors such that E((x-m)'*(x-m)) = C = cov(x). If\n% Alternatively x=(n,m',c,w,mode)' will generate column vectors satisfying E((x-m)*(x-m)') = C = cov(x').\n\n% Bugs/suggestions\n% (1) New mode 'x' to approximate chi squared\n\n% Copyright (C) Mike Brookes 1998\n% Version: $Id: v_randvec.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% first sort out the input arguments\n\nsm=size(m);\nif nargin<3\n c=ones(sm); % default to unit variance\nend\nsc=size(c);\np=max(sm(2),sc(2)); % data dimension\nk=sm(1); % number of mixtures\nfullc=(length(sc)>2) || (sc(1)>k);\nif nargin<4\n mode='g'; % default to gaussian\n w=ones(k,1);\nelse\n if ischar(w)\n mode = w; % w argument has been omitted\n w=ones(k,1);\n elseif nargin<5\n mode='g';\n end\nend\nty=mode(1); % ignore all but first character for type\nx=zeros(n,p); % initialize output array\nif sm(2)~=p\n m=repmat(m,1,p); % if m is given as a scalar\nend\nif sc(2) ~=p\n c=repmat(c,1,p); % if c is given as a scalar\nend\nq=sqrt(0.5);\nif k>1\n kx=v_randiscr(w,n);\nelse\n kx=ones(n,1);\nend\nfor kk=1:k\n nx=find(kx==kk);\n nn=length(nx);\n if nn % check if we need to generate any from mixture kk\n\n % extract the mean and cov for this mixture\n\n mm=m(kk,:); % mean vector\n if fullc % full covariance matrix\n cc=c(:,:,kk);\n if ty=='l' % lognormal distribution - convert mean and covariance\n cc=log(1+cc./(mm.'*mm));\n mm=log(mm)-0.5*diag(cc).';\n end\n else\n cc=c(kk,:);\n if ty=='l' % lognormal distribution - convert mean and covariance\n cc=log(1+cc(:).'./mm.^2);\n mm=log(mm)-0.5*cc;\n end\n end\n\n % now generate nn complex or real values\n\n if ty=='c' % generate complex values\n xx=q*randn(nn,p)+1i*q*randn(nn,p); % complex-valued unit variance values\n else\n xx=randn(nn,p); % real-valued unit variance values\n end;\n\n % scale by the square root of the covariance matrix\n\n if fullc % full covariance covariance\n [v,d]=eig((cc+cc')/2); % force covariance matrix to be hermitian\n xx=(xx.*repmat(sqrt(abs(diag(d))).',nn,1))*v'+repmat(mm,nn,1); % and also positive definite\n else\n xx=xx.*repmat(sqrt(abs(cc)),nn,1)+repmat(mm,nn,1); % different mean/cov for each column\n end\n x(nx,:)=xx;\n end\nend\nif ty=='l' % lognormal distribution\n x=exp(x);\nend\nif ~nargout\n if p==1\n if ty=='c'\n plot(real(x), imag(x),'+');\n xlabel('Real');\n ylabel('Imag');\n else\n nbin=max(min(floor(sqrt(n)),50),5);\n hist(x,nbin);\n xlabel('X');\n ylabel('Frequency');\n end\n else\n [vv,iv]=sort(var(x,0,1));\n iv=sort(iv(end-1:end));\n plot(real(x(:,iv(1))), real(x(:,iv(2))),'+');\n if ty=='c'\n xylab='Real[ x(%d) ]';\n else\n xylab='x(%d)';\n end\n xlabel(sprintf(xylab,iv(1)));\n ylabel(sprintf(xylab,iv(2)));\n end\nend\n\n", "meta": {"author": "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_randvec.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7104298299382138}} {"text": "function [ Gnew] = gsp_graph_sparsify(G,epsilon)\n%GSP_GRAPH_SPARSIFY sparsify a graph using Spielman-Srivastava algorithm\n% Usage: Gnew = gsp_graph_sparsify(G,epsilon);\n%\n% Input parameters\n% G : Graph structure or Laplacian matrix\n% epsilon : Sparsification parameter\n%\n% Ouput parameters:\n% Gnew : New sparsified graph or new laplacian\n%\n% This function sparsifies a graph using Spielman-Srivastava algorithm.\n% Note that *epsilon* should be between $1/\\sqrt(N)$ and $1$.\n%\n% Example:::\n%\n% epsilon = 0.5;\n% param.distribute = 1;\n% nnparam.k = 20;\n% param.nnparam = nnparam;\n% G = gsp_sensor(256,param);\n% G2 = gsp_graph_sparsify(G,epsilon);\n% figure(1)\n% gsp_plot_graph(G);\n% title('Original graph')\n% figure(2)\n% gsp_plot_graph(G2);\n% title('Sparsified graph')\n%\n% References: spielman2011graph rudelson1999random rudelson2007sampling\n\n% Author: David Shuman, Nathanael Perraudin\n% Date : 22 June 2014\n% Testing: test_sparsify\n\n\n% Test the input parameters\nif isstruct(G)\n if isfield(G,'lap_type')\n if ~strcmp(G.lap_type,'combinatorial')\n error('Not implemented yet');\n end\n end\n L = G.L;\nelse\n L = G;\nend \n\nN=size(L,1);\n\nif N<3\n error('GSP_GRAPH_SPARSIFY: Cannot sparsify a graph with less than 3 nodes');\nend\n\n% Epsilon should be between 1/sqrt(N) and 1, with a larger epsilon leading to a sparser graph\nif ( (epsilon <= 1/sqrt(N)) || (epsilon >1) )\n error('GSP_GRAPH_SPARSIFY: Epsilon out of required range');\nend\n\n\n% Compute resistance distances\nresistance_distances = gsp_resistance_distances(L);\n\n% Get the weight matrix, and check if the original graph is connected\nif isstruct(G)\n W = G.W;\nelse\n W = diag(diag(L)) - L;\nend\nW(W<1e-10) = 0;\nW = sparse(W);\noriginal_connected=gsp_check_connectivity_undirected(W);\nif (original_connected==0)\n warning('Original graph not connected before sparsification');\nend\n\n% Initialize the probability distribution that will be used to select edges in the sparsified graph\n[start_nodes,end_nodes,weights]=find(tril(W));\nweights=max(0,weights);\nRe=max(0,resistance_distances(sub2ind(size(resistance_distances),start_nodes,end_nodes)));\nPe=weights.*Re;\nPe=Pe/sum(Pe);\n \nmax_tries=10; % maximum number of tries to get a connected graph\n\nfor i=1:max_tries\n \n % Set Q\n C0=1/30; % Rudelson, 1996 Random Vectors in the Isotropic Position (too hard to figure out actual C0)\n C= 4*C0; % Rudelson and Vershynin, 2007, Thm. 3.1\n q=round(9*C^2*N*log(N)/(epsilon^2));\n\n % Choose random edges in the new graph according the probability\n % distribution initialized above\n results=gendist(Pe',q,1);\n spin_counts=hist(results,1:length(Pe'));\n per_spin_weights=weights./(q*Pe);\n\n % Tally the new weights and form the new graph\n new_weights=spin_counts'.*per_spin_weights;\n \n sparserW=sparse(start_nodes,end_nodes,new_weights,N,N);\n sparserW=sparserW+sparserW';\n sparserL=diag(sum(sparserW))-sparserW;\n sparserA=sign(sparserW);\n\n % Check if new graph is connected. If not, reduce epsilon and try again\n new_graph_connected=gsp_check_connectivity_undirected(sparserA);\n if new_graph_connected\n break;\n elseif i==max_tries\n warning('Despite attempts to reduce epsilon, sparsified graph is disconnected');\n else\n epsilon=epsilon-(epsilon-1/sqrt(N))/2;\n end\nend\n\nif isstruct(G)\n if ~G.directed\n sparserW = (sparserW + sparserW')/2;\n sparserL = (sparserL + sparserL')/2;\n end\n Gnew=G;\n Gnew.W = sparserW;\n Gnew.L = sparserL;\n Gnew.A = sparserA;\n Gnew.d = diag(sparserL);\n Gnew.Ne = nnz(Gnew.W)/2;\nelse\n Gnew = sparse(sparserL);\nend\n\n\nend\n\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/utils/gsp_graph_sparsify.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7104298259006485}} {"text": "function [ x, w ] = square_symq ( degree, n )\n\n%*****************************************************************************80\n%\n%% SQUARE_SYMQ returns a symmetric quadrature rule for the square.\n%\n% Discussion:\n%\n% This procedure returns a quadrature rule for smooth functions\n% on the unit square [-1,1]^2.\n%\n% All quadratures are accurate to 15 digits\n% All weights are positive and inside the square\n%\n% The nodes are symmetrically arranged.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 July 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This 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 degree of the quadrature rule.\n% 1 <= DEGREE <= 20.\n%\n% Input, integer N, the number of nodes.\n% This can be determined by a call to RULE_FULL_SIZE(DEGREE).\n%\n% Output, real X(2,N), the coordinates of the nodes.\n%\n% Output, real W(N), the weights.\n%\n if ( degree == 1 )\n [ x, w ] = rule01 ( n );\n elseif ( degree == 2 )\n [ x, w ] = rule02 ( n );\n elseif ( degree == 3 )\n [ x, w ] = rule03 ( n );\n elseif ( degree == 4 )\n [ x, w ] = rule04 ( n );\n elseif ( degree == 5 )\n [ x, w ] = rule05 ( n );\n elseif ( degree == 6 )\n [ x, w ] = rule06 ( n );\n elseif ( degree == 7 )\n [ x, w ] = rule07 ( n );\n elseif ( degree == 8 )\n [ x, w ] = rule08 ( n );\n elseif ( degree == 9 )\n [ x, w ] = rule09 ( n );\n elseif ( degree == 10 )\n [ x, w ] = rule10 ( n );\n elseif ( degree == 11 )\n [ x, w ] = rule11 ( n );\n elseif ( degree == 12 )\n [ x, w ] = rule12 ( n );\n elseif ( degree == 13 )\n [ x, w ] = rule13 ( n );\n elseif ( degree == 14 )\n [ x, w ] = rule14 ( n );\n elseif ( degree == 15 )\n [ x, w ] = rule15 ( n );\n elseif ( degree == 16 )\n [ x, w ] = rule16 ( n );\n elseif ( degree == 17 )\n [ x, w ] = rule17 ( n );\n elseif ( degree == 18 )\n [ x, w ] = rule18 ( n );\n elseif ( degree == 19 )\n [ x, w ] = rule19 ( n );\n elseif ( degree == 20 )\n [ x, w ] = rule20 ( n );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SQUARESYMVQ - Fatal error!\\n' );\n fprintf ( 1, ' Illegal value of DEGREE.\\n' );\n error ( 'SQUARE_SYMQ - Fatal error!' );\n end\n\n w_sum = sum ( w(1:n) );\n\n w(1:n) = 4.0 * w(1:n) / w_sum;\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/square_symq_rule/square_symq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7104298213551035}} {"text": "function nScatt = diracnorm_scat(x,cascade)\n\t% Calculation of a normalized scattering representation\n\t% nScatt is an array of size 2N which stores a\n\t% piecewise constant signal giving\n\t% the 2^J normalized values || SJ [p]f||/||SJ[p] delta||\n\t% over intervals of lengths proportional to ||SJ[p] delta||^2 .\n\t% Normalized scattering transforms are defined in the paper\n\t% \"Group Invariant Scattering\", S. Mallat, http://arxiv.org/abs/1101.2286\n\t\n\tN=size(x,1); % N must be an integer multiplied by a very high power of 2\n\t%Compute the scattering transform of the signal x and output it in a table\n\tSx=scat(x,cascade);\n\t\n\t%Prepare the dirac signal\n\tdirac = zeros(N,1);\n\tdirac(N/2) = 1;\n\t%Compute its scattering transform and output it in the form of a table\n\n\tSdirac=scat(dirac, cascade);\n\t%%\n\t%fprintf('scat time\\n');\n\t[Scatt order2]=reorder_scat(Sx);\n\n\t%%\n\tnSdirac=reorder_scat(Sdirac);\n\t\n\t%%\n\t%fprintf('reordering time\\n');\n\t\n\tlsig=2*N/2^(length(Sx{2}.signal));\n\t\n\t\n\tfor k=0:lsig:2*N-lsig\n\t\t\n\t\tnormd=norm(nSdirac(k+1:k+lsig));\n\t\tnormx=norm(Scatt(k+1:k+lsig))/normd;\n\t\t\n\t\t% the order is coded in the smallest digits of normx\n\t\tnormx = 10^(-6) * floor(normx * 10^(6));\n\t\tScatt(k+1:k+lsig) = normx + order2(k+1)* 10^(-7);\n\t\t\n\t\tnSdirac(k+1:k+lsig)=normd^2;\n\t\t\n\tend\n\t\n\tC=sum(nSdirac)/lsig;\n\t\n\tp=0;\n\tfor k=0:lsig:2*N-lsig\n\t\tstep=nSdirac(k+1) * 2 * N/C;\n\t\t\n\t\tnScatt(floor(p+1):round(p+step))=Scatt(k+1);\n\t\tp=p+step;\n\tend\n\t\n\t\n\t\nend\n\n\n", "meta": {"author": "scatnet", "repo": "scatnet", "sha": "59d935afa20359845282a3518134e24244862c1f", "save_path": "github-repos/MATLAB/scatnet-scatnet", "path": "github-repos/MATLAB/scatnet-scatnet/scatnet-59d935afa20359845282a3518134e24244862c1f/scatutils/diracnorm_scat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.7853085758631158, "lm_q1q2_score": 0.7104298152987552}} {"text": "function [rrho, xxvec, yyvec] = density(x, y, dx, dy, xy0);\n% [rho, xvec, yvec] = density(x, y, dx, dy, [x0 x1 y0 y1]); \n% \n% 2-D probability density plot.\n%\n% Input: Vectors x and y of equal length. If dx and/or dy are omitted, the\n% default is 75 bins in each direction.\n% \n% If dx or dy is negative, then the variable is taken as the number of\n% bins rather than a grid resolution.\n%\n% The vector containing the limits can be padded with NaNs if only\n% certain limits are desired, e g if x0 and y1 are wanted:\n%\n% density(x, y, [.5 nan nan 45])\n%\n% Output: The density matrix RHO together with vectors XVEC and YVEC. \n% If no output arguments are specified, DENSITY will plot the density\n% function with the prescribed axes using PCOLOR. \n%\n% Requires bin.m. Tested under MatLab 4.2, 5.0, and 5.1.\n%\n% See also bin.m for further details about dx, x0, etc, and ffgrid.m.\n%\n\n% 1.9.97 Oyvind.Breivik@gfi.uib.no.\n%\n% Oyvind Breivik\n% Department of Geophysics\n% University of Bergen\n% NORWAY\n\nDX = -75; % Default grid size\n\nx = x(:);\n\nif nargin < 2\n y = x;\nend\n\ny = y(:);\n\nxy = NaN*ones(1,4);\n\nif (nargin < 4)\n xy0 = min(x);\nend\n\nif (nargin == 3 & length(dx) > 1)\n xy0 = dx;\n dx = DX;\nend\n\nif nargin < 3\n dx = DX;\nend\n\nif (nargin == 4 & length(dy) > 1)\n xy0 = dy;\n dy = dx;\nend\nif nargin < 4\n dy = dx;\nend\n\nnxy = length(xy0);\nxy(1:nxy) = xy0;\n\nif (isnan(xy(4)))\n xy(4) = max(y);\nend\nif (isnan(xy(3)))\n xy(3) = min(y);\nend\nif (isnan(xy(2)))\n xy(2) = max(x);\nend\nif (isnan(xy(1)))\n xy(1) = min(x);\nend\nx0 = xy(1); x1 = xy(2); y0 = xy(3); y1 = xy(4);\n\nif (dx < 0)\n dx = (x1 - x0)/abs(dx);\nend\nif (dy < 0)\n dy = (y1 - y0)/abs(dy);\nend\n\nix = bin(x, dx, x0, x1);\niy = bin(y, dy, y0, y1); % bin data in (x,y)-space\n\nxvec = x0:dx:x1;\nyvec = y0:dy:y1;\n\nnx = length(xvec);\nny = length(yvec);\n\ninx = (ix >= 1) & (ix <= nx);\niny = (iy >= 1) & (iy <= ny);\nin = (inx & iny);\nix = ix(in); iy = iy(in);\nN = length(ix); % how many datapoints are left now?\n\nrho = zeros(length(xvec), length(yvec)) + eps;\n\nfor i = 1:N\n rho(ix(i), iy(i)) = rho(ix(i), iy(i)) + 1;\nend\n\nrho = rho/(N*dx*dy); % Density is n per dx per dy\n\nrho = rho'; % Get in shape\n\nif nargout == 0\n pcolor(xvec, yvec, rho)\n colorbar\n colormap jet\n xlabel(inputname(1))\n ylabel(inputname(2))\n dum = size(rho');\n str = sprintf('%d data points, grid: %dx%d', N, dum(1)-1, dum(2)-1);\n title(str);\nend\n\nif nargout > 0\n rrho = rho;\nend\n\nif nargout > 1\n xxvec = xvec;\n yyvec = yvec;\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/293-uneven/density.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7104125526633177}} {"text": "function centroid = voronoi_centroids ( n, first, list_num, list, xyz, v_num, v_xyz )\n\n%*****************************************************************************80\n%\n%% VORONOI_CENTROIDS computes the centroids of each polygon in a Voronoi diagram.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 02 May 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of data points and Voronoi polygons.\n%\n% Input, integer FIRST(N+1), for each polygon, points to the location\n% in LIST of the index.\n%\n% Input, integer LIST_NUM, the number of items in LIST.\n%\n% Input, integer LIST(LIST_NUM), the indices of vertices that form \n% each polygon.\n%\n% Input, real XYZ(3,N), the coodinates of the data points.\n%\n% Input, integer V_NUM, the number of Voronoi vertices.\n%\n% Input, real V_XYZ(3,V_NUM), the coordinates of the Voronoi vertices.\n%\n% Output, real CENTROID(3,N), the centroid of each Voronoi polygon.\n%\n centroid = zeros ( 3, n );\n\n r = 1.0;\n\n for poly = 1 : n\n%\n% Compute the area of each triangle formed by one side of the polygon\n% and the Delaunay point.\n%\n v3 = list(first(poly+1)-1);\n\n for l = first(poly) : first(poly+1) - 1\n\n v2 = v3;\n v3 = list(l);\n\n stri_area = stri_vertices_to_area ( r, ...\n xyz(1:3,poly), v_xyz(1:3,v2), v_xyz(1:3,v3) );\n\n stri_centroid = stri_vertices_to_centroid ( r, ...\n xyz(1:3,poly), v_xyz(1:3,v2), v_xyz(1:3,v3) );\n\n centroid(1:3,poly) = centroid(1:3,poly) + stri_area * stri_centroid(1:3,1);\n\n end\n\n centroid(1:3,poly) = centroid(1:3,poly) / norm ( centroid(1:3,poly) );\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_voronoi/voronoi_centroids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7104096787253442}} {"text": "function [xd,xn,option] = denoise(x,h,type,option)\n% [xd,xn,option] = denoise(x,h,type,option); \n%\n% DENOISE is a generic program for wavelet based denoising.\n% The program will denoise the signal x using the 2-band wavelet\n% system described by the filter h using either the traditional \n% discrete wavelet transform (DWT) or the linear shift invariant \n% discrete wavelet transform (also known as the undecimated DWT\n% (UDWT)). \n%\n% Input: \n% x : 1D or 2D signal to be denoised\n% h : Scaling filter to be applied\n% type : Type of transform (Default: type = 0)\n% 0 --> Discrete wavelet transform (DWT)\n% 1 --> Undecimated DWT (UDWT)\n% option : Default settings is marked with '*':\n% *type = 0 --> option = [0 3.0 0 0 0 0]\n% type = 1 --> option = [0 3.6 0 1 0 0]\n% option(1) : Whether to threshold low-pass part\n% 0 --> Don't threshold low pass component \n% 1 --> Threshold low pass component\n% option(2) : Threshold multiplier, c. The threshold is\n% computed as: \n% thld = c*MAD(noise_estimate)). \n% The default values are:\n% c = 3.0 for the DWT based denoising\n% c = 3.6 for the UDWT based denoising\n% option(3) : Type of variance estimator\n% 0 --> MAD (mean absolute deviation)\n% 1 --> STD (classical numerical std estimate)\n% option(4) : Type of thresholding\n% 0 --> Soft thresholding\n% 1 --> Hard thresholding\n% option(5) : Number of levels, L, in wavelet decomposition. By\n% setting this to the default value '0' a maximal\n% decomposition is used.\n% option(6) : Actual threshold to use (setting this to\n% anything but 0 will mean that option(3)\n% is ignored)\n%\n% Output: \n% xd : Estimate of noise free signal \n% xn : The estimated noise signal (x-xd)\n% option : A vector of actual parameters used by the\n% program. The vector is configured the same way as\n% the input option vector with one added element\n% option(7) = type.\n%\n% HERE'S AN EASY WAY TO RUN THE EXAMPLES:\n% Cut-and-paste the example you want to run to a new file \n% called ex.m, for example. Delete out the % at the beginning \n% of each line in ex.m (Can use search-and-replace in your editor\n% to replace it with a space). Type 'ex' in matlab and hit return.\n%\n% Example 1: \n% h = daubcqf(6); [s,N] = makesig('Doppler'); n = randn(1,N);\n% x = s + n/10; % (approximately 10dB SNR)\n% figure;plot(x);hold on;plot(s,'r');\n%\n% %Denoise x with the default method based on the DWT\n% [xd,xn,opt1] = denoise(x,h);\n% figure;plot(xd);hold on;plot(s,'r');\n%\n% %Denoise x using the undecimated (LSI) wavelet transform\n% [yd,yn,opt2] = denoise(x,h,1);\n% figure;plot(yd);hold on;plot(s,'r');\n%\n% Example 2: (on an image) \n% h = daubcqf(6); load lena; \n% noisyLena = lena + 25 * randn(size(lena));\n% figure; colormap(gray); imagesc(lena); title('Original Image');\n% figure; colormap(gray); imagesc(noisyLena); title('Noisy Image'); \n% Denoise lena with the default method based on the DWT\n% [denoisedLena,xn,opt1] = denoise(noisyLena,h);\n% figure; colormap(gray); imagesc(denoisedLena); title('denoised Image');\n% \n%\n% See also: mdwt, midwt, mrdwt, mirdwt, SoftTh, HardTh, setopt\n%\n\n%File Name: denoise.m\n%Last Modification Date: 04/15/97\t10:44:28\n%Current Version: denoise.m\t2.4\n%File Creation Date: Mon Feb 20 08:33:15 1995\n%Author: Jan Erik Odegard \n%\n%Copyright (c) 2000 RICE UNIVERSITY. All rights reserved.\n%Created by Jan Erik Odegard, Department of ECE, Rice University. \n%\n%This software is distributed and licensed to you on a non-exclusive \n%basis, free-of-charge. Redistribution and use in source and binary forms, \n%with or without modification, are permitted provided that the following \n%conditions are met:\n%\n%1. Redistribution of source code must retain the above copyright notice, \n% this list of conditions and the following disclaimer.\n%2. Redistribution in binary form must reproduce the above copyright notice, \n% this list of conditions and the following disclaimer in the \n% documentation and/or other materials provided with the distribution.\n%3. All advertising materials mentioning features or use of this software \n% must display the following acknowledgment: This product includes \n% software developed by Rice University, Houston, Texas and its contributors.\n%4. Neither the name of the University 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%\n%THIS SOFTWARE IS PROVIDED BY WILLIAM MARSH RICE UNIVERSITY, HOUSTON, TEXAS, \n%AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, \n%BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS \n%FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RICE UNIVERSITY \n%OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, \n%EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n%PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; \n%OR BUSINESS INTERRUPTIONS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \n%WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n%OTHERWISE), PRODUCT LIABILITY, OR OTHERWISE ARISING IN ANY WAY OUT OF THE \n%USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n%\n%For information on commercial licenses, contact Rice University's Office of \n%Technology Transfer at techtran@rice.edu or (713) 348-6173\n%\n%Change History: Fixed output of function and an error in the computation\n% of the threshold for redundant denoising.\n% \n%\n% This code is composed of several of our old codes for\n% wavelet based denoising. In an effort to make the mess\n% more manageable we decided to create on code that would \n% handle all the various wavelet based denoising methods.\n% However, only time will show (as we discover new and \n% improved forms of denoising) if we can succeed in our goals.\n% \n%\n\nif(nargin < 2)\n error('You need to provide at least 2 inputs: x and h');\nend;\nif(nargin < 3),\n type = 0;\n option = [];\nelseif(nargin < 4)\n option = [];\nend;\nif(isempty(type)),\n type = 0;\nend;\nif(type == 0),\n default_opt = [0 3.0 0 0 0 0];\nelseif(type == 1),\n default_opt = [0 3.6 0 1 0 0];\nelse,\n error(['Unknown denoising method',10,...\n\t 'If it is any good we need to have a serious talk :-)']);\nend;\noption = setopt(option,default_opt);\n[mx,nx] = size(x);\ndim = min(mx,nx);\nif(dim == 1),\n n = max(mx,nx);\nelse,\n n = dim;\nend;\nif(option(5) == 0),\n L = floor(log2(n));\nelse\n L = option(5);\nend;\nif(type == 0), \t\t\t% Denoising by DWT\n xd = mdwt(x,h,L);\n if (option(6) == 0),\n tmp = xd(floor(mx/2)+1:mx,floor(nx/2)+1:nx);\n if(option(3) == 0),\n thld = option(2)*median(abs(tmp(:)))/.67;\n elseif(option(3) == 1),\n thld = option(2)*std(tmp(:));\n else\n error('Unknown threshold estimator, Use either MAD or STD');\n end;\n else,\n thld = option(6);\n end;\n if(dim == 1)\n ix = 1:n/(2^L);\n ykeep = xd(ix);\n else\n ix = 1:mx/(2^L);\n jx = 1:nx/(2^L);\n ykeep = xd(ix,jx);\n end;\n if(option(4) == 0),\n xd = SoftTh(xd,thld);\n elseif(option(4) == 1),\n xd = HardTh(xd,thld);\n else,\n error('Unknown threshold rule. Use either Soft (0) or Hard (1)');\n end;\n if (option(1) == 0),\n if(dim == 1),\n xd(ix) = ykeep;\n else,\n xd(ix,jx) = ykeep;\n end;\n end;\n xd = midwt(xd,h,L);\nelseif(type == 1), \t\t\t% Denoising by UDWT\n [xl,xh] = mrdwt(x,h,L);\n if(dim == 1),\n c_offset = 1;\n else,\n c_offset = 2*nx + 1;\n end;\n if (option(6) == 0),\n tmp = xh(:,c_offset:c_offset+nx-1);\n if(option(3) == 0),\n thld = option(2)*median(abs(tmp(:)))/.67;\n elseif(option(3) == 1),\n thld = option(2)*std(tmp(:));\n else\n error('Unknown threshold estimator, Use either MAD or STD');\n end;\n else,\n thld = option(6);\n end;\n if(option(4) == 0),\n xh = SoftTh(xh,thld);\n if(option(1) == 1),\n xl = SoftTh(xl,thld);\n end;\n elseif(option(4) == 1),\n xh = HardTh(xh,thld);\n if(option(1) == 1),\n xl = HardTh(xl,thld);\n end;\n else,\n error('Unknown threshold rule. Use either Soft (0) or Hard (1)');\n end;\n xd = mirdwt(xl,xh,h,L);\nelse, \t\t\t\t\t% Denoising by unknown method\n error(['Unknown denoising method',10,...\n 'If it is any good we need to have a serious talk :-)']);\nend;\noption(6) = thld;\noption(7) = type;\nxn = x - xd; \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_WaveletRice/denoise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7104096730810683}} {"text": "function [Yi]=interp1_ND(X,Y,Xi,interpDim,interpMethod)\n\n% function [Yi]=interp1_ND(X,Y,Xi,interpDim,interpMethod)\n% ------------------------------------------------------------------------\n% This function is similar to interp1. However it can perform 1D\n% interpolation for multidimensional arrays. E.g. Time interpolation for 3D\n% image data varying in time. The direction of interpolation is specified\n% by interpDim, and the method by interpMethod\n% ('nearest','linear','cubic','pchip').\n%\n%\n% Reference for pchip method:\n% F. N. Fritsch and R. E. Carlson, \"Monotone Piecewise Cubic\n% Interpolation\", SIAM J. Numerical Analysis 17, 1980, 238-246.\n% David Kahaner, Cleve Moler and Stephen Nash, Numerical Methods\n% and Software, Prentice Hall, 1988.\n%\n% Kevin Mattheus Moerman\n% gibbon.toolbox@gmail.com\n% \n% 2015/03/04\n%------------------------------------------------------------------------\n\n%% Check input\n\n%Check number of dimensions\nnDimsX = ndims(X);\nnDimsXi = ndims(Xi);\n\nif nDimsX~=nDimsXi\n if size(Xi,nDimsX)~=1\n error('Input arrays have different number of dimensions');\n end\nend\n\n%Check column/row form\nif iscolumn(X)\n X=X';\nend\n\nif iscolumn(Xi)\n Xi=Xi';\nend\n\nif isvector(X)\n interpDim=2;\nend\n\n%% Cast in 2D array format\n\nsiz=size(X);\nsiz_i=size(Xi);\n\ndimInd=1:nDimsX;\nlogicNotInterpDim=dimInd~=interpDim;\npermOrder=[sort(dimInd(logicNotInterpDim)) interpDim];\n\n%Permuting array order so that interpolation dimension is last\nX = permute(X,permOrder);\nY = permute(Y,permOrder);\nXi = permute(Xi,permOrder);\n\n%Convert to 2D array with interpolation performed allong column direction\nsiz1=prod(siz(logicNotInterpDim));\nX=reshape(X(:),[siz1, numel(X)/siz1]);\nY=reshape(Y(:),[siz1, numel(Y)/siz1]);\nXi=reshape(Xi(:),[siz1, numel(Xi)/siz1]);\n\n%%\n\nsiz_2D=size(X);\nsiz_i_2D=size(Xi);\n\nswitch interpMethod\n case {'cubic','pchip'}\n diff_Y=diff(Y,1,2);\n diff_X=diff(X,1,2); \n K=diff_Y./diff_X;\nend\n\nswitch interpMethod\n case 'cubic'\n M=zeros(siz_2D);\n M(:,1)=K(:,1);\n M(:,end)=K(:,end);\n M(:,2:end-1)=0.5*(K(:,1:end-1)+K(:,2:end));\n case 'pchip'\n M = pchipSlopes(X,Y,K); \nend\n\n%%\n\nI=(1:siz_2D(1))';\n\n%Initialize\nYi=nan(siz_i_2D);\np0=zeros(size(X,1),1); p1=p0;\nswitch interpMethod\n case 'cubic'\n m0=p0; m1=p0;\n case 'pchip'\n m0=p0; m1=p0;\nend\n\nfor q=1:1:siz_i_2D(end)\n \n %Find close point pair to define interval\n D=abs(X-Xi(:,q*ones(1,size(X,2))));\n \n [~,J1]=min(D,[],2);\n indMin1=sub2ind(siz_2D,I,J1);\n D(indMin1)=inf;\n [~,J2]=min(D,[],2);\n indSort=[J1 J2];\n indSort=sort(indSort(:,1:2),2); %Sorted indices of closest two\n \n ind1=sub2ind(siz_2D,I,indSort(:,1));\n ind2=sub2ind(siz_2D,I,indSort(:,2));\n \n w=X(ind2)-X(ind1); %interval width\n t=(Xi(:,q)-X(ind1))./w; %t coordinate in domain\n p0(1:end)=Y(ind1); %First point\n p1(1:end)=Y(ind2); %End point\n switch interpMethod\n case {'cubic','pchip'}\n m0(1:end)=M(ind1); %First derivative\n m1(1:end)=M(ind2); %Final derivative \n \n h00=2.*t.^3-3.*t.^2+1;\n h10=t.^3-2*t.^2+t;\n h01=-2*t.^3+3*t.^2;\n h11=t.^3-t.^2;\n pt=h00.*p0 + w.*h10.*m0 + h01.*p1 + w.*h11.*m1; \n case 'linear'\n pt=t.*p1+(1-t).*p0;\n case 'nearest'\n logicPrev=t<=0.5;\n pt(logicPrev)=p0(logicPrev);\n pt(~logicPrev)=p1(~logicPrev);\n end\n \n Yi(:,q)=pt; %Store in array\n \nend\n\n%% Cast back in original form\n\n% Xi=reshape(Xi(:),siz_i(permOrder));\n% Xi=ipermute(Xi,permOrder);\n\nYi=reshape(Yi(:),siz_i(permOrder));\nYi=ipermute(Yi,permOrder);\n\nend\n%%\nfunction M = pchipSlopes(X,Y,dYdX)\n%PCHIPSLOPES Derivative values for shape-preserving Piecewise Cubic Hermite\n% Interpolation.\n% d = pchipslopes(x,y,del) computes the first derivatives, d(k) = P'(x(k)).\n\nn = size(X,2);\n\n% Slopes at interior points.\n% d(k) = weighted average of del(k-1) and del(k) when they have the same sign.\n% d(k) = 0 when del(k-1) and del(k) have opposites signs or either is zero.\n\nM = zeros(size(Y));\n\n[I,J]= find(sign(dYdX(:,1:n-2)).*sign(dYdX(:,2:n-1)) > 0);\nind=sub2ind(size(X),I,J);\nind1=sub2ind(size(X),I,J+1);\n\nh = diff(X,1,2);\nhs = h(ind)+h(ind1);\nw1 = (h(ind)+hs)./(3*hs);\nw2 = (hs+h(ind1))./(3*hs);\ndmax = max(abs(dYdX(ind)), abs(dYdX(ind1)));\ndmin = min(abs(dYdX(ind)), abs(dYdX(ind1)));\nM(ind1) = dmin./conj(w1.*(dYdX(ind)./dmax) + w2.*(dYdX(ind1)./dmax));\n\n% Slopes at end points.\n% Set d(1) and d(n) via non-centered, shape-preserving three-point formulae.\n\nM(:,1) = ((2*h(:,1)+h(:,2)).*dYdX(:,1) - h(:,1).*dYdX(:,2))./(h(:,1)+h(:,2));\nL = (sign(M(:,1)) ~= sign(dYdX(:,1)));\nM(L,1) = 0;\n\nL = ((sign(dYdX(:,1)) ~= sign(dYdX(:,2))) & (abs(M(:,1)) > abs(3*dYdX(:,1))));\nM(L,1) = 3*dYdX(L,1);\n\nM(:,n) = ((2*h(:,n-1)+h(:,n-2)).*dYdX(:,n-1) - h(:,n-1).*dYdX(:,n-2))./(h(:,n-1)+h(:,n-2));\n\nL= sign(M(:,n)) ~= sign(dYdX(:,n-1));\nM(L,n) = 0;\n \nL= (sign(dYdX(:,n-1)) ~= sign(dYdX(:,n-2))) & (abs(M(:,n)) > abs(3*dYdX(:,n-1)));\nM(L,n) = 3*dYdX(L,n-1);\n\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/interp1_ND.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7103666058263775}} {"text": "function result = ball_unit_f3_nd ( func, n )\n\n%*****************************************************************************80\n%\n%% BALL_UNIT_F3_ND approximates an integral inside the unit ball in ND.\n%\n% Integration region:\n%\n% Points X(1:N) such that:\n%\n% Sum ( X(1:N)**2 ) <= 1.\n%\n% Discussion:\n%\n% A 2**(N+1)-1 point 5-th degree formula is used, Stroud number SN:5-4.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 23 May 2004\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% Output, real RESULT, the approximate integral of the function.\n%\n quad = 0.0E+00;\n%\n% The first point is the center of the ball.\n%\n x(1:n) = 0.0E+00;\n\n weight = 4.0E+00 / ( n + 2 )^2;\n quad = quad + weight * feval ( func, n, x );\n\n s = 1.0E+00 / sqrt ( ( n + 4 ) );\n\n for i = 1 : n\n\n ri = sqrt ( ( i + 2 ) / ( n + 4 ) );\n%\n% Set up the first point, with (I-1) zeroes, RI, and then N-I S's.\n%\n for j = 1 : n\n\n if ( j < i )\n x(j) = 0.0E+00;\n elseif ( j == i )\n x(j) = ri;\n else\n x(j) = s;\n end\n\n end\n\n weight = 2.0E+00^( i - n ) * ( n + 4 ) / ( ( i + 1 ) * ( i + 2 ) * ( n + 2 ) );\n%\n% Now go through all sign permutations of the basic point.\n%\n for j = 1 : 2^(n+1-i)\n\n jtemp = j - 1;\n\n for k = i : n\n\n if ( mod ( jtemp, 2 ) == 1 )\n x(k) = - abs ( x(k) );\n else\n x(k) = abs ( x(k) );\n end\n\n jtemp = floor ( jtemp / 2 );\n\n end\n\n quad = quad + weight * feval ( func, n, x );\n\n end\n\n end\n\n volume = ball_unit_volume_nd ( n );\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_unit_f3_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.8175744806385543, "lm_q1q2_score": 0.7103305920171875}} {"text": "function qmr_test ( )\n\n%*****************************************************************************80\n%\n%% QMR_TEST tests QMR.\n%\n% Modified:\n%\n% 27 March 2006\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QMR_TEST:\\n' );\n fprintf ( 1, ' QMR uses the Quasi-Minimum Residual \\n' );\n fprintf ( 1, ' iterative method to approximate the solution \\n' );\n fprintf ( 1, ' of a linear system A * x = b.\\n' );\n\n n = 10;\n\n A = zeros ( n, n );\n\n for i = 1 : n\n A(i,i) = 2.0;\n end\n for i = 1 : n-1\n A(i,i+1) = -1;\n end\n for i = 2 : n\n A(i-1,i) = -1;\n end\n x = [ 1 : n ]';\n b = A * x;\n x = ones ( n, 1 );\n\n M = 0;\n max_it = 10;\n tol = 0.0001;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For this example, the order of the system is N = %d\\n', n );\n fprintf ( 1, ' The matrix A is the simple tridiagonal -1, 2, -1.\\n' );\n fprintf ( 1, ' The correct solution is x = [ 1, 2, ..., n].\\n' );\n fprintf ( 1, ' The right hand side b is determined by computing A * x.\\n' );\n fprintf ( 1, ' The exact x is then replaced by a vector of all 1''s for\\n' );\n fprintf ( 1, ' use as a starting guess.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Other parameters are set as follows:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The maximum number of steps is %d.\\n', max_it );\n fprintf ( 1, ' The error tolerance is %f\\n', tol );\n\n [ x, error_norm, iter, flag ] = qmr ( A, x, b, M, max_it, tol );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The QMR routine has returned with FLAG = %d\\n', flag );\n if ( flag == 0 )\n fprintf ( 1, ' This indicates that the iteration has converged.\\n' );\n elseif ( flag == 1 ) \n fprintf ( 1, ' This indicates that the iteration has NOT converged.\\n' );\n end\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The number of iterations taken was %d\\n', iter );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The L2 norm of the error per iteration:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : iter\n fprintf ( 1, ' %4d %f\\n', i, error_norm(i) );\n end\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The computed solution vector X:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n\n fprintf ( 1, ' %4d %f\\n', i, x(i) );\n end\n \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QMR_TEST:\\n' );\n fprintf ( 1, ' Normal end of execution.\\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/templates/qmr_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7102747192430118}} {"text": "function TF = raisedCos (f,Tb,r)\n% Raised Cosine Filter\n% f = Frequency Matrix\n% Tb = Bit Period\n% r = Rolloff Factor\n\nW0 = 1/(2*Tb);\nW = (r+1)*W0;\nx = abs(f)*(1/(W-W0));\nx = x + ((W - 2*W0)/(W-W0))*ones(size(x));\nTF = cos((pi/4)*x).^2;\nxx = find(abs(f) < (2*W0 - W));\nfor ll = xx, TF(ll) = 1;end\nxx = find(abs(f) > W);\nfor ll = xx, TF(ll) = 0;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/14496-coaxial-cable-based-cdma-system-simulation/Copy of Part - II/raisedCos.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107984180243, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.7102130574859423}} {"text": "function [Y] = mnbinpdf(X, W, K)\n%MNBINPDF Maszle's negative binomial probability density function\n%\n% Y = MNBINPDF(X, W, K)\n%\n% returns the probabilities of the values X using a negative binomial\n% distribution with mean W and clumping parameter K. \n%\n% This is an alternate form of the negative binomial commonly\n% employed in biology to describe aggregated count data. \n% W and K are related to the traditional parametrization by the\n% relationships: \n%\n% P = K/(K + W), and K = R,\n%\n% with the distinction that K is any positive real number, not just\n% positive integers.\n%\n% X should only be integers and is rounded if not. Calculation is\n% optimized by taking the exponential of the GAMMALN function.\n%\n% See also MNBINRND\n\n\n\n%----------------------------------------------------------------------\n% Copyright (c) 1997. Don R. Maszle. All rights reserved.\n%\n% -- Revisions -----\n% Author: Don R. Maszle\n% E-mail: maze@sparky.berkeley.edu\n% -- SCCS ---------\n%----------------------------------------------------------------------\n\n\n\n%----------------------------------------------------------------------\n% We use the definition from Bradley and May, Trans. R.Soc.Trop.Med.Hyg.\n% v72(3), 1978, p262.\n\n\n% A notational convenience\na = W/(W + K);\nX = round(X);\n\n\nY = ((1 - a).^K) ...\n .* (exp( gammaln(X + K) + X.*log(a) - gammaln(K) - gammaln(X + 1)));", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/201-mnbinrnd/mnbinpdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642557, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.7102130561569464}} {"text": "%dcm (Cba) to rotation vector (r^a)\n%Cba: B to A transformation matrix\n%r^a=Rotation vector defined in A. (Rotate A around r with mag(r) to obtain B)\n%the magnitude of the returning rotation vector will be between [0 and PI]\n\n%This is the implementaion of savage(3-31).\nfunction rvec=dcm2rot(dcm)\n\nsinPHI=0.5*sqrt((dcm(3,2)-dcm(2,3))^2+(dcm(1,3)-dcm(3,1))^2+(dcm(2,1)-dcm(1,2))^2);\ncosPHI=0.5*(dcm(1,1)+dcm(2,2)+dcm(3,3)-1);\n\nPHI=atan2(sinPHI,cosPHI);\n\nif (cosPHI>=0)\n if (sinPHI==0)\n F=1;\n else\n F=PHI/sinPHI;\n end\n rvec=0.5*F*[dcm(3,2)-dcm(2,3);dcm(1,3)-dcm(3,1);dcm(2,1)-dcm(1,2)];\nelse\n sr_a=1-cosPHI;\n mu1=sqrt((dcm(1,1)-1)/sr_a+1);\n mu2=sqrt((dcm(2,2)-1)/sr_a+1);\n mu3=sqrt((dcm(3,3)-1)/sr_a+1);\n if (mu1>=mu2 && mu1>=mu3)\n u1=mu1*sign(dcm(3,2)-dcm(2,3));\n u2=1/2/u1*(dcm(1,2)+dcm(2,1))/sr_a;\n u3=1/2/u1*(dcm(1,3)+dcm(3,1))/sr_a;\n elseif (mu2>=mu3)\n u2=mu2*sign(dcm(1,3)-dcm(3,1));\n u3=1/2/u2*(dcm(2,3)+dcm(3,2))/sr_a;\n u1=1/2/u2*(dcm(1,2)+dcm(2,1))/sr_a; \n else\n u3=mu3*sign(dcm(2,1)-dcm(1,2));\n u1=1/2/u3*(dcm(1,3)+dcm(3,1))/sr_a;\n u2=1/2/u3*(dcm(2,3)+dcm(3,2))/sr_a;\n end\n rvec=PHI*[u1;u2;u3];\nend", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/TransFunctions/dcm2rot_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.710213049511965}} {"text": "function [p]=rmEvaluate2Fits(rss1,rss2,df1,df2,n,units,wtest)\n% rmEvaluate2Fits - probability that fit1 == fit2\n%\n% output = rmEvaluate2Fits(rss1,rss2,df1,df2,n,units,wtest);\n%\n% Performs f-test and general likelihood ratio (Wilks likelihood)\n% tests. Outputs the probability of Ho: data1 == data2.\n% Assumes df1>=df2.\n%\n% rss : residual sum of squares (model 1 and 2)\n% df : degrees of freedom (model 1 and 2)\n% n : number of data points\n% units: 'p', 'log10p' ['p'] \n% wtest: 'ftest','glr'\n% \n% 2006/02 SOD: wrote it.\n\nif ieNotDefined('rss1'), error('Need rss1.'); end;\nif ieNotDefined('rss2'), error('Need rss2.'); end;\nif ieNotDefined('df1'), error('Need df1.'); end;\nif ieNotDefined('df2'), error('Need df2.'); end;\nif ieNotDefined('n'), error('Need n.'); end;\nif ieNotDefined('units'),wtest = 'p'; end;\nif ieNotDefined('wtest'),wtest = 'glr'; end;\n \n% some sanity checks\nif df1 == df2,\n disp(sprintf('[%s]:error: df1 == df2.',mfilename));\n return;\nend;\nif df1df2 flipping datasets!',mfilename));\n dftmp = df1;\n df1 = df2;\n df2 = dftmp;\n rsstmp = rss1;\n rss1 = rss2;\n rss2 = rsstmp;\nend;\n\n% now do tests\nswitch lower(wtest),\n case {'f','ftest'}\n % ftest \n if df1~=df2,\n f = ((rss1-rss2)./rss2) ./ ((df1-df2)./df2); \n p = 1-fcdf(f,df1-df2,df2);\n else\n f = rss1./rss2;\n p = 1-fcdf(f,df2,df1);\n end;\n\n case {'g','glr','wilks'}\n % From Fan et al (2001) Generalized likelihood ratio statistics and Wilks\n % phenomenon. The Annals of Statistics. 29(1): 153-193.\n % calculate lambda (glr computation)\n lambda = (n./2).*log(rss1./rss2);\n \n % probability function: Wilks phenomenon lambda approximates\n % chi-squared distribution.\n df = df1-df2;\n p = 1-chi2cdf(lambda,df);\nend;\n\n% convert units if requested\nswitch lower(units),\n case 'log10p',\n sp = sign(p);\n sp(sp==0) = 1;\n p = abs(p);\n p(p<1e-50) = 10^-50; % remove 0\n p = -log10(p) .* sp;\n case 'p', \n % do nothing\n otherwise,\n error('[%s]:Unknown unit: %s',mfilename,units);\nend;\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/retinotopyModel/rmEvaluate2Fits.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7102006384622477}} {"text": "function chebyshev_polynomial_test09 ( )\n\n%*****************************************************************************80\n%\n%% CHEBYSHEV_POLYNOMIAL_TEST09 compares a function and projection over [-1,+1].\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 April 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHEBYSHEV_POLYNOMIAL_TEST09:\\n' );\n fprintf ( 1, ' T_PROJECT_COEFFICIENTS computes the Chebyshev interpolant C(F)(N,X)\\n' );\n fprintf ( 1, ' of a function F(X) defined over [-1,+1].\\n' );\n fprintf ( 1, ' T_PROJECT_VALUE evaluates that projection.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Compute projections of order N to exp(x) over [-1,+1],\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N Max||F(X)-C(F)(N,X)||\\n' );\n fprintf ( 1, '\\n' );\n for n = 0 : 10\n c = t_project_coefficients ( n, @exp );\n m = 101;\n x = ( linspace ( -1.0, +1.0, m ) )';\n v = t_project_value ( m, n, x, c );\n r = v - exp ( x );\n fprintf ( 1, ' %2d %12.4g\\n', n, max ( abs ( r ) ) );\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_test09.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7101369387159258}} {"text": "function u = bsv ( a, b, alpha, beta, nu, n, output )\n\n%*****************************************************************************80\n%\n%% BSV applies Newton's method to a discretized steady viscous Burgers equation.\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% Input, real A, B, the left and right endpoints.\n%\n% Input, real ALPHA, BETA, the Dirichlet boundary values at the left\n% and right.\n%\n% Input, real NU, the viscosity. Normally, 0 < NU.\n%\n% Input, integer N, the number of nodes to use between A and B.\n%\n% Input, logical OUTPUT, is TRUE if printout is desired.\n%\n% Output, real U(N), the computed discretized solution.\n%\n if ( n < 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BSV - Fatal error!\\n' );\n fprintf ( 1, ' N < 2.\\n' );\n error ( 'BSV - Fatal error!\\n' );\n end\n%\n% Set some iteration parameters.\n%\n newton_step_max = 50;\n newton_resid_tol = sqrt ( eps );\n newton_step_tol = sqrt ( eps );\n%\n% Use equally spaced nodes from A to B.\n%\n dx = ( b - a ) / ( n - 1 );\n%\n% The initial guess will be the linear interpolant to the boundary conditions.\n%\n u = ( linspace ( alpha, beta, n ) )';\n%\n% Prepare for the Newton iteration.\n%\n J = sparse ( [], [], [], n, n, 3 * n );\n newton_step = 0;\n\n if ( output )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Step ||F(U)||\\n' );\n fprintf ( 1, '\\n' );\n end \n\n while ( newton_step <= newton_step_max )\n\n f(1,1) = u(1) - alpha;\n\n% for i = 2 : n - 1\n% f(i,1) = 0.5 * ( u(i+1)^2 - u(i-1)^2 ) / ( 2.0 * dx ) ...\n% - nu * ( u(i+1) - 2.0 * u(i) + u(i-1) ) / ( dx^2 );\n% end\n\n f(2:n-1,1) = 0.5 * ( u(3:n).^2 - u(1:n-2).^2 ) / ( 2.0 * dx ) ...\n - nu * ( u(3:n) - 2.0 * u(2:n-1) + u(1:n-2) ) / ( dx^2 );\n\n f(n,1) = u(n) - beta;\n\n f_norm = norm ( f, inf );\n\n if ( output )\n fprintf ( 1, ' %4d %g\\n', newton_step, f_norm );\n end\n\n if ( f_norm < newton_resid_tol ) \n break\n end\n%\n% Define the Jacobian matrix.\n%\n J(1,1) = 1.0;\n for i = 2 : n - 1\n J(i,i-1) = - 2.0 * u(i-1) / ( 4.0 * dx ) - nu / dx^2;\n J(i,i) = 2.0 * nu / dx^2;\n J(i,i+1) = 2.0 * u(i+1) / ( 4.0 * dx ) - nu / dx^2;\n end\n J(n,n) = 1.0;\n%\n% Solve the linear system J * du = -f to get the Newton update.\n%\n du = J \\ f;\n du_norm = norm ( du, inf );\n\n u_norm = norm ( u, inf );\n if ( du_norm < newton_step_tol * ( u_norm + 1.0 ) )\n break\n end\n\n u = u - du;\n newton_step = newton_step + 1;\n\n end\n\n if ( newton_step_max < newton_step )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BSV - Warning!\\n' );\n fprintf ( 1, ' The Newton iteration did not converge.\\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.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8354835432479661, "lm_q1q2_score": 0.7101369231466911}} {"text": "function b = center_logistic(u,y);\ns = mean(y);\nb = log( s / (1 - s ) ) - mean(u);\nfor i=1:20\n\tsigma = 1./ ( 1 + exp( - u - b ) );\n\tphider = sum(sigma - y) ;\n\tphider2 = sum(sigma .* ( 1- sigma));\n\tbnew = b - phider / phider2;\n\tif norm(bnew-b) < 1e-16, break; end\n\tb=bnew;\n\nend\n\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/hkl-3.0/center_logistic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7101192408771005}} {"text": "function point = pointOnLine(line, pos)\n%POINTONLINE Create a point on a line at a given position on the line\n%\n% P = pointOnLine(LINE, POS);\n% Creates the point belonging to the line LINE, and located at the\n% distance D from the line origin.\n% LINE has the form [x0 y0 dx dy].\n% LINE and D should have the same number N of rows. The result will have\n% N rows ans 2 column (x and y positions).\n%\n% See also:\n% lines2d, points2d, onLine, onLine, linePosition\n%\n% ---------\n%\n% author : David Legland \n% INRA - TPV URPOI - BIA IMASTE\n% created the 07/04/2004.\n%\n\n\nangle = lineAngle(line);\npoint = [line(:,1) + pos .* cos(angle), line(:,2) + pos .* sin(angle)];\n ", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom2d/pointOnLine.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7101192376303774}} {"text": "%% MULTIGRID OF FOR THE STOKES EQNS IN 2D\n%\n% This example is to show the convergence of multigrid methods for various\n% finite element approximation of the Stokes equation on the unit square:\n%\n% -div(mu*grad u) + grad p = f in \\Omega,\n% - div u = 0 in \\Omega,\n% u = g_D on \\Gamma.\n%\n% with the pure Dirichlet boundary condition.\n%\n\n%% Setting\nclear all; close all;\n[node,elem] = squaremesh([0,1,0,1],0.5);\n% [node,elem] = circlemesh(0,0,1,0.25);\n[node,elem] = uniformrefine(node,elem);\nshowmesh(node,elem);\npde = Stokesdata1; \n% pde = StokesZulehnerdata;\nbdFlag = setboundary(node,elem,'Dirichlet');\noption.L0 = 1;\noption.maxIt = 4;\noption.printlevel = 1;\noption.plotflag = 0;\noption.rateflag = 0;\n\n%% MG options\noption.solver = 'mg';\noption.smoothingstep = 2;\noption.smootherbarSp = 'SGS';\n\n%% RT0-P0\ndisplay('RT0-P0')\noption.elemType = 'RT0-P0';\noption.refType = 'bisect';\nfemStokesHdiv(node,elem,pde,bdFlag,option);\n\n% %% RT0-P0\n% display('BDM1B-P0')\n% option.elemType = 'BDM1B-P0';\n% femStokesHdiv(node,elem,pde,bdFlag,option);\n\n%% CR-P0 element\ndisplay('CR-P0')\noption.elemType = 'CRP0';\nfemStokes(node,elem,pde,bdFlag,option);\n\n%% P2-P0 element\ndisplay('P2-P0')\noption.elemType = 'P2P0';\nfemStokes(node,elem,pde,bdFlag,option);\n\n%% isoP2-P0 element\ndisplay('isoP2-P0')\noption.elemType = 'isoP2P0';\nfemStokes(node,elem,pde,bdFlag,option);\n\n%% isoP2-P1 element\ndisplay('isoP2-P1')\noption.elemType = 'isoP2P1';\nfemStokes(node,elem,pde,bdFlag,option);\n\n% %% P1b-P1 element\n% display('P1b-P0')\n% option.elemType = 'P1bP1';\n% femStokes(node,elem,pde,bdFlag,option);\n\n%% P2-P1 element\ndisplay('P2-P1')\noption.elemType = 'P2P1';\n% option.smoothingStep = 3;\n% option.smootherbarSp = 'VCYCLE';\n% option.smootherbarSpPara = 0.75;\nfemStokes(node,elem,pde,bdFlag,option);\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/example/mgrateStokes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7101192369539603}} {"text": "function [param]=sine_fit(x,y,fixed_params,initial_params,plot_flag)\n% Optimization of parameters of the sine function to time series\n%\n% Syntax:\n% [param]=sine_fit(x,y) \n%\n% that is the same that\n% [param]=sine_fit(x,y,[],[],[]) % no fixed_params, automatic initial_params\n%\n% [param]=sine_fit(x,y,fixed_params) % automatic initial_params\n% [param]=sine_fit(x,y,[],initial_params) % use it when the estimation is poor\n% [param]=sine_fit(x,y,fixed_params,initial_params,plot_flag)\n%\n% param = [offset, amplitude, phaseshift, frequency]\n%\n% if fixed_params=[NaN, NaN , NaN , NaN] % or fixed_params=[]\n% optimization of offset, amplitude, phase shift and frequency (default)\n%\n% if fixed_params=[NaN, 1 , NaN , 1/(2*pi)]\n% optimization of offset and phase shift of a sine of amplitude=1 and frequency=1/(2*pi)\n%\n% if fixed_params=[0, NaN , NaN , NaN] \n% optimization of amplitude, phase shift and frequency of a sine of offset=0\n%\n%\n% Example:\n% %% generate data vectors (x and y)\n% fsine = @(param,timeval) param(1) + param(2) * sin( param(3) + 2*pi*param(4)*timeval );\n% param=[0 1 0 1/(2*pi)]; % offset, amplitude, phaseshift, frequency\n% timevec=0:0.1:10*pi;\n% x=timevec;\n% y=fsine(param,timevec) + 0.1*randn(size(x));\n%\n% %% standard parameter estimation\n% [estimated_params]=sine_fit(x,y)\n%\n% %% parameter estimation with forced 1.5 fixed amplitude\n% [estimated_params]=sine_fit(x,y,[NaN 1.5 NaN NaN])\n%\n% %% parameter estimation without plotting\n% [estimated_params]=sine_fit(x,y,[],[],0)\n%\n%\n% Doubts, bugs: rpavao@gmail.com\n\n\n% warning off\n\n\nif nargin<=1 %fail\n fprintf('');\n help sine_fit\n return\nend\n\nautomatic_initial_params=NaN(1,4);\nautomatic_initial_params(1)=median(y);\nautomatic_initial_params(2)=mean(minmax(y));\nautomatic_initial_params(3)=0;\n[~,pos]=findpeaks(smooth(y,10));\nautomatic_initial_params(4)=1/max(diff(x(pos)));\n\n% phas_shift estimator, not working...\n% [~,pos]=max(y);\n% automatic_initial_params(3)=mod(x(pos),automatic_initial_params(4));\n\nif nargin==2 %simplest valid input\n fixed_params=NaN(1,4);\n initial_params=automatic_initial_params;\n plot_flag=1; \nend\nif nargin==3\n initial_params=automatic_initial_params;\n plot_flag=1; \nend\nif nargin==4\n plot_flag=1; \nend\n\nif exist('fixed_params','var')\n if isempty(fixed_params)\n fixed_params=NaN(1,4);\n end\nend\nif exist('initial_params','var')\n if isempty(initial_params)\n initial_params=automatic_initial_params;\n end\nend\nif exist('plot_flag','var')\n if isempty(plot_flag)\n plot_flag=1;\n end\nend\n\n\nf_str='f = @(param,timeval)';\nfree_param_count=0;\nbool_vec=NaN(1,4);\nfor i=1:4;\n if isnan(fixed_params(i))\n free_param_count=free_param_count+1;\n f_str=[f_str ' param(' num2str(free_param_count) ')'];\n bool_vec(i)=1;\n else\n f_str=[f_str ' ' num2str(fixed_params(i))];\n bool_vec(i)=0;\n end\n if i==1; f_str=[f_str ' +']; end\n if i==2; f_str=[f_str ' * sin(']; end\n if i==3; f_str=[f_str ' + 2*pi*']; end\n if i==4; f_str=[f_str '*timeval );']; end\nend\n\neval(f_str)\n\n[BETA,RESID,J,COVB,MSE] = nlinfit(x,y,f,initial_params(bool_vec==1));\n\nfree_param_count=0;\nfor i=1:4;\n if isnan(fixed_params(i))\n free_param_count=free_param_count+1;\n param(i)=BETA(free_param_count);\n else\n param(i)=fixed_params(i);\n end \nend\n \nif plot_flag==1 \n x_vector=min(x):mean(diff(x))/2:max(x);\n plot(x,y,'k.',x_vector,f(BETA,x_vector),'r-')\n xlim(minmax(x_vector))\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/41246-sine-function-fit/sine_fit.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7100371937813601}} {"text": "clear all, close all, clc\nnu=0.001; % Diffusion constant\n\n% Define spatial domain\nL = 20; % Length of domain \nN = 1000; % Number of discretization points\ndx = L/N;\nx = -L/2:dx:L/2-dx; % Define x domain\n\n% Define discrete wavenumbers\nkappa = (2*pi/L)*[-N/2:N/2-1];\nkappa = fftshift(kappa'); % Re-order fft wavenumbers\n\n% Initial condition \nu0 = sech(x); \n\n% Simulate PDE in spatial domain\ndt = 0.025;\nt = 0:dt:100*dt;\n[t,u] = ode45(@(t,u)rhsBurgers(t,u,kappa,nu),t,u0);\n\n% Plot solution in time\nsubplot(1,2,1)\nh=waterfall(real(u(1:10:end,:)));\nset(h,'LineWidth',2,'FaceAlpha',.5);\ncolormap(jet/1.5)\nview(5,55)\n\nsubplot(1,2,2)\nimagesc(flipud(real(u)));\ncolormap jet\n\n%% FIGURES (PRODUCTION)\nfigure\nCC = colormap(jet(100));\ndt = 0.1;\nfor k = 1:100\n if(mod(k-1,10)==0)\n plot(x,real(u(k,:)),'k','LineWidth',1.5)\n% plot(x,real(u(k,:)),'Color',CC(k,:),'LineWidth',1.5)\n hold on, grid on, drawnow\n end \nend\n% xlabel('Spatial variable, x')\n% ylabel('Temperature, u(x,t)')\naxis([-L/2 L/2 -.1 1.1])\nset(gca,'LineWidth',1.2,'FontSize',12);\nset(gcf,'Position',[100 100 550 220]);\nset(gcf,'PaperPositionMode','auto')\nprint('-depsc2', '-loose', '../../figures/FFTBurgers1');\n\n%\nfigure\nsubplot(1,2,1)\nh=waterfall(real(u(1:10:end,:)));\nset(h,'LineWidth',2,'FaceAlpha',.5);\ncolormap(jet/1.5)\nview(5,55)\nset(gca,'LineWidth',1.5)\nset(gca,'XTick',[0 500 1000],'XTickLabels',{})\nset(gca,'ZTick',[0 .5 1],'ZTickLabels',{})\nset(gca,'YTick',[0 5 10],'YTickLabels',{})\nset(gca,'YLim',[1 11])\nset(gca,'ZLim',[-.1 1.1])\n\nsubplot(1,2,2)\nimagesc(flipud(real(u)));\nset(gca,'LineWidth',1.5)\nset(gca,'XTick',[0 500 1000],'XTickLabels',{})\nset(gca,'YTick',[0 50 100],'YTickLabels',{})\n\ncolormap jet\nset(gcf,'Position',[100 100 600 250])\nset(gcf,'PaperPositionMode','auto')\nprint('-depsc2', '-loose', '../../figures/FFTBurgers2');", "meta": {"author": "dynamicslab", "repo": "databook_matlab", "sha": "d390d39d18489a4804ee87a143ae8db8a1f3010b", "save_path": "github-repos/MATLAB/dynamicslab-databook_matlab", "path": "github-repos/MATLAB/dynamicslab-databook_matlab/databook_matlab-d390d39d18489a4804ee87a143ae8db8a1f3010b/CH02/CH02_SEC03_3_FFTBurgers.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7100371798011027}} {"text": "function [a,t,tLength]=BSplinePolyFitMultiDim(tau,tauLengths,y,k,numCentralKnots,useSparse)\n%%BSPLINEPOLYFITMULTIDIM Given a set of real vector (or scalar) points as\n% well as real or complex scalar function values, this function\n% returns the knots and coefficients for a set of b-splines that\n% can be used to interpolate to a desired polynomial degree within\n% the sampled region of the function. B-splines can have continuous\n% derivatives across the entire sampled region and can be easily\n% differentiated. This function determines the knots to use by\n% taking the tensor product of the approximate knots from\n% Equation 10 of Chapter 13 of [1]. The knots are not optimal. The\n% first and last knots in each dimensions are repeated. This\n% function can provide interpolation coefficients for multiple sets\n% of values at once. \n%\n%INPUTS: tau A numPointsXnumDims matrix of the coordinates of the points in\n% each dimension in ascending order. The full grid of points\n% in all dimensions could be found using\n% [tau1,tau2,etc.]=ndgrid(tau(1:tauLengths(1),1),tau(1:tauLengths(2),2),...)\n% and the dimensions can be put together into the full set of\n% numDimsXtotalNumPoints points as\n% tauTotal=[tau1(:).';tau2(:).';...]. Note that using meshgrid\n% in 2D/3D will put the points in the wrong order; one has to\n% use the ordering of ndgrid. These values must be real.\n% tauLengths A numDimsX1 or a 1XnumDims vector this lists the number of\n% points in each dimension of tau. The total number of sample\n% points is totalNumPoints=prod(tauLengths).\n% y This is the totalNumPointsXnumSets full sets of function\n% values taken at all of the points implied by the vectors in\n% tau for numSets different interpolation problems. The ordering\n% of the points is the same as the ordering of tauTotal, which\n% is described above. These values can be real or complex.\n% k A numDimsX1 or 1XnumDims set of the order of the b-splines in\n% each dimension. The value k-1 is the polynomial order of the\n% approximation being performed. If the order is the same in all\n% dimensions, then a single scalar can be passed.\n% numCentralKnots This optional parameter is used if one passes a higher\n% density of points in tau than is needed, because one wants to\n% perform least squares interpolation. This is the numDimsX1 or\n% 1XnumDims list of the number of knots in the central region of\n% knots in each dimension. It varies from 0 to n-k. The higher\n% the number, the more knots are used total. A total of\n% numCentralKnots+2*k will be returned by this function, though,\n% as explained below, the first and last knots in each dimension\n% are not used.\n% useSparse The linear system being solved for the coefficients can be\n% quite large, but is not necessarily dense. If useSparse is\n% true, then the matrix for the system will be allocated as a\n% sparse matrix. This can slow down the algorithm, but it can\n% also keep Matlab from running out of memory on large systems.\n% The default if this parameter is omitted or an empty matrix is\n% passed is true.\n%\n%OUTPUTS: a A hypermatrix with numDim+1 indices containing the set of\n% coefficients for the b-splines covering all of the\n% interpolation intervals with the final index selecting the set\n% if numSets>1. If numSets=1, then the final index is unitary,\n% meaning that there are effectively only numDim dimensions. This\n% and the following outputs can be passed to\n% BSplineInterpValMultiDim to perform interpolation over the\n% region spanned by the tau values.\n% t The maxNumKnotsXnumDims set of knots for the interpolation\n% function. The first and last k(curDim)-1 knots in each\n% dimension are outside of the ends of the region with data or\n% mark the ends of the region with data. The number of rows is\n% the maximum number needed for all of the dimensions. tLength\n% says how many items in each column are actually used. The knots\n% are the same for each set.\n% tLength A numDimX1 vector where tLength(i) says the number of elements\n% in t(:,i). The lengths are the same for each set.\n%\n%The comments ot the function BSplinePolyFit describe how Equation 7 in\n%Chapter IX is used in one dimension. The issue of multiple dimensions is\n%addressed in Chapter 17 of [1] with a focus on solving the problem in\n%2D. The basic equation to be solved in 2D is given by Equation 11 in\n%Chapter 17 of [1] and it can be easily extended to an arbitrary number\n%of dimensions. Chapter 17 gives a solution that is more efficient in 2D\n%than solving Equation 11. However, we choose to solve the equation to make\n%the problem valid for an arbitrary number of dimensions.\n%\n%The ability to do a least-squares fit involves making fewer inner knots\n%than suggested in the text. Rather than making n-k knots, we make\n%numCentralKnots. However, this invalidates the approximation in Equation\n%10 of Chapter 13 of [1] for selecting knots. The correction applied is to\n%make the average taken in the equation to involve more points.\n%Additionally, the knots in Chapter 13 are univariate. We make them\n%multivariate by taking a tensor product.\n%\n%EXAMPLE 1:\n%Here, we fit a curve to 2D data on an irregular grid. We choose a\n%sufficiently high order that it recreates the polynomial exactly and we\n%verify this by looking at the maximum error on a fine grid and plotting\n%the results.\n% f=@(x,y)(x.^4-2*x.^2+x).*(y.^4-2*y.^2+y);\n% numDims=2;\n% numPointsX=10;\n% numPointsY=11;\n% tauLengths=[numPointsX;numPointsY];\n% tau=zeros(max(tauLengths),numDims);\n% tau(1:tauLengths(1),1)=linspace(-1.5,1.5,numPointsX);\n% tau(1:tauLengths(2),2)=linspace(-1.5,1.5,numPointsY);\n% %Note that using meshgrid would have put the elements in the wong order.\n% %ndgrid must be used.\n% [tau1,tau2]=ndgrid(tau(1:tauLengths(1),1),tau(1:tauLengths(2),2));\n% y=f(tau1,tau2);\n% \n% k=[5;5];\n% [a,t,tLength]=BSplinePolyFitMultiDim(tau,tauLengths,y(:),k);\n% \n% numPointsX=100;\n% numPointsY=101;\n% pointsX=linspace(-1.5,1.5,numPointsX);\n% pointsY=linspace(-1.5,1.5,numPointsY);\n% [X,Y]=ndgrid(pointsX,pointsY);\n% x=[X(:).';Y(:).'];\n% \n% zTrue=f(X,Y);\n% \n% z=BSplineInterpValMultiDim(x,t,tLength,a,k);\n% z=reshape(z,[numPointsX,numPointsY]);\n% \n% figure(1)\n% clf\n% surface(X,Y,z,'EdgeColor','none')\n% title('Interpolated Surface')\n% \n% figure(2)\n% clf\n% surface(X,Y,zTrue,'EdgeColor','none')\n% title('True Surface')\n% max(abs(zTrue(:)-z(:)))\n%One sees that the curves are the same and that the difference at any point\n%is on the order of finite precision error. This is consistent with the\n%fact that the order of the spline fit was chosen to be the same as the\n%order of the true polynomial.\n%\n%EXAMPLE 2:\n%Here, we fit a curve to 3D data on an irregular grid. We choose a\n%sufficiently high order that it recreates the polynomial exactly and we\n%verify this by looking at the maximum error on a fine grid.\n% f=@(x,y,z)(x.^4-2*x.^2+x).*(y.^4-2*y.^2+y).*(z.^4-3*z.^2+z);\n% numDims=3;\n% numPointsX=10;\n% numPointsY=11;\n% numPointsZ=9;\n% tauLengths=[numPointsX;numPointsY;numPointsZ];\n% tau=NaN(max(tauLengths),numDims);\n% tau(1:tauLengths(1),1)=linspace(-1.5,1.5,numPointsX);\n% tau(1:tauLengths(2),2)=linspace(-1.5,1.5,numPointsY);\n% tau(1:tauLengths(3),3)=linspace(-1.5,1.5,numPointsZ);\n% %Note that using meshgrid would have put the elements in the wong order.\n% %ndgrid must be used.\n% [tau1,tau2,tau3]=ndgrid(tau(1:tauLengths(1),1),tau(1:tauLengths(2),2),tau(1:tauLengths(3),3));\n% y=f(tau1,tau2,tau3);\n% \n% k=[5;5;5];\n% [a,t,tLength]=BSplinePolyFitMultiDim(tau,tauLengths,y(:),k);\n% \n% numPointsX=50;\n% numPointsY=51;\n% numPointsZ=49;\n% pointsX=linspace(-1.5,1.5,numPointsX);\n% pointsY=linspace(-1.5,1.5,numPointsY);\n% pointsZ=linspace(-1.5,1.5,numPointsZ);\n% [X,Y,Z]=ndgrid(pointsX,pointsY,pointsZ);\n% x=[X(:).';Y(:).';Z(:).'];\n% \n% wTrue=f(X,Y,Z);\n% w=BSplineInterpValMultiDim(x,t,tLength,a,k);\n% max(abs(wTrue(:)-w(:)))\n%As was the case with Example 1, the maximum error is on the order of what\n%one would expect due to finite precision limitations.\n%\n%EXAMPLE 3:\n%In this case, a complex 2D function is fit and interpolated.\n% numPoints=50;\n% xMin=0;\n% xMax=3;\n% yMin=0;\n% yMax=3;\n% x=linspace(xMin,xMax,numPoints);\n% y=linspace(yMin,yMax,numPoints);\n% [X,Y]=ndgrid(x,y);\n% f=@(x,y)((sin(5*y)+1j*cos(10*x)).*exp(1j*(x.^2-2*y.^2)));\n% \n% fxy=f(X(:),Y(:));\n% k=[5;5];\n% tau=[x(:),y(:)];\n% tauLengths=[numPoints,numPoints];\n% [a,t,tLength]=BSplinePolyFitMultiDim(tau,tauLengths,fxy,k);\n% \n% %Interpolate on a finer grid.\n% numPoints=100;\n% x=linspace(xMin,xMax,numPoints);\n% y=linspace(xMin,xMax,numPoints);\n% [X,Y]=ndgrid(x,y);\n% \n% fxy=f(X(:),Y(:));\n% pts=[X(:).';Y(:).'];\n% fxyInterp=reshape(BSplineInterpValMultiDim(pts,t,tLength,a,k),[numPoints,numPoints]);\n% \n% fxy=reshape(fxy,[numPoints,numPoints]);\n% \n% figure(1)\n% clf\n% hold on\n% surface(X,Y,real(fxy),'EdgeColor','none')\n% title('Real Function Values')\n% colorbar()\n% \n% figure(2)\n% clf\n% hold on\n% surface(X,Y,imag(fxy),'EdgeColor','none')\n% title('Imaginary Function Values')\n% colorbar()\n% \n% figure(3)\n% clf\n% hold on\n% surface(X,Y,abs(real(fxyInterp)-real(fxy)),'EdgeColor','none')\n% title('Real Interpolation Error')\n% colorbar()\n% \n% figure(4)\n% clf\n% hold on\n% surface(X,Y,abs(imag(fxyInterp)-imag(fxy)),'EdgeColor','none')\n% title('Imaginary Interpolation Error')\n% colorbar()\n%\n%REFERENCES:\n%[1] C. de Boor, A Practical Guide to Splines. New York: Springer-Verlag,\n% 1978.\n%\n%April 2017 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDims=size(tau,2);\nn=tauLengths(:);\nnumSets=size(y,2);\n\nif(nargin<6)\n useSparse=false;\nend\n\n%The total number of points.\nNTotal=prod(n);\nif(NTotal~=size(y,1))\n error('The dimensionalities of the inputs are not consistent.')\nend\n\nif(isscalar(k))\n k=repmat(k,[numDims,1]); \nend\nk=k(:);\n\nif(nargin<5||isempty(numCentralKnots))\n numCentralKnots=n-k;\nelseif(any(numCentralKnots<0)||any(numCentralKnots(:)>n-k))\n error('The value of numCentralKnots is invalid.')\nend\nnumCentralKnots=numCentralKnots(:);\n\ndeltaVal=n-k-numCentralKnots;\n\ntLength=numCentralKnots+2*k;\nmaxTLength=max(tLength);\n\nt=zeros(maxTLength,numDims);\nfor curDim=1:numDims\n taLengthCur=tauLengths(curDim);\n tauCur=tau(1:taLengthCur,curDim);\n kCur=k(curDim);\n deltaValCur=deltaVal(curDim);\n numCentKnotsCur=numCentralKnots(curDim);\n \n t(1:kCur,curDim)=tauCur(1);\n t((numCentKnotsCur+kCur+1):(numCentKnotsCur+2*kCur),curDim)=tauCur(n(curDim));\n\n %The ad-hoc point choice from 10 of Chapter 13, modified to take more\n %points if a least-squares solution is being performed.\n for i=1:numCentKnotsCur\n t(k+i,curDim)=sum(tauCur((i+1):(i+kCur-1+deltaValCur)))/(kCur-1+deltaValCur);\n end\nend\n\n%Given the locations of the knots, we build the equations. The a values are\n%of the form a(d1,d2,..dnumDims). To access them, we stack them one after\n%another in the same order as a(:) would in Matlab.\ntotalNumA=prod(numCentralKnots+k);\n\nif(useSparse)\n %The amount of memory used will grow as B is filled in.\n B=sparse(NTotal,totalNumA);\nelse\n B=zeros(NTotal,totalNumA);\nend\n\nspanMin=ones(numDims,1);\ntIdxVals=k;\n\n%tauIdxVals holds the index of the value of tau used in each dimension\ntauIdxVals=ones(numDims,1);\ntauVal=zeros(numDims,1);\n%Fill in tauVal with the current value.\nfor curDim=1:numDims\n tauVal(curDim)=tau(1,curDim);\nend\n\n%The number of B values produced per call to evalBSplinePolysMultiDim.\nnumBCurEls=prod(k);\n\n%We have to go through all of the indices.\nfor curEq=1:NTotal\n BCur=evalBSplinePolysMultiDim(t,tLength,tauVal,k,tIdxVals);\n %We have to put the elements in BCur into the proper spots in B. These\n %spots start at spanMin in each dimension.\n for curEl=1:numBCurEls\n dimIdx=index2NDim(k,curEl);\n %The multidimensional index of the a value by which the current B\n %value is multiplied.\n aDimIdx=spanMin+dimIdx-1;\n aIdx=nDim2Index(n-deltaVal,aDimIdx); \n \n B(curEq,aIdx)=BCur(curEl);\n end\n \n if(curEq==NTotal)\n break;\n end\n \n %Now, we increment tauIdxVals to move onto a new value of tau in each\n %dimension. the values are kept in the tauVal array. Each time a value\n %is incremented, we have to check whether the corresponding entry in\n %tIdxVals and spanMin should be incremented.\n curIdx=1;\n tauIdxVals(curIdx)=tauIdxVals(curIdx)+1;\n while(tauIdxVals(curIdx)>tauLengths(curIdx))\n %If it exceeds k, then go back to 1.\n tauIdxVals(curIdx)=1;\n tauVal(curIdx)=tau(1,curIdx);\n\n tIdxVals(curIdx)=k(curIdx);\n spanMin(curIdx)=1;\n \n %Increment tIdxVals and spanMin as necessary to reach the valid\n %region.\n while(tauVal(curIdx)>t(tIdxVals(curIdx)+1,curIdx))\n tIdxVals(curIdx)=tIdxVals(curIdx)+1;\n spanMin(curIdx)=spanMin(curIdx)+1;\n end\n \n curIdx=curIdx+1;\n tauIdxVals(curIdx)=tauIdxVals(curIdx)+1;\n end\n\n %Increment tIdxVals and spanMin as necessary to reach the valid\n %region.\n tauVal(curIdx)=tau(tauIdxVals(curIdx),curIdx);\n while(tauVal(curIdx)>t(tIdxVals(curIdx)+1,curIdx))\n tIdxVals(curIdx)=tIdxVals(curIdx)+1;\n spanMin(curIdx)=spanMin(curIdx)+1;\n end\nend\n\na=B\\y;\nif(numDims>1)\n a=reshape(a,[(numCentralKnots+k)',numSets]);\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/BSplinePolyFitMultiDim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.7100371748934694}} {"text": "function [d] = spm_kl_eig_normal (m_q,c_q,c_p)\n% KL divergence between normal densities using eigendecomposition \n% function [d] = spm_kl_eig_normal (m_q,c_q,c_p)\n%\n% Calculate the KL distance \n%\n% KL (Q||P) = where avg is wrt Q\n%\n% between two Normal densities Q and P where P is\n% zero mean and has a diagonal covariance.\n%\n% m_q, c_q Mean and covariance of first Normal density\n% c_p Covariance of second (zero-mean) Normal density\n%___________________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Will Penny \n% $Id: spm_kl_eig_normal.m 1143 2008-02-07 19:33:33Z spm $\n\nd=length(m_q);\nm_q=m_q(:);\n\nldcp=0.5*sum(log(diag(c_p)));\n[v,eigvals]=eig(c_q);\nldcq=-0.5*sum(log(diag(eigvals)));\nTerm1=ldcp+ldcq;\n\ninv_c_p=diag(1./diag(c_p));\nTerm2=0.5*trace(inv_c_p*c_q)+0.5*m_q'*inv_c_p*m_q;\nd=Term1+Term2-0.5*d;\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/spectral/spm_kl_eig_normal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.7100147671765951}} {"text": "function jdate = julian (month, day, year)\n\n% Julian date\n\n% Input\n\n% month = calendar month [1 - 12]\n% day = calendar day [1 - 31]\n% year = calendar year [yyyy]\n\n% Output\n\n% jdate = Julian date\n\n% special notes\n\n% (1) calendar year must include all digits\n\n% (2) will report October 5, 1582 to October 14, 1582\n% as invalid calendar dates and stop\n\n% Orbital Mechanics with Matlab\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ny = year;\nm = month;\nb = 0;\nc = 0;\n\nif (m <= 2)\n y = y - 1;\n m = m + 12;\nend\n\nif (y < 0)\n c = -.75;\nend\n\n% check for valid calendar date\n\nif (year < 1582)\n % null\nelseif (year > 1582)\n a = fix(y / 100);\n b = 2 - a + floor(a / 4);\nelseif (month < 10)\n % null\nelseif (month > 10)\n a = fix(y / 100);\n b = 2 - a + floor(a / 4);\nelseif (day <= 4)\n % null\nelseif (day > 14)\n a = fix(y / 100);\n b = 2 - a + floor(a / 4);\nelse\n clc; home;\n\n fprintf('\\n\\n this is an invalid calendar date!!\\n');\n\n keycheck;\n\n return;\nend\n\njd = fix(365.25 * y + c) + fix(30.6001 * (m + 1));\n\njdate = jd + day + b + 1720994.5;\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/jpl_ephem/julian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.7100147584558982}} {"text": "function value = fedn ( dim_num, x )\n\n%*****************************************************************************80\n%\n%% FEDN(X(1:DIM_NUM)) = exp ( sum ( X(1:DIM_NUM) ) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 February 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, real X(DIM_NUM), the argument.\n%\n% Output, real VALUE, the value of the function at X.\n%\n value = exp ( sum ( x(1:dim_num) ) );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/nintlib/fedn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.8333246015211008, "lm_q1q2_score": 0.7099532292150277}} {"text": "function [t,t1] = geyer_icse(x,maxlag)\n% GEYER_ICSE - Compute autocorrelation time tau using Geyer's\n% initial convex sequence estimator\n% \n% C = GEYER_ICSE(X) returns autocorrelation time tau.\n% C = GEYER_ICSE(X,MAXLAG) returns autocorrelation time tau with \n% MAXLAG . Default MAXLAG = M-1.\n%\n% References:\n% [1] C. J. Geyer, (1992). \"Practical Markov Chain Monte Carlo\",\n% Statistical Science, 7(4):473-511\n%\n% Copyright (C) 2002 Aki Vehtari\n\n% This software is distributed under the GNU General Public \n% Licence (version 3 or later); please refer to the file \n% Licence.txt, included with the software, for details.\n\n% compute autocorrelation\nif nargin > 1\n cc=acorr(x,maxlag);\nelse\n cc=acorr(x);\nend\n[n,m]=size(cc);\n\n% acorr returns values starting from lag 1, so add lag 0 here\ncc=[ones(1,m);cc];\nn=n+1;\n\n% now make n even\nif mod(n,2)\n n=n-1;\n cc(end,:)=[];\nend\n\n% loop through variables\nt=zeros(1,m);\nt1=zeros(1,m);\nopt=optimset('LargeScale','off','display','off');\nfor i1=1:m\n c=cc(:,i1);\n c=sum(reshape(c,2,n/2),1);\n ci=find(c<0);\n if isempty(ci)\n warning(sprintf('Inital positive could not be found for variable %d, using maxlag value',i1));\n ci=n/2;\n else\n ci=ci(1)-1; % initial positive\n end\n c=[c(1:ci) 0]; % initial positive sequence\n t1(i1)=-1+2*sum(c); % initial positive sequence estimator\n if ci>2\n ca=fmincon(@se,c,[],[],[],[],0*c,c,@sc,opt,c); % monotone convex sequence\n else\n ca=c;\n end\n t(i1)=-1+2*sum(ca); % monotone convex sequence estimator\nend\n\nfunction e = se(x,xx)\n% SE - Error in monotone convex sequene estimator\ne=sum((xx-x).^2);\n\nfunction [c,ceq] = sc(x,xx)\n% SE - Constraint in monotone convex sequene estimator\nceq=0*x;\nc=ceq;\nd=diff(x);\ndd=-diff(d);\nd(d<0)=0;d=d.^2;\ndd(dd<0)=0;dd=dd.^2;\nc(1:end-1)=d;c(2:end)=c(2:end)+d;\nc(1:end-2)=dd;c(2:end-1)=c(2:end-1)+dd;c(3:end)=c(3:end)+dd;\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/diag/geyer_icse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7099532096322244}} {"text": "% Cobb-Douglas production function\n% Y=F(K,N)=K^{alpha}*N^{1-alpha}\n% In per capita form y=k^{alpha}\n\nfunction y=cobb(k)\nglobal alpha\nif alpha>0 & alpha<1\n y=k.^alpha;\nelse\n y=-inf*abs(k);\n disp('invalid capital share')\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/3289-neoclassic-growth-model-in-dynamic-economic-theory/cobb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576266, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.709941400192821}} {"text": "function [ unique_num, seed ] = point_radial_tol_unique_count ( m, n, a, ...\n tol, seed )\n\n%*****************************************************************************80\n%\n%% POINT_RADIAL_TOL_UNIQUE_COUNT counts the tolerably unique points.\n%\n% Discussion:\n%\n% The input data is an M x N array A, representing the M-dimensional\n% coordinates of N points.\n%\n% The output is the number of tolerably unique points in the list.\n%\n% This program performs the same task as POINT_TOL_UNIQUE_COUNT.\n% But that program is guaranteed to use N^2 comparisons.\n%\n% It is hoped that this function, on the other hand, will tend\n% to use O(N) comparisons after an O(NLog(N)) sort.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 July 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows.\n%\n% Input, integer N, the number of columns.\n%\n% Input, real A(M,N), the array of N columns of data.\n%\n% Input, real TOL, a tolerance for equality.\n%\n% Input/output, integer SEED, a seed for the random\n% number generator.\n%\n% Output, integer UNIQUE_NUM, the number of tolerably\n% unique points.\n%\n if ( n <= 0 )\n unique_num = 0;\n return\n end\n%\n% Assign a base point Z randomly in the convex hull.\n%\n [ w, seed ] = r8vec_uniform_01 ( n, seed );\n\n z = zeros ( m, 1 );\n for i = 1 : m\n z(i) = a(i,1:n) * w(1:n,1) / sum ( w(1:n) );\n end\n%\n% Compute the radial distance R of each point to Z.\n%\n r = zeros ( n, 1 );\n for j = 1 : n\n r(j) = sqrt ( sum ( ( a(1:m,j) - z(1:m) ).^2 ) );\n end\n%\n% Implicitly sort the R array.\n%\n indx = r8vec_sort_heap_index_a ( n, r );\n%\n% To determine if a point I is tolerably unique, we only have to check\n% whether it is distinct from all points J such that R(I) <= R(J) <= R(J)+TOL.\n%\n unique_num = 0;\n unique(1:n) = 1;\n\n for i = 1 : n\n\n if ( unique(indx(i)) )\n%\n% Point INDX(I) is unique, in that no earlier point is near it.\n%\n unique_num = unique_num + 1;\n%\n% Look for later points which are close to point INDX(I)\n% in terms of R.\n%\n hi = i;\n\n while ( hi < n )\n if ( r(indx(i)) + tol < r(indx(hi+1)) )\n break\n end\n hi = hi + 1;\n end\n%\n% Points INDX(I+1) through INDX(HI) have an R value close to\n% point INDX(I). Are they truly close to point INDEX(I)?\n%\n for j = i + 1 : hi\n if ( unique(indx(j)) )\n dist = sqrt ( sum ( ( a(1:m,indx(i)) - a(1:m,indx(j)) ).^2 ) );\n if ( dist <= tol )\n unique(indx(j)) = 0;\n end\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/point_merge/point_radial_tol_unique_count.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7098711932050337}} {"text": "%\n% n=erlangbinv(p,rho)\n%\n% This function finds the smallest n such the Erlang B probability that\n% a system with n servers, no waiting line, Poisson arrival rate lambda,\n% service rate (per server) mu, and intensity rho=lambda/mu will have\n% a probability <=p of having all servers busy. \n%\n% The Erlang B probability is given by \n%\n% B=(rho^m/m!)/(sum(rho^k/k!),k=0..m)\n%\n% We use a recurrence relation which is more accurate than direct evaluation \n% of the formula. This recurrence relation is a \"folk theorem\". The author\n% would appreciate a reference to its first publication. The recurrence is\n%\n% B(0,rho)=1\n%\n% B(n,rho)=(rho*B(n-1,rho)/n)/(1+rho*B(n-1,rho)/n)\n%\n% This routine simply loops through the recursion until B is <= p, and\n% then returns n. \n%\nfunction n=erlangbinv(p,rho)\n%\n% Start the recursion with B=1.\n%\nB=1;\n%\n% Loop, iterating the recursion until the probability is <= p.\n%\nn=1;\nwhile (1 == 1),\n B=((rho*B)/n)/(1+rho*B/n);\n if (B <= p),\n return;\n end; \n n=n+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/824-erlang-b-and-c-probabilities/erlang/erlangbinv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7098206603579815}} {"text": "function out = nrlremap(x, a, c)\n% NRLREMAP Lin-log style remap\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\nif nargin<3\n c = 220; % Output \"knee\" in lin-log curve\nend\nif nargin<2\n a = 1; % Scale factor of 99th percentile for input \"knee\"\nend\n\nA = abs(single(x));\nAmin = min(A(:));\nP99 = pctl(A(:),99);\nb = (255-c)/log10((max(A(:))-Amin)/((a*P99)-Amin));\n\nout = uint8(zeros(size(x)));\nlinear_region = (A<=a*P99);\nout(linear_region) = (A(linear_region) - Amin)*c/((a*P99)-Amin);\nout(~linear_region) = b*log10((A(~linear_region)-Amin)/((a*P99)-Amin))+c;\n\nend\n\nfunction ptile = pctl(v, p)\nptile = interp1(linspace(0.5/numel(v), 1-0.5/numel(v), numel(v))', sort(v(:)), p*0.01, 'spline');\nend\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Visualization/remap/remap_funcs/nrlremap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.7098206569730798}} {"text": "function [ypred, ll, mse] = eval_AR_perf(coef, C, y, model)\n% Evaluate the performance of an AR model.\n% \n% Inputs\n% coef(:,:,k,m) - coef. matrix to use for k steps back, model m\n% C(:,:,m) - cov. matrix for model m\n% y(:,t) - observation at time t\n% model(t) - which model to use at time t (defaults to 1 if not specified)\n%\n% Outputs\n% ypred(:,t) - the predicted value of y at t based on the evidence thru t-1.\n% ll - log likelihood\n% mse - mean squared error = sum_t d_t . d_t, where d_t = pred(y_t) - y(t)\n\n[s T] = size(y);\nk = size(coef, 3);\nM = size(coef, 4);\n\nif nargin<4, model = ones(1, T); end\n\nypred = zeros(s, T);\nypred(:, 1:k) = y(:, 1:k);\nmse = 0;\nll = 0;\nfor j=1:M\n c(j) = log(normal_coef(C(:,:,j)));\n invC(:,:,j) = inv(C(:,:,j));\nend\ncoef = reshape(coef, [s s*k M]);\n\nfor t=k+1:T\n m = model(t-k);\n past = y(:,t-1:-1:t-k);\n ypred(:,t) = coef(:, :, m) * past(:);\n d = ypred(:,t) - y(:,t);\n mse = mse + d' * d;\n ll = ll + c(m) - 0.5*(d' * invC(:,:,m) * d);\nend\nmse = mse / (T-k+1);\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/Kalman/eval_AR_perf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825847, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7098201210786342}} {"text": "function result = tetra_07 ( func, x, y, z )\n\n%*****************************************************************************80\n%\n%% TETRA_07 approximates an integral inside a tetrahedron in 3D.\n%\n% Integration region:\n%\n% Points inside a tetrahedron whose four corners are given.\n%\n% Discussion:\n%\n% A 64 point 7-th degree conical product Gauss formula is used,\n% Stroud number T3:7-1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 29 November 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% Stroud and Secrest,\n% Gaussian Quadrature Formulas,\n% Prentice Hall, 1966, pages 42-43.\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the user supplied\n% function of three variables which is to be integrated,\n% of the form:\n% function value = func ( x, y, z )\n%\n% Input, real X(4), Y(4), Z(4), the X, Y and Z coordinates of\n% the vertices.\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n norder = 4;\n weight2 = [ ...\n 0.1355069134, 0.2034645680, 0.1298475476, 0.0311809709 ];\n weight3 = [ ...\n 0.1108884156, 0.1434587898, 0.0686338872, 0.0103522407 ];\n xtab2 = [ ...\n 0.0571041961E+00, 0.2768430136E+00, 0.5835904324E+00, 0.8602401357E+00 ];\n xtab3 = [ ...\n 0.0485005495E+00, 0.2386007376E+00, 0.5170472951E+00, 0.7958514179E+00 ];\n%\n% Get the Gauss-Legendre weights and abscissas for [-1,1].\n%\n [ xtab1, weight1 ] = legendre_set ( norder );\n%\n% Adjust the rule for the interval [0,1].\n%\n a = -1.0E+00;\n b = +1.0E+00;\n\n c = 0.0E+00;\n d = 1.0E+00;\n\n [ xtab1, weight1 ] = rule_adjust ( a, b, c, d, norder, xtab1, weight1 );\n%\n% Carry out the quadrature.\n%\n quad = 0.0;\n\n for i = 1 : norder\n for j = 1 : norder\n for k = 1 : norder\n%\n% Compute the barycentric coordinates of the point in the unit triangle.\n%\n t = xtab3(k);\n u = xtab2(j) * ( 1.0E+00 - xtab3(k) );\n v = xtab1(i) * ( 1.0E+00 - xtab2(j) ) * ( 1.0E+00 - xtab3(k) );\n w = 1.0E+00 - t - u - v;\n%\n% Compute the corresponding point in the triangle.\n%\n xval = t * x(1) + u * x(2) + v * x(3) + w * x(4);\n yval = t * y(1) + u * y(2) + v * y(3) + w * y(4);\n zval = t * z(1) + u * z(2) + v * z(3) + w * z(4);\n quad = quad + 6.0 * weight1(i) * weight2(j) * weight3(k) ...\n * feval ( func, xval, yval, zval );\n\n end\n end\n end\n\n volume = tetra_volume ( x, y, z );\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/tetra_07.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7098201031993596}} {"text": "function [x,t]=meanLinTrajConstEnds(x0,x2,deltaT,q0,order,N,FFun,QFun)\n%%MEANLINTRAJCONSTENDS Generate a the mean trajectory based on a linear\n% dynamic model with additive noise, as is typically used in\n% tracking systems, given known locations of the start and\n% end points. A polynomial dynamic model is used by default,\n% but one can specify other models.\n%\n%INPUTS: x0, x2 The xDimX1 target states at the beginning and end of the\n% region over which paths are to be simulated. These are\n% treated as known values.\n% deltaT The time between when state x0 occurred and when state x2\n% occurred. This is a positive value.\n% q0 The power spectral density of the process noise. This is\n% passed to QFun, as described below and by default would\n% corresponds to the same-named input in QPolyKal. With the\n% default polynomial dynamic model, FPolyKal and QPolyKal, q0\n% has no effect on the result and is just set to 1 if an\n% empty matrix is passed.\n% order The order >=0 of the filter. If order=1, then it is\n% constant velocity, 2 means constant acceleration, 3 means\n% constant jerk, etc. This is passed to FFun and QFun. If\n% custom FFun and QFun functions are used and this is not\n% needed, then an empty matrix can be passed. The default if\n% omitted or an empty matrix is passed is 1.\n% N The number of points in the random path to generate between\n% x0 and x2. The default if omitted or an empty matrix is\n% passed is 100; N>=0.\n% FFun, QFun Optional function handles to functions that respectively\n% provide the state transition matrix and the process noise\n% covariance matrix as a function of the time duration over\n% which the prediction is taken. The defaults if omitted or\n% empty matrices are passed are handles to FPolyKal and\n% QPolyKal. The functions are called as FFun(T,xDim,order)\n% and QFun(T,xDim,order,q0), where T is the duration over\n% which the prediction is taken.\n%\n%OUTPUTS: x The xDimX(N+2) set of mean trajectory according to the\n% specified model. x(:,1) is always x0 and x(:,N+2) is always x2.\n% t The (N+2)X1 set of time offsets (starting at 0) where the\n% values in x are generated.\n%\n%Consider a process at points 0, 1, and 2, where we are given the value at\n%time x0. The transition models are:\n%x1=F0*x0+w1\n%x2=F1*x1+w2\n%Where x0 is given (deterministic) and w1 and w2 are independent zero-mean\n%Gaussian random variables with covariance matrices Q1 and Q1.\n%x1 and x2 are jointly normal with mean mu and covariance matrix Sigma:\n%mu=[x1Pred; = [F0*x0\n% x2Pred] F1*F0*x0];\n%Sigma=[ Q1, Q1*F1'; =[Pxx, Pxz;\n% F1*Q1, F1*Q1*F1'+Q2] Pxz',Pzz];\n%When given the value of x2, the conditional distribution of x1|x0,x2 is\n%the same as the Kalman filter update taking the measurement covariance\n%matrix to be Q2, the measurement matrix H to be F1, the prior state to be\n%F0*x0, and the covariance of the prior state to be Q1. Thus, as derived,\n%for example, in [Ch. 5,1], [2], the posterior distribution of x1 is\n%Gaussian with mean and covariance matrix\n%x1Bar=x1Pred+Pxz/Pzz*(x2-x2Pred)\n%This function is similar to randLinTrajConstEnds.\n%\n%EXAMPLE:\n%This plots a trajectory that eventually has to turn around, since the\n%endpoint is not close to the direction of the initial velocity vector.\n% x0=[1e3;0;30;20];\n% x2=[709;\n% 527;\n% -39;\n% 4];\n% deltaT=100;\n% x=meanLinTrajConstEnds(x0,x2,deltaT);\n% figure(1)\n% clf\n% plot(x(1,:),x(2,:))\n% h1=xlabel('x');\n% h2=ylabel('y');\n% set(gca,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h1,'FontSize',14,'FontWeight','bold','FontName','Times')\n% set(h2,'FontSize',14,'FontWeight','bold','FontName','Times')\n%\n%November 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nif(nargin<6||isempty(N))\n N=100;\nend\n\nif(nargin<5||isempty(order))\n order=1;\nend\n\nif(nargin<4||isempty(q0))\n q0=1;\nend\n\nxDim=size(x0,1);\n\nif(nargin<8||isempty(QFun))\n Q=@(T)QPolyKal(T,xDim,order,q0);\nelse\n Q=@(T)QFun(T,xDim,order,q);\nend\n\nif(nargin<7||isempty(FFun))\n F=@(T)FPolyKal(T,xDim,order);\nelse\n F=@(T)FFun(T,xDim,order);\nend\n\nx=zeros(xDim,N+2);\n\n%The increment between the sample points.\ndeltaTInc=deltaT/(N+1);\n\nx(:,1,:)=x0;\nx(:,N+2,:)=x2;\n\nF0=F(deltaTInc);\nQ1=Q(deltaTInc);\nfor curPoint=1:N\n deltaT0=deltaTInc*(curPoint-1);\n deltaT2=deltaT-deltaT0-deltaTInc;\n\n F1=F(deltaT2);\n Q2=Q(deltaT2);\n\n Pxz=Q1*F1';\n Pzz=F1*Q1*F1'+Q2;\n x1Pred=F0*x(:,curPoint);\n x2Pred=F1*F0*x(:,curPoint);\n x1Mean=x1Pred+Pxz*inv(Pzz)*(x2-x2Pred);\n\n x(:,curPoint+1)=x1Mean;\nend\n\nif(nargout>1)\n t=[0;deltaTInc*(1:(N+1)).'];\n t(end)=deltaT;%Make it exact despite finite precision limitations.\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/Dynamic_Models/meanLinTrajConstEnds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.7098068850830404}} {"text": "function [soln,eqn,info] = Poisson(node,elem,bdFlag,pde,option)\n%% POISSON Poisson equation: P1 linear element.\n%\n% u = Poisson(node,elem,bdFlag,pde) produces the linear finite element\n% approximation of the Poisson equation\n% \n% -div(d*grad(u))=f in \\Omega, with \n% Dirichlet boundary condition u=g_D on \\Gamma_D, \n% Neumann boundary condition d*grad(u)*n=g_N on \\Gamma_N,\n% Robin boundary condition g_R*u + d*grad(u)*n=g_N on \\Gamma _R\n% \n% The mesh is given by node and elem and the boundary edge is by\n% bdFlag. See meshdoc, bddoc for details. The data is given by the\n% structure pde which contains function handles f, g_D, g_N, g_R, or d.\n% For general elliptic equations with convection and reaction\n% coefficients, see ellipticpde.\n% \n% soln = Poisson(node,elem,bdFlag,pde,option) specifies the options.\n%\n% In the output, soln structure contains\n% - soln.u: solution u\n% - soln.Du: gradient of u\n%\n% In the input, option structures contains\n% - option.dquadorder: quadrature order for diffusion coefficients\n% - option.fquadorder: quadrature order for computing right hand side f\n% - option.solver\n% 'direct': the built in direct solver \\ (mldivide)\n% 'mg': multigrid-type solvers mg is used.\n% 'amg': algebraic multigrid method is used.\n% 'none': only assemble the matrix equation but not solve. \n% The default setting is to use the direct solver for small size problems\n% and multigrid solvers for large size problems. For more options on the\n% multigrid solver mg, type help mg.\n%\n% The function Poisson assembes the matrix equation AD*u = b and solves\n% it by the direct solver (small size <= 2e3) or the multigrid solver\n% (large size > 2e3). The Dirichlet boundary condition is built into the\n% matrix AD and the Neumann boundary condition is build into b.\n%\n% The diffusion coefficient d is a scalar function or a column array with\n% the same length as the elem array. \n%\n% When only one type of boundary condition is imposed, the input argument\n% bdFlag can be skipped. The boundary condition is implicitly given in\n% the pde structure by specifying g_D or g_N only. See examples below.\n%\n% [soln,eqn] = Poisson(node,elem,bdFlag,pde) returns also the equation\n% structure eqn, which includes: \n% - eqn.AD: modified stiffness matrix AD;\n% - eqn.b: the right hand side. \n% - eqn.Lap: non-modified stiffness matrix\n%\n% The solution u = AD\\b. The matrix eqn.Lap can be used to evulate the\n% bilinear form a(u,v) = u'*eqn.Lap*v, especially the enery norm of a finite\n% element function u is given by by sqrt(u'*eqn.Lap*u). \n%\n% [soln,eqn,info] = Poisson(node,elem,bdFlag,pde) returns also the\n% information on the assembeling and solver, which includes:\n% - info.assembleTime: time to assemble the matrix equation\n% - info.solverTime: time to solve the matrix equation\n% - info.itStep: number of iteration steps for the mg solver\n% - info.error: l2 norm of the residual b - A*u\n% - info.flag: flag for the mg solver.\n% flag = 0: converge within max iteration \n% flag = 1: iterated maxIt times but did not converge\n% flag = 2: direct solver\n% flag = 3: no solve\n%\n% Example\n% squarePoisson; Poissonfemrate;\n%\n% Example\n% clear all\n% node = [0,0; 1,0; 1,1; 0,1];\n% elem = [2,3,1; 4,1,3]; \n% for k = 1:4\n% [node,elem] = uniformrefine(node,elem);\n% end\n% % Homogenous Dirichlet boundary condition\n% pde.f = inline('ones(size(p,1),1)','p');\n% pde.g_D = 0;\n% u = Poisson(node,elem,[],pde);\n% figure(1); \n% showresult(node,elem,u);\n%\n% See also Poisson3, femPoisson, squarePoisson, Poissonfemrate\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n\n%% Preprocess\nif ~exist('bdFlag','var'), bdFlag = []; end\nif ~exist('option','var'), option = []; end\n% important constants\nN = size(node,1); \nNT = size(elem,1);\nNdof = N;\n\n%% Diffusion coefficient\ntime = cputime; % record assembling time\nif ~isfield(pde,'d'), pde.d = []; end\nif ~isfield(option,'dquadorder'), option.dquadorder = 1; end\nif ~isempty(pde.d) && isnumeric(pde.d)\n K = pde.d; % d is an array\nend\nif ~isempty(pde.d) && ~isnumeric(pde.d) % d is a function \n [lambda,weight] = quadpts(option.dquadorder);\n nQuad = size(lambda,1);\n K = zeros(NT,1);\n for p = 1:nQuad\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 K = K + weight(p)*pde.d(pxy); \n end\nend\n\n%% Compute geometric quantities and gradient of local basis\n[Dphi,area] = gradbasis(node,elem);\n\n%% Assemble stiffness matrix\nA = sparse(Ndof,Ndof);\nfor i = 1:3\n for j = i:3\n % $A_{ij}|_{\\tau} = \\int_{\\tau}K\\nabla \\phi_i\\cdot \\nabla \\phi_j dxdy$ \n Aij = (Dphi(:,1,i).*Dphi(:,1,j) + Dphi(:,2,i).*Dphi(:,2,j)).*area;\n if ~isempty(pde.d)\n Aij = K.*Aij;\n end\n if (j==i)\n A = A + sparse(elem(:,i),elem(:,j),Aij,Ndof,Ndof);\n else\n A = A + sparse([elem(:,i);elem(:,j)],[elem(:,j);elem(:,i)],...\n [Aij; Aij],Ndof,Ndof); \n end \n end\nend\nclear K Aij\n\n%% Assemble the right hand side\nb = zeros(Ndof,1);\nif ~isfield(option,'fquadorder')\n option.fquadorder = 3; % default order\nend\nif ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n pde.f = [];\nend\nif isreal(pde.f) % f is a real number or vector and not a function\n switch length(pde.f)\n case NT % f is piecewise constant\n bt = pde.f.*area/3;\n b = accumarray(elem(:),[bt; bt; bt],[Ndof 1]);\n case N % f is piecewise linear\n bt = zeros(NT,3);\n bt(:,1) = area.*(2*pde.f(elem(:,1)) + pde.f(elem(:,2)) + pde.f(elem(:,3)))/12;\n bt(:,2) = area.*(2*pde.f(elem(:,2)) + pde.f(elem(:,3)) + pde.f(elem(:,1)))/12;\n bt(:,3) = area.*(2*pde.f(elem(:,3)) + pde.f(elem(:,1)) + pde.f(elem(:,2)))/12;\n b = accumarray(elem(:),bt(:),[Ndof 1]);\n case 1 % f is a scalar e.g. f = 1\n bt = pde.f*area/3;\n b = accumarray(elem(:),[bt; bt; bt],[Ndof 1]);\n end\nend\nif ~isempty(pde.f) && ~isreal(pde.f) % f is a function \n [lambda,weight] = quadpts(option.fquadorder);\n phi = lambda; % linear bases\n\tnQuad = size(lambda,1);\n bt = zeros(NT,3);\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 for i = 1:3\n bt(:,i) = bt(:,i) + weight(p)*phi(p,i)*fp;\n end\n end\n bt = bt.*repmat(area,1,3);\n b = accumarray(elem(:),bt(:),[Ndof 1]);\nend\nclear pxy bt\n\n%% Set up boundary conditions\n[AD,b,u,freeNode,isPureNeumann] = getbd(b);\n\n%% Record assembling time\nassembleTime = cputime - time;\nif ~isfield(option,'printlevel'), option.printlevel = 1; end\nif option.printlevel >= 2\n fprintf('Time to assemble matrix equation %4.2g s\\n',assembleTime);\nend\n\n%% Solve the system of linear equations\nif isempty(freeNode), return; end\n% Set up solver type\nif isempty(option) || ~isfield(option,'solver') || isfield(option,'mgoption') % no option.solver\n if Ndof <= 2e3 % Direct solver for small size systems\n option.solver = 'direct';\n else % MGCG solver for large size systems\n option.solver = 'mg';\n end\nend\nif isPureNeumann\n option.solver = 'mg';\nend\nsolver = option.solver;\n% solve\nswitch solver\n case 'direct'\n t = cputime;\n u(freeNode) = AD(freeNode,freeNode)\\b(freeNode);\n residual = norm(b - AD*u);\n info = struct('solverTime',cputime - t,'itStep',0,'err',residual,'flag',2,'stopErr',residual);\n case 'none'\n info = struct('solverTime',[],'itStep',0,'err',[],'flag',3,'stopErr',[]);\n case 'mg'\n if ~isfield(option,'mgoption') % no option.mgoption\n option.mgoption.x0 = u;\n option.mgoption.solver = 'CG';\n end\n [u,info] = mg(AD,b,elem,option.mgoption);\n case 'amg'\n if ~isfield(option,'amgoption') % no option.amgoption\n option.amgoption.x0 = u;\n option.amgoption.solver = 'CG';\n end\n [u(freeNode),info] = amg(AD(freeNode,freeNode),b(freeNode),option.amgoption); \nend\n% post-process for pure Neumann problem\nif isPureNeumann\n patchArea = accumarray(elem(:),[area;area;area]/3, [N 1]); \n uc = sum(u.*patchArea)/sum(area);\n u = u - uc; % int u = 0\nend\n\n%% Compute Du\ndudx = u(elem(:,1)).*Dphi(:,1,1) + u(elem(:,2)).*Dphi(:,1,2) ...\n + u(elem(:,3)).*Dphi(:,1,3);\ndudy = u(elem(:,1)).*Dphi(:,2,1) + u(elem(:,2)).*Dphi(:,2,2) ...\n + u(elem(:,3)).*Dphi(:,2,3); \nDu = [dudx, dudy];\n\n%% Output\nif nargout == 1\n soln = u;\nelse\n soln = struct('u',u,'Du',Du);\n eqn = struct('A',AD,'b',b,'freeNode',freeNode,'Lap',A);\n info.assembleTime = assembleTime;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbd\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function [AD,b,u,freeNode,isPureNeumann] = getbd(b)\n %% Set up of boundary conditions.\n %\n % 1) Modify the matrix for Dirichlet boundary nodes, which are not degree\n % of freedom. Values at these nodes are evaluatation of pde.g_D. The\n % original stiffness matrix A is turn into the matrix AD by enforcing\n % AD(fixedNode,fixedNode)=I, AD(fixedNode,freeNode)=0, AD(freeNode,fixedNode)=0.\n %\n % 2) Modify the right hand side b. The Neumann boundary integral is added\n % to b. For Dirichlet boundary ndoes, b(fixedNode) is the evaluation of\n % pde.g_D.\n %\n % Special attentation should be given for the pure Neumann boundary\n % condition. To enforce the compatible condition, the vector b should have\n % mean value zero. To avoid a singular matrix, the 1st node is chosen as\n % fixedNode. \n %\n % The order of assigning Neumann and Dirichlet boundary condition is\n % important to get the right setting at the intersection nodes of Dirichlet\n % and Neumann boundary edges.\n %\n % Reference: Long Chen. Finite Element Methods and its Programming. Lecture\n % Notes.\n\n u = zeros(Ndof,1); \n %% Initial check\n if ~isfield(pde,'g_D'), pde.g_D = []; end\n if ~isfield(pde,'g_N'), pde.g_N = []; end\n if ~isfield(pde,'g_R'), pde.g_R = []; end\n\n %% Part 1: Modify the matrix for Dirichlet and Robin condition\n % Robin boundary condition\n Robin = [];\n isRobin = (bdFlag(:) == 3);\n if any(isRobin)\n allEdge = [elem(:,[2,3]); elem(:,[3,1]); elem(:,[1,2])];\n Robin = allEdge(isRobin,:);\n end\n if ~isempty(Robin) && ~isempty(pde.g_R) && ~(isnumeric(pde.g_R) && (pde.g_R == 0))\n ve = node(Robin(:,1),:) - node(Robin(:,2),:);\n edgeLength = sqrt(sum(ve.^2,2)); \n mid = (node(Robin(:,1),:) + node(Robin(:,2),:))/2;\n % use Simplson rule to compute int g_R phi_iphi_j ds\n ii = [Robin(:,1),Robin(:,1),Robin(:,2),Robin(:,2)];\n jj = [Robin(:,1),Robin(:,2),Robin(:,1),Robin(:,2)];\n temp = pde.g_R(mid).*edgeLength;\n ss = [1/3*temp, 1/6*temp, 1/6*temp, 1/3*temp];\n A = A + sparse(ii,jj,ss,Ndof,Ndof);\n end\n \n % Find Dirichlet boundary nodes: fixedNode\n fixedNode = []; freeNode = [];\n if ~isempty(bdFlag) % find boundary edges and boundary nodes\n [fixedNode,bdEdge,isBdNode] = findboundary(elem,bdFlag);\n freeNode = ~isBdNode;\n end\n if isempty(bdFlag) && ~isempty(pde.g_D) && isempty(pde.g_N) && isempty(pde.g_R)\n % no bdFlag, only pde.g_D is given\n [fixedNode,bdEdge,isBdNode] = findboundary(elem);\n freeNode = ~isBdNode;\n end\n \n % Modify the matrix for different boundary conditions \n % Dirichlet boundary condition\n % Build Dirichlet boundary condition into the matrix AD by enforcing\n % AD(fixedNode,fixedNode)=I, AD(fixedNode,freeNode)=0, AD(freeNode,fixedNode)=0.\n if ~isempty(fixedNode)\n bdidx = zeros(Ndof,1); \n bdidx(fixedNode) = 1;\n Tbd = spdiags(bdidx,0,Ndof,Ndof);\n T = spdiags(1-bdidx,0,Ndof,Ndof);\n AD = T*A*T + Tbd;\n end\n % Neumann boundary condition\n isPureNeumann = false;\n if isempty(fixedNode) && isempty(Robin) % pure Neumann boundary condition\n isPureNeumann = true;\n AD = A;\n AD(1,1) = AD(1,1) + 1e-6;\n% fixedNode = 1;\n% freeNode = 2:Ndof; % eliminate the kernel by enforcing u(1) = 0;\n end\n % Robin boundary condition\n if isempty(fixedNode) && ~isempty(Robin)\n AD = A;\n end\n \n %% Part 2: Find boundary edges and modify the right hand side b\n % Find boundary edges: Neumann\n Neumann = []; \n if ~isempty(bdFlag) % bdFlag specifies different bd conditions\n Neumann = bdEdge; \n end\n if isempty(bdFlag) && (~isempty(pde.g_N) || ~isempty(pde.g_R))\n % no bdFlag, only pde.g_N or pde.g_R is given in the input\n [tempvar,Neumann] = findboundary(elem); %#ok\n end\n\n % Neumann boundary condition\n if isnumeric(pde.g_N) && all(pde.g_N == 0)\n pde.g_N = [];\n end\n if ~isempty(Neumann) && ~isempty(pde.g_N)\n el = sqrt(sum((node(Neumann(:,1),:) - node(Neumann(:,2),:)).^2,2));\n if ~isfield(option,'gNquadorder')\n option.gNquadorder = 2; % default order exact for linear gN\n end\n [lambdagN,weightgN] = quadpts1(option.gNquadorder);\n phigN = lambdagN; % linear bases\n nQuadgN = size(lambdagN,1);\n ge = zeros(size(Neumann,1),2);\n for pp = 1:nQuadgN\n % quadrature points in the x-y coordinate\n ppxy = lambdagN(pp,1)*node(Neumann(:,1),:) ...\n + lambdagN(pp,2)*node(Neumann(:,2),:);\n gNp = pde.g_N(ppxy);\n for igN = 1:2\n ge(:,igN) = ge(:,igN) + weightgN(pp)*phigN(pp,igN)*gNp;\n end\n end\n ge = ge.*repmat(el,1,2);\n b = b + accumarray(Neumann(:), ge(:),[Ndof,1]); \n end\n % The case with non-empty Neumann edges but g_N=0 or g_N=[] corresponds to\n % the zero flux boundary condition on Neumann edges and no modification of\n % A,u,b is needed.\n\n % Dirichlet boundary condition\n if isnumeric(pde.g_D) && all(pde.g_D == 0) % zero g_D\n pde.g_D = [];\n end\n if ~isPureNeumann && ~isempty(fixedNode) && ~isempty(pde.g_D)\n if isnumeric(pde.g_D) % pde.g_D could be a numerical array \n u(fixedNode) = pde.g_D(fixedNode); \n else % pde.g_D is a function handle\n u(fixedNode) = pde.g_D(node(fixedNode,:));\n end\n b = b - A*u;\n end\n if ~isempty(fixedNode) % non-empty Dirichlet boundary condition\n b(fixedNode) = u(fixedNode);\n end\n % The case with non-empty Dirichlet nodes but g_D=0 or g_D=[] corresponds\n % to the zero Dirichlet boundary condition and no modification of u,b is\n % needed.\n\n % Pure Neumann boundary condition\n if isPureNeumann\n b = b - mean(b); % compatiable condition (f,1) + = 0\n% b(1) = 0;\n end\n end % end of getbd\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nend % end of Poisson\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/Poisson.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.7097391889010687}} {"text": "function [ n_data, x, fx ] = arctan_values ( n_data )\n\n%*****************************************************************************80\n%\n%% ARCTAN_VALUES returns some values of the arc tangent function.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% ArcTan[x]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 June 2007\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 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 X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 11;\n\n fx_vec = [ ...\n 0.00000000000000000000, ...\n 0.24497866312686415417, ...\n 0.32175055439664219340, ...\n 0.46364760900080611621, ...\n 0.78539816339744830962, ...\n 1.1071487177940905030, ...\n 1.2490457723982544258, ...\n 1.3258176636680324651, ...\n 1.3734007669450158609, ...\n 1.4711276743037345919, ...\n 1.5208379310729538578 ];\n\n x_vec = [ ...\n 0.00000000000000000000, ...\n 0.25000000000000000000, ...\n 0.33333333333333333333, ...\n 0.50000000000000000000, ...\n 1.0000000000000000000, ...\n 2.0000000000000000000, ...\n 3.0000000000000000000, ...\n 4.0000000000000000000, ...\n 5.0000000000000000000, ...\n 10.000000000000000000, ...\n 20.000000000000000000 ];\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/arctan_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7097391851903755}} {"text": "function gray_3x3 = image_denoise_gray_3x3 ( gray )\n\n%*****************************************************************************80\n%\n%% IMAGE_DENOISE_GRAY_3X3 filters out noise from a gray scale image.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 December 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, uint8 GRAY(:,:), the noisy grayscale data.\n%\n% Output, uint8 GRAY_3X3(:,:), the grayscale data for the filtered image.\n%\n [ m, n ] = size ( gray );\n gray3d = zeros ( 9, m, n );\n%\n% For pixel (I,J), GRAY3D(*,I,J) contains the current pixel value\n% and the 8 neighboring values.\n%\n gray3d(1,:,:) = circshift ( gray, [ -1, -1 ] );\n gray3d(2,:,:) = circshift ( gray, [ -1, 0 ] );\n gray3d(3,:,:) = circshift ( gray, [ -1, 1 ] );\n gray3d(4,:,:) = circshift ( gray, [ 0, -1 ] );\n gray3d(5,:,:) = circshift ( gray, [ 0, 0 ] );\n gray3d(6,:,:) = circshift ( gray, [ 0, 1 ] );\n gray3d(7,:,:) = circshift ( gray, [ 1, -1 ] );\n gray3d(8,:,:) = circshift ( gray, [ 1, 0 ] );\n gray3d(9,:,:) = circshift ( gray, [ 1, 1 ] );\n%\n% By taking the median of the 9 values, we hope to drop any noisy pixels.\n%\n gray3d = median ( gray3d );\n%\n% The MEDIAN command returned a 3D array with a first dimension of 1.\n% For convenience, we suppress the first dimension.\n%\n gray_3x3(:,:) = gray3d(1,:,:);\n%\n% GRAY is a UINT8 array. The MEDIAN operation returned a DOUBLE value.\n% So we have to convert the array back to UINT8.\n%\n gray_3x3 = uint8 ( gray_3x3 );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/image_denoise/image_denoise_gray_3x3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7097236467891953}} {"text": "% MAIN Illustrates how to use the EPnP algorithm described in:\n%\n% Francesc Moreno-Noguer, Vincent Lepetit, Pascal Fua.\n% Accurate Non-Iterative O(n) Solution to the PnP Problem. \n% In Proceedings of ICCV, 2007. \n%\n% Copyright (C) <2007> \n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the version 3 of the GNU General Public License\n% as published by the Free Software Foundation.\n% \n% This program is distributed in the hope that it will be useful, but\n% WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n% General Public License for more details. \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n%\n% Francesc Moreno-Noguer, CVLab-EPFL, September 2007.\n% fmorenoguer@gmail.com, http://cvlab.epfl.ch/~fmoreno/ \n\nclear all; close all;\n\naddpath data;\naddpath error;\naddpath EPnP;\n\n\nfprintf('\\n---------EPnP--------------\\n');\n%1.-Generate simulated input data------------------------------------------\nload_points=0;\nif ~load_points\n n=50; %number of points\n std_noise=10; %noise in the measurements (in pixels)\n [A,point,Rt]=generate_noisy_input_data(n,std_noise);\n save('data\\input_data_noise.mat','A','point','Rt');\nelse\n load('data\\input_data_noise.mat','A','point','Rt');\n n=size(point,2);\n draw_noisy_input_data(point);\nend\n\n%2.-Inputs format--------------------------------\nx3d=zeros(n,4);\nx2d=zeros(n,3); \nA=A(:,1:3);\nfor i=1:n\n x3d_h(i,:)=[point(i).Xworld',1]; \n x2d_h(i,:)=[point(i).Ximg(1:2)',1];\n\n %world and camera coordinates\n X3d_world(i,:)=point(i).Xworld';\n X3d_cam(i,:)=point(i).Xcam';\nend\n\n\n%3.-EPnP----------------------------------------------------\nXw=x3d_h(:,1:3);\nU=x2d_h(:,1:2);\n\n[Rp,Tp,Xc,sol]=efficient_pnp(x3d_h,x2d_h,A);\n\n%draw Results\nfor i=1:n\n point(i).Xcam_est=Xc(i,:)';\nend\nfigure; h=gcf;\nplot_3d_reconstruction(point,'EPnP (Old)',h);\nxlim([-2 2]); ylim([-2 2]);\n\n%compute error\nerror=reprojection_error_usingRT(Xw,U,Rp,Tp,A);\nfprintf('error EPnP: %.3f\\n',error);\n\n\n%3.-EPnP_GAUSS_NEWTON----------------------------------------------------\nXw=x3d_h(:,1:3);\nU=x2d_h(:,1:2);\n\n[Rp,Tp,Xc,sol]=efficient_pnp_gauss(x3d_h,x2d_h,A);\n\n%draw Results\nfor i=1:n\n point(i).Xcam_est=Xc(i,:)';\nend\nfigure; h=gcf;\nplot_3d_reconstruction(point,'EPnP Gauss Newton',h);\n\n%compute error\nerror=reprojection_error_usingRT(Xw,U,Rp,Tp,A);\nfprintf('error EPnP_Gauss_Newton: %.3f\\n',error);\nxlim([-2 2]); ylim([-2 2]);\n\n\n\n\n", "meta": {"author": "cvlab-epfl", "repo": "EPnP", "sha": "f9d27b186d9c754b72e076b3843f47ad136e9799", "save_path": "github-repos/MATLAB/cvlab-epfl-EPnP", "path": "github-repos/MATLAB/cvlab-epfl-EPnP/EPnP-f9d27b186d9c754b72e076b3843f47ad136e9799/matlab/main.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.7097210177192095}} {"text": "function y = poly_env( p, x )\n\n%POLY_ENV Evaluate the convex or concave envelope of a polynomial.\n% POLY_ENV( P, X ) uses a semidefinite program to compute the value of the\n% convex or concave envelope of the polynomial represented by the vector\n% P. The format of the vector P is identical to that required by POLYVAL,\n% with two additional restrictions. First, the elements of P must be real\n% and finite. Second, the length of P must 0, 2, or odd (1,3,5,...)\n%\n% If the polynomial described by P is convex or concave, then a call to\n% POLY_ENV( P, X ) produces the same result as POLYVAL( P, X ).\n%\n% POLY_ENV looks at the first nonzero element of P (presumably, but not\n% necessarily, P(1)) to determine if a convex or concave envelope is to\n% be selected. If P(1)>0, then a convex envelope is produced---i.e., the\n% function that is the tightest convex lower bound for POLYVAL(P,X).\n% Otherwise, a concave envelope is produced---the function that is the\n% tightest concave upper bound for POLYVAL(P,X).\n%\n% If the degree N of P is odd---except for the special case N==1---no\n% proper convex/concave envelope exists. Therefore, POLY_ENV returns an\n% error in such cases.\n%\n% If X is an array, the result will be computed elementwise.\n%\n% Disciplined convex programming information:\n% POLY_ENV(P,X) is convex or concave and nonmotonic in X; therefore,\n% in CVX expressions, X must be affine, unless the polynomial \n% described by P has a degree of 0 or 1. P must be constant.\n\n%\n% Check the polynomial\n%\n\nsp = size( p );\nif isempty( p ),\n p = zeros( 1, 0 );\nelseif ~isa( p, 'double' ) || ~isreal( p ) || length( sp ) > 2 || ~any( sp == 1 ),\n cvx_throw( 'First argument must be a non-empty real vector.' );\nelseif any( isnan( p ) | isinf( p ) ),\n cvx_throw( 'First argument must not contain Inf or NaN.' );\nend\nn = prod( sp );\nif n > 2 && rem( n, 2 ) == 0,\n cvx_throw( 'The length of the vector p must be odd.' );\nend\n\n%\n% Check the second argument\n%\n\nif n > 1 && ( ~cvx_isaffine( x ) || ~isreal( x ) ),\n cvx_throw( 'The second argument must be real and affine.' );\nend\n\n%\n% Handle the special cases\n%\n\nsx = size( x );\nndxs = find( p );\nif isempty( ndxs ),\n y = zeros( sx );\n return\nelse\n for k = ndxs(:)',\n pt = p( k : end );\n if ~any( isinf( pt ./ pt(1) ) ),\n p = pt;\n break;\n end\n end\nend\nn = length( p );\nswitch n,\n case 0,\n y = zeros(sx);\n return\n case 1,\n y = p(1) * ones(sx);\n return\n case 2,\n y = p(1) * x + p(2);\n return\n case 3,\n % Quadratic\n b2a = p(2) ./ ( 2 * p(1) );\n y = p(1) * ( square( x + b2a ) - b2a * b2a ) + p(3);\n return\n otherwise,\n if all( p(2:end) == 0 ),\n y = p(1) * ( x .^ (n-1) ) + p(end);\n return\n end\nend\n\n%\n% Build and solve the SDP\n%\n\ndegr = n - 1;\ndeg2 = 0.5 * degr + 1;\nnv = prod( sx );\npsign = sign(p(1));\np = psign * reshape( p, 1, n );\ncvx_begin sdp\n variable y(sx);\n variable P(deg2,deg2,sx) hankel;\n if cvx_isconstant( x )\n minimize(sum(y)); %#ok\n else\n minimize(y); %#ok\n end\n P >= 0; %#ok\n 1 == P(1,1,:); %#ok\n x == reshape( P(2,1,:), sx ); %#ok\n y == reshape( p(end:-1:1) * [ reshape( P(1,:,:), deg2, nv ) ; reshape( P(2:end,end,:), deg2-1, nv ) ], sx ); %#ok\ncvx_end\n\ny = cvx_optval * psign;\n\n% Copyright 2005-2014 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\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/functions/poly_env.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7097209961365305}} {"text": "%KCENTRES Finds K center objects from a distance matrix\n% \n% [LAB,J,DM] = KCENTRES(D,K,N)\n% \n% INPUT\n% D Distance matrix between, e.g. M objects (may be a dataset)\n% K Number of center objects to be found (optional; default: 1)\n% N Number of trials starting from a random initialization\n% (optional; default: 1)\n%\n% OUTPUT\n% LAB Integer labels: each object is assigned to its nearest center\n% J Indices of the center objects\n% DM A list of distances corresponding to J: for each center in J \n% the maximum distance of the objects assigned to this center.\t\n%\n% DESCRIPTION \n% Finds K center objects from a symmetric distance matrix D. The center \n% objects are chosen from all M objects such that the maximum of the \n% distances over all objects to the nearest center is minimized. For K > 1,\n% the results depend on a random initialization. The procedure is repeated \n% N times and the best result is returned. \n%\n% If N = 0, initialisation is not random, but done by a systematic\n% selection based on a greedy approach.\n% \n% SEE ALSO (PRTools Guide)\n% HCLUST, PRKMEANS, EMCLUST, MODESEEK\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: kcentres.m,v 1.5 2008/07/03 09:08:43 duin Exp $\n\nfunction [labels,Jopt,dm] = kcentres(d,k,n)\n\t\n\tif (nargin < 3) | isempty(n)\n n = 1;\n prwarning(4,'Number of trials not supplied, assuming one.');\n end\n\n\tif (nargin < 2) | isempty(k)\n k = 1;\n prwarning(4,'Number of centers not supplied, assuming one.');\n end\n\t\n\tif(isdataset(d))\n\t\td = +d;\n\t\tprwarning(4,'Distance matrix is convert to double.');\n\tend\n\n\t[m,m2] = size(d);\n\tif ( ~issym(d,1e-12) | any(diag(d) > 1e-14) )\n\t\terror('Distance matrix should be symmetric and have zero diagonal')\n\tend\n\n% checking for a zero diagonal \n\tt = eye(m) == 1;\t\n\tif(~all(d(t)==0))\n\t\terror('Distance matrix should have a zero diagonal.')\n\tend\n\n\tif (k == 1)\n\t\tdmax = max(d);\n\t\t[dm,Jopt] = min(dmax);\n\t\tlabels = repmat(1,m,1);\n\t\treturn;\n\tend\n\n\tif k > m\n\t\terror('Number of centres should not exceed number of objects')\n\tend\n\t\n\t% We are here only if K (> 1) centers are to be found.\n\t% Loop over number of trials.\n\tdmax = max(max(d));\n\tdopt = inf;\n\ts = sprintf('k-centres, %i attempts: ',n);\n\tprwaitbar(n,s,n>1);\n\tif n == 0\n\t\tnrep = 1; \n\telse \n\t\tnrep = n; \n\tend\n\tfor tri = 1:nrep\n\t\tprwaitbar(n,tri,[s int2str(tri)]);\n\t\tif n == 0\n\t\t\tM = kcentresort(d,k); % systematic initialisation\n\t\telse\n\t\t\tM = randperm(m); M = M(1:k);\t\t% Random initializations\n\t\tend\n \t\tJ = zeros(1,k); \t\t\t\t\t \t % Center objects to be found.\n\n\t\t% Iterate until J == M. See below.\n\t\twhile 1,\n\t\t\t[dm,I] = min(d(M,:));\n\n\t\t\t% Find K centers. \n\t\t\tfor i = 1:k \n\t\t\t\tJJ = find(I==i); \n\t\t\t\tif (isempty(JJ))\n\t\t\t\t\t%JJ can be empty if two or more objects are in the same position of \n\t\t\t\t\t% feature space in dataset\n\t\t\t\t\tJ(i) = 0;\t\t\t\t\t\t\t\t\t\n\t\t\t\telse\n\t\t\t\t\t\t% Find objects closest to the object M(i)\n\t\t\t\t\t[dummy,j,dm] = kcentres(d(JJ,JJ),1,1);\n\t\t\t\t\tJ(i) = JJ(j);\n\t\t\t\tend\n\t\t\tend\n\n\t\t\tJ(find(J==0)) = [];\n\t\t\tk = length(J);\n\t\t\tif k == 0\n\t\t\t\terror('kcentres fails as some objects are identical: add some noise')\n\t\t\tend\n\t\t\tif (length(M) == k) & (all(M == J))\n\t\t\t\t% K centers are found.\n\t\t\t\t[dmin,labs] = min(d(J,:));\n\t\t\t\tdmin = max(dmin);\n\t\t\t\tbreak;\n\t\t\tend\n\t\t\tM = J;\n\t\tend\n\n\t\t% Store the optimal centers in JOPT.\n\t\n\t\tif (dmin <= dopt)\n\t\t\tdopt = dmin;\n\t\t\tlabels = labs';\n\t\t\tJopt = J;\n\t\tend\n\t\n\tend\n\tprwaitbar(0)\n\t\n\t% Determine the best centers over the N trials.\n\tdm = zeros(1,k); \n\tfor i=1:k\n\t\tL = find(labels==i);\n\t\tdm(i) = max(d(Jopt(i),L));\n\tend\n\nreturn;\n\n%KCENTRESORT Sort objects given by dissimilarity matrix\n%\n% N = KCENTRESORT(D,P,CRIT)\n%\n% INPUT\n% D Square dissimilarity matrix, zeros on diagonal\n% P Number of prototypes to be selected\n% CRIT 'dist' or 'centre'\n%\n% OUTPUT\n% N Indices of selected prototypes\n%\n% DESCRIPTION\n% Sort objects given by square dissim matrix D using a greedy approach\n% such that the maximum NN distance from all objects (prototypes)\n% to the first K: max(min(D(:,N(1:K),[],2)) is minimized.\n%\n% This routines tries to sample the objects such that they are evenly\n% spaced judged from their dissimilarities. This may be used as\n% initialisation in KCENTRES. It works reasonably, but not very good.\n%\n% SEE ALSO (PRTools Guide)\n% KCENTRES\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 N = kcentresort(d,p,crit);\n\nd = +d;\nm = size(d,1);\nif nargin < 3, crit = 'dist'; end\nif nargin < 2 | isempty(p), p = m; end\nL = [1:m];\nN = zeros(1,p);\n[dd,n] = min(max(d,[],2)); % this is the first (central) prototype\ne = d(:,n); % store here the distances to the nearest prototype (dNNP)\nf = min(d,repmat(e,1,m)); % replace distances that are larger than dNNP by dNNP\nN(1) = n; % ranking of selected prototypes\nL(n) = []; % candidate prototypes (all not yet selected objects)\n\nfor k=2:p % extend prototype set\n if strcmp(crit,'centre')\n [dd,n] = min(max(f(L,L),[],1)); % This selects the next prototype out of candidates in L\n e = min([d(:,L(n)) e],[],2); % update dNNP\n f = min(d,repmat(e,1,m)); % update replacement of distances that are larger\n % than dNNP by dNNP\n elseif strcmp(crit,'dist')\n [dd,n] = max(mean(d(N(find(N > 0)),L)));\n else\n error('Illegal crit')\n end\n N(k) = L(n); % update list of selected prototypes\n L(n) = []; % update list of candidate prototypes\nend\n\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/kcentres.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7096628483230243}} {"text": "function b = r8mat_l1_inverse ( n, a )\n\n%*****************************************************************************80\n%\n%% R8MAT_L1_INVERSE inverts a unit lower triangular R8MAT.\n%\n% Discussion:\n%\n% A unit lower triangular matrix is a matrix with only 1's on the main\n% diagonal, and only 0's above the main diagonal.\n%\n% The inverse of a unit lower triangular matrix is also\n% a unit lower triangular matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 October 2005\n%\n% Author:\n%\n% Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% A Nijenhuis and H Wilf,\n% Combinatorial Algorithms,\n% Academic Press, 1978, second edition,\n% ISBN 0-12-519260-6.\n%\n% Parameters:\n%\n% Input, integer N, number of rows and columns in the matrix.\n%\n% Input, real A(N,N), the unit lower triangular matrix.\n%\n% Output, real B(N,N), the inverse matrix.\n%\n for i = 1 : n\n\n for j = 1 : n\n\n if ( i < j )\n b(i,j) = 0.0;\n elseif ( j == i )\n b(i,j) = 1.0;\n else\n b(i,j) = -( a(i,1:i-1) * b(1:i-1,j) );\n end\n\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/r8lib/r8mat_l1_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7096628461351612}} {"text": "function [x fx] = newtonArmijo(func,init,arguments,varargin)\n%function [x fx] = newton(func,init,arguments,varargin)\n% do a newton minimization\n% func must return the likelihood and the value of the update -H^{-1}g\n\n[max_its init_alpha thresh debug min_alpha max_inner_its] = process_options(varargin,'max-its',1000,'init-alpha',1,'thresh',1e-8,'debug',0,'min-alpha',1e-15,'max-inner-its',1000);\nx = init;\nbeta = 1e-4; tau = 0.25; \n\niterator = newIterator(max_its,'thresh',thresh,'debug',debug);\nalpha = init_alpha;\nwhile ~iterator.done\n [old_score gradient step] = feval(func,x,arguments{:});\n \n %do armijo linear-searchto find step size\n new_score = feval(func,x+alpha*step,arguments{:});\n inner_its = 0;\n while inner_its < max_inner_its && alpha > min_alpha && (isnan(new_score) || isinf(new_score) || new_score > old_score + beta * gradient' * (alpha * step))\n %if debug, fprintf('alpha: %.2e -> %.2e\\n',alpha,alpha*tau); end\n alpha = alpha * tau;\n new_score = feval(func,x+alpha*step,arguments{:});\n inner_its = inner_its + 1;\n end\n if alpha < min_alpha, alpha == 0; end\n try %try to take a step, if you can\n x = x + alpha * step;\n alpha = alpha ./ tau; %walk back one step\n fx(iterator.its+1) = new_score;\n iterator = updateIterator(iterator,-new_score);\n catch\n iterator.done = true;\n end\nend\n\n", "meta": {"author": "jacobeisenstein", "repo": "SAGE", "sha": "5776655f6c09f2c24a96485a0985660e64664415", "save_path": "github-repos/MATLAB/jacobeisenstein-SAGE", "path": "github-repos/MATLAB/jacobeisenstein-SAGE/SAGE-5776655f6c09f2c24a96485a0985660e64664415/utils/newtonArmijo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7096628438727022}} {"text": "function [ v, d ] = pts_pca( x, kernel )\n% PTS_PCA Linear and Kernel Principal Component Analysis (PCA and KPCA)\n%\n% [ V, D ] = PTS_PCA(X)\n%\n% Center X and compute eigenvectors V and eigenvalues D using linear PCA.\n%\n% X is a matrix where each column is a vector. Each row is a sample of a\n% variable.\n%\n% The eigenproblem solved is\n%\n% S * v = d * v\n%\n% where v is each eigenvector, and d each corresponding eigenvalue. S is\n% the biased covariance matrix\n%\n% S = 1/M * Xc * Xc'\n%\n% where Xc is the matrix of centered vectors X.\n%\n% NOTE: If there are less vectors than variables, or kernel PCA is\n% selected, MDS is used to speed up computation of eigenvectors.\n%\n% NOTE: Tiny eigenvalues can give numerical errors, so eigenvalues <\n% 1e-13 and the corresponding eigenvectors are removed from the output.\n% Negative eigenvalues are assumed to arise from numerical errors, and\n% removed too.\n%\n% NOTE: Matlab's function cov() computes the _unbiased_ covariance.\n%\n% [ A, DA ] = PTS_PCA(X, KERNEL)\n%\n% Generalization to any type of kernel. KERNEL is a struct with the\n% kernel description\n%\n% Linear PCA, as above\n%\n% KERNEL.type = 'linear'\n%\n% Kernel PCA, Polynomial homogeneous order q\n%\n% KERNEL.type = 'polyh'\n% KERNEL.params = q\n%\n% Kernel PCA, Gaussian with standard deviation sigma\n%\n% KERNEL.type = 'gauss'\n% KERNEL.params = sigma\n%\n% Because in general we want to avoid any explicit computations in\n% feature space, we solve the eigenproblem [1]\n%\n% Kc * a = da * a\n%\n% where a is each \"coefficient eigenvector\", and da = m * d, where m is\n% the number of vectors X. Kc is the kernel matrix of centered feature\n% vectors phi(X).\n%\n% If you want to obtain the eigenvectors and eigenvalues in feature space\n% (for those cases where feature space is finite dimensional), you need\n% to compute the feature space training vectors phi(X), center them to\n% phic, and do\n%\n% v = phic * a * diag(1./sqrt(da))\n% d = da / m\n%\n% where m is the number of training vectors. (Note that v computed as\n% above is equal to v computed from the feature vectors save possibly the\n% sign).\n%\n% [1] B. Schölkopf, A.J. Smola and K.-R. Müller. \"Kernel Principal\n% Component Analysis\". In \"Advances in Kernel Methods - SV Learning\", B.\n% Schölkopf, C.J.C. Burges and A.J. Smola, eds. pp. 327--352, MIT Press,\n% 1999.\n\n% Author: Ramon Casero \n% Copyright © 2009-2011 University of Oxford\n% Version: 1.1.0\n% $Rev: 434 $\n% $Date: 2011-06-03 17:16:33 +0100 (Fri, 03 Jun 2011) $\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\nerror( nargchk( 1, 2, nargin, 'struct' ) );\nerror( nargoutchk( 0, 2, nargout, 'struct' ) );\n\nif ndims( x ) > 2\n error( 'X must be a matrix, not a volume' )\nend\n\n% get sizes\n% N: vector length\n% M: number of training vectors\n[ N, M ] = size( x );\n\n% defaults\nif ( nargin < 2 || isempty( kernel ) )\n kernel.type = 'linear';\nend\n\nswitch kernel.type\n \n case 'linear'\n \n % center training vectors\n xmean = mean( x, 2 );\n x = x - repmat( xmean, 1, M );\n\n % compute matrix for eigenproblem\n if ( M < N ) % \"kernel matrix\" trick to speed up computation\n x_cov = x' * x;\n else % normal case, covariance matrix\n x_cov = x * x' / M;\n end\n\n % compute eigenvalues and eigenvectors\n [ v, d ] = eig( x_cov );\n\n % save memory by reducing eigenvalues to a vector\n d = diag( d );\n\n % reoder in decreasing order of signed modulus value\n [~, idx] = sort(abs(d).*sign(d), 1, 'descend');\n d = d(idx);\n v = v(:, idx);\n \n % if \"kernel matrix\" trick was used, it is necessary to convert the\n % coefficient eigenvectors and eigenvalues to feature space\n % eigenvectors and eigenvalues\n if ( M < N )\n \n % scale eigenvectors\n v = x * ( v * diag( 1 ./ sqrt( d ) ) );\n \n % scale eigenvalues\n d = d / M;\n \n end\n \n otherwise\n\n % for kernel PCA, we use a generalization of the speed up trick\n % above\n k = pts_kmat( kernel, x );\n \n % center kernel matrix (this is the same as centering the feature\n % space training vectors and then computing the kernel matrix)\n onesm = ones( M ) / M;\n k = k - onesm * k - k * onesm + onesm * k * onesm;\n \n % k must be symmetric in order to avoid complex eigenvalues, and in\n % theory it should be, but there are small errors due to numeric\n % precision when the centered kernel matrix is computed\n k = ( k + k' ) / 2;\n \n % compute eigenvalues and eigenvectors\n [ v, d ] = eig( k );\n\n % save memory by reducing eigenvalues to a vector\n d = diag( d );\n\n % reoder in decreasing order of signed modulus value\n [~, idx] = sort(abs(d).*sign(d), 1, 'descend');\n d = d(idx);\n v = v(:, idx);\n \nend\n", "meta": {"author": "tomdoel", "repo": "pulmonarytoolkit", "sha": "09688a006d548fb85795df0338d1ed4f4a010fb9", "save_path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit", "path": "github-repos/MATLAB/tomdoel-pulmonarytoolkit/pulmonarytoolkit-09688a006d548fb85795df0338d1ed4f4a010fb9/External/gerardus/matlab/PointsToolbox/pts_pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7096553584227642}} {"text": "function value = c1_geg_monomial_integral ( alpha, expon )\n\n%*****************************************************************************80\n%\n%% C1_GEG_MONOMIAL_INTEGRAL: integral of monomial with Gegenbauer weight on C1.\n%\n% Discussion:\n%\n% C1_GEG is the interval [-1,+1] with the Gegenbauer weight function\n%\n% w(alpha;x) = (1-x^2)^alpha\n%\n% with -1.0 < alpha.\n%\n% value = integral ( -1 <= x <= +1 ) x^expon (1-x^2)^alpha dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real ALPHA, the exponent of (1-X^2).\n% - 1.0 < ALPHA.\n%\n% Input, integer EXPON, the exponent.\n% 0 <= EXPON.\n%\n% Output, real VALUE, the value of the integral.\n%\n if ( alpha <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'C1_GEG_MONOMIAL_INTEGRAL - Fatal error!\\n' );\n fprintf ( 1, ' ALPHA <= -1.0\\n' );\n error ( 'C1_GEG_MONOMIAL_INTEGRAL - Fatal error!' );\n end\n\n if ( mod ( expon, 2 ) == 1 )\n value = 0.0;\n return\n end\n\n c = expon;\n\n arg1 = - alpha;\n arg2 = 1.0 + c;\n arg3 = 2.0 + alpha + c;\n arg4 = - 1.0;\n\n value1 = r8_hyper_2f1 ( arg1, arg2, arg3, arg4 );\n\n value = 2.0 * gamma ( 1.0 + c ) * gamma ( 1.0 + alpha ) ...\n * value1 / gamma ( 2.0 + alpha + 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/stroud/c1_geg_monomial_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7096553495624575}} {"text": "% Stability domain of second order extrapolated BDF scheme\n\n% Copyright 2001 P. Wesseling\n% This program and its subprograms may be freely used, modified and distributed\n% under the GNU General Public License: http://www.gnu.org/copyleft/gpl.html\n\n% Theory is given in Section 5.8 of\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 generates Fig. 5.7 in the book\n\nfigure(1), clf, hold on\n\n\t\t% Plot of stability domain\ntheta = 0:0.01:0.5; theta = theta*pi;\na = (6*cos(theta)-9)./(2*cos(2*theta) - 4*cos(theta)) - 3/2;\nb = (sin(theta).*(2-cos(theta)))./(cos(2*theta) - 2*cos(theta));\nz = - a - i*b; plot(z)\n\n\t\t% Plot of oval\na = 1; b =(2*a/4)^(1/4); theta = 0:0.002:1; theta = theta*pi;\nz = - a*(1-cos(theta)) + i*b*(sin(theta)).^0.5; plot(z,'--')\n\n\t\t% Plot of parabola\nyy = 0:0.02:1.8; b = 1; par = -(yy/b).^2; plot(par,yy,'.')\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/chap5.8/Extrapolated_BDF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403999037784, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7096126595198134}} {"text": "function [tout,yout] = pendulumDE(tVals,omega0,startAngle)\n\n% Copyright 2008-2009 The MathWorks, Inc.\n\n% Equations of motion\neqnsOfMotion = @(t,x) [x(2); -omega0^2*sin(x(1))];\n\n[tout,yout] = ode45(eqnsOfMotion,tVals,[startAngle; 0]);\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/22732-matlab-in-physics-visualisation/Lecture1/pendulumDE.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7096032996165534}} {"text": "function A = sdt_A(H, F)\n% Calculate signal detection theory A statistic: \n% a non-parametric estimate of sensitivity in ROC analysis\n% per Zhang and Mueller (2005)\n%\n% :Usage:\n% ::\n%\n% A = sdt_A(H, F)\n%\n% :Inputs:\n%\n% **H:**\n% hit rate\n%\n% **F:**\n% false alarm rate\n%\n% :Outputs:\n%\n% **A:**\n% A measure of sensitivity of a detector, essentially the area under\n% the ROC curve for either \"normal\" (H>=F) or \"reverse skill\" (F>H)\n% case (ranges from 0.5 to 1).\n%\n% Meaning of values where F > H (\"reverse skill\"): \n%\n% The meaningful measure of sensitivity in this case is A(F,H) \n% as opposed to A(H,F). Subject is assumed to still be sensitive, \n% but to have inverted their interpretation (or \"reverse skill\"). \n% \n% To distinguish from the normal case, such results are returned\n% as (1 - sdt_A(F,H)), so the full range from 0 to 1 is used.\n% For comparisons of sensitivity use abs(sdt_A(H,F) - 0.5).\n%\n% :Example:\n%\n% sdt_A(0.6,0.8) = 0.325. This indicates the same sensitivity as \n% sdt_A(0.8,0.6) = 0.675, but with reversed skill. \n%\n% ..\n% Author: Joe Wielgosz 8/13/2009\n% ..\n\n\nif F <= H % Normal case\n\n if (F <= 0.5) && (0.5 <= H)\n A = 0.75 + (H-F)/4 - F*(1-H);\n elseif (F <= H) && (H <= 0.5)\n A = 0.75 + (H-F)/4 - F/(4*H);\n else % (0.5 < F) && (F <= H)\n A = 0.75 + (H-F)/4 - (1-H)/(4*(1-F));\n end\n \nelse % \"Reverse skill\" - more false positives than hits\n % Using Jason Buhle's approach\n A = 1 - sdt_A(F, H);\n% A = NaN;\nend\n \nend\n", "meta": {"author": "canlab", "repo": "CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/Statistics_tools/sdt_A.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.916109606718245, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7096032794378151}} {"text": "function [fevd_estimates]=olsfevd(irf_estimates,IRFperiods,gamma,n)\n\n\n\n% function [fevd_estimates]=olsfevd(irf_estimates,IRFperiods,gamma,n,endo,datapath)\n% computes and displays fevd values for the OLS VAR model\n% inputs: - cell 'irf_estimates': lower bound, point estimates, and upper bound for the IRFs \n% - integer 'IRFperiods': number of periods for IRFs\n% - matrix 'gamma': structural disturbance variance-covariance matrix (defined p 48 of technical guide)\n% - integer 'n': number of endogenous variables in the BVAR model (defined p 7 of technical guide)\n% - cell 'endo': list of endogenous variables of the model\n% - string 'datapath': user-supplied path to excel data spreadsheet\n% outputs: - cell 'fevd_estimates': lower bound, point estimates, and upper bound for the FEVD \n\n\n\n% this function implements the procedure described p55-56\n\n\n% preliminary tasks\n% create the first cell\ntemp=cell(n,n+1);\n\n% start by filling the first column of every Tij matrix in the cell\n% loop over rows of temp\nfor jj=1:n\n % loop over columns of temp\n for ii=1:n\n % square each element\n temp{jj,ii}(:,1)=irf_estimates{jj,ii}(:,1).^2;\n end\nend\n% fill all the other entries of the Tij matrices\n% loop over rows of temp\nfor jj=1:n\n % loop over columns of temp\n for ii=1:n\n % loop over remaining columns\n for kk=2:IRFperiods\n % define the column as the square of the corresponding column in orthogonalised_irf_record\n % additioned to the value of the preceeding columns, which creates the cumulation\n temp{jj,ii}(:,kk)=irf_estimates{jj,ii}(:,kk).^2+temp{jj,ii}(:,kk-1);\n end\n end\nend\n% multiply each matrix in the cell by the variance of the structural shocks\n% loop over rows of temp\nfor ii=1:n\n% loop over columns of temp\n for jj=1:n\n % multiply column jj of the matrix by the variance of the structural shock\n temp{ii,jj}(1,:)=temp{ii,jj}(1,:)*gamma(jj,jj);\n end\nend\n\n% obtain now the values for Ti, the (n+1)th matrix of each row\n% loop over rows of temp\nfor ii=1:n\n% start the summation over Tij matrices\ntemp{ii,n+1}=temp{ii,1};\n % sum over remaining columns\n for jj=2:n\n temp{ii,n+1}=temp{ii,n+1}+temp{ii,jj};\n end \nend\n\n% create the output cell fevd_record\nfevd_estimates=cell(n,n);\n% fill the cell\n% loop over rows of fevd_estimates\nfor ii=1:n\n % loop over columns of fevd_estimates\n for jj=1:n\n % define the matrix Vfij as the division (pairwise entry) of Tfij by Tfj\n fevd_estimates{ii,jj}=temp{ii,jj}./temp{ii,n+1};\n end\nend\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/olsfevd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.7095766885103157}} {"text": "function x = complex_lorentz( sx, dim )\n\n%COMPLEX_LORENTZ Complex second-order cone.\n% COMPLEX_LORENTZ(N), where N is a positive integer, creates a column\n% variable of length N and a scalar variable, and constrains them\n% to lie in a second-order cone. That is, given the declaration\n% variable x(n) complex\n% variable y\n% the constraint\n% {x,y} == complex_lorentz(n)\n% is equivalent to\n% norm(x,2) <= y\n% The inequality form is more natural, and preferred in most cases. But\n% in fact, the COMPLEX_LORENTZ set form is used by CVX itself to convert\n% complex NORM()-based constraints to solvable form.\n%\n% COMPLEX_LORENTZ(SX,DIM), where SX is a valid size vector and DIM is a\n% positive integer, creates an array variable of size SX and an array\n% variable of size SY (see below) and applies the second-order cone\n% constraint along dimension DIM. That is, given the declarations\n% sy = sx; sy(min(dim,length(sx)+1))=1;\n% variable x(sx) complex\n% variable y(sy)\n% the constraint\n% {x,y} == complex_lorentz(sx,dim)\n% is equivalent to\n% norms(x,2,dim) <= y\n% Again, the inequality form is preferred, but CVX uses the set form\n% internally. DIM is optional; if it is omitted, the first non-singleton\n% dimension is used.\n%\n% LORENTZ(SX,DIM,CPLX) creates real second-order cones if CPLX is FALSE,\n% and complex second-order cones if CPLX is TRUE. The latter case is\n% equivalent to COMPLEX_LORENTZ(SX,DIM).\n%\n% Disciplined convex programming information:\n% LORENTZ is a cvx set specification. See the user guide for\n% details on how to use sets.\n\nif nargin == 1,\n x = lorentz( sx, [], true );\nelse\n x = lorentz( sx, dim, true );\nend\n\n% Copyright 2005-2014 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\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/sets/complex_lorentz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7095766731315025}} {"text": "function [x,y] = snakedeform(x,y,alpha,beta,gamma,kappa,fx,fy,ITER)\n% -------In this function, the initial contour of Active Coutour Model(Snake)\n% will be deformed in the given external force field.\n%\n% alpha: elasticity parameter\n% beta: rigidity parameter\n% gamma: viscosity parameter\n% kappa: external force weight\n% fx,fy: external force field\n\nN = length(x);\n\nalpha = alpha* ones(1,N); \nbeta = beta*ones(1,N);\n\n% produce the five diagnal vectors\nalpham1 = [alpha(2:N) alpha(1)];\nalphap1 = [alpha(N) alpha(1:N-1)];\nbetam1 = [beta(2:N) beta(1)];\nbetap1 = [beta(N) beta(1:N-1)];\n\na = betam1;\nb = -alpha - 2*beta - 2*betam1;\nc = alpha + alphap1 +betam1 + 4*beta + betap1;\nd = -alphap1 - 2*beta - 2*betap1;\ne = betap1;\n\n% generate the parameters matrix\nA = diag(a(1:N-2),-2) + diag(a(N-1:N),N-2);\nA = A + diag(b(1:N-1),-1) + diag(b(N), N-1);\nA = A + diag(c);\nA = A + diag(d(1:N-1),1) + diag(d(N),-(N-1));\nA = A + diag(e(1:N-2),2) + diag(e(N-1:N),-(N-2));\n\ninvAI = inv(A + gamma * diag(ones(1,N)));\n\nfor count = 1:ITER,\n vfx = interp2(fx,x,y,'*linear');\n vfy = interp2(fy,x,y,'*linear');\n \n % deform snake\n x = invAI * (gamma* x + kappa*vfx);\n y = invAI * (gamma* y + kappa*vfy);\nend\n", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/分割算法/Segmentation-of-Ultrasound-Images-master/Code/snakedeform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285007525904, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.7095115188548844}} {"text": "% Isoparametric Formulation Implementation\n% clear memory\nclear all; \n\nfigure(5)\n\n% Displacements\nsubplot(1,2,1); hold on;\n%plot(xx,displacements_exact,'-r'); \n\n% Stress\nsubplot(1,2,2); hold on;\n%plot(xx,stress_exact,'-r');\n\n%% Physical Parameters\n% Initial Area\nA0 = 2; % m^2\n\n% Modulus of elasticity\nE = 8; % N/m^2\n\n% Length of bar\nLtotal = 4; % m \n\n%% Build Elements\n% number of elements,\n%numberElements = 4; \ntest = [1 2 4 8];\nfor numberElements = test\n\n% number of nodes,\nnumberNodes = 2*numberElements+1;\n\n% node coordinates,\nx = linspace(2,6,numberNodes)';\n\n% Generation of coordinates and connectivities\nL = zeros(numberElements,1); elementNodes = zeros(numberElements,3); \nL(1) = Ltotal/numberElements; elementNodes(1,:) = [1,2,3];\nfor i = 2:numberElements \n L(i) = L(1); elementNodes(i,:) = elementNodes(i-1,:) + 2; \nend\nnodeCoordinates = x;\n\n% element center coordinate\nx_mid = 0.5*(x(elementNodes(:,3))-x(elementNodes(:,1)))+x(elementNodes(:,1));\n\n% Evaluate area the center of each element.\n% A: area of cross section\nA = A0*x_mid;\n\n% for structure:\n % displacements: displacement vector\n % force : force vector\n % stiffness: stiffness matrix\nforce=zeros(numberNodes,1);\nstiffness=zeros(numberNodes,numberNodes); \n% computation of the system stiffness matrix and force vector\nfor e=1:numberElements; \n % elementDof: element degrees of freedom (Dof)\n elementDof=elementNodes(e,:) ;\n detJacobian=L(e)/2;\n invJacobian=1/detJacobian;\n ngp = 3;\n [w,xi]=gauss1d(ngp);\n xc=0.5*(nodeCoordinates(elementDof(1))+nodeCoordinates(elementDof(3)));\n for ip=1:ngp;\n [shape,naturalDerivatives]=shapeFunctionL3(xi(ip)); \n B=naturalDerivatives*invJacobian;\n stiffness(elementDof,elementDof)=...\n stiffness(elementDof,elementDof)+ B'*B*w(ip)*detJacobian*E*A(e);\n force(elementDof) = force(elementDof)+...\n 8*(xc+detJacobian*xi(ip))*shape'*detJacobian*w(ip);\n end\nend \n \n%% BCs and solution\n% prescribed dofs\nprescribedDof = find(nodeCoordinates == 2); % fixed at node x = 2 m\n% solution\nGDof=numberNodes;\ndisplacements=solution(GDof,prescribedDof,stiffness,force);\n% output displacements/reactions\noutputDisplacementsReactions(displacements,stiffness, ...\n numberNodes,prescribedDof,force)\n\n%% Stress\nelementCoords=zeros(numberElements*ngp,1);\nstress=zeros(numberElements*ngp,1);\nfor e=1:numberElements; \n % elementDof: element degrees of freedom (Dof)\n elementDof=elementNodes(e,:); \n detJacobian=L(e)/2;\n invJacobian=1/detJacobian;\n [w,xi]=gauss1d(ngp);\n xc=0.5*(nodeCoordinates(elementDof(1))+nodeCoordinates(elementDof(3)));\n for ip=1:ngp;\n [shape,naturalDerivatives]=shapeFunctionL3(xi(ip));\n B=naturalDerivatives*invJacobian;\n elementCoords(ip+(e-1)*3,1)=xc+xi(ip)*detJacobian;\n stress(ip+(e-1)*3,1)=E*B*displacements(elementDof,1);\n end\nend \n\n%% plot figures\n\nswitch numberElements\n case 1\n line='r*--';\n case 2\n line='g*--';\n case 4\n line='k*--';\n case 8\n line='m*--';\nend\n\n% Displacements\nsubplot(1,2,1); plot(nodeCoordinates,displacements,line)\n\n% Stress\nsubplot(1,2,2); axis([2,6,0,26]); plot(elementCoords,stress,line)\n\nend %end for\nsubplot(1,2,1); legend('Exact','NEL=1','NEL=2','NEL=4','NEL=8',4); hold off\nsubplot(1,2,2); legend('Exact','NEL=1','NEL=2','NEL=4','NEL=8',1); hold off\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/FEM/BarIsoParametric/HWproblem4dIso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850075259039, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.7095115034905044}} {"text": "\n% Local Linear Embedding\n% This function implements the weight computation defined in\n% Sam T. Roweis, Lawrence K. Saul, \"Nonlinear Dimensionality \n% Reduction by Local Linear Embedding\", Science, 2000.\n% 'w' is the weights for representing the row-vector 'pt' in terms\n% of the dimensions x neighborCount matrix 'neighbors'.\n% 'conditionerMult' is the multiplier of the identity matrix added\n% to the neighborhood correlation matrix before inversion.\n\nfunction w = localLinearEmbedding(pt, neighbors, conditionerMult)\n % each column of neighbors represent a neighbor, each row a dimension\n % pt is a row vector\n corr = neighbors' * neighbors + conditionerMult * eye(size(neighbors, 2));\n ptDotN = neighbors' * pt;\n alpha = 1 - sum(corr \\ ptDotN);\n beta = sum(corr \\ ones(size(corr, 1), 1)); % sum of elements of inv(corr)\n lagrangeMult = alpha / beta;\n w = corr \\ (ptDotN + lagrangeMult);\nend", "meta": {"author": "yaksoy", "repo": "AffinityBasedMattingToolbox", "sha": "ab3951065321b67d3ad67333779cbb2078474939", "save_path": "github-repos/MATLAB/yaksoy-AffinityBasedMattingToolbox", "path": "github-repos/MATLAB/yaksoy-AffinityBasedMattingToolbox/AffinityBasedMattingToolbox-ab3951065321b67d3ad67333779cbb2078474939/common/localLinearEmbedding.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.7095114916327474}} {"text": "function pols = llegepols1 ( degree, x )\n\n%*****************************************************************************80\n%\n%% LLEGEPOLS1 evaluates orthogonal polynomials on the symmetric interval.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 July 2014\n%\n% Author:\n%\n% Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.\n% This 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 maximum degree.\n%\n% Input, real X, the evaluation point.\n%\n% Output, real POLS(DEGREE+1)), the orthogonal\n% polynomials evaluated at X.\n%\n pols = zeros ( degree + 1, 1 );\n\n pkp1 = 1.0;\n pols(1) = pkp1;\n\n if ( degree == 0 )\n return\n end\n\n pk = pkp1;\n pkp1 = x;\n pols(2) = pkp1;\n\n if ( degree == 1 )\n return\n end\n\n for k = 1 : degree - 1\n\n pkm1 = pk;\n pk = pkp1;\n pkp1 = ( ( 2 * k + 1 ) * x * pk ...\n - ( k ) * pkm1 ) ...\n / ( k + 1 );\n\n pols(k+2) = pkp1;\n\n end\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/square_arbq_rule/llegepols1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.7093955227061193}} {"text": "% StackExchange Mathematics Q3674241\n% https://math.stackexchange.com/questions/3674241\n% Solve argmina∥ax−y∥1 - Minimizer of the L1 Norm of the Difference of a Vectors\n% References:\n% 1. \n% Remarks:\n% 1. sa\n% TODO:\n% \t1. ds\n% Release Notes\n% - 1.0.000 14/05/2020\n% * First release.\n\n\n%% General Parameters\n\nsubStreamNumberDefault = 42; % 500, Very Good!\n% cvx_solver('Gurobi');\n\nhRunTime = tic();\n\ncvx_begin('quiet')\n% cvx_begin()\n % cvx_precision('best');\n variable valA(1, 1);\n minimize( norm(valA * vX - vY, 1) );\ncvx_end\n\nrunTime = toc(hRunTime);\n\n% vX = mX(:);\n\ndisp([' ']);\ndisp([solverString, ' Solution Summary']);\ndisp(['The ', solverString, ' Solver Status - ', cvx_status]);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(valA))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(valA), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n\n%% Solution by Minimum Search\n\nsolverString = 'Solution by 1D Search of the Minimum';\n\nhRunTime = tic();\n\nvalA = fminsearch(hObjFun, mean(vY ./ vX));\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([solverString, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(valA))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(valA), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n\n%% Solution by Root Search\n\nsolverString = 'Solution by 1D Search of the Roto of the Gradient';\n\nhF = @(valA) sign(valA * vX - vY).' * vX;\n\nhRunTime = tic();\n\nvalA = fzero(hF, mean(vY ./ vX));\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([solverString, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(valA))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(valA), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n\n%% Solution by Analytic Form\n\nsolverString = 'Solution by Analytic Form';\n\nhRunTime = tic();\n\nvalA = SolveScaledL1(vX, vY);\n\nrunTime = toc(hRunTime);\n\ndisp([' ']);\ndisp([solverString, ' Solution Summary']);\ndisp(['The Optimal Value Is Given By - ', num2str(hObjFun(valA))]);\ndisp(['The Optimal Argument Is Given By - [ ', num2str(valA), ' ]']);\ndisp(['The Run Time Is Given By - ', num2str(runTime), ' [Sec]']);\ndisp([' ']);\n\n\n%% Display Results\n\nvA = sort(vY ./ vX, 'ascend');\nvB = zeros(numElements, 1);\nvC = zeros(numElements, 1);\n\nfor ii = 1:numElements\n vB(ii) = hS(vA(ii)).' * vX;\n vC(ii) = hObjFun(vA(ii));\nend\n\nvD = linspace(vA(1) - 1, vA(numElements) + 1, numPts);\nvD = sort([vD(:); vA], 'ascend');\nvE = zeros(numPts + numElements, 1);\nvF = zeros(numPts + numElements, 1);\n\nfor ii = 1:(numPts + numElements)\n vE(ii) = hS(vD(ii)).' * vX;\n vF(ii) = hObjFun(vD(ii));\nend\n\nfigureIdx = figureIdx + 1;\n\nhFigure = figure('Position', figPosLarge);\n\nhAxes = axes();\nset(hAxes, 'NextPlot', 'add');\nhLineSeries = plot(vD, vE);\nset(hLineSeries, 'LineWidth', lineWidthNormal);\nhLineSeries = plot(vD, zeros(numPts + numElements, 1));\nset(hLineSeries, 'LineWidth', lineWidthNormal);\nhLineSeries = plot(vA, vB);\nset(hLineSeries, 'LineStyle', 'none', 'Marker', '*', 'MarkerSize', markerSizeLarge);\nset(get(hAxes, 'Title'), 'String', ['Value of f''(a)'], 'FontSize', fontSizeTitle);\nset(get(hAxes, 'XLabel'), 'String', 'a', ...\n 'FontSize', fontSizeAxis);\nset(get(hAxes, 'YLabel'), 'String', '$ {f}^{''} \\left( a \\right) $', ...\n 'FontSize', fontSizeAxis, 'Interpreter', 'latex');\nhLegend = ClickableLegend({['Values of All Points'], ['Zero Range'], ['Junction Points']});\n\nif(generateFigures == ON)\n % saveas(hFigure,['Figure', num2str(figureIdx, figureCounterSpec), '.png']);\n print(hFigure, ['Figure', num2str(figureIdx, figureCounterSpec), '.png'], '-dpng', '-r0'); %\n\nsS.SchmidFactor(r)\n\n%%\n% Ommiting the tension direction r the command\n% returns the Schmid factor as\n% a \n\nSF = sS.SchmidFactor\n\n% plot the Schmid factor in dependency of the tension direction\nplot(SF)\n\n% find the tension directions with the maximum Schmid factor\n[SFMax,pos] = max(SF)\n\n% and annotate them\nannotate(pos)\n\n%% Stress Tensor\n% Instead by the tension direction the stress might be specified by a\n% stress tensor\n\nsigma = stressTensor.uniaxial(vector3d.Z)\n\n%%\n% Then the Schmid factor for the slip system |sS| and the stress tensor\n% |sigma| is computed by\n\nsS.SchmidFactor(sigma)\n\n%% Active Slip System\n% In general a crystal contains not only one slip system but at least all\n% symmetrically equivalent ones. Those can be computed with\n\nsSAll = sS.symmetrise('antipodal')\n\n%%\n% The option |antipodal| indicates that Burgers vectors in oposite\n% direction should not be distinguished.\n% Now\n\ntau = sSAll.SchmidFactor(r)\n\n%%\n% returns a list of Schmid factors and we can find the slip system with the\n% largest Schmid factor using\n\n[tauMax,id] = max(abs(tau))\n\nsSAll(id)\n\n%%\n% The above computation can be easily extended to a list of tension\n% directions\n\n% define a grid of tension directions\nr = plotS2Grid('resolution',0.5*degree,'upper');\n\n% compute the Schmid factors for all slip systems and all tension\n% directions\ntau = sSAll.SchmidFactor(r);\n\n% tau is a matrix with columns representing the Schmid factors for the\n% different slip systems. Lets take the maximum rhowise\n[tauMax,id] = max(abs(tau),[],2);\n\n% vizualize the maximum Schmid factor\ncontourf(r,tauMax)\nmtexColorbar\n\n%%\n% We may also plot the index of the active slip system\npcolor(r,id)\n\nmtexColorMap black2white\n\n%%\n% and observe that within the fundamental sectors the active slip system\n% remains the same. We can even visualize the the plane normal and the slip\n% direction\n\n% if we ommit the option antipodal we can distinguish\n% between the oposite burger vectors\nsSAll = sS.symmetrise\n\n% take as directions the centers of the fundamental regions\nr = symmetrise(CS.fundamentalSector.center,CS);\n\n% compute the Schmid factor\ntau = sSAll.SchmidFactor(r);\n\n% here we do not need to take the absolut value since we consider both\n% burger vectors +/- b\n[~,id] = max(tau,[],2);\n\n% plot active slip plane in red\nhold on\nquiver(r,sSAll(id).n,'LineWidth',2,'Color','r');\n\n% plot active slip direction in green\nhold on\nquiver(r,sSAll(id).b.normalize,'LineWidth',2,'Color','g');\nhold off\n\n%%\n% If we perform this computation in terms of spherical functions we obtain\n\n% ommiting |r| gives us a list of 12 spherical functions\ntau = sSAll.SchmidFactor\n\n% now we take the max of the absolute value over all these functions\ncontourf(max(abs(tau),[],1),'upper')\nmtexColorbar\n\n\n%% The Schmid factor for EBSD data\n% So far we have always assumed that the stress tensor is already given\n% relatively to the crystal coordinate system. Next, we want to examine the\n% case where the stress is given in specimen coordinates and we know the\n% orientation of the crystal. Lets import some EBSD data and computet the\n% grains\n\nmtexdata csl\n\n% take some subset\nebsd = ebsd(ebsd.inpolygon([0,0,200,50]))\n\ngrains = calcGrains(ebsd);\ngrains = smooth(grains,5);\n\nplot(ebsd,ebsd.orientations,'micronbar','off')\nhold on\nplot(grains.boundary,'linewidth',2)\nhold off\n\n%%\n% We want to consider the following slip systems\n\nsS = slipSystem.fcc(ebsd.CS)\nsS = sS.symmetrise;\n\n%%\n% Since, those slip systems are in crystal coordinates but the stress\n% tensor is in specimen coordinates we either have to rotate the slip\n% systems into specimen coordinates or the stress tensor into crystal\n% coordinates. In the following sections we will demonstrate both ways.\n% Lets start with the first one\n\n% rotate slip systems into specimen coordinates\nsSLocal = grains.meanOrientation * sS\n\n%%\n% These slip systems are now arranged in matrix form\n% where the rows corrspond to the crystal reference frames of the different\n% grains and the rows are the symmetrically equivalent slip systems.\n% Computing the Schmid faktor we end up with a matrix of the same size\n\n% compute Schmid factor\nsigma = stressTensor.uniaxial(vector3d.X)\nSF = sSLocal.SchmidFactor(sigma);\n\n% take the maxium allong the rows\n[SFMax,active] = max(SF,[],2);\n\n% plot the maximum Schmid factor\nplot(grains,SFMax,'micronbar','off','linewidth',2)\nmtexColorbar location southoutside\n\n%%\n% Next we want to visualize the active slip systems.\n\n% take the active slip system and rotate it in specimen coordinates\nsSactive = grains.meanOrientation .* sS(active);\n\nhold on\n% visualize the trace of the slip plane\nquiver(grains,sSactive.trace,'color','b')\n\n% and the slip direction\nquiver(grains,sSactive.b,'color','r')\nhold off\n\n%%\n% We observe that the Burgers vector is in most case aligned with the\n% trace. In those cases where trace and Burgers vector are not aligned the\n% slip plane is not perpendicular to the surface and the Burgers vector\n% sticks out of the surface.\n\n%%\n% Next we want to demonstrate the alternative route\n\n% rotate the stress tensor into crystal coordinates\nsigmaLocal = inv(grains.meanOrientation) * sigma\n\n%%\n% This becomes a list of stress tensors with respect to crystal coordinates\n% - one for each grain. Now we have both the slip systems as well as the\n% stress tensor in crystal coordiantes and can compute the Schmid factor\n\n% the resulting matrix is the same as above\nSF = sS.SchmidFactor(sigmaLocal);\n\n% and hence we may proceed analogously\n% take the maxium allong the rows\n[SFMax,active] = max(SF,[],2);\n\n% plot the maximum Schmid factor\nplot(grains,SFMax)\nmtexColorbar\n\n% take the active slip system and rotate it in specimen coordinates\nsSactive = grains.meanOrientation .* sS(active);\n\nhold on\n% visualize the trace of the slip plane\nquiver(grains,sSactive.trace,'color','b')\n\n% and the slip direction\nquiver(grains,sSactive.b,'color','r')\n\nhold off\n\n%% Strain based analysis on the same data set\n\neps = strainTensor(diag([1,0,-1]))\n\nepsCrystal = inv(grains.meanOrientation) * eps\n\n[M, b, W] = calcTaylor(epsCrystal, sS);\n\nplot(grains,M,'micronbar','off')\nmtexColorbar southoutside\n\n%%\n\n[ bMax , bMaxId ] = max( b , [ ] , 2 ) ;\nsSGrains = grains.meanOrientation .* sS(bMaxId) ;\nhold on\nquiver ( grains , sSGrains.b)\nquiver ( grains , sSGrains.trace)\nhold off\n\n\n\n\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/Plasticity/PlasticDeformation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.7093646784244362}} {"text": "function value = he_triple_product_integral ( i, j, k )\n\n%*****************************************************************************80\n%\n%% HE_TRIPLE_PRODUCT_INTEGRAL: integral of He(i,x)*He(j,x)*He(k,x)*e^(-x^2/2).\n%\n% Discussion:\n%\n% VALUE = integral ( -oo < x < +oo ) He(i,x)*He(j,x)*He(k,x) exp(-x^2/2) dx\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Dongbin Xiu,\n% Numerical Methods for Stochastic Computations: A Spectral Method Approach,\n% Princeton, 2010,\n% ISBN13: 978-0-691-14212-8,\n% LC: QA274.23.X58.\n%\n% Parameters:\n%\n% Input, integer I, J, K, the polynomial indices.\n%\n% Output, real VALUE, the value of the integral.\n%\n s = floor ( ( i + j + k ) / 2 );\n\n if ( s < i || s < j || s < k )\n value = 0.0;\n elseif ( mod ( i + j + k, 2 ) ~= 0 )\n value = 0.0;\n else\n value = r8_factorial ( i ) / r8_factorial ( s - i ) ...\n * r8_factorial ( j ) / r8_factorial ( s - j ) ...\n * r8_factorial ( k ) / r8_factorial ( s - 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/pce_ode_hermite/he_triple_product_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7092365092783395}} {"text": "function vectarrow(p0,p1)\n%Arrowline 3-D vector plot.\n% vectarrow(p0,p1) plots a line vector with arrow pointing from point p0\n% to point p1. The function can plot both 2D and 3D vector with arrow\n% depending on the dimension of the input\n%\n% Example:\n% 3D vector\n% p0 = [1 2 3]; % Coordinate of the first point p0\n% p1 = [4 5 6]; % Coordinate of the second point p1\n% vectarrow(p0,p1)\n%\n% 2D vector\n% p0 = [1 2]; % Coordinate of the first point p0\n% p1 = [4 5]; % Coordinate of the second point p1\n% vectarrow(p0,p1)\n%\n% See also Vectline\n\n% Rentian Xiong 4-18-05\n% $Revision: 1.0\n\n if max(size(p0))==3\n if max(size(p1))==3\n x0 = p0(1);\n y0 = p0(2);\n z0 = p0(3);\n x1 = p1(1);\n y1 = p1(2);\n z1 = p1(3);\n plot3([x0;x1],[y0;y1],[z0;z1]); % Draw a line between p0 and p1\n \n p = p1-p0;\n alpha = 0.1; % Size of arrow head relative to the length of the vector\n beta = 0.1; % Width of the base of the arrow head relative to the length\n \n hu = [x1-alpha*(p(1)+beta*(p(2)+eps)); x1; x1-alpha*(p(1)-beta*(p(2)+eps))];\n hv = [y1-alpha*(p(2)-beta*(p(1)+eps)); y1; y1-alpha*(p(2)+beta*(p(1)+eps))];\n hw = [z1-alpha*p(3);z1;z1-alpha*p(3)];\n \n hold on\n plot3(hu(:),hv(:),hw(:)) % Plot arrow head\n grid on\n xlabel('x')\n ylabel('y')\n zlabel('z')\n hold off\n else\n error('p0 and p1 must have the same dimension')\n end\n elseif max(size(p0))==2\n if max(size(p1))==2\n x0 = p0(1);\n y0 = p0(2);\n x1 = p1(1);\n y1 = p1(2);\n plot([x0;x1],[y0;y1]); % Draw a line between p0 and p1\n \n p = p1-p0;\n alpha = 0.1; % Size of arrow head relative to the length of the vector\n beta = 0.1; % Width of the base of the arrow head relative to the length\n \n hu = [x1-alpha*(p(1)+beta*(p(2)+eps)); x1; x1-alpha*(p(1)-beta*(p(2)+eps))];\n hv = [y1-alpha*(p(2)-beta*(p(1)+eps)); y1; y1-alpha*(p(2)+beta*(p(1)+eps))];\n \n hold on\n plot(hu(:),hv(:)) % Plot arrow head\n grid on\n xlabel('x')\n ylabel('y')\n hold off\n else\n error('p0 and p1 must have the same dimension')\n end\n else\n error('this function only accepts 2D or 3D vector')\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/7470-plot-2d3d-vector-with-arrow/vectarrow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7091180315726024}} {"text": "function [U,S,V] = pca(A,k,its,l)\n%PCA Low-rank approximation in SVD form.\n%\n%\n% [U,S,V] = PCA(A) constructs a nearly optimal rank-6 approximation\n% USV' to A, using 2 full iterations of a block Lanczos method\n% of block size 6+2=8, started with an n x 8 random matrix,\n% when A is m x n; the ref. below explains \"nearly optimal.\"\n% The smallest dimension of A must be >= 6 when A is\n% the only input to PCA.\n%\n% [U,S,V] = PCA(A,k) constructs a nearly optimal rank-k approximation\n% USV' to A, using 2 full iterations of a block Lanczos method\n% of block size k+2, started with an n x (k+2) random matrix,\n% when A is m x n; the ref. below explains \"nearly optimal.\"\n% k must be a positive integer <= the smallest dimension of A.\n%\n% [U,S,V] = PCA(A,k,its) constructs a nearly optimal rank-k approx. USV'\n% to A, using its full iterations of a block Lanczos method\n% of block size k+2, started with an n x (k+2) random matrix,\n% when A is m x n; the ref. below explains \"nearly optimal.\"\n% k must be a positive integer <= the smallest dimension of A,\n% and its must be a nonnegative integer.\n%\n% [U,S,V] = PCA(A,k,its,l) constructs a nearly optimal rank-k approx.\n% USV' to A, using its full iterates of a block Lanczos method\n% of block size l, started with an n x l random matrix,\n% when A is m x n; the ref. below explains \"nearly optimal.\"\n% k must be a positive integer <= the smallest dimension of A,\n% its must be a nonnegative integer,\n% and l must be a positive integer >= k.\n%\n%\n% The low-rank approximation USV' is in the form of an SVD in the sense\n% that the columns of U are orthonormal, as are the columns of V,\n% the entries of S are all nonnegative, and the only nonzero entries\n% of S appear in non-increasing order on its diagonal.\n% U is m x k, V is n x k, and S is k x k, when A is m x n.\n%\n% Increasing its or l improves the accuracy of the approximation USV'\n% to A; the ref. below describes how the accuracy depends on its and l.\n%\n%\n% Note: PCA invokes RAND. To obtain repeatable results,\n% invoke RAND('seed',j) with a fixed integer j before invoking PCA.\n%\n% Note: PCA currently requires the user to center and normalize the rows\n% or columns of the input matrix A before invoking PCA (if such\n% is desired).\n%\n% Note: The user may ascertain the accuracy of the approximation USV'\n% to A by invoking DIFFSNORM(A,U,S,V).\n%\n%\n% inputs (the first is required):\n% A -- matrix being approximated\n% k -- rank of the approximation being constructed;\n% k must be a positive integer <= the smallest dimension of A,\n% and defaults to 6\n% its -- number of full iterations of a block Lanczos method to conduct;\n% its must be a nonnegative integer, and defaults to 2\n% l -- block size of the block Lanczos iterations;\n% l must be a positive integer >= k, and defaults to k+2\n%\n% outputs (all three are required):\n% U -- m x k matrix in the rank-k approximation USV' to A,\n% where A is m x n; the columns of U are orthonormal\n% S -- k x k matrix in the rank-k approximation USV' to A,\n% where A is m x n; the entries of S are all nonnegative,\n% and its only nonzero entries appear in nonincreasing order\n% on the diagonal\n% V -- n x k matrix in the rank-k approximation USV' to A,\n% where A is m x n; the columns of V are orthonormal\n%\n%\n% Example:\n% A = rand(1000,2)*rand(2,1000);\n% A = A/normest(A);\n% [U,S,V] = pca(A,2,0);\n% diffsnorm(A,U,S,V)\n%\n% This code snippet produces a rank-2 approximation USV' to A such that\n% the columns of U are orthonormal, as are the columns of V, and\n% the entries of S are all nonnegative and are zero off the diagonal.\n% diffsnorm(A,U,S,V) outputs an estimate of the spectral norm\n% of A-USV', which should be close to the machine precision.\n%\n%\n% Reference:\n% Nathan Halko, Per-Gunnar Martinsson, and Joel Tropp,\n% Finding structure with randomness: Stochastic algorithms\n% for constructing approximate matrix decompositions,\n% arXiv:0909.4061 [math.NA; math.PR], 2009\n% (available at http://arxiv.org).\n%\n%\n% See also PCACOV, PRINCOMP, SVDS.\n%\n\n% Copyright 2009 Mark Tygert.\n\n%\n% Check the number of inputs.\n%\nif(nargin < 1)\n error('MATLAB:pca:TooFewIn',...\n 'There must be at least 1 input.')\nend\n\nif(nargin > 4)\n error('MATLAB:pca:TooManyIn',...\n 'There must be at most 4 inputs.')\nend\n\n%\n% Check the number of outputs.\n%\nif(nargout ~= 3)\n error('MATLAB:pca:WrongNumOut',...\n 'There must be exactly 3 outputs.')\nend\n\n%\n% Set the inputs k, its, and l to default values, if necessary.\n%\nif(nargin == 1)\n k = 6;\n its = 2;\n l = k+2;\nend\n\nif(nargin == 2)\n its = 2;\n l = k+2;\nend\n\nif(nargin == 3)\n l = k+2;\nend\n\n%\n% Check the first input argument.\n%\nif(~isfloat(A))\n error('MATLAB:pca:In1NotFloat',...\n 'Input 1 must be a floating-point matrix.')\nend\n\nif(isempty(A))\n error('MATLAB:pca:In1Empty',...\n 'Input 1 must not be empty.')\nend\n\n%\n% Retrieve the dimensions of A.\n%\n[m n] = size(A);\n\n%\n% Check the remaining input arguments.\n%\nif(size(k,1) ~= 1 || size(k,2) ~= 1)\n error('MATLAB:pca:In2Not1x1',...\n 'Input 2 must be a scalar.')\nend\n\nif(size(its,1) ~= 1 || size(its,2) ~= 1)\n error('MATLAB:pca:In3Not1x1',...\n 'Input 3 must be a scalar.')\nend\n\nif(size(l,1) ~= 1 || size(l,2) ~= 1)\n error('MATLAB:pca:In4Not1x1',...\n 'Input 4 must be a scalar.')\nend\n\nif(k <= 0)\n error('MATLAB:pca:In2NonPos',...\n 'Input 2 must be > 0.')\nend\n\nif((k > m) || (k > n))\n error('MATLAB:pca:In2TooBig',...\n 'Input 2 must be <= the smallest dimension of Input 1.')\nend\n\nif(its < 0)\n error('MATLAB:pca:In3Neg',...\n 'Input 3 must be >= 0.')\nend\n\nif(l < k)\n error('MATLAB:pca:In4ltIn2',...\n 'Input 4 must be >= Input 2.')\nend\n\n%\n% SVD A directly if (its+1)*l >= m/1.25 or (its+1)*l >= n/1.25.\n%\nif(((its+1)*l >= m/1.25) || ((its+1)*l >= n/1.25))\n\n if(~issparse(A))\n [U,S,V] = svd(A,'econ');\n end\n\n if(issparse(A))\n [U,S,V] = svd(full(A),'econ');\n end\n%\n% Retain only the leftmost k columns of U, the leftmost k columns of V,\n% and the uppermost leftmost k x k block of S.\n%\n U = U(:,1:k);\n V = V(:,1:k);\n S = S(1:k,1:k);\n\n return\n\nend\n\n\nif(m >= n)\n\n%\n% Apply A to a random matrix, obtaining H.\n%\n\n if(isreal(A))\n H = A*(2*rand(n,l)-ones(n,l));\n end\n\n if(~isreal(A))\n H = A*( (2*rand(n,l)-ones(n,l)) + i*(2*rand(n,l)-ones(n,l)) );\n end\n\n\n%\n% Initialize F to its final size and fill its leftmost block with H.\n%\n F = zeros(m,(its+1)*l);\n F(1:m, 1:l) = H;\n\n%\n% Apply A*A' to H a total of its times,\n% augmenting F with the new H each time.\n%\n for it = 1:its\n H = (H'*A)';\n H = A*H;\n F(1:m, (1+it*l):((it+1)*l)) = H;\n end\n\n clear H;\n\n%\n% Form a matrix Q whose columns constitute an orthonormal basis\n% for the columns of F.\n%\n [Q,R,E] = qr(F,0);\n\n clear F R E;\n\n%\n% SVD Q'*A to obtain approximations to the singular values\n% and right singular vectors of A; adjust the left singular vectors\n% of Q'*A to approximate the left singular vectors of A.\n%\n [U2,S,V] = svd(Q'*A,'econ');\n U = Q*U2;\n\n clear Q U2;\n\n%\n% Retain only the leftmost k columns of U, the leftmost k columns of V,\n% and the uppermost leftmost k x k block of S.\n%\n U = U(:,1:k);\n V = V(:,1:k);\n S = S(1:k,1:k);\n\nend\n\n\nif(m < n)\n\n%\n% Apply A' to a random matrix, obtaining H.\n%\n\n if(isreal(A))\n H = ((2*rand(l,m)-ones(l,m))*A)';\n end\n\n if(~isreal(A))\n H = (( (2*rand(l,m)-ones(l,m)) + i*(2*rand(l,m)-ones(l,m)) )*A)';\n end\n\n\n%\n% Initialize F to its final size and fill its leftmost block with H.\n%\n F = zeros(n,(its+1)*l);\n F(1:n, 1:l) = H;\n\n%\n% Apply A'*A to H a total of its times,\n% augmenting F with the new H each time.\n%\n for it = 1:its\n H = A*H;\n H = (H'*A)';\n F(1:n, (1+it*l):((it+1)*l)) = H;\n end\n\n clear H;\n\n%\n% Form a matrix Q whose columns constitute an orthonormal basis\n% for the columns of F.\n%\n [Q,R,E] = qr(F,0);\n\n clear F R E;\n\n%\n% SVD A*Q to obtain approximations to the singular values\n% and left singular vectors of A; adjust the right singular vectors\n% of A*Q to approximate the right singular vectors of A.\n%\n [U,S,V2] = svd(A*Q,'econ');\n V = Q*V2;\n\n clear Q V2;\n\n%\n% Retain only the leftmost k columns of U, the leftmost k columns of V,\n% and the uppermost leftmost k x k block of S.\n%\n U = U(:,1:k);\n V = V(:,1:k);\n S = S(1:k,1:k);\n\nend\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/pca.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7090842433202743}} {"text": "function [xf, S, cnt] = LMFsolveOLD(varargin)\n% Solve a Set of Overdetermined Nonlinear Equations in Least-Squares Sense.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% A solution is obtained by a Fletcher version of the Levenberg-Maquardt \n% algoritm for minimization of a sum of squares of equation residuals. \n%\n% [Xf, Ssq, CNT] = LMFsolveOLD(FUN,Xo,Options)\n% FUN is a function handle or a function M-file name that evaluates\n% m-vector of equation residuals,\n% Xo is n-vector of initial guesses of solution,\n% Options is an optional set of Name/Value pairs of control parameters \n% of the algorithm. It may be also preset by calling:\n% Options = LMFsolveOLD('default'), or by a set of Name/Value pairs:\n% Options = LMFsolveOLD('Name',Value, ... ), or updating the Options\n% set by calling\n% Options = LMFsolveOLD(Options,'Name',Value, ...).\n%\n% Name Values {default} Description\n% 'Display' integer Display iteration information\n% {0} no display\n% k display initial and every k-th iteration;\n% 'Jacobian' handle Jacobian matrix function handle; {@finjac}\n% 'FunTol' {1e-7} norm(FUN(x),1) stopping tolerance;\n% 'XTol' {1e-7} norm(x-xold,1) stopping tolerance;\n% 'MaxIter' {100} Maximum number of iterations;\n% 'ScaleD' Scale control:\n% value D = eye(m)*value;\n% vector D = diag(vector);\n% {[]} D(k,k) = JJ(k,k) for JJ(k,k)>0, or\n% = 1 otherwise,\n% where JJ = J.'*J\n% Not defined fields of the Options structure are filled by default values.\n%\n% Output Arguments:\n% Xf final solution approximation\n% Ssq sum of squares of residuals\n% Cnt >0 count of iterations\n% -MaxIter, did not converge in MaxIter iterations\n\n% Example:\n% The general Rosenbrock's function has the form\n% f(x) = 100(x(1)-x(2)^2)^2 + (1-x(1))^2\n% Optimum solution gives f(x)=0 for x(1)=x(2)=1. Function f(x) can be \n% expressed in the form \n% f(x) = f1(x)^2 =f2(x)^2,\n% where f1(x) = 10(x(1)-x(2)^2) and f2(x) = 1-x(1).\n% Values of the functions f1(x) and f2(x) can be used as residuals.\n% LMFsolveOLD finds the solution of this problem in 5 iterations. The more \n% complicated problem sounds:\n% Find the least squares solution of the Rosenbrock valey inside a circle \n% of the unit diameter centered at the origin. It is necessary to build \n% third function, which is zero inside the circle and increasing outside it. \n% This property has, say, the next function:\n% f3(x) = sqrt(x(1)^2 + x(2)^2) - r, where r is a radius of the circle.\n% Its implementation using anonymous functions has the form\n% R = @(x) sqrt(x'*x)-.5; % A distance from the radius r=0.5\n% ros= @(x) [10*(x(2)-x(1)^2); 1-x(1); (R(x)>0)*R(x)*1000];\n% [x,ssq,cnt]=LMFsolveOLD(ros,[-1.2,1],'Display',1,'MaxIter',50)\n% Solution: x = [0.4556; 0.2059], |x| = 0.5000\n% sum of squares: ssq = 0.2966, \n% number of iterations: cnt = 18.\n%\n% Note: \n% Users with older MATLAB versions, which have no anonymous functions\n% implemented, have to call LMFsolveOLD with named function for residuals. \n% For above example it is\n%\n% [x,ssq,cnt]=LMFsolveOLD('rosen',[-1.2,1]);\n%\n% where the function rosen.m is of the form\n%\n% function r = rosen(x)\n%% Rosenbrock valey with a constraint\n% R = sqrt(x(1)^2+x(2)^2)-.5;\n%% Residuals:\n% r = [ 10*(x(2)-x(1)^2) % first part\n% 1-x(1) % second part\n% (R>0)*R*1000. % penalty\n% ];\n\n% Reference:\n% Fletcher, R., (1971): A Modified Marquardt Subroutine for Nonlinear Least\n% Squares. Rpt. AERE-R 6799, Harwell\n\n% M. Balda, \n% Institute of Thermomechanics, \n% Academy of Sciences of The Czech Republic,\n% balda AT cdm DOT cas DOT cz\n% 2007-07-02\n% 2007-10-08 formal changes, improved description\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% OPTIONS\n %%%%%%%\n% Default Options\nif nargin==1 && strcmpi('default',varargin(1))\n xf.Display = 0; % no print of iterations\n xf.Jacobian = @finjac; % finite difference Jacobian approximation\n xf.MaxIter = 100; % maximum number of iterations allowed\n xf.ScaleD = []; % automatic scaling by D = diag(diag(J'*J))\n xf.FunTol = 1e-7; % tolerace for final function value\n xf.XTol = 1e-4; % tolerance on difference of x-solutions\n return\n \n% Updating Options\nelseif isstruct(varargin{1}) % Options=LMFsolveOLD(Options,'Name','Value',...)\n if ~isfield(varargin{1},'Jacobian')\n error('Options Structure not Correct for LMFsolveOLD.')\n end\n xf=varargin{1}; % Options\n for i=2:2:nargin-1\n name=varargin{i}; % option to be updated\n if ~ischar(name)\n error('Parameter Names Must be Strings.')\n end\n name=lower(name(isletter(name)));\n value=varargin{i+1}; % value of the option \n if strncmp(name,'d',1), xf.Display = value;\n elseif strncmp(name,'f',1), xf.FunTol = value(1);\n elseif strncmp(name,'x',1), xf.XTol = value(1);\n elseif strncmp(name,'j',1), xf.Jacobian = value;\n elseif strncmp(name,'m',1), xf.MaxIter = value(1);\n elseif strncmp(name,'s',1), xf.ScaleD = value;\n else disp(['Unknown Parameter Name --> ' name])\n end\n end\n return\n \n% Pairs of Options \nelseif ischar(varargin{1}) % check for Options=LMFsolveOLD('Name',Value,...)\n Pnames=char('display','funtol','xtol','jacobian','maxiter','scaled');\n if strncmpi(varargin{1},Pnames,length(varargin{1}))\n xf=LMFsolveOLD('default'); % get default values\n xf=LMFsolveOLD(xf,varargin{:});\n return\n end\nend\n\n% LMFSOLVEOLD(FUN,Xo,Options)\n %%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nFUN=varargin{1}; % function handle\nif ~(isvarname(FUN) || isa(FUN,'function_handle'))\n error('FUN Must be a Function Handle or M-file Name.')\nend\n\nxc=varargin{2}; % Xo\n\nif nargin>2 % OPTIONS\n if isstruct(varargin{3})\n options=varargin{3};\n else\n if ~exist('options','var')\n options = LMFsolveOLD('default');\n end\n for i=3:2:size(varargin,2)-1\n options=LMFsolveOLD(options, varargin{i},varargin{i+1});\n end\n end\nelse\n if ~exist('options','var')\n options = LMFsolveOLD('default');\n end\nend\n\nx=xc(:);\nlx=length(x);\n\nr=feval(FUN,x); % Residuals at starting point\n%~~~~~~~~~~~~~~\nS=r'*r;\nepsx=options.XTol(:);\nepsf=options.FunTol(:);\nif length(epsx)1\n D=diag(sqrt(abs(D(1:lx)))); % vector of individual scaling\n else\n D=sqrt(abs(D))*eye(lx); % scalar of unique scaling\n end\nend\n\nRlo=0.25; Rhi=0.75;\nl=1; lc=.75; is=0;\ncnt=0;\nipr=options.Display;\nprintit(-1); % Table header\nd=options.XTol; % vector for the first cycle\nmaxit = options.MaxIter; % maximum permitted number of iterations\n\nwhile cnt=epsx) && ... %%%%%%%%%%%%%%%%%%%%\n any(abs(r)>=epsf)\n d=(A+l*D)\\v; % negative solution increment\n xd=x-d;\n rd=feval(FUN,xd);\n% ~~~~~~~~~~~~~~~~~ \n Sd=rd.'*rd;\n dS=d.'*(2*v-A*d); % predicted reduction\n R=(S-Sd)/dS;\n\n if R>Rhi\n l=l/2;\n if l10\n nu=10;\n end\n if l==0\n lc=1/max(abs(diag(inv(A))));\n l=lc;\n nu=nu/2;\n end\n l=nu*l;\n end\n cnt=cnt+1;\n if ipr>0 && (rem(cnt,ipr)==0 || cnt==1)\n printit(cnt,[S,l,R,x(:).'])\n printit(0,[lc,d(:).'])\n end\n if Sd>S && is==0\n is=1;\n St=S; xt=x; rt=r; Jt=J; At=A; vt=v;\n end\n if Sd0\n S=Sd; x=xd; r=rd;\n J=options.Jacobian(FUN,r,x,epsx);\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n A=J.'*J; v=J.'*r;\n else\n S=St; x=xt; r=rt; J=Jt; A=At; v=vt;\n end\n if Sd0 print out first row of results\n\nif ipr>0\n if cnt<0 % table header\n disp('')\n disp(char('*'*ones(1,100)))\n disp([' cnt SUM(r^2) l R' blanks(21) 'x(i) ...'])\n disp([blanks(24) 'lc' blanks(32) 'dx(i) ...'])\n disp(char('*'*ones(1,100)))\n disp('')\n else % iteration output\n if cnt>0 || rem(cnt,ipr)==0\n f='%12.4e ';\n form=[f f f f '\\n' blanks(49)];\n if cnt>0\n fprintf(['%4.0f ' f f f ' x = '],[cnt,mx(1:3)])\n fprintf(form,mx(4:length(mx)))\n else\n fprintf([blanks(18) f blanks(13) 'dx = '], mx(1))\n fprintf(form,mx(2:length(mx)))\n end\n fprintf('\\n')\n end\n end\nend\nend\n\n% FINJAC numerical approximation to Jacobi matrix\n% %%%%%%\nfunction J = finjac(FUN,r,x,epsx)\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nlx=length(x);\nJ=zeros(length(r),lx);\nfor k=1:lx\n dx=.25*epsx(k);\n xd=x;\n xd(k)=xd(k)+dx;\n rd=feval(FUN,xd);\n% ~~~~~~~~~~~~~~~~ \n J(:,k)=((rd-r)/dx);\nend\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/16063-lmfsolve-m-levenberg-marquardt-fletcher-algorithm-for-nonlinear-least-squares-problems/LMFsolveOLD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.709060237030002}} {"text": "function value = digamma ( x )\n\n%*****************************************************************************80\n%\n%% DIGAMMA calculates the digamma or Psi function = d ( LOG ( GAMMA ( X ) ) ) / dX\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 September 2004\n%\n% Author:\n%\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% J Bernardo,\n% Psi ( Digamma ) Function,\n% Algorithm AS 103,\n% Applied Statistics,\n% Volume 25, Number 3, pages 315-317, 1976.\n%\n% Parameters:\n%\n% Input, real X, the argument of the digamma function.\n% 0 < X.\n%\n% Output, real VALUE, the value of the digamma function at X.\n%\n c = 8.5;\n d1 = -0.5772156649;\n s = 0.00001;\n s3 = 0.08333333333;\n s4 = 0.0083333333333;\n s5 = 0.003968253968;\n%\n% The argument must be positive.\n%\n if ( x <= 0.0 )\n\n value = 0.0;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'DIGAMMA - Fatal error!\\n' );\n fprintf ( 1, ' X <= 0.\\n' );\n error ( 'DIGAMMA - Fatal error!' );\n%\n% Use approximation if argument <= S.\n%\n elseif ( x <= s )\n\n value = d1 - 1.0 / x;\n%\n% Reduce the argument to DIGAMMA(X + N) where C <= (X + N).\n%\n else\n\n value = 0.0;\n y = x;\n\n while ( y < c )\n value = value - 1.0 / y;\n y = y + 1.0;\n end\n%\n% Use Stirling's (actually de Moivre's) expansion if C < argument.\n%\n r = 1.0 / ( y * y );\n value = value + log ( y ) - 0.5 / y - r * ( s3 - r * ( s4 - r * s5 ) );\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/digamma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7090602298238418}} {"text": "function value = cn_geg_monomial_integral ( n, alpha, expon )\n\n%*****************************************************************************80\n%\n%% CN_GEG_MONOMIAL_INTEGRAL: integral of monomial with Gegenbauer weight on CN.\n%\n% Discussion:\n%\n% CN_GEG is the cube [-1,+1]^N with the Gegenbauer weight function\n%\n% w(alpha;x) = product ( 1 <= i <= n ) (1-x(i)^2)^alpha.\n%\n% with -1.0 < alpha.\n%\n% value = integral ( CN )\n% product ( 1 <= i <= n ) x(I)^expon(i) (1-x(i)^2)^alpha dx(i)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 30 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n%\n% Input, real ALPHA, the exponent of (1-X).\n% -1.0 < ALPHA.\n%\n% Input, integer EXPON(N), the exponents.\n%\n% Output, real VALUE, the value of the integral.\n%\n if ( alpha <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CN_GEG_MONOMIAL_INTEGRAL - Fatal error!\\n' );\n fprintf ( 1, ' ALPHA <= -1.0\\n' );\n error ( 'CN_GEG_MONOMIAL_INTEGRAL - Fatal error!' );\n end\n\n value = 1.0;\n for i = 1 : n\n value2 = c1_geg_monomial_integral ( alpha, expon(i) );\n value = value * value2;\n end\n\n return\n\nend\n", "meta": {"author": "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_geg_monomial_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.7090602205897538}} {"text": "function a = wilk04 ( )\n\n%*****************************************************************************80\n%\n%% WILK04 returns the WILK04 matrix.\n%\n% Formula:\n%\n% 0.9143D-04 0.0 0.0 0.0\n% 0.8762 0.7156D-04 0.0 0.0\n% 0.7943 0.8143 0.9504D-04 0.0\n% 0.8017 0.6123 0.7165 0.7123D-04\n%\n% Properties:\n%\n% A is lower triangular.\n%\n% LAMBDA = ( 0.9143D-04, 0.7156D-04, 0.9504D-04, 0.7123D-04 ).\n%\n% Discussion:\n%\n% Since the matrix is already in lower triangular form, errors can\n% occur only in the backsubstitution. However, even a double\n% precision calculation will show a significant degradation in the\n% solution. It is also instructive to compare the actual error in\n% the solution to the residual error, A*x-b.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% James Wilkinson,\n% Rounding Errors in Algebraic Processes,\n% Prentice Hall, 1963, page 105.\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) = [ 0.9143E-04, 0.8762, 0.7943, 0.8017; ...\n 0.0000, 0.7156E-04, 0.8143, 0.6123; ...\n 0.0000, 0.0000, 0.9504E-04, 0.7165; ...\n 0.0000, 0.0000, 0.0000, 0.7123E-04 ];\n\n return\nend\n", "meta": {"author": "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/wilk04.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7090602194673754}} {"text": "function jed = ymdf_to_jed_eg_civil ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_JED_EG_CIVIL converts an Egyptian Civil YMDF date to a JED.\n%\n% Discussion:\n%\n% The Egyptian Civil calendar used a year of 365 days. The year comprised\n% 12 months of 30 days, with 5 epagomenal days occurring at the end of\n% the year. Since the observed year is about 365.25 days long, and no\n% attempt was made to adjust the Egyptian Civil year to the observed year,\n% the calendar dates gradually drifted with respect to the observed dates.\n%\n% The epoch or first day of the Egyptian Civil calendar is taken as\n% JED = 1448638.5.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 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 Julian Ephemeris Date.\n%\n\n%\n% Convert the calendar date to a computational date.\n%\n y_prime = y + 3968 - floor ( ( 13 - m ) / 13 );\n m_prime = mod ( m + 12, 13 );\n d_prime = d - 1;\n%\n% Convert the computational date to a JED.\n%\n jed = 365 * y_prime + 30 * m_prime + d_prime - 47 + 1 - 0.5;\n jed = jed + 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_eg_civil.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7090602185618264}} {"text": "function [mWalkout, fR95, fProb, PHI, R] = calc_Schusterwalk(mCatalog)\n% function [mWalkout, fR95, fProb, PHI, R] = calc_Schusterwalk(mCatalog)\n% ------------------------------------------------------------------------\n% Calculate random walkout (Schuster's method). See Rydelek & Sacks, Nature\n% 1989.\n%\n% Incoming variables:\n% mCatalog : EQ catalog\n%\n% Outgoing variables:\n% mWalkout : Random walkout phases\n% fR95 : Critical radius at 95% level\n% fProb : Probability to obtain vector of length >= R\n% PHI : Sum of phase angles\n% R : Possible maximum length of vector\n%\n% J. Woessner, woessner@seismo.ifg.ethz.ch\n% last update: 13.03.03\n\n% Get hours and minutes, calculate minutes\nvH = mCatalog(:,8);\nvMin = mCatalog(:,9);\nvTime = vH*60+vMin;\n\n% Calculate degrees and radians\nvThetaDegree = vTime*180/720;\nvThetaRad = vTime*pi/720;\n\nmWalkout(1,1)=0;\nmWalkout(1,2)=0;\nfor i=1:length(mCatalog(:,8))\n mWalkout(i+1,1)=mWalkout(i,1)+sin(vThetaRad(i));\n mWalkout(i+1,2)=mWalkout(i,2)+cos(vThetaRad(i));\nend\n\nA=sum(sin(vThetaRad));\nB=sum(cos(vThetaRad));\nR=sqrt(A^2+B^2);\nPHI=atan(B/A);\n% length(mCatalog(:,8))\n% if mWalkout(length(mCatalog(:,8)),2)<0\n% PHI=PHI+pi;\n% end\n\nN=length(mCatalog(:,8));\n% Critical radius at 95% confidence level\nfR95=1.73*sqrt(N); % Rydelek & Sacks, Nature 1989\n% Probability to obtain vector of length >= R from a random walkout\nfProb=exp(-R^2/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/jochen/seisvar/calc/calc_Schusterwalk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.7090318633110019}} {"text": "function [x1] = simulate_CRP(alpha,n)\n% simulate labels from CRP process with concentration alpha\n% IN:\n% - alpha: concentration parameter of the CRP\n% - n: size of the time series\n% OUT:\n% - x1: CRP-label process (vector of size 1Xn)\n\n% initial condition\nx1 = zeros(1,n);\nx1(1) = 1;\n\n% loop over time samples\nfor i=2:n\n Ki = max(x1(1:i-1)); % number of classes so far\n nk = zeros(Ki,1);\n for k=1:Ki\n nk(k) = sum(x1(1:i-1)==k);\n end\n p = [nk;alpha]./(alpha+i-1);\n x1(i) = VBA_random ('Categorical', p);\n \nend", "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/classification/CRP/simulate_CRP.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.70899782957416}} {"text": "function X = bartelsStewart(A, B, C, D, E, xsplit, ysplit)\n%BARTELSSTEWART Solution to generalized Sylvester matrix equation. \n% \n% Computes the solution to the Sylvester equation\n%\n% AXB^T + CXD^T = E\n%\n% by using the Bartels--Stewart algorithm, see \n%\n% J. D. Gardiner, A. J. Laub, J. J. Amato, & C. B. Moler, Solution of \n% the Sylvester matrix equation AXB^T+ CXD^T= E, ACM Transactions on \n% Mathematical Software (TOMS), 18(2), 223-231.\n% \n% This Bartels--Stewart solver also takes information xsplit, ysplit so\n% that if possible it decouples the even and odd modes.\n\n% Copyright 2017 by The University of Oxford and The Chebfun2 Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\ntol = eps();\n\n% If the RHS is zero then the solution is the zero solution (assuming\n% uniqueness).\nif ( norm(E) < 10*tol )\n X = zeros(size(E));\n return\nend\n\n% If the equation is even/odd in the x-direction then we can split the problem\n% into two subproblems. We enforce P and S as upper triangular because they\n% are up to rounding errors, and we need to do back substitution with\n% them.\nif ( ysplit )\n % This is equivalent to qz(full(A),full(C)), but faster.\n [P, S, Q1, Z1] = qzsplit(A, C); \n P = triu(P); \n S = triu(S);\nelse\n [P, S, Q1, Z1] = qz(full(A), full(C)); \n P = triu(P); \n S = triu(S);\nend\n\n% If the PDE is even/odd in the y-direction then we can split (further)\n% into double as many subproblems.\nif ( xsplit )\n % Faster QZ when even/odd modes decouple in x-direction: \n [T, R, Q2, Z2] = qzsplit(D, B);\nelse\n % QZ does not take matrices in sparse format:\n [T, R, Q2, Z2] = qz(full(D), full(B));\nend\n\n% Now use the generalised Bartels--Stewart solver found in Gardiner et al.\n% (1992). The Sylvester matrix equation now contains quasi upper-triangular\n% matrices and we can do a backwards substitution.\n\n% transform the righthand side.\nF = Q1*E*Q2.';\n\n% Solution will be a m by n matrix.\nm = size(A, 1); \nn = size(B, 1); \nY = zeros(m, n);\n\n% Do a backwards substitution type algorithm to construct the solution.\nk=n;\nPY = zeros(m);\nSY = zeros(m);\n\n% Construct columns n,n-1,...,3,2 of the transformed solution. The first\n% column is treated as special at the end.\nwhile k > 1\n % There are two cases, either the subdiagonal contains a zero\n % T(k,k-1)=0 and then it is a backwards substitution, or T(k,k-1)~=0\n % and then we solve a 2x2 system instead.\n \n if ( T(k,k-1) == 0 )\n % Simple case (almost always end up here).\n rhs = F(:,k);\n if ( k < n )\n \n PY(:,k+1) = P*Y(:,k+1);\n SY(:,k+1) = S*Y(:,k+1);\n \n for jj = k+1:n\n rhs = rhs - R(k,jj)*PY(:,jj) - T(k,jj)*SY(:,jj);\n end\n \n end\n \n % find the kth column of the transformed solution.\n Y(:,k) = (R(k,k)*P + T(k,k)*S) \\ rhs;\n \n % go to next column\n k = k-1;\n \n else\n % This is a straight copy from the Gardiner et al. paper, and just\n % solves for two columns at once. (works because of\n % quasi-triangular matrices.\n \n % Operator reduction.\n rhs1 = F(:,k-1);\n rhs2 = F(:,k);\n \n for jj = k+1:n\n yj = Y(:,jj);\n rhs1 = rhs1 - R(k-1,jj)*P*yj - T(k-1,jj)*S*yj;\n rhs2 = rhs2 - R(k,jj)*P*yj - T(k,jj)*S*yj;\n end\n \n % 2 by 2 system.\n SM = zeros(2*n);\n up = 1:n;\n down = n+1:2*n;\n \n SM(up,up) = R(k-1,k-1)*P + T(k-1,k-1)*S;\n SM(up,down) = R(k-1,k)*P + T(k-1,k)*S;\n SM(down,up) = R(k,k-1)*P + T(k,k-1)*S;\n SM(down,down) = R(k,k)*P + T(k,k)*S;\n \n % Permute the columns and rows: \n Spermuted = zeros(2*n);\n Spermuted(1:2:2*n,1:2:2*n) = SM(1:n,1:n); \n Spermuted(2:2:2*n,2:2:2*n) = SM(n+1:2*n,n+1:2*n); \n\n % Solve.\n UM = Spermuted \\ [rhs1; rhs2];\n \n Y(:,k-1) = UM(up); \n Y(:,k) = UM(down);\n\n PY(:,k) = P*Y(:,k);\n PY(:,k-1) = P*Y(:,k-1);\n SY(:,k) = S*Y(:,k); \n SY(:,k-1) = S*Y(:,k-1);\n \n % We solved for two columns so go two columns further.\n k=k-2;\n \n end\n \nend\n\nif ( k == 1 )\n % Now we have just the first column to compute.\n rhs = F(:,1);\n PY(:,2) = P*Y(:,2);\n SY(:,2) = S*Y(:,2);\n for jj = 2:n\n rhs = rhs - R(1,jj)*PY(:,jj) - T(1,jj)*SY(:,jj);\n end\n Y(:,1) = (R(1,1)*P + T(1,1)*S) \\ rhs;\nend\n\n% We have now computed the transformed solution so we just transform it\n% back.\nX = Z1*Y*Z2.';\n\nend\n\nfunction [P, S, Q1, Z1] = qzsplit(A, C)\n%QZSPLIT A faster qz factorisation for problems that decouple.\n%\n% This is equivalent to standard qz, except we take account of symmetry to\n% reduce the computational requirements of the QZ factorisation.\n\n% Do the QZ by splitting the problem into two subproblems. \nA = full(A); \n\nA1 = A(1:2:end,1:2:end); \nC = full(C); \nC1 = C(1:2:end,1:2:end);\n[P1, S1, Q1, Z1] = qz(A1, C1);\n\nA2 = A(2:2:end,2:2:end); \nC2 = C(2:2:end,2:2:end);\n[P2, S2, Q2, Z2] = qz(A2, C2);\n\n[P, S, Q1, Z1] = reform(P1, P2, S1, S2, Q1, Q2, Z1, Z2);\n\nend\n\nfunction [P, S, Q, Z] = reform(P1, P2, S1, S2, Q1, Q2, Z1, Z2)\n%REFORM Recombine subproblems to form the QZ factorization. \n\n% Initialise all the variables. \nhf1 = size(P1, 1);\nn = 2*hf1 - 1;\nP = zeros(n);\nS = zeros(n);\nQ = zeros(n);\nZ = zeros(n);\n\n% Push the subproblem back together.\nP(1:hf1,1:hf1) = P1; \nP(hf1+1:end,hf1+1:end) = P2;\n\nS(1:hf1,1:hf1) = S1; \nS(hf1+1:end,hf1+1:end) = S2;\n\nQ(1:hf1,1:2:end) = Q1; \nQ(hf1+1:end,2:2:end) = Q2;\n\nZ(1:2:end,1:hf1) = Z1; \nZ(2:2:end,hf1+1:end) = Z2;\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/@chebop2/bartelsStewart.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7089230125095738}} {"text": "function lik = ml_gauss_lik(y,X,w,e_var)\n%ML_GAUSS_LIK Gaussian Likelihood\n%\n% input -----------------------------------------------------------------\n%\n% o y : (N x 1), output. \n%\n% o X : (N x D), input, N samples of dimension D.\n%\n% o w : (D+1 x 1), linear regressor weights.\n%\n% o e_var : (1 x 1), noise variance.\n%\n% output ----------------------------------------------------------------\n% \n% o lik : (N x 1), \n%\n\n\n[N,D] = size(X);\n\n% (N x 1) - (N x D+1) (D+1 x 1)\n% (N x 1) - (N x 1)\n\ndiff = y - [X,ones(N,1)] * w';\nz = sum(diff .* diff);\n\nlik = 1.0/( (2 * pi * e_var)^(D/2)) * exp(-1/(2*e_var) * z);\n\n\n\nend\n\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/regression/gp/ml_gauss_lik.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.7089230111338108}} {"text": "function [esTheta, esPhi] = mieScatteredField(An, Bn, theta, phi, frequency)\n\n% Compute the complex-value scattered electric far field of a sphere\n% using pre-computed coefficients An and Bn. Based on the treatment in:\n%\n% Ruck, et. al. \"Radar Cross Section Handbook\", Plenum Press, 1970.\n% \n% The incident electric field is in the -z direction (theta = 0) and is\n% theta-polarized. The time-harmonic convention exp(jwt) is assumed, and\n% the Green's function is of the form exp(-jkr)/r.\n% \n% Inputs:\n% An: Array of Mie solution constants\n% Bn: Array of Mie solution constants\n% (An and Bn should have the same length)\n% theta: Scattered field theta angle (radians)\n% phi: Scattered field phi angle (radians)\n% Outputs:\n% esTheta: Theta-polarized electric field at the given scattering angles\n% esPhi: Phi-polarized electric field at the given scattering angles\n%\n% Output electric field values are normalized such that the square of the\n% magnitude is the radar cross section (RCS) in square meters.\n%\n% Author: Walton C. Gibson, email: kalla@tripoint.org\n\n% speed of light\nc = 299792458.0;\n \n% wavenumber\nk = 2.0*pi*frequency/c;\n\nsinTheta = abs(sin(theta)); % note: theta only defined from from 0 to pi \ncosTheta = cos(theta); % ok for theta > pi \n \n% first two values of the Associated Legendre Polynomial\nplm(1) = -sinTheta;\nplm(2) = -3.0*sinTheta*cosTheta;\n\nS1 = 0.0;\nS2 = 0.0;\n\np = plm(1);\n\n% compute coefficients for scattered electric far field\nfor iMode = 1:length(An)\n\n % derivative of associated Legendre Polynomial\n if abs(cosTheta) < 0.999999\n if iMode == 1\n dp = cosTheta*plm(1)/sqrt(1.0 - cosTheta*cosTheta);\n else\n dp = (iMode*cosTheta*plm(iMode) - (iMode + 1)*plm(iMode - 1))/sqrt(1.0 - cosTheta*cosTheta);\n end\n end\n \n if abs(sinTheta) > 1.0e-6\n term1 = An(iMode)*p/sinTheta;\n term2 = Bn(iMode)*p/sinTheta;\n end\n\n if cosTheta > 0.999999\n % Ruck, et. al. (3.1-12)\n val = ((i)^(iMode-1))*(iMode*(iMode+1)/2)*(An(iMode) - i*Bn(iMode));\n S1 = S1 + val;\n S2 = S2 + val;\n elseif cosTheta < -0.999999\n % Ruck, et. al. (3.1-14)\n val = ((-i)^(iMode-1))*(iMode*(iMode+1)/2)*(An(iMode) + i*Bn(iMode));\n S1 = S1 + val;\n S2 = S2 - val;\n else\n % Ruck, et. al. (3.1-6)\n S1 = S1 + ((i)^(iMode+1))*(term1 - i*Bn(iMode)*dp);\n % Ruck, et. al. (3.1-7)\n S2 = S2 + ((i)^(iMode+1))*(An(iMode)*dp - i*term2);\n end\n \n % recurrence relationship for next Associated Legendre Polynomial\n if iMode > 1\n plm(iMode + 1) = (2.0*iMode + 1)*cosTheta*plm(iMode)/iMode - (iMode + 1)*plm(iMode - 1)/iMode;\n end\n p = plm(iMode + 1);\nend\n\n% complex-value scattered electric far field, Ruck, et. al. (3.1-5)\nesTheta = S1*cos(phi);\nesPhi = -S2*sin(phi);\n\n% normalize electric field so square of magnitude is RCS in square meters\nesTheta = esTheta*sqrt(4.0*pi)/k;\nesPhi = esPhi*sqrt(4.0*pi)/k;\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/20430-scattered-field-of-a-conducting-and-stratified-spheres/mieScatteredField.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7089230063134225}} {"text": "%% Script for the Birthday Paradox simulation\n\n% Define paramenters for simulation\n\n numtrials = 2e5;\n groupsize = 30;\n\n% Preallocate some memory for the matches\n\n matches = zeros(1, numtrials);\n\n parfor trial = 1:numtrials\n\n matches(trial) = birthday(groupsize);\n \n end\n\n% Probability is the sum of matches divided by number of trials\n\n prob = sum ( matches ) / numtrials;\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/birthday_remote/birthdayscript.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7089229925349196}} {"text": "% getFWHM_uhe(r)\n%\n% Get FWHM (mm) of the ultra-high-energy collimator PSF\n% at some distances 'r' (mm) from the collimator\n%\n% Qiang (Victor) Lin\n% Modified by A. Yendiki, 2/5/02\n\nfunction FWHM = getFWHM_uhe(r)\n\nr(r < 0) = 0;\n\n% Radius (mm) FWHM (mm?)\n% 20 5.6135\n% 75 13.8277 \n% 130 18.2010\n% 185 22.2908\n% 245 26.9498\n\nfw20 = 5.6135;\nfw75 = 13.8277;\nfw130 = 18.2010;\nfw185 = 22.2908;\nfw245 = 26.9498;\n\n\nFWHM = (fw75 - (75-r) * ((fw75-fw20)/(75-20))) .* (r <= 75) ...\n + (fw130 - (130-r) * ((fw130-fw75)/(130-75))) .* (r <= 130 & r > 75) ...\n + (fw185 - (185-r) * ((fw185-fw130)/(185-130))) .* (r <= 185 & r > 130) ...\n + (fw185 - (185-r) * ((fw245-fw185)/(245-185))) .* (r > 185);\n\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/blob/getFWHM_uhe.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094437, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.7088839038529607}} {"text": "function [X,Y,beta_c,noise] = GenDataLinear(m,beta,v)\n\n\nX = randn(m, length(beta));\nX = X./repmat(sqrt(sum(X.^2,1)),size(X,1),1);\nnoise = randn(m,1)/sqrt(v);\nbeta_c = beta(:);\nY = X*beta_c+noise;", "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/bayesianlogreg/GenDataLinear.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088045171237, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.708825058182312}} {"text": "function [P,f,alpha] = fastlomb(x,t,varargin)\n% FASTLOMB caculates the Lomb normalized periodogram (aka Lomb-Scargle, Gauss-Vanicek or Least-Squares spectrum) of a vector x with coordinates in t. \n% The coordinates need not be equally spaced. In fact if they are, it is\n% probably preferable to use PWELCH or SPECTRUM. For more details on the\n% Lomb normalized periodogram, see the excellent section 13.8 in [1], pp.\n% 569-577.\n%\n% This code is a transcription of the Fortran subroutine fasper in [1]\n% (pp.575-577), so it is a really fast (albeit not really exact)\n% implementation of the Lomb periodogram. Also Matlab's characteristics\n% have been taken into account in order to make it even faster for\n% Matlab. For an exact calculation of the Lomb periodogram use LOMB,\n% which is however about 100 times slower.\n%\n% If the 'fig' flag is on, the periodogram is created, along with some\n% default statistical significance levels: .001, .005, .01, .05, .1, .5.\n% If the user wants more significance levels, they can give them as input\n% to the function. Those will be red. \n%\n% SYNTAX\n% [P,f,alpha] = fastlomb(x,t,fig,hifac,ofac,a);\n% [P,f,alpha] = fastlomb(x,t,fig,hifac,ofac);\n% [P,f,alpha] = fastlomb(x,t,fig,hifac);\n% [P,f,alpha] = fastlomb(x,t,fig);\n% [P,f,alpha] = fastlomb(x,t);\n%\n% INPUTS\n% x: the vector whose spectrum is wanted.\n% t: coordinates of x (should have the same length).\n% fig: if 0 (default), no figure is created.\n% hifac: the maximum frequency returned is \n% (hifac) x (average Nyquist frequency)\n% See \"THE hifac PARAMETER\" in the NOTES section below for more\n% details on the hifac parameter. Default is 1 (i.e. max frequency\n% is the Nyquist frequency).\n% ofac: oversampling factor. Typically it should be 4 or larger. Default\n% is 4. See \"INTERPRETATION AND SELECTION OF THE ofac PARAMETER\"\n% in the NOTES section below for more details on the choice of\n% ofac parameter. \n% a: additional significance levels to be drawn on the figure.\n%\n% OUTPUTS\n% P: the Lomb normalized periodogram \n% f: respective frequencies \n% alpha: statistical significance for each value of P \n%\n% NOTES\n% A. INTERPRETATION AND SELECTION OF THE ofac PARAMETER [1]\n% The lowest independent frequency f to be examined is the inverse of\n% the span of the input data, \n% 1/(tmax-tmin)=1/T. \n% This is the frequency such that the data can include one complete\n% cycle. In an FFT method, higher independent frequencies would be\n% integer multiples of 1/T . Because we are interested in the\n% statistical significance of ANY peak that may occur, however, we\n% should over-sample more finely than at interval 1/T, so that sample\n% points lie close to the top of ANY peak. This oversampling parameter\n% is the ofac. A value ofac >~4 might be typical in use.\n%\n% B. THE hifac PARAMETER [1]\n% Let fhi be the highest frequency of interest. One way to choose fhi is\n% to compare it with the Nyquist frequency, fc, which we would obtain, if\n% the N data points were evenly spaced over the same span T, that is \n% fc = N/(2T). \n% The input parameter hifac, is defined as fhi/fc. In other words, hifac\n% shows how higher (or lower) that the fc we want to go.\n%\n% REFERENCES\n% [1] W.H. Press, S.A. Teukolsky, W.T. Vetterling and B.P. Flannery,\n% \"Numerical recipes in Fortran 77: the art of scientific computing\",\n% 2nd ed., vol. 1, Cambridge University Press, NY, USA, 2001. \n%\n% C. Saragiotis, Nov 2008\n\n\n%% Inputs check and initialization \nif nargin < 2, error('%s: there must be at least 2 inputs.',mfilename); end\nMACC = 10; % Number of interpolation points per 1/4 cycle of the highest frequency\n\n[x,t,hifac,ofac,a_usr,f,fig] = init(x,t,varargin{:});\nnt = length(t);\n\nmx = mean(x);\nx = x-mx;\nvx = var(x); \nif vx==0, error('x has zero variance'); end\n\nnf = length(f);\nnfreq = 2^nextpow2(ofac*hifac*nt*MACC); \n% ndim = 2*nfreq;\n\ntmin = t(1);\ntmax = t(end);\nT = tmax-tmin;\n\n%% Extirpolation \nfac = 2*nfreq/(T*ofac);\n[wk1,wk2] = extirpolate(t-tmin,x,fac,nfreq,MACC);\n\n%% Take the FFT's \nW = fft(wk1);\nreft1 = real(W(2:nf+1)); % only positive frequencies, without f=0\nimft1 = imag(W(2:nf+1));\n\nW = fft(wk2);\nreft2 = real(W(2:nf+1)); \nimft2 = imag(W(2:nf+1)); \n\n%% Main \nhypo = sqrt(reft2.^2+imft2.^2);\nhc2wt = 0.5*reft2./hypo; \nhs2wt = 0.5*imft2./hypo;\ncwt = sqrt(0.5+hc2wt);\nswt = (sign(hs2wt)+(hs2wt==0)).*(sqrt(0.5-hc2wt)); \nden = 0.5*nt + hc2wt.*reft2 + hs2wt.*imft2;\ncterm = (cwt.*reft1 + swt.*imft1).^2./den;\nsterm = (cwt.*imft1 - swt.*reft1).^2./(nt-den);\nP = (cterm+sterm)/(2*vx);\nP = P(:);\n\n%% Significance \nM = 2*nf/ofac;\nalpha = 1 - (1-exp(-P)).^M; % statistical significance\nalpha(alpha<0.1) = M*exp(-P(alpha<0.1)); % (to avoid round-off errors)\n\n%% Figure \nif fig\n figure\n styles = {':','-.','--'};\n\n a = [0.001 0.005 0.01 0.05 0.1 0.5];\n La = length(a);\n z = -log(1-(1-a).^(1/M));\n% widths = [.5*ones(1,floor(La/3)) 1*ones(1,La-2*floor(La/3)) 2*ones(1,floor(La/3))];\n hold on;\n for i=1:La\n line([f(1),0.87*f(end)],[z(i),z(i)],'Color','k','LineStyle',styles{ceil(i*3/La)});%,'LineWidth',widths(i));\n text(0.9*f(end),z(i),strcat('\\alpha = ',num2str(a(i))),'fontsize',8); %,'fontname','symbol');\n% lgd{i}=strcat('\\alpha=',num2str(a(i)));\n end\n if ~isempty(a_usr)\n [tmp,ind] = intersect(a_usr,a);\n a_usr(ind)=[];\n La_usr = length(a_usr);\n z_usr = -log(1-(1-a_usr).^(1/M));\n for i = 1:La_usr\n line([f(1),0.87*f(end)],[z_usr(i),z_usr(i)],'Color','r','LineStyle',styles{ceil(i*3/La_usr)});%,'LineWidth',widths(i));\n text(0.9*f(end),z_usr(i),strcat('\\alpha = ',num2str(a_usr(i))),'fontsize',8); %,'fontname','symbol');\n % lgd{La+i}=strcat('\\alpha=',num2str(a_usr(i)));\n end\n z = [z z_usr];\n end\n% legend(lgd);\n plot(f,P,'k');\n title('Lomb-Scargle normalized periodogram')\n xlabel('f (Hz)'); ylabel('P(f)')\n xlim([0 f(end)]); ylim([0,1.2*max([z'; P])]);\n hold off;\nend\n\nend\n\n\n%% #### Local functions\n\n%% init (initialize) \nfunction [x,t,hifac,ofac,a,f,fig] = init(x,t,varargin)\n if nargin < 6, a = []; % set default value for a \n else a = sort(varargin{4}); \n a = a(:)';\n end\n if nargin < 5, ofac = 4; % set default value for ofac \n else ofac = varargin{3};\n end\n if nargin < 4, hifac = 1; % set default value for hifac \n else hifac = varargin{2};\n end\n if nargin < 3, fig = 0; % set default value for hifac \n else fig = varargin{1};\n end\n\n if isempty(ofac), ofac = 4; end\n if isempty(hifac), hifac = 1; end\n if isempty(fig), fig = 0; end\n \n if ~isvector(x) ||~isvector(t),\n error('%s: inputs x and t must be vectors',mfilename);\n else\n x = x(:); t = t(:);\n nt = length(t);\n if length(x)~=nt\n error('%s: Inputs x and t must have the same length',mfilename);\n end\n end\n\n [t,ind] = unique(t); % discard double entries and sort t\n x = x(ind);\n if length(x)~=nt, disp(sprintf('WARNING %s: Double entries have been eliminated',mfilename)); end\n\n T = t(end) - t(1);\n nf = round(0.5*ofac*hifac*nt);\n f = (1:nf)'/(T*ofac); \nend\n\n%% extirpolation \nfunction [wk1,wk2] = extirpolate(t,x,fac,nfreq,MACC)\n nt = length(x);\n wk1 = zeros(2*nfreq,1);\n wk2 = zeros(2*nfreq,1);\n\n for j = 1:nt \n ck = 1 + mod(fix(t(j)*fac),2*nfreq);\n ckk = 1 + mod(2*(ck-1), 2*nfreq);\n wk1 = spread(x(j),wk1,ck, MACC);\n wk2 = spread(1 ,wk2,ckk,MACC);\n end\nend\n\n%% spread \nfunction yy = spread(y,yy,x,m)\n\n nfac = [1 1 2 6 24 120 720 5040 40320 362880];\n n = length(yy);\n\n if x == round(x) % Original Fortran 77 code: ix=x\n % if(x.eq.float(ix)) then...\n yy(x) = yy(x) + y;\n else\n % Original Fortran 77 code: i1 = min( max( int(x-0.5*m+1.0),1 ), n-m+1 )\n i1 = min([ max([ floor(x-0.5*m+1),1 ]), n-m+1 ]);\n i2 = i1+m-1;\n nden = nfac(m);\n fac = x-i1;\n\n fac = fac*prod(x - (i1+1:i2));\n yy(i2) = yy(i2) + y*fac/(nden*(x-i2));\n\n for j = i2-1:-1:i1\n nden = (nden/(j+1-i1))*(j-i2);\n yy(j) = yy(j) + y*fac/(nden*(x-j));\n end\n\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/22215-lomb-normalized-periodogram/fastlomb.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.7087600236322311}} {"text": "function[varargout]=maternimp(varargin)\n%MATERNIMP Impulse response function for the Matern random process.\n%\n% [T,G]=MATERNIMP(N,ALPHA,LAMBDA) returns first N points for the impulse \n% response function G for a *unit-variance* complex-valued Matern process \n% with slope parameter ALPHA and damping or range parameter LAMBDA.\n%\n% The impulse response function is also known as the Green's function.\n%\n% T is an array of times T=[EPSILON 1:1:N] where the first point is set to\n% a very small number, set to EPSILON=1e-6 to avoid the potential for \n% infinite values at T=0 for some parameter settings. \n%\n% The sample interval is taken to be unity. The damping parameter LAMBDA\n% is understood to have units of the inverse of the sample interval.\n%\n% Note that for LAMBDA=0, the case of fractional Brownian motion, G is \n% formally defined but is not useful because it does not decay. \n%\n% The input parameters ALPHA and LAMBDA may either be scalars or arrays \n% of the same length M. If the latter, then the output autocovariance\n% function R will be a matrix with N rows and M columns. \n%\n% See MATERNSPEC for a more thorough discussion of the Matern process.\n%\n% For details on the Matern process and impulse response function, see:\n%\n% Lilly, Sykulski, Early, and Olhede, (2017). Fractional Brownian\n% motion, the Matern process, and stochastic modeling of turbulent \n% dispersion. Nonlinear Processes in Geophysics, 24: 481--514.\n% __________________________________________________________________\n%\n% Oscillatory Matern\n%\n% MATERNIMP(N,ALPHA,C), where C is complex, uses LAMBDA=REAL(C) for the\n% damping parameter and also sets a rotation frequency to OMEGA=-IMAG(C). \n%\n% The associated oscillatory process undergoes rotations at frequency \n% OMEGA in addition to the damping at timescale 1/LAMBDA.\n% __________________________________________________________________\n%\n% Specified times\n%\n% G=MATERNIMP(T,ALPHA,LAMBDA) where the first argument is an *array*\n% rather than a scalar, will alternately return the impulse response at\n% the specified times T. Note T is not output again in this case.\n% __________________________________________________________________\n%\n% Use in fast generation\n%\n% [T,G]=MATERNIMP([],ALPHA,LAMBDA) where the first argument is the empty \n% set, evaluates the Green's function at the points T = [0:1:N-1]'+1/2.\n% This form is utilized in the fast generation method implemented by \n% MATERNOISE and discussed in Section 5 of Lilly et al. (2017).\n% __________________________________________________________________\n%\n% See also MATERNSPEC, MATERNCOV, MATERNOISE, MATERNFIT.\n%\n% 'maternimp --t' runs some tests.\n%\n% Usage: [t,G]=maternimp(N,alpha,lambda);\n% G=maternimp(t,alpha,lambda);\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2013--2017 J.M. Lilly --- type 'help jlab_license' for details\n\n\nif strcmpi(varargin{1}, '--t')\n maternimp_test,return\nend\n\nN=[];\ntau=[];\n\nif length(varargin)==3\n if length(varargin{1})==1\n N=varargin{1};\n else\n tau=varargin{1};\n end\nend\n\nif isempty(tau)\n tau=[0:1:N-1]'+1/2;\nend\n\nalpha=varargin{2};\nlambda=real(varargin{3});\nomegao=-imag(varargin{3});\narrayify(alpha,omegao,lambda);\n\nG=zeros(size(tau,1),length(lambda));\nif size(tau,2)~=length(lambda)\n tau=vrep(tau,length(lambda),2);\nend\nfor i=1:length(lambda)\n U=frac(1,2).*(1+sign(tau(:,i)));\n d=sqrt(frac(lambda(i).^(2*alpha(i)-1),materncfun(alpha(i))));\n G(:,i)=d.*U.*(tau(:,i).^(alpha(i)-1)).*exp(-tau(:,i).*lambda(i)).*exp(sqrt(-1)*omegao(i)*tau(:,i)).*frac(1,gamma(alpha(i)));\nend\n\nif ~isempty(N)\n varargout{1}=tau;\n varargout{2}=G;\nelse\n varargout{1}=G;\nend\n\n\nfunction[]=maternimp_test\nalpha=[1 1.5 2 3 4];\nh=[.01 .02 .05 .2 1]/10;\n[alpha,h]=meshgrid(alpha,h);\nvcolon(alpha,h);\n[tau,g]=maternimp(15000,alpha,h);\nd=sqrt(frac(h.^(2*alpha-1),materncfun(alpha)));\nfor i=1:size(g,2)\n g(:,i)=g(:,i)./d(i);\nend\nreporttest('MATERNIMP integral of Green''s function matches analytic form',aresame((sum(g,1)'.*(h.^alpha))'-1,zeros(size(h')),2.5e-2))\n\nt=[0:1:150]';\nalpha=1.4;h=1/10;\ng=maternimp(t,alpha,h);\nR1=conv(g,flipud(g));\n[tau,R2]=materncov(1,length(t),1,alpha,h,'full');\neps=sum(squared(R1-R2))./sum(squared(R1));\nreporttest('MATERNIMP Green''s function convolves to autocovariance sample rate',eps<1e-3)\n\n\nN=1000;\nalpha=1.4;h=1/10;\n[tau,g]=maternimp(N,alpha,h);\nR1=conv(g,flipud(g));\n[tau,R2]=materncov(1,N,1,alpha,h,'full');\neps=sum(squared(R1-R2))./sum(squared(R1));\nreporttest('MATERNIMP Green''s function convolves to autocovariance without time input',eps<1e-3)\n\n", "meta": {"author": "jonathanlilly", "repo": "jLab", "sha": "9f32f63e647209bc1cb81c8713deb954857f1919", "save_path": "github-repos/MATLAB/jonathanlilly-jLab", "path": "github-repos/MATLAB/jonathanlilly-jLab/jLab-9f32f63e647209bc1cb81c8713deb954857f1919/jmatern/maternimp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.7087429436687742}} {"text": "function h = p32_h ( n, x )\n\n%*****************************************************************************80\n%\n%% P32_H evaluates the Hessian for problem 32.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 January 2001\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of variables.\n%\n% Input, real X(N), the values of the variables.\n%\n% Output, real H(N,N), the N by N Hessian matrix.\n%\n h = zeros ( n, n );\n\n m = 7;\n a = [ \n 4.0, 4.0, 4.0, 4.0; ...\n 1.0, 1.0, 1.0, 1.0; ...\n 8.0, 8.0, 8.0, 8.0; ...\n 6.0, 6.0, 6.0, 6.0; ...\n 3.0, 7.0, 3.0, 7.0; ...\n 2.0, 9.0, 2.0, 9.0; ...\n 5.0, 5.0, 3.0, 3.0 ]';\n\n c = [ 0.1, 0.2, 0.2, 0.4, 0.6, 0.6, 0.3 ]';\n\n for ii = 1 : n\n for jj = 1 : n\n for j = 1 : m\n d = c(j) + sum ( ( x(1:n) - a(1:n,j) ).^2 );\n h(ii,jj) = h(ii,jj) - 8.0 * ( x(ii) - a(ii,j) ) * ( x(jj) - a(jj,j) ) / d^3;\n if ( ii == jj )\n h(ii,jj) = h(ii,jj) + 2.0 / d^2;\n end\n end\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_opt/p32_h.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8031737940012417, "lm_q1q2_score": 0.7087429423994354}} {"text": "function y=roundTies2EvenOdd(x,mode)\n%%ROUNDTIES2EVENODD Round the values in x to the nearest integer. Ties will\n% either round to even or odd integers.\n%\n%INPUTS: x A scalar, vector, matrix of values to round to the nearest\n% integer.\n% mode A parameter specifying how ties (when the value is an integer\n% +0.5) are handled. Possible values are\n% 0 (The default if omitted or an empty matrix is passed) Round\n% ties to even integers.\n% 1 Round ties to odd integers.\n%\n%OUTPUTS: y x rounded with the selected handling of ties.\n%\n%EXAMPLE:\n%As an example of rounding to even versus odd integers, consider:\n% x=[-1.5,-2.5,-3.5,-1.1,-1.9,-2.1,-2.9,0,1.5,2.5,3.5,1.1,1.9,2.1,2.9];\n% y1=roundTies2EvenOdd(x,0)\n% y2=roundTies2EvenOdd(x,1)\n%One will find that\n%y1=[-2,-2,-4,-1,-2,-2,-3,0,2,2,4,1,2,2,3]\n%y2=[-1,-3,-3,-1,-2,-2,-3,0,1,3,3,1,2,2,3]\n%\n%November 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n if(nargin<2||isempty(mode))\n mode=0;\n end\n \n switch(mode)\n case 0%Round with ties going to even\n y=round(x);\n sel1=abs(x-fix(x))==0.5 & mod(fix(x),2)==0;\n y(sel1)=fix(x(sel1));\n case 1%Round with ties going to odd.\n y=round(x);\n sel1=abs(x-fix(x))==0.5 & mod(fix(x),2)==1;\n y(sel1)=fix(x(sel1));\n otherwise\n error('Wrong Mode specified')\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/Misc/roundTies2EvenOdd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.8824278664544911, "lm_q1q2_score": 0.7087429395113745}} {"text": "function interior_point = point_inside_polygon(V)\n % POINT_INSIDE_POLYGON return some point inside of the given polygon\n %\n % interior_point = point_inside_polygon(V)\n %\n % Input\n % V n by 2 vertex array\n % Output\n % interior_point a point inside V\n %\n % Copyright 2011, Alec Jacobson (jacobson@inf.ethz.ch)\n\n assert(size(V,1) >= 3);\n % start with a point above the polygon in the middle\n p = 1.0 + [mean(V(:,1)) max(V(:,2))];\n\n % first hits are just mid points on segments\n first_hits = ...\n [V(:,1) + V([end, 1:(end-1)],1) , ...\n V(:,2) + V([end, 1:(end-1)],2)]/2;\n\n distance_to_p = ... \n sum((repmat(p,size(first_hits,1),1) - first_hits).^2,2);\n\n first_hit = first_hits(distance_to_p == min(distance_to_p),:);\n first_hit = first_hit(1,:);\n\n x1 = p(1);\n y1 = p(2);\n x2 = first_hit(1);\n y2 = first_hit(2);\n x3 = V(1:end,1);\n y3 = V(1:end,2);\n x4 = V([end, 1:(end-1)],1);\n y4 = V([end, 1:(end-1)],2);\n % Find intersections along this ray with each line segment's line\n % from http://en.wikipedia.org/wiki/Line-line_intersection\n second_hits = ...\n [((x1.*y2-y1.*x2).*(x3-x4) - (x1-x2).*(x3.*y4-y3.*x4))./...\n ((x1-x2).*(y3-y4) - (y1 - y2).*(x3-x4)), ...\n ((x1.*y2-y1.*x2).*(y3-y4) - (y1-y2).*(x3.*y4-y3.*x4))./...\n ((x1-x2).*(y3-y4) - (y1 - y2).*(x3-x4))];\n\n % Check if intersection is really on line segment, handling vertical and\n % horizontal lines\n valid_second_hits = ...\n second_hits( ...\n ((second_hits(:,1) >= x3 & second_hits(:,1) <= x4 )| ...\n (second_hits(:,1) <= x3 & second_hits(:,1) >= x4 ) | ...\n (x3 == x4) ...\n ) & ...\n ((second_hits(:,2) >= y3 & second_hits(:,2) <= y4 )| ...\n (second_hits(:,2) <= y3 & second_hits(:,2) >= y4 ) | ...\n (y3 == y4) ...\n ) & ~((x3 == x4)&(y3 == y4))...\n ,:);\n\n distance_to_first_hit = ... \n sum((repmat(first_hit,size(valid_second_hits,1),1) - ...\n valid_second_hits).^2,2);\n\n EPSILON = 10.0^-15;\n valid_second_hits = ...\n valid_second_hits(distance_to_first_hit>EPSILON,:);\n distance_to_first_hit = ...\n distance_to_first_hit(distance_to_first_hit>EPSILON,:);\n\n second_hit = valid_second_hits(...\n distance_to_first_hit == min(distance_to_first_hit),:);\n % shouldn't have to do this:\n second_hit = second_hit(1,:);\n\n interior_point = (first_hit + second_hit)/2;\n\nend\n", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/z_gptoolbox/mesh/point_inside_polygon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7087155040045731}} {"text": "function d = grPropagateDistance(v, e, v0, l)\n%GRPROPAGATEDISTANCE Propagates distances from a vertex to other vertices\n%\n% DISTS = grPropagateDistance(V, E, V0, L)\n% V0 is index of initial vertex\n% E is array of source and target vertices\n% L is the vector of length of each edge. If not specified, length 1 is\n% assumed for all edges.\n% The result DISTS is a column array with as many rows as the number of\n% vertices, containing the geodesic distance of each vertex to the vertex\n% of index V0.\n%\n% Example\n% nodes = [20 20;20 50;20 80;50 50;80 20;80 50;80 80];\n% edges = [1 2;2 3;2 4;4 6;5 6;6 7];\n% figure; drawGraph(nodes, edges);\n% axis([0 100 0 100]); axis equal; hold on\n% DISTS = grPropagateDistance(nodes, edges, 2)\n% DISTS = \n% 1\n% 0\n% 1\n% 1\n% 3\n% 2\n% 3\n% drawNodeLabels(nodes+1, DISTS);\n%\n% See Also\n% graphRadius, graphCenter, graphDiameter, graphPeripheralVertices\n% grVertexEccentricity\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-09-07, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2010 INRA - Cepia Software Platform.\n\n\n% initialize empty array for result\nNv = length(v);\nd = ones(Nv, 1)*inf;\nd(v0) = 0;\n\n% ensure there is a valid length array\nif nargin < 4\n l = ones(size(e,1), 1);\nend\n\n% iterate from germ vertex until there are no more vertices to process\nverticesToProcess = v0;\nwhile ~isempty(verticesToProcess)\n % init new iteration\n newVerticesToProcess = [];\n\n % iterate over vertices that need to be updated\n for i = 1:length(verticesToProcess)\n vertex = verticesToProcess(i);\n \n % iterate over neighbor edges of current vertex\n vertexEdges = grAdjacentEdges(e, vertex);\n for j = 1:length(vertexEdges)\n iEdge = vertexEdges(j);\n \n % compute distance between current vertex and its neighbor\n vertex2 = grOppositeNode(e(iEdge,:), vertex);\n newDist = d(vertex) + l(iEdge);\n \n % update geodesic distance of neighbor node if needed\n if newDist < d(vertex2)\n d(vertex2) = newDist;\n newVerticesToProcess = [newVerticesToProcess ; vertex2]; %#ok\n end\n end\n end\n \n % update set of vertices for next tieration\n verticesToProcess = newVerticesToProcess;\nend\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/graphs/grPropagateDistance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7086704220408447}} {"text": "function [kHz] = radps2kHz(radps)\n% Convert frequency from radians per second to kilohertz.\n% Chad A. Greene 2012\nkHz = radps/(2*pi)/1000;", "meta": {"author": "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/radps2kHz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009642742806, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.7086670898441058}} {"text": "function [u,Du,eqn,info] = Poisson3T1(node,elem,pde,bdFlag, option)\n%% POISSON3T1 Poisson equation: trilinear element.\n%\n% u = Poisson3T1(node,elem,pde,bdFlag) produces the trilinear finite element\n% approximation of the Poisson equation\n% \n% -div(d*grad(u))=f in \\Omega, with \n% Dirichlet boundary condition u=g_D on \\Gamma_D, \n% Neumann boundary condition d*grad(u)*n=g_N on \\Gamma_N,\n% Robin boundary condition g_R*u + d*grad(u)*n=g_N on \\Gamma _R\n%\n% Author: Huayi Wei < huayiwei1984@gmail.com>. \n%\n% See also: PoissonQ1\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n\nif ~exist('option','var'), option = []; end\n[N,Dim] = size(node); \n[NT,NV] = size(elem);\nNdof = N;\n\ntic;\n\n%% Stiffness matrix and mass matrix in each direction\nhx = node(elem(:,2),1) - node(elem(:,1),1);\nhy = node(elem(:,4),2) - node(elem(:,1),2);\nhz = node(elem(:,5),3) - node(elem(:,1),3);\nvolume = abs(hx.*hy.*hz);\nAx = 1./hx*[1 -1];\nMx = hx*[1/3 1/6];\nAy = 1./hy*[1 -1];\nMy = hy*[1/3 1/6];\nAz = 1./hz*[1 -1];\nMz = hz*[1/3 1/6];\n\n%% Assemble stiffness matrix\n% generate sparse pattern\nii = zeros(36*NT,1); jj = zeros(36*NT,1); \nindex = 0;\nfor i = 1:NV\n for j = i:NV\n ii(index+1:index+NT) = double(elem(:,i)); \n jj(index+1:index+NT) = double(elem(:,j)); \n index = index + NT;\n end\nend\n% index map\nitoixiyiz = [[1 2 2 1 1 2 2 1]' [1 1 2 2 1 1 2 2]' [1 1 1 1 2 2 2 2]'];\n\nif ~isfield(pde,'d'), pde.d = []; end\nsA = zeros(36*NT,1);\nindex = 0;\nfor i = 1:NV\n for j = i:NV\n ix = itoixiyiz(i,1); jx = itoixiyiz(j,1);\n iy = itoixiyiz(i,2); jy = itoixiyiz(j,2);\n iz = itoixiyiz(i,3); jz = itoixiyiz(j,3);\n Aij = Ax(:,2-(ix==jx)).*My(:,2-(iy==jy)).*Mz(:,2-(iz==jz)) ...\n + Mx(:,2-(ix==jx)).*Ay(:,2-(iy==jy)).*Mz(:,2-(iz==jz)) ...\n + Mx(:,2-(ix==jx)).*My(:,2-(iy==jy)).*Az(:,2-(iz==jz));\n if ~isempty(pde.d) && isnumeric(pde.d) % d is piecewise constant\n Aij = pde.d.*Aij;\n end\n sA(index+1:index+NT) = Aij;\n index = index + NT;\n end\nend\n% assemble the matrix\ndiagIdx = (ii == jj); upperIdx = ~diagIdx;\nA = sparse(ii(diagIdx),jj(diagIdx),sA(diagIdx),Ndof,Ndof);\nAU = sparse(ii(upperIdx),jj(upperIdx),sA(upperIdx),Ndof,Ndof);\nA = A + AU + AU';\nclear Aij ii jj sA\n\n%% Assemble the right hand side\nb = zeros(N,1);\nif ~isfield(option,'fquadorder')\n option.fquadorder = 3; % default order\nend\nif ~isfield(pde,'f') || (isreal(pde.f) && (pde.f==0))\n pde.f = [];\nend\n\nif ~isempty(pde.f) \n [GaussPt, weight] = quadptscube(option.fquadorder);\n lambdax = GaussPt(:,1);\n lambday = GaussPt(:,2);\n lambdaz = GaussPt(:,3); \n nQuad = size(GaussPt,1);\n bt = zeros(NT,NV);\n for p = 1:nQuad\n\t\t% quadrature points in the x-y-z coordinate\n phi2d = kron([lambday(p) 1-lambday(p)],[lambdax(p); 1-lambdax(p)]);\n phi = transpose(kron([lambdaz(p) 1-lambdaz(p)],phi2d([1 2 4 3])));\n J = volume;\n% [phi, tempvar, J] = hexbasis(node,elem, pts(p,:));\n pxyz = zeros(NT, Dim);\n for k = 1:Dim\n xk = node(:,k);\n pxyz(:,k) = xk(elem)*phi(:);\n end\n\t\tfp = pde.f(pxyz);\n bt = bt + (weight(p)*fp.*J)*phi';\n end\n b = accumarray(elem(:),bt(:),[Ndof 1]);\nend\nclear pxyz bt\n\n%% Set up boundary conditions\nif ~exist('bdFlag','var'), bdFlag = []; end\n[AD,b,u,freeNode,isPureNeumann] = getbd3(b);\n\n%% Record assembling time\nassembleTime = toc;\nif ~isfield(option,'printlevel'), option.printlevel = 1; end\nif option.printlevel >= 2\n fprintf('Time to assemble matrix equation %4.2g s\\n',assembleTime);\nend\n\n%% Solve the system of linear equations\nif isempty(freeNode), return; end\n% Set up solver type\nif isempty(option) || ~isfield(option,'solver') % no option.solver\n if Ndof <= 2e3 % Direct solver for small size systems\n option.solver = 'direct';\n else % MGCG solver for large size systems\n option.solver = 'mg';\n end\nend\nsolver = option.solver;\n% solve\nswitch solver\n case 'direct'\n tic;\n u(freeNode) = AD(freeNode,freeNode)\\b(freeNode);\n residual = norm(b - AD*u);\n info = struct('solverTime',toc,'itStep',0,'err',residual,'flag',2,'stopErr',residual);\n case 'none'\n info = struct('solverTime',[],'itStep',0,'err',[],'flag',3,'stopErr',[]);\n case 'mg'\n% option.x0 = u;\n option.solver = 'CG';\n% [u,info] = mg(AD,b,elem,option);\n [u(freeNode),info] = amg(AD(freeNode,freeNode),b(freeNode),option); \n case 'amg'\n option.solver = 'CG';\n [u(freeNode),info] = amg(AD(freeNode,freeNode),b(freeNode),option); \nend\n% post-process for pure Neumann problem\nif isPureNeumann\n patchArea = accumarray(elem(:),[J;J;J;J;J;J;J;J]/8, [N 1]); % TODO: Here is J?\n uc = sum(u.*patchArea)/sum(J);\n u = u - uc; % int u = 0\nend\n\n%% Output information\neqn = struct('A',AD,'b',b,'freeNode',freeNode);\ninfo.assembleTime = assembleTime;\n\n%% Compute Du\nDu = [];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% subfunctions getbd3\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n function [AD,b,u,freeNode,isPureNeumann] = getbd3(b)\n %% Set up of boundary conditions.\n %\n % 1) Modify the matrix for Dirichlet boundary nodes, which are not degree\n % of freedom. Values at these nodes are evaluatation of pde.g_D. The\n % original stiffness matrix A is turn into the matrix AD by enforcing\n % AD(fixedNode,fixedNode)=I, AD(fixedNode,freeNode)=0, AD(freeNode,fixedNode)=0.\n %\n % 2) Modify the right hand side b. The Neumann boundary integral is added\n % to b. For Dirichlet boundary ndoes, b(fixedNode) is the evaluation of\n % pde.g_D.\n %\n % Special attentation should be given for the pure Neumann boundary\n % condition. To enforce the compatible condition, the vector b should have\n % mean value zero. To avoid a singular matrix, the 1st node is chosen as\n % fixedNode. \n %\n % The order of assigning Neumann and Dirichlet boundary condition is\n % important to get the right setting at the intersection nodes of Dirichlet\n % and Neumann boundary edges.\n %\n % Reference: Long Chen. Finite Element Methods and its Programming. Lecture\n % Notes.\n\n u = zeros(Ndof,1); \n %% Initial check\n if ~isfield(pde,'g_D'), pde.g_D = []; end\n if ~isfield(pde,'g_N'), pde.g_N = []; end\n if ~isfield(pde,'g_R'), pde.g_R = []; end\n\n %% Part 1: Modify the matrix for Dirichlet and Robin condition\n % Robin boundary condition\n Robin = [];\n isRobin = (bdFlag(:) == 3);\n if any(isRobin)\n allFace = [elem(:,[1 4 3 2]); elem(:,[1 2 6 5]); elem(:,[5 6 7 8]);...\n elem(:,[8 7 3 4]); elem(:,[4 1 5 8]); elem(:,[2 3 7 6])];\n Robin = allFace(isRobin,:);\n end\n if ~isempty(Robin) && ~isempty(pde.g_R) && ~(isnumeric(pde.g_R) && (pde.g_R == 0))\n %% To do: this is for tet mesh. Modify for hex mesh later.\n v12 = node(Robin(:,2),:)-node(Robin(:,1),:);\n v13 = node(Robin(:,3),:)-node(Robin(:,1),:);\n area = 0.5*sqrt(abs(sum(mycross(v12,v13,2).^2,2)));\n if ~isfield(option,'gRquadorder')\n option.gRquadorder = 3; % default order exact for linear gR\n end\n [lambdagR,weightgR] = quadpts(option.gRquadorder);\n nQuadgR = size(lambdagR,1);\n bdphi = lambdagR;\n NR = size(Robin,1);\n ss = zeros(NR,3,3);\n % int g_R phi_i phi_j\n for pp = 1:nQuadgR\n ppxyz = lambdagR(pp,1)*node(Robin(:,1),:) ...\n + lambdagR(pp,2)*node(Robin(:,2),:) ...\n + lambdagR(pp,3)*node(Robin(:,3),:);\n gRp = pde.g_R(ppxyz);\n for iR = 1:3\n for jR = iR:3\n ss(:,iR,jR) = ss(:,iR,jR) + ...\n weightgR(pp)*gRp*bdphi(pp,iR).*bdphi(pp,jR);\n end\n end\n end\n ss(:) = ss(:).*repmat(area,9,1); \n index = 0;\n for iR = 1:3\n for jR = 1:3\n iiR(index+1:index+NR) = double(Robin(:,iR)); \n jjR(index+1:index+NR) = double(Robin(:,jR)); \n if jR>=iR\n ssR(index+1:index+NR) = ss(:,iR,jR);\n else\n ssR(index+1:index+NR) = ss(:,jR,iR);\n end\n index = index + NR;\n end\n end\n A = A + sparse(iiR,jjR,ssR,Ndof,Ndof); \n end\n\n % Find Dirichlet boundary nodes: fixedNode\n fixedNode = []; freeNode = [];\n if ~isempty(bdFlag) % bdFlag specifies different bd conditions\n [fixedNode,bdFace,isBdNode] = findboundary3(elem,bdFlag);\n freeNode = find(~isBdNode);\n end\n if isempty(bdFlag) && ~isempty(pde.g_D) && isempty(pde.g_N) && isempty(pde.g_R)\n % no bdFlag, only pde.g_D is given\n [fixedNode,bdFace,isBdNode] = findboundary3(elem);\n freeNode = find(~isBdNode);\n end\n isPureNeumann = false;\n if isempty(fixedNode) && isempty(Robin) % pure Neumann boundary condition\n % pde.g_N could be empty which is homogenous Neumann boundary condition\n isPureNeumann = true;\n fixedNode = 1;\n freeNode = 2:Ndof; % eliminate the kernel by enforcing u(1) = 0;\n end\n % Modify the matrix\n % Build Dirichlet boundary condition into the matrix AD by enforcing\n % AD(fixedNode,fixedNode)=I, AD(fixedNode,freeNode)=0, AD(freeNode,fixedNode)=0.\n bdidx = zeros(Ndof,1); \n bdidx(fixedNode) = 1;\n Tbd = spdiags(bdidx,0,Ndof,Ndof);\n T = spdiags(1-bdidx,0,Ndof,Ndof);\n AD = T*A*T + Tbd;\n\n %% Part 2: Find boundary faces and modify the load b\n % Find boundary faces: Neumann\n Neumann = [];\n if ~isempty(bdFlag) % bdFlag specifies different bd conditions\n Neumann = bdFace; \n end\n if isempty(bdFlag) && (~isempty(pde.g_N) || ~isempty(pde.g_R))\n % no bdFlag, only pde.g_N or pde.g_R is given in the input\n [tempvar,Neumann] = findboundary3(elem); %#ok\n end\n\n % Neumann boundary condition\n if ~isempty(Neumann) && ~isempty(pde.g_N) && ~(isnumeric(pde.g_N) && (pde.g_N == 0))\n v12 = node(Neumann(:,2),:)-node(Neumann(:,1),:);\n v14 = node(Neumann(:,4),:)-node(Neumann(:,1),:);\n area = sqrt(abs(sum(mycross(v12,v14,2).^2,2)));\n % three middle points rule\n if ~isfield(option,'gNquadorder')\n option.gNquadorder = 3; % default order exact for linear gN\n end\n [GaussPt,weightgN] = quadptsquad(option.gNquadorder);\n xxi = GaussPt(:,1);\n eta = GaussPt(:,2);\n nQuadgN = size(GaussPt,1);\n % barycentrical coordinate for four basis\n lambdagN = zeros(nQuadgN,4);\n lambdagN(:,1) = (1 - xxi).*(1 - eta);\n lambdagN(:,2) = xxi.*(1 - eta);\n lambdagN(:,3) = xxi.*eta;\n lambdagN(:,4) = (1 - xxi).*eta;\n ge = zeros(size(Neumann,1),4);\n for pp = 1:nQuadgN\n % quadrature points in the x-y coordinate\n ppxyz = node(Neumann(:,1),:)*lambdagN(pp,1) + node(Neumann(:,2),:)*lambdagN(pp,2)...\n + node(Neumann(:,3),:)*lambdagN(pp,3) + node(Neumann(:,4),:)*lambdagN(pp,4);\n gNp = pde.g_N(ppxyz);\n for iN = 1:4\n ge(:,iN) = ge(:,iN) + weightgN(pp)*lambdagN(pp,iN)*gNp;\n end\n end\n ge = ge.*repmat(area,1,4);\n b = b + accumarray(Neumann(:),ge(:),[Ndof,1]); \n end\n % The case with non-empty Neumann edges but g_N=0 or g_N=[] corresponds to\n % the zero flux boundary condition on Neumann edges and no modification of\n % A,u,b is needed.\n\n % Dirichlet boundary condition\n if ~isPureNeumann && ~isempty(fixedNode) && ...\n ~isempty(pde.g_D) && ~(isnumeric(pde.g_D) && all(pde.g_D == 0)) % nonzero g_D\n if isnumeric(pde.g_D)\n u(fixedNode) = pde.g_D(fixedNode);\n else\n u(fixedNode) = pde.g_D(node(fixedNode,:));\n end\n b = b - A*u;\n end\n if ~isPureNeumann % non-empty Dirichlet boundary condition \n b(fixedNode) = u(fixedNode);\n end\n % The case with non-empty Dirichlet nodes but g_D=0 or g_D=[] corresponds\n % to the zero Dirichlet boundary condition and no modification of u,b is\n % needed.\n\n % Pure Neumann boundary condition\n if isPureNeumann\n b = b - mean(b); % compatilbe condition: sum(b) = 0\n b(1) = 0;\n end\n end % end of getbd3\nend % end of Poisson3Q1\n", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/equation/Poisson3T1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.7086670803225418}} {"text": "function [C,S]=fitSpherHarmonics(M,points,vals,a,c)\n%%FITSPHERHARMONICS Given a number of field values at a diversity\n% of points in spherical coordinates (either range, azimuth\n% and elevation, or just azimuth and elevation), fit fully\n% normalized spherical harmonic coefficients up to a\n% particular degree to the data. The data being fitted can be\n% real or complex. One can fit multiple sets of data at once\n% as long as they share the same set of points.\n%\n%INPUTS: M The maximum degree of the coefficients to use.\n% points The 2XN or 3XN set of points in spherical coordinates in the\n% form [r;azimuth;elevation] or just [azimuth;elevation]. Azimuth\n% is measured counterclockwise from the x-axis in the x-y plane.\n% Elevation is measured up from the x-y plane (towards the\n% z-axis). Angles must be given in radians. Note the system to be\n% observable, N>=(M+1)^2.\n% vals The NXnumSets sets of real or complex values at the given\n% points.\n% a The real or complex numerator in the (a/r)^n term in the\n% spherical harmonic sum. If this parameter is omitted or an empty\n% matrix is passed, then a=1 is used.\n% c The real or complex constant value by which the spherical\n% harmonic series is multiplied. If this parameter is omitted or\n% an empty matrix is passed, then c=1 is used.\n%\n%OUTPUTS: C A numCoeffsXnumSets collections of arrays, one for each set of\n% values passed, holding the coefficient terms that are\n% multiplied by cosines in the spherical harmonic expansion. If\n% given to a CountingClusterSet class, C(n+1,m+1) is the\n% coefficient of degree n and order m. This and S can be given to\n% the function spherHarmonicEval.\n% S A numCoeffsXnumSets collection of arrays, one for each set of\n% values passed, holding the coefficient terms that are\n% multiplied by sines in the spherical harmonic expansion. S has\n% the same structure as C. \n%\n%The spherical harmonic series being fit is assumed to be of the form\n%V=(c/r)*sum_{n=0}^M\\sum_{m=0}^n(a/r)^n*(C(n+1,m+1)*cos(m*lambda)+S(n+1,m+1)*sin(m*lambda))*\\bar{P}_{nm}(sin(theta))\n%where \\bar{P}_{nm} is a fully-normalized associated Legendre polynomial.\n%This function uses the LegendreCos function to evaluate the Legendre\n%polynomials and it them constructs a linear system to solve for the values\n%of C and S. Unobservable values of S are where m=0, so S(n+1,0+1)=0 and\n%those components are not part of the estimation problem.\n%\n%Real spherical harmonic models are often used for gravitational, magnetic\n%field and some terrain modeling, as discussed in part of [1], whereas\n%complex spherical harmonic models are often used for electromagnetic\n%modeling.\n%\n%The complex spherical harmonic model that is usually used in\n%electromagnetics is \n%V=(c/r)*sum_{n=0}^M\\sum_{m=-n}^n(a/r)^n*A(n+1,m+1)*\\bar{P}_{nm}(sin(theta))*exp(1j*m*lambda)\n%Initially, it just looks like one has combined the S and C values into one\n%complex coefficient A and then multiplied the sin term by 1j. However, if\n%that were all that had been done, one wouldn't be able to match many\n%models, because if A(n+1,m+1)=AR+1j*AI, expanding the term\n%A(n+1,m+1)*exp(1j*m*lambda), one gets \n%aR*cos(m*lambda)-aI*sin(m*lambda)+1j*(aI*cos(m*lambda)+aR*sin(m*lambda))\n%Where one can see that it is not possible to independently set the real\n%and the imaginary terms. However, note that the formulation of the inner\n%sum used for complex values starts at -m and not at 0. This extension of\n%the sum allows one to uniquely form real and complex terms. Though such a\n%symmetry does not occur at m=0, that does not actually matter, since the\n%sine terms are zero, so one can still independently set the real and the\n%imaginary coefficients parts. Indeed, it can be shown that the resulting\n%expression allows one to fit the real and complex parts independently if a\n%and c are real.\n%\n%EXAMPLE:\n%We take the coefficients for the World Magnetic Model, evaluate the\n%magnetic field values at a number of points around the globe, use this\n%function to reconstruct the spherical harmonic coefficients from the field\n%values and compare the computed coefficients with the coefficients used to\n%generate the field values.\n% [C,S,a,c]=getWMMCoeffs();\n% M=(1/2)*(sqrt(1+8*length(C))-1);\n% \n% %Evaluate the model on a grid.\n% numPoints=21;\n% totalGridPoints=numPoints*numPoints;\n% deltaLat=180/numPoints;\n% lat=-90+(0:(numPoints-1))*deltaLat;\n% lat=lat*(pi/180);%Convert latitude to radians.\n% \n% deltaLon=360/numPoints;\n% lon=-180+(0:(numPoints-1))*deltaLon;\n% lon=lon*(pi/180);%Convert longitude to radians.\n% [latGrid,lonGrid]=ndgrid(lat,lon);\n% latLonEllipse=[latGrid(:)';lonGrid(:)'];\n% %Convert from ellipsoidal latitudes to spherical latitudes (This assumes\n% %that the points are on the surface of the reference ellipsoid).\n% points=ellips2Sphere([latLonEllipse;zeros(1,totalGridPoints)]);\n% \n% %Evaluate the magnetic field values at the given points.\n% V=spherHarmonicEval(C,S,points,a,c);\n% \n% %Reconstruct the coefficients from the magnetic field values.\n% [CFit,SFit]=fitSpherHarmonics(M,points,V,a,c);\n% \n% %Check how good the fit is to the original set of coefficients.\n% sel1=C(:)~=0;\n% max(abs(CFit(sel1)-C(sel1))./C(sel1))\n% sel1=S(:)~=0;\n% max(abs(SFit(sel1)-S(sel1))./S(sel1))\n%In both instances, the maximum relative error should have been less than\n%8e-10. The fact that there is any error stems from finite precision\n%effects.\n%\n%REFERENCES:\n%[1] D. F. Crouse, \"An overview of major terrestrial, celestial, and\n% temporal coordinate systems for target tracking,\" Naval Research\n% Laboratory, Washington, DC, Tech. Rep. NRL/FR/5344-16-10,279, 10 Aug.\n% 2016.\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<5||isempty(c))\n c=1; \nend\n\nif(nargin<4||isempty(a))\n a=1; \nend\n\npointDims=size(points,1);\n\nnumEq=size(points,2);\n\n%The total number of associated Legendre polynomials.\nnumPBar=(M+1)*(M+2)/2;\n\n%The M+1 being subtracted is the number of S_{n,0} values,\n%because these can just be set to zero as they are never used; they are\n%always multiplied by sin(0).\nnumCCoeffs=numPBar;\nnumSCoeffs=numPBar-(M+1);\n\n%The total number of coefficients if all values for C and S must be\n%computed. \ncoeffsTotal=numCCoeffs+numSCoeffs;\n\nif(coeffsTotal>numEq)\n warning('The value of M is too large for the number of values provided. The exact solution is unobservable.') \nend\n\n%The columns of Y corresponds to the C coefficients followed by the S\n%coefficients.\nY=zeros(numEq,coeffsTotal);\nfor curEq=1:numEq\n curPoint=points(:,curEq);\n \n if(pointDims==3)\n r=curPoint(1);\n Az=curPoint(2);\n coLat=pi/2-curPoint(3);\n else\n r=1;\n Az=curPoint(1);\n coLat=pi/2-curPoint(2);\n end\n %We now have r, azimuth, and colatitude.\n\n %Get all of the associated Legendre polynomials.\n PBarVals=LegendreCos(coLat,M);\n PBarVector=PBarVals(:);\n \n outerCoeff=c/r;\n innerCoeff=1;\n for n=0:M\n for m=0:n\n %The index of PBarVals(n+1,m+1) in the vector PBarVector.\n idx=n*(n+1)/2+m+1;\n \n coeffVal=outerCoeff*innerCoeff*PBarVector(idx);\n\n Y(curEq,idx)=coeffVal*cos(m*Az);\n if(m>0)\n %The -(n+1) deals with the fact that there are no values of\n %S for m=0.\n Y(curEq,numCCoeffs+idx-(n+1))=coeffVal*sin(m*Az);\n end\n end\n innerCoeff=innerCoeff*(a/r);\n end\nend\n\n%If one were to use linsolve(Y,vals(:)), many systems would complain about\n%Y having poor conditioning.\ncoeffs=lsqminnorm(Y,vals);\n\nC=coeffs(1:numPBar,:);\n\n%Fill in S, noting that the unused parts are left set to zero.\nnumSets=size(vals,2);\nSData=zeros(numPBar,numSets);\ncurSIdx=numCCoeffs+1;\nfor n=1:M\n for m=1:n\n idx=n*(n+1)/2+m+1;\n SData(idx,:)=coeffs(curSIdx,:);\n curSIdx=curSIdx+1;\n end\nend\nS=SData;\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/Spherical_Harmonics/fitSpherHarmonics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7086670742996115}} {"text": "function zCD=spherITRS2SpherCD(zSpher,param1,param2,S11)\n%%SPHERITRS2SPHERCD Convert points given in spherical coordinates in the\n% International Terrestrial Reference System (ITRS), a\n% standard Earth-Cenetred-Earth-fixed (ECEF) coordinate\n% system, into centered dipole (CD) coordinates expressed in\n% spherical form, the form most commonly used in papers. CD\n% coordinates is a type of coordinate system where the z-axis\n% is aligned with the magnetic dipole of the Earth (under a\n% dipole model). This coordinate system is useful when\n% studying the ionosphere.\n%\n%INPUTS: zSpher One or more points given in terms of range, azimuth\n% (geocentric longitude) and elevation (geocentric latitude),\n% with the angles in radians, or in terms of just azimuth\n% and elevation if a conversion of directions is desired in\n% the ITRS. To convert N points, zSpher is a 3XN matrix with\n% each column having the format [range;azimuth; elevation] or\n% it is a 2XN matrix with each column having format [azimuth;\n% elevation]. Azimuth is measured counterclockwise from the\n% x-axis in the x-y plane. Elevation is measured up from the\n% x-y plane (towards the z-axis).\n%param1,param2,S11 These optional parameters specify the magnetic field\n% parameters from which the direction of the CD pole is\n% derived. These aprameters are impied set base don how the\n% function is called:\n% 1) spherITRS2SpherCD(zSpher)\n% If all of the other parameters are omitted, then the CD\n% pole parameters for the latest epoch of the\n% International Geomagnetic Reference Field (IGRF) are\n% used; the Schmidt semi-normalized coefficients are\n% obtained using the function getIGRFCoeffs.\n% 2) spherITRS2SpherCD(zSpher, year)\n% The parameters of the IGRF for the specified epoch year\n% are used. The year is in the Gregorian calendar and is\n% specified as noted in the comments to the getIGRFCoeffs\n% function.\n% 3) spherITRS2SpherCD(zSpher, year, model). This is the same\n% as spher2CenteredDipole(zSpher, year), except model can\n% be 'IGRF' or 'WMM' to specify which magnetic field model\n% to use. 'WMM' refers to the World magnetic model using\n% the function getWMMCoeffs. Note than an empty year\n% matrix can be passed to get the latest epoch year of\n% either model.\n% 4) spherITRS2SpherCD(zSpher,C10,C11,S11). In this instance,\n% the first few Schmidt semi-normalized coefficients for a\n% magnetic field model are given. These are the only three\n% coefficients used to define the orientation of the CD\n% pole. If using the getWMMCoeffs or getIGRFCoeffs\n% function to get the coordinates, then from the outputs\n% of those functions (specifying in the second input that\n% they should not be fully normalized), the outputs C and\n% S of the functions are used here as\n% C10=C(1+1,0+1), C11=C(1+1,1+1), S11=C(1+1,1+1).\n%\n%OUTPUTS: zCD The points in zSpher converted into centered dipole\n% coordinates under the selected model. If zSpher is 3XN, then\n% zCD consists of range as well as azimuth and elevation. If\n% zSpher was 2XN, then zCD just consists of azimuth and\n% elevation. All angles are in radians.\n%\n%The definition of centered dipole (CD) coordinates is taken from [1].\n%However, as opposed to using the spherical trignonometric equations in the\n%paper, the rotation is performed in Cartesian coordinates so as to avoid\n%singularities.\n%\n%REFERENCES:\n%[1] A. C. Fraser-Smith, \"Centered and eccentric geomagnetic dipoles and\n% their poles 1600-1985,\" Reviews of Geophysics, vol. 25, no. 1, pp.\n% 1-16, Feb. 1987.\n%\n%June 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\nnumDim=size(zSpher,1);\n\n%%Determine the centered dipole location from a magnetic field model.\nif(nargin==1||nargin==2||nargin==3)\n if(nargin==1||isempty(param1))\n %If only position components were given, then just use the values for\n %the reference epoch of the IGRF. The unnormalized coefficients are\n %desired.\n [C,S]=getIGRFCoeffs([],false);\n elseif(nargin==2)\n %If a reference year is given, then use that in the IGRF. \n [C,S]=getIGRFCoeffs(param1,false);\n elseif(nargin==3)%If one wishes to select the magnetic field model.\n switch(param2)\n case 'IGRF'\n if(isempty(param1))\n [C,S]=getIGRFCoeffs([],false);\n else%If the year is given\n [C,S]=getIGRFCoeffs(param1,false);\n end\n case 'WMM'\n if(isempty(param1))\n [C,S]=getWMMCoeffs([],false);\n else%If the year is given\n [C,S]=getWMMCoeffs(param1,false);\n end\n otherwise\n error('Unknown magnetic field model selected')\n end\n end\n \n g10=C(2);\n g11=C(3);\n h11=S(3);\nelseif(nargin==4)\n %If the required coefficients are directly provided.\n g10=param1;\n g11=param2;\n h11=S11;\nend\n\n%Perform the rotation in Cartesian coordinates (avoiding the singularities\n%of Equation 3 of [1])\nxRot=ITRS2CartCD(spher2Cart(zSpher),g10,g11,h11);\n\n%Convert the points back to spherical coordinates to return.\nzCD=Cart2Sphere(xRot);\n\nif(numDim<3)\n%If range was not provided, discard the unit ranges that arose using the\n%spher2Cart conversion.\n zCD=zCD(2:3,:);\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/Magnetism/spherITRS2SpherCD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.7086670665753328}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% this function solves the eigenvalue problem omega=f(epsi,kx,ky) for\n%%% in-plane propagation (i.e. z=0) in a 2D-PhC; the problem can be\n%%% separated in two orthogonal polarizations, E-pol & H-pol\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [omegaE, omegaH]=eigsEH(kGx,kGy,epsi,N,bands)\neta=inv(epsi);\nA=inv(eta*(kGx^2+kGy^2)); %%% matrix for E-pol\nB=inv(kGx*eta*kGx+kGy*eta*kGy); %%% matrix for H-pol\n%%% options used in \"eigs\" calculations - tolerance 1e-12, intermediate results of iterations will\n%%% not be displayed\nopts.tol=1e-12; opts.disp=0; \n%%% calculate the largest eigs, which become the smallest after inversion\nDe=eigs(A,bands,'lr',opts);\nDh=eigs(B,bands,'lr',opts);\n%%% eigenvalues \"omega\" are put in a column vector and sorted in ascending order\nomegaE=sqrt(sort(1./De));\nomegaH=sqrt(sort(1./Dh));\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/21834-photonic-bands-for-a-2d-photonic-crystal/eigsEH.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9496693645535723, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.7085853326583416}} {"text": "% ONE DIMENSIONAL EFG PROGRAM\n% SET UP NODAL COORDINATES ALONG BAR, DETERMINE NUMBER OF CELLS\nx = [0.0:.1:1.0];\nnnodes = length(x); \nncells = nnodes-1;\nnosDeDirichlet = 1;\n\n% SET PARAMETERS FOR WEIGHT FUNCTION, MATERIAL PROPERITES\ndmax = 2.0;\nE=1.0; area=1.0;\n\n% DETERMINE DMI FOR EACH NODE\ndm = dmax*(x(2)-x(1))*ones(1,nnodes);\n\n%SET UP GAUSS POINTS, WEIGHTS, AND JACOBIAN FOR EACH CELL\ngg = zeros(1,ncells);\njac = (x(2)-x(1))/2;\nweight = 2;\ngg = -.05:.1:0.95; gg(1) = 0.0;\n\n% INITIALIZE MATRICES\nk = zeros(nnodes);\nf = zeros(nnodes,1);\nGG = zeros(nnodes,nosDeDirichlet);\n\n% LOOP OVER GAUSS POINTS\nfor j = 1:length(gg)\n xg = gg(j);\n\n% DETERMINE DISTANCE BETWEEN NODES AND GAUSS POINT\ndif = xg*ones(1,nnodes)-x;\n \n% SET UP WEIGHTS W AND DW FOR EACH NODE\nclear w dw\nfor i=1:nnodes\ndrdx = sign(dif(i))/dm(i);\nr = abs(dif(i))/dm(i);\nif r<=0.5\n w(i) = (2/3) - 4*r*r + 4*r^3;\n dw(i) = (-8*r + 12*r^2)*drdx;\nelseif r<=1.0\n w(i) = (4/3)-4*r+4*r*r -(4/3)*r^3;\n dw(i) = (-4 + 8*r-4*r^2)*drdx;\nelseif r>1.0\nw(i) = 0.0;\ndw(i) = 0.0;\nend\nend\n\n%SET UP SHAPE FUNCTIONS AND DERIVATIVES\nwon = ones(1,nnodes);\np = [won;x];\nB = p.*[w;w];\npp = zeros(2);\nA = zeros(2);\ndA = zeros(2);\nfor i=1:nnodes\n pp = p(1:2,i)*p(1:2,i)';\n A = A+w(1,i)*pp;\n dA = dA+dw(1,i)*pp;\nend\nAinv = inv(A);\npg = [1 xg];\nphi(j,:) = pg*Ainv*B;\ndb = p.*[dw;dw];\nda = -Ainv*(dA*Ainv);\ndphi(j,:) = [0 1]*Ainv*B+pg*(da*B+Ainv*db);\n\n%ASSEMBLE DISCRETE EQUATIONS\nif j == 1\n GG(1:3,1) = -phi(1:3)';\nend\n%else\n k = k+(weight*E*area*jac)*(dphi(j,:)'*dphi(j,:));\n fbody = area*xg;\n f = f+(weight*fbody*jac)*phi(j,:)';\n%end\nend\n\n% ENFORCE BOUNDARY CONDITIONS USING LAGRANGE MULTIPLIERS\nq = [0];\nm = [k GG;GG' zeros(1)];\n\n% SOLVE FOR NODAL PARAMETERS\nd = m\\[f' q]';\nu = d(1:nnodes);\n\nresult = phi*u;\nfor i=1:length(x)\n exact(i) = 0.5*(x(i)) - x(i)^3/6.0;\nend\n%%\nplot(x,u);\ntitle('valores u');\nfigure();\nplot(x,result);\ntitle('valores u*phi');\nfigure();\nplot(x,exact);\ntitle('valores exatos');\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/FEM/efg1d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.7085175609752373}} {"text": "function [DI, k] = detectChange(obj, t1, t2)\n% A naive implementation of the Multivariate Alteration Detection Algorithm\n% Partially refer to http://people.compute.dtu.dk/alan/software.html\n% and https://github.com/mortcanty/earthengine\n[rows, cols, chns1] = size(t1);\nchns2 = size(t2, 3);\nchns = min(chns1, chns2);\nx1 = reshape(double(t1), cols*rows, chns1);\nx1 = x1 - mean(x1, 1); % Subtract mean\nx2 = reshape(double(t2), cols*rows, chns2);\nx2 = x2 - mean(x2, 1);\nsigma = cov([x1 x2]);\nsigma11 = sigma(1:chns1, 1:chns1);\nsigma12 = sigma(1:chns1, chns1+1:end);\nsigma21 = sigma(chns1+1:end, 1:chns1);\nsigma22 = sigma(chns1+1:end, chns1+1:end);\n\n[a, e1] = eig(sigma12 / sigma22 * sigma21, sigma11);\ne1 = sqrt(diag(e1));\n[b, e2] = eig(sigma21 / sigma11 * sigma12, sigma22);\ne2 = sqrt(diag(e2));\n[~, idx1] = sort(e1, 'descend');\na = a(:,idx1);\na = a(:,chns:-1:1); % My choice is simply to drop the part of (q-p)\n[~, idx2] = sort(e2, 'descend');\nb = b(:,idx2);\nb = b(:,chns:-1:1);\n\n% Normalize a for unit dispersion\n% Ensure that a'*s11*a=I to meet the constraints\nvars1 = (a'*sigma11*a);\na = a ./ sqrt(diag(vars1))';\n% Similiar operations on b\nvars2 = (b'*sigma22*b);\nb = b ./ sqrt(diag(vars2))';\n\n% Ensure sum of positive correlations between x1 and x1*a is positive\n% I have no idea what this is used for???\ninvStd1 = diag(1./std(x1));\nsgn = diag(sign(sum(invStd1*sigma11*a)));\na = a*sgn;\n\n% Assure positive correlation between pair of canonical variates\nb = b .* diag(sign(a'*sigma12*b))';\n\nmad = x1*a - x2*b;\n\n% Normalize mad\n% This is no regular operation, yet appears to improve the result\nmad = (mad - mean(mad)) ./ (std(mad)+eps);\n\nchi2 = sum(mad.^2, 2);\nprob = chi2cdf(chi2, chns);\nDI = reshape(abs(mad), rows, cols, chns);\n\n% Select bands\nk = min(chns, obj.nMADUsed);\nDI = DI(:,:,1:k);\nend", "meta": {"author": "Bobholamovic", "repo": "ChangeDetectionToolbox", "sha": "167877b866665511d9d5e7e184f964bcda5f4016", "save_path": "github-repos/MATLAB/Bobholamovic-ChangeDetectionToolbox", "path": "github-repos/MATLAB/Bobholamovic-ChangeDetectionToolbox/ChangeDetectionToolbox-167877b866665511d9d5e7e184f964bcda5f4016/+Algorithms/@MAD/detectChange.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.7085175559212634}} {"text": "function can = mpot_to_cpot(mom)\n% MPOT_TO_CPOT Convert a moment potential to canonical form.\n% mom = mpot_to_cpot(can)\n\n[g, h, K] = moment_to_canonical(mom.logp, mom.mu, mom.Sigma);\ncan = cpot(mom.domain, mom.sizes, g, h, K);\n\n%%%%%%%%%%%\n\nfunction [g, h, K] = moment_to_canonical(logp, mu, Sigma)\n% MOMENT_TO_CANONICAL Convert moment characteristics to canonical form.\n% [g, h, K] = moment_to_canonical(logp, mu, Sigma)\n\nK = inv(Sigma);\nh = K*mu;\nn = length(K);\nif isempty(mu)\n g = logp + 0.5*(log(det(K)) - n*log(2*pi));\nelse\n g = logp + 0.5*(log(det(K)) - n*log(2*pi) - mu'*K*mu);\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/potentials/@mpot/mpot_to_cpot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.7905303285397348, "lm_q1q2_score": 0.7085139012202671}} {"text": "% Author: Ricardo Baptista and Matthias Poloczek\n% Date: June 2018\n%\n% See LICENSE.md for copyright information\n%\n\nfunction ising_mom = ising_model_moments(Q)\n\nn_vars = size(Q,1);\n\n% Generate all binary vectors\nbin_vals = dec2bin(0:2^n_vars-1)-'0';\nbin_vals(bin_vals == 0) = -1;\nn_vectors = size(bin_vals,1);\n\n% Compute values of PDF\npdf_vals = zeros(n_vectors,1);\nfor i=1:n_vectors\n\tpdf_vals(i) = exp(bin_vals(i,:)*Q*bin_vals(i,:)');\nend\n\n% Compute normalizing constant\nnorm_const = sum(pdf_vals);\n\n% Generate matrix to store moments\nising_mom = zeros(n_vars,n_vars);\n\n% Compute second moment for each pair of values\nfor i=1:n_vars\n\tfor j=1:n_vars\n\t\tbin_pair = bin_vals(:,i).*bin_vals(:,j);\n\t\tising_mom(i,j) = sum(bin_pair.*pdf_vals)/norm_const;\n\tend\nend", "meta": {"author": "baptistar", "repo": "BOCS", "sha": "fef0d4e34e376e8bb0dae9955d70c2155530b9eb", "save_path": "github-repos/MATLAB/baptistar-BOCS", "path": "github-repos/MATLAB/baptistar-BOCS/BOCS-fef0d4e34e376e8bb0dae9955d70c2155530b9eb/test_problems/IsingModel/ising_model_moments.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7085138791884268}} {"text": "function [P1,P2]=mg_ellblock(nelx,nely,x,y) \n%mg_ellblock prolongation for part of L-shaped and step domains\n% [P1,P2] = mg_ellblock(nelx,nely,x,y);\n% input\n% nelx number of elements in x-direction\n% nely number of elements in y-direction\n% x x coordinate vector for coarse grid\n% y y coordinate vector for coarse grid\n% output\n% P1 component of prolongation operator for upper left of\n% step [-1,h]x[0,1]\n% P2 component of prolngation operator for border between\n% upper left of step and right part of step\n%\n% IFISS function: AR; 19 November, 2001.\n% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage\necx=nelx/2; ecy=nely/2;\ntx = x(2:nelx+1) - x(1:nelx);\nbx = zeros(nelx,1);\nbx(1:2:nelx-1) = x(3:2:nelx+1) - x(1:2:nelx-1);\nbx(2:2:nelx) = bx(1:2:nelx-1);\ndx = tx./bx;\n%\nty = y(2:nely+1) - y(1:nely);\nby = zeros(nely,1);\nby(1:2:nely-1) = y(3:2:nely+1) - y(1:2:nely-1);\nby(2:2:nely) = by(1:2:nely-1);\ndy = ty./by;\n%\np = spalloc(2*ecx+1,ecx+1,3*ecx+1);\nfor j=2:ecx\n p(2*j-2,j) = dx(2*j-3);\n p(2*j-1,j) = 1.0;\n p(2*j ,j) = dx(2*j);\nend\nj=1;\n p(2*j-1,1) = 1.0; \n p(2*j ,1) = dx(2*j);\nj=ecx+1;\n p(2*j-2,j) = dx(2*j-3);\n p(2*j-1,j) = 1.0;\n%\n% main block (last row/column omitted)\nP1=spalloc( (2*ecy+1)*(2*ecx), (ecy+1)*(ecx), (3*ecy+1)*(3*ecx+1) );\n%\nsp=p(1:end-1,1:end-1);\nfor j=2:ecy,\n cols = (j-1)*(ecx)+[1:ecx];\n P1((2*j-3)*(2*ecx)+[1:2*ecx],cols) = dy(2*j-3)*sp;\n P1((2*j-2)*(2*ecx)+[1:2*ecx],cols) = sp;\n P1((2*j-1)*(2*ecx)+[1:2*ecx],cols) = dy(2*j)*sp;\nend\nj=1;\n cols = (j-1)*(ecx)+[1:ecx];\n P1((2*j-2)*(2*ecx)+[1:2*ecx],cols) = sp;\n P1((2*j-1)*(2*ecx)+[1:2*ecx],cols) = dy(2*j)*sp;\nj=ecy+1;\n cols = (j-1)*(ecx)+[1:ecx];\n P1((2*j-3)*(2*ecx)+[1:2*ecx],cols) = dy(2*j-3)*sp;\n P1((2*j-2)*(2*ecx)+[1:2*ecx],cols) = sp;\n%\n% coupling with large block\nP2=spalloc((2*ecy+1)*(2*ecx),(ecy+1)*(ecx+1),(3*ecy+1)*(3*ecx+1) );\nentry=p(2*ecx,ecx+1);\nfor j=2:ecy,\n cols = (j-1)*(ecx+1)+1;\n P2((2*j-3)*(2*ecx)+[2*ecx],cols) = dy(2*j-3)*entry;\n P2((2*j-2)*(2*ecx)+[2*ecx],cols) = entry;\n P2((2*j-1)*(2*ecx)+[2*ecx],cols) = dy(2*j)*entry;\nend\nj=1;\n cols = (j-1)*(ecx+1)+1;\n P2((2*j-2)*(2*ecx)+[2*ecx],cols) = entry;\n P2((2*j-1)*(2*ecx)+[2*ecx],cols) = dy(2*j)*entry;\nj=ecy+1;\n cols = (j-1)*(ecx+1)+1;\n P2((2*j-3)*(2*ecx)+[2*ecx],cols) = dy(2*j-3)*entry;\n P2((2*j-2)*(2*ecx)+[2*ecx],cols) = entry;\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/solvers/mg_ellblock.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.7085138726163581}} {"text": "% This is a demonstration of Radon inversion from few angles using the Potts model.\n% Tested on Mac OS 10.9, Matlab 2015a, \n% If everything worked correctly a result as \n% in results/plFigPottsRec7Angles.fig should appear\n% Warning: This experiment can take more than one hour\n\n% load Shepp-Logan\nimg = phantom(256);\n\n% Radon transform with 7 equidistant projection angles \nnAngles = 7; \ntheta = (1:nAngles)/nAngles * 180;\nA = radonop(theta, size(img,1));\ndata = A * img;\n\n% raw filtered backprojection and a regularized one\nuFbp = iradon(data, theta, 'Linear', 'Ram-Lak', 1, size(img, 1));\nuFbpReg = iradon(data, theta, 'Linear', 'Hamming', 0.3, size(img, 1));\n\n% joint reconstruction and segmentation using the Potts model\ngamma = 0.04;\nuPotts = minL2iPotts2DADMM(data, gamma, A, 'verbose', 1, 'groundTruth', img, 'isotropic', 1 );\n\n% show results\nsubplot(2,3,1)\nimshow(img)\ntitle('Original')\nsubplot(2,3,2)\nimagesc(data)\ntitle('Data (Sinogram)')\nsubplot(2,3,4)\nimshow(uFbp)\ntitle('FBP result')\nsubplot(2,3,5)\nimshow(uFbpReg)\ntitle('FBP with Hamming window')\nsubplot(2,3,6)\nimshow(uPotts)\ntitle('Potts result')\n", "meta": {"author": "mstorath", "repo": "Pottslab", "sha": "53571378ef2f60b1104fc8dacc1d8f03427987a9", "save_path": "github-repos/MATLAB/mstorath-Pottslab", "path": "github-repos/MATLAB/mstorath-Pottslab/Pottslab-53571378ef2f60b1104fc8dacc1d8f03427987a9/Demos/2D/demoPotts2DRadon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012671214071, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.7084876406462701}} {"text": "function gbasis=groebner(polyset,ord,varnames,tol)\n% GROEBNER - calculate the reduced Groebner basis of a set of polynomials\n% usage: gbasis = groebner(polyset,ord)\n% gbasis = groebner(polyset,ord,varnames)\n% gbasis = groebner(polyset,ord,varnames,tol)\n%\n% INPUTS: polyset, ord, varnames, tol\n% polyset is a cell array of multivariate polynomial coefficients\n% the cell elements can be all strings or all arrays.\n% If the polynomials are specified with arrays, each row of the array\n% represents a single term. The first element is the coefficient and\n% the others are the degrees of each unknown in the term.\n% e.g. [-1,2,1;1,0,1] represents -x1^2*x2+x2\n% If the polynomials are specified as strings, they must use variable\n% names 'x1','x2',... (unless varnames is provided) and be valid inputs\n% for str2poly.m\n% ord is a string specifying the monomial ordering:\n% 'lex': lexicographical, order by highest power of most significant\n% indeterminate, e.g. x1>x2^2, x1*x2>x1.\n% 'grlex': graded lex, order by total degree then lex,\n% e.g. x1^2*x2 > x1*x2^2 > x1^2\n% 'grevlex': graded reverse lex, order by total degree then by lowest\n% power of least significant indeterminate, e.g. x1*x2^2 > x1*x2*x3\n% (for all cases have x1>x2>...>xn)\n% note: revlex is not a well-ordering because 1>x1>x1^2>...\n% varnames (optional) is a cell array of variable names if polyset is a\n% cell array of strings and the variable names are not 'x1', 'x2', etc.\n% If specified, there must always be at least 2 variables.\n% tol (optional) is the zero tolerance for coefficients, otherwise\n% catastrophic cancellation may occur. Default value is 0\n%\n% OUTPUTS: gbasis\n% gbasis is the reduced Groebner basis of the set of polynomials, in the\n% same format (strings or matrices) as polyset{1}.\n%\n% ALGORITHM:\n% A modified Buchberger's algorithm is used. In Buchberger's algorithm,\n% at each step calculate Sij = (Lij/ai)*Pi - (Lij/aj)*Pj, for all pairs of\n% polynomials Pi, Pj, where ai and aj are the leading terms of Pi and Pj,\n% and Lij is the least common multiple of ai and aj; then reduce Sij with\n% respect to the polynomials and add it to the set (note that Sij always \n% reduces to zero if ai and aj have no variables in common). The\n% algorithm terminates when no new polynomials can be added to the set.\n% This function reduces the polynomials at each step in order to find the\n% reduced Groebner basis.\n%\n% EXAMPLE: simplify equations x^2+2xy^2=0, xy+2y^3=1\n% A1=[1,2,0;2,1,2]; % 1*x^2*y^0 + 2*x^1*y^2\n% A2=[-1,0,0;1,1,1;2,0,3]; % -1*x^0*y^0 + 1*x^1*y^1 + 2*x^0*y^3\n% y=groebner({A1,A2},'lex');\n% poly2str(y) % returns {'x2^3-0.5', 'x1'}\n%\n% EXAMPLE: same, but with equations specified as strings:\n% groebner({'x^2+2*x*y^2','x*y+2*y^3-1'},'lex',{'x','y'})\n% % returns {'y^3-0.5','x'}\n%\n% EXAMPLE: show that a set of equations is inconsistent\n% groebner({'x + y', 'x^2 - 1', 'y^2 - 2*x'}, 'lex', {'x', 'y'})\n% % returns {'1'}\n%\n%\n% KNOWN ISSUES\n%\n% 0. GENERAL: while a significant effort has been made to ensure that the\n% program works as described, unidentified bugs may remain and the results\n% should be regarded with caution. In particular, the suite of tests\n% performed was by no means comprehensive.\n%\n% 1. ACCURACY: the algorithm by default works in floating-point which\n% ultimately cannot perform exact arithmetic, so unexpected silent errors may\n% occur even when the coefficients are specified as integers. A workaround\n% is to use other data types but this has its own issues (see below).\n%\n% 1a. EXAMPLE (roundoff - linearly independent polynomials)\n% eps % returns 2.2204e-16 (32-bit PC windows machine epsilon)\n% groebner({'x1+x2','x1+1.000000000000001*x2'},'lex') % ok, returns {'x2','x1'}\n% groebner({'x1+x2','x1+1.0000000000000001*x2'},'lex') % not ok, returns {'x2+x1'}\n%\n% 1b. EXAMPLE (roundoff - linearly dependent polynomials)\n% 2/sqrt(2)-sqrt(2) % expect 0, returns -2.2204e-016\n% poly2str(groebner({[1,1,0;sqrt(2),0,1],[1/sqrt(2),1,0;1,0,1]},'lex')) % ok, returns {'1.41421*x2+x1'}\n% poly2str(groebner({[1,1,0;sqrt(2),0,1],[sqrt(2),1,0;2,0,1]},'lex')) % not ok, returns {'x2','x1'}\n% poly2str(groebner({[1,1,0;sqrt(2),0,1],[sqrt(2),1,0;2,0,1]},'lex',{},1e-14)) % ok, returns {'1.41421*x2+x1'}\n%\n% 1c. EXAMPLE (courtesy of Christophe Lauwerys - catastrophic cancellation & tolerance bug)\n% groebner({'t^3+x+y','t^2+0.5*x^2-x-z^2','t^2+y-z^2'},'lex',{'t','x','y','z'}) % ans{1} contains Inf\n%\n% 1d. EXAMPLE (from Mathematica documentation - catastrophic cancellation because of large intermediate coefficients)\n% % expect 3 polynomials returns, one of degree 8 in z; instead can get '1'\n% groebner({'x^2 + y^2 + z^2 - 1', 'x*y - z + 2', 'z^2 - 2*x + 3*y'}, 'lex', {'x', 'y','z'})\n%\n% 2. NON-DOUBLE INPUTS: use of non-double coefficients is not supported. While\n% it may be tempting to introduce symbolic coefficients, it is not clear how\n% they should be consistently treated - for example 'A*x' could reduce to '0'\n% or 'x' or both, depending upon the assumptions on the coefficient A.\n%\n% 3. EFFICIENCY: The reduction algorithms aren't terribly efficient. One of\n% the major bottlenecks at present is the calculation of the leading term,\n% which currently involves a call to sortrows each time. It could be more\n% efficient to maintain an ordered list or even a priority queue (e.g.\n% implemented as a heap). Also lattice reduction algorithms such as LLL\n% might speed things up.\n%\n%\n% SEE ALSO:\n% poly2str, str2poly, polynsolve\n\n% Author: Ben Petschel 19/6/2009\n%\n% Change history:\n% 19/6/2009 - first release (ord='grlex' and ord='grevlex' not\n% implemented yet)\n% 22/6/2009 - implemented ord='grlex' and ord='grevlex'\n% reduction algorithm now reduces lower-order terms as well\n% 23/6/2009 - removed ord='revlex' because it is not a well-ordering\n% 17/7/2009 - fixed bug in handling polynomials with >=3 variables\n% 20/3/2010 - changed polynomial representation from multidimensional\n% arrays to 2d arrays (more memory efficient with large number of vars)\n% 11/10/2010 - bugfix for handling error tolerance\n\nif (numel(polyset)>0) && ischar(polyset{1}),\n charout = true;\n if nargin<3,\n polyset = str2poly(polyset);\n else\n polyset = str2poly(polyset,varnames);\n end;\nelse\n charout = false;\nend;\n\nif nargin<4,\n tol = 0;\nend;\n\n% determine the number of degrees\nnd=max(cellfun(@(x)size(x,2)-1,polyset)); % error if = 0\nif nd == 0\n error('number of variables must be >= 1');\nend;\n\ngbasis = fullreduce(polyset,ord,tol,nd);\noldgbasis = {};\n\nwhile ~isequal(oldgbasis,gbasis),\n oldgbasis = gbasis;\n Qset = SPoly(gbasis,ord,tol,nd);\n gbasis = fullreduce([gbasis,Qset],ord,tol,nd);\nend;\n\nif charout,\n if nargin<3,\n gbasis = poly2str(gbasis);\n else\n gbasis = poly2str(gbasis,varnames);\n end;\nend;\n\nend % main function groebner(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Qset = SPoly(Pset,ord,tol,nd)\n% calculates all reduced S-polynomials of Pset (Pset must be reduced)\n% Sij = (Lij/ai)*Pi - (Lij/aj)*Pj,\n% for all pairs of polynomials Pi, Pj, where ai and aj are the leading\n% terms of Pi and Pj, and Lij is the least common multiple of ai and aj\n% then reduces Sij wrt Pset\n\nQset = {};\nfor i=1:numel(Pset)-1,\n for j=i+1:numel(Pset),\n [c1,d1] = leadterm(Pset{i},ord,tol,nd);\n [c2,d2] = leadterm(Pset{j},ord,tol,nd);\n if any(and(d1>0,d2>0)),\n % leading terms have a variable in common, so S-poly is nontrivial\n L = max(d1,d2); % LCM of leading terms\n S = addpolys(multiplyterm(Pset{i},L-d1),multconst(multiplyterm(Pset{j},L-d2),-1));\n S = reduceset(S,Pset,ord,tol,nd);\n %if any(S(:)~=0),\n if abs(leadterm(S,ord,tol,nd))>tol\n Qset{end+1}=S; % add S to the list\n end;\n end;\n end;\nend;\n\nend % helper function SPoly(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Qset = fullreduce(Pset,ord,tol,nd)\n% reduces all polynomials wrt each other\nQset = Pset;\noldQset = {};\n\nwhile ~isequal(oldQset,Qset),\n oldQset = Qset;\n for i=1:numel(Qset)-1,\n for j=i+1:numel(Qset),\n Qset{i}=reduce(Qset{i},Qset{j},ord,tol,nd);\n Qset{j}=reduce(Qset{j},Qset{i},ord,tol,nd);\n end;\n end;\nend;\n\n% keep only the nonzero results (to within zero tolerance tol)\nQset = Qset(cellfun(@(x)abs(leadterm(x,ord,tol,nd))>tol,Qset));\n\nif numel(Qset)==1,\n % special case, a single equation can slip through without being reduced\n c = leadterm(Qset{1},ord,tol,nd);\n % coefficients occupy first column of the array\n Qset{1} = multconst(Qset{1},1/c); % know c~=0 because have already removed zero eqns\nend;\n\nend % helper function fullreduce(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Q = reduceset(P,Pset,ord,tol,nd)\n% reduces P wrt all polynomials in Pset\nQ = P;\noldQ = [];\n\nwhile ~isequal(oldQ,Q),\n oldQ = Q;\n for i=1:numel(Pset),\n Q=reduce(Q,Pset{i},ord,tol,nd);\n end;\nend;\n\nend % helper function reduceset(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Q1=reduce(P1,P2,ord,tol,nd)\n% reduces a polynomial P1 by subtracting multiples of P2 so that leading\n% term coefficient is 1 and leading term of P2 does not divide that of P1\n\nQ2=P2;\n[c2,d2] = leadterm(Q2,ord,tol,nd);\nif abs(c2)<=tol,\n % ignore terms less than tol\n keepgoing = false;\n Q1 = P1;\nelse\n keepgoing = true;\n Q2 = multconst(Q2,1/c2);\n Q1 = 0; % will successively add terms to Q\n % remove the leading terms, in order to reduce wrt lower terms\n remain = P1;\nend;\n\n\nwhile keepgoing,\n [c1,d1] = leadterm(remain,ord,tol,nd);\n if abs(c1)<=tol,\n % ignore terms less than tol\n keepgoing = false;\n else\n %reduce remain by Q2, if possible, or remove leading term\n if d1>=d2,\n % can reduce Q1 by Q2, so subtract a multiple of Q2 from Q1\n remain = addpolys(remain,multconst(multiplyterm(Q2,d1-d2),-c1));\n else\n % cannot reduce any further wrt leading term, but try lower terms\n lead = multiplyterm(c1,d1);\n remain = addpolys(remain,multconst(lead,-1));\n Q1 = addpolys(Q1,lead); % add irreducible terms to Q1\n end;\n end;\nend;\n\n% reduce leading coefficient, if possible\nc1 = leadterm(Q1,ord,tol,nd);\nif abs(c1)>tol,\n Q1 = multconst(Q1,1/c1);\nend;\n\nend % helper function reduce(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Q=multconst(P,c)\n% returns c*P where c is a constant\n\nQ = P;\nQ(:,1)=Q(:,1)*c;\n\nend % helper function multconst(...)\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction Q=addpolys(P1,P2)\n% adds two polynomials\n\ns1 = size(P1,2);\ns2 = size(P2,2);\n\nif s1>s2\n Q = [P1;P2,zeros(size(P2,1),s1-s2)];\nelse\n Q = [P1,zeros(size(P1,1),s2-s1);P2];\nend;\n\nQ = sortrows(Q,2:size(Q,2));\ni=1;\nwhile itol,1,'last');\n if isempty(ind),\n coeff = 0;\n deg = zeros(1,d-1);\n else\n coeff = P(ind,1);\n deg = P(ind,2:end);\n end;\n \nend; % if all(P(:)==0)\n\nif nd>d-1,\n deg = [deg,zeros(1,nd-d+1)];\nend;\n\nend % helper function leadterm(...)\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/24478-groebner/groebner.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7084631070659512}} {"text": "function heat_oned_test01 ( )\n\n%*****************************************************************************80\n%\n%% HEAT_ONED_TEST01 runs Jeff Borggaard's test case.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 December 2012\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HEAT_ONED_TEST01:\\n' );\n fprintf ( 1, ' Run Jeff Borggaard''s test case.\\n' );\n%\n% Set up the problem.\n%\n mu = 0.1;\n h = 100.0;\n rho = 40.0;\n degree = 2;\n xa = 0.0;\n xb = 1.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Viscosity parameter MU = %g\\n', mu );\n fprintf ( 1, ' Heat transfer coefficient H = %g\\n', h );\n fprintf ( 1, ' Mesh density RHO = %g\\n', rho );\n fprintf ( 1, ' Requesting finite elements of degree %d\\n', degree );\n fprintf ( 1, ' Spatial interval is [%g,%g].\\n', xa, xb ); \n\n [ A, B, M, n_nodes, x ] = heat_oned_setup ( mu, h, rho, degree, xa, xb );\n%\n% Compute the solution over time.\n%\n t_initial = 0.0;\n t_step = 0.001;\n t_save = 0.01;\n t_final = 5.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Initial time = %g\\n', t_initial );\n fprintf ( 1, ' Final time = %g\\n', t_final );\n fprintf ( 1, ' Time step = %g\\n', t_step );\n fprintf ( 1, ' Data save step = %g\\n', t_save );\n\n w_save = heat_oned ( A, B, M, n_nodes, x, t_initial, t_final, t_step, t_save );\n%\n% Plot the results.\n%\n t_plot = [ t_initial : t_save : t_final ];\n\n figure ( 1 )\n mesh ( t_plot, x, w_save )\n xlabel ( '<---Time--->' )\n ylabel ( '<---X--->' )\n zlabel ( '<--U(X,T)-->' )\n title ( 'U(X,T) as computed by HEAT\\_ONED' )\n\n filename = 'heat_oned_test01.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Plot saved 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/heat_oned/heat_oned_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7084631021191784}} {"text": "function [ n_data, x, fx ] = erf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% ERF_VALUES returns some values of the ERF or \"error\" function.\n%\n% Discussion:\n%\n% The error function is defined by:\n%\n% ERF(X) = ( 2 / sqrt ( PI ) * integral ( 0 <= T <= X ) exp ( - T^2 ) dT\n%\n% In Mathematica, the function can be evaluated by:\n%\n% Erf[x]\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz, 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 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 X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 21;\n\n fx_vec = [ ...\n 0.0000000000000000E+00, ...\n 0.1124629160182849E+00, ...\n 0.2227025892104785E+00, ...\n 0.3286267594591274E+00, ...\n 0.4283923550466685E+00, ...\n 0.5204998778130465E+00, ...\n 0.6038560908479259E+00, ...\n 0.6778011938374185E+00, ...\n 0.7421009647076605E+00, ...\n 0.7969082124228321E+00, ...\n 0.8427007929497149E+00, ...\n 0.8802050695740817E+00, ...\n 0.9103139782296354E+00, ...\n 0.9340079449406524E+00, ...\n 0.9522851197626488E+00, ...\n 0.9661051464753107E+00, ...\n 0.9763483833446440E+00, ...\n 0.9837904585907746E+00, ...\n 0.9890905016357307E+00, ...\n 0.9927904292352575E+00, ...\n 0.9953222650189527E+00 ]; \n\n x_vec = [ ...\n 0.0E+00, ... \n 0.1E+00, ... \n 0.2E+00, ... \n 0.3E+00, ... \n 0.4E+00, ... \n 0.5E+00, ... \n 0.6E+00, ... \n 0.7E+00, ... \n 0.8E+00, ... \n 0.9E+00, ... \n 1.0E+00, ... \n 1.1E+00, ... \n 1.2E+00, ... \n 1.3E+00, ... \n 1.4E+00, ... \n 1.5E+00, ... \n 1.6E+00, ... \n 1.7E+00, ... \n 1.8E+00, ... \n 1.9E+00, ... \n 2.0E+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 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/erf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7084630922256325}} {"text": "function [kx, ky] = gradientKernels(sigma)\n% Create kernels for computing gradient within 2D images.\n%\n% KX = gradientKernels(SIGMA)\n% [KX, KY] = gradientKernels(SIGMA)\n% Generates the gradient kernel(s) used for computing gradients within 2D\n% images.\n% This is a low-level function that is called by the functions that\n% compute gradients.\n% \n%\n% Example\n% [kx, ky] = gradientKernels(2);\n%\n% See also\n% imGradient, imGradientFilter, orientedGaussianKernel\n%\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% INRAE - BIA Research Unit - BIBS Platform (Nantes)\n% Created: 2022-06-01, using Matlab 9.9.0.1570001 (R2020b) Update 4\n% Copyright 2022 INRAE.\n\nif nargin == 0 || sigma == 0\n % Default case: normalised sobel matrix\n kx = fspecial('sobel')' / 8;\n \nelse\n % compute size according to sigma\n Nx = ceil((3*sigma));\n lx = -Nx:Nx;\n ky = exp(-((lx / sigma) .^2) * .5);\n kx = -(lx / sigma) .* ky;\n kx = ky' * kx;\n kx = kx / sum(kx(kx > 0));\nend\n\n% optional kernel for gradient in Y-direction\nif nargout > 1\n ky = kx';\nend\n", "meta": {"author": "mattools", "repo": "matImage", "sha": "94d892c7beac0db32daadf2646ce37f58e894caf", "save_path": "github-repos/MATLAB/mattools-matImage", "path": "github-repos/MATLAB/mattools-matImage/matImage-94d892c7beac0db32daadf2646ce37f58e894caf/matImage/imFilters/gradientKernels.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7084457816026811}} {"text": "function [x, c, funVal, ValueL]=LogisticR(A, y, z, opts)\n%\n%%\n% Function LogisticR\n% Logistic Loss with the L1-norm Regularization\n%\n%% Problem\n%\n% min f(x,c) = - weight_i * log (p_i) + 1/2 rsL2 * ||x||_2^2\n% + z * \\|x\\|_1\n%\n% By default, rsL2=0.\n%\n% a_i denotes a training sample,\n% and a_i' corresponds to the i-th row of the data matrix A\n%\n% y_i (either 1 or -1) is the response\n%\n% p_i= 1/ (1+ exp(-y_i (x' * a_i + c) ) ) denotes the probability\n%\n% weight_i denotes the weight for the i-th sample\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 - Lq/L1 norm regularization parameter (z >=0)\n% opts- Optional inputs (default value: opts=[])\n%\n%% Output parameters:\n% x- The obtained weight of size n x 1\n% c- The obtained intercept (scalar)\n% funVal- Function value during iterations\n%\n%% Copyright (C) 2009-2010 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 February 18, 2010.\n%\n%% Related papers\n%\n% [1] Jun Liu, Jianhui Chen, and Jieping Ye, Large-Scale Sparse Logistic\n% Regression, KDD09\n%\n% [2] Jun Liu and Jieping Ye, Efficient Euclidean Projections\n% in Linear Time, ICML 2009.\n%\n%% Related functions\n%\n% sll_opts, initFactor, pathSolutionLeast\n% LogisticC, nnLogisticR, nnLogisticC\n%\n%%\n\n%% Verify and initialize the parameters\n%%\nif (nargin <3)\n error('\\n Inputs: A, y, and z 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<=0)\n error('\\n z should be positive!\\n');\nend\n\nopts=sll_opts(opts); % run sll_opts to set default values (flags)\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% The parameter 'weight' contains the weight for each training sample.\n% See the definition of the problem above.\n% The summation of the weights for all the samples equals to 1.\nif (isfield(opts,'sWeight'))\n sWeight=opts.sWeight;\n\n if ( length(sWeight)~=2 || sWeight(1) <=0 || sWeight(2) <= 0)\n error('\\n Check opts.sWeight, which contains two positive values');\n end\n\n % we process the weight, so that the summation of the weights for all\n % the samples is 1.\n\n p_flag=(y==1); % the indices of the postive samples\n m1=sum(p_flag) * sWeight(1); % the total weight for the positive samples\n m2=sum(~p_flag) * sWeight(2); % the total weight for the positive samples\n\n weight(p_flag,1)=sWeight(1)/(m1+m2);\n weight(~p_flag,1)=sWeight(2)/(m1+m2);\nelse\n weight=ones(m,1)/m; % if not specified, we apply equal weight\nend\n\n%% Starting point initialization\n\n% process the regularization parameter\n\n% L2 norm regularization\nif isfield(opts,'rsL2')\n rsL2=opts.rsL2;\n if (rsL2<0)\n error('\\n opts.rsL2 should be nonnegative!');\n end\nelse\n rsL2=0;\nend\n\np_flag=(y==1); % the indices of the postive samples\nm1=sum(weight(p_flag)); % the total weight for the positive samples\nm2=1-m1; % the total weight for the positive samples\n\n% L1 norm regularization\nif (opts.rFlag==0)\n lambda=z;\nelse % z here is the scaling factor lying in [0,1]\n if (z<0 || z>1)\n error('\\n opts.rFlag=1, and z should be in [0,1]');\n end\n\n % we compute ATb for computing lambda_max, when the input z is a ratio\n\n b(p_flag,1)=m2; b(~p_flag,1)=-m1;\n b=b.*weight;\n\n % compute AT b\n if (opts.nFlag==0)\n ATb =A'*b;\n elseif (opts.nFlag==1)\n ATb= A'*b - sum(b) * mu'; ATb=ATb./nu;\n else\n invNu=b./nu; ATb=A'*invNu-sum(invNu)*mu';\n end\n\n lambda_max=max(abs(ATb));\n lambda=z*lambda_max;\n\n rsL2=rsL2*lambda_max; % the input rsL2 is a ratio of lambda_max\nend\n\n% initialize a starting point\nif opts.init==2\n x=zeros(n,1); c=log(m1/m2);\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=zeros(n,1);\n end\n\n if isfield(opts,'c0')\n c=opts.c0;\n else\n c=log(m1/m2);\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\n%% The main program\n\n%% The Armijo Goldstein line search scheme + accelearted gradient descent\n\nif (opts.mFlag==0 && opts.lFlag==0)\n\n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1/m + rsL2; % the intial guess of the Lipschitz continuous gradient\n\n weighty=weight.*y;\n % the product between weight and y\n\n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,1);\n cp=c; ccp=0;\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; sc=c + beta* ccp;\n\n % --------------------------- step 2 ---------------------------\n % line search for L and compute the new approximate solution x\n\n % compute As=A*s\n As=Ax + beta* (Ax-Axp);\n\n % aa= - diag(y) * (A * s + sc)\n aa=- y.*(As+ sc);\n\n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_s= weight' * ( log( exp(-bb) + exp(aa-bb) ) + bb )+...\n rsL2/2 * s'*s;\n\n % compute prob=[p_1;p_2;...;p_m]\n prob=1./( 1+ exp(aa) );\n\n % b= - diag(y.* weight) * (1 - prob)\n b= -weighty.*(1-prob);\n\n gc=sum(b); % the gradient of c\n\n % compute g= AT b, the gradient of x\n if (opts.nFlag==0)\n g=A'*b;\n elseif (opts.nFlag==1)\n g=A'*b - sum(b) * mu'; g=g./nu;\n else\n invNu=b./nu; g=A'*invNu-sum(invNu)*mu';\n end\n\n g=g+ rsL2 * s; % add the squared L2 norm regularization term\n\n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n cp=c;\n\n while (1)\n % let s walk in a step in the antigradient of s to get v\n % and then do the Lq/L1-norm regularized projection\n v=s-g/L; c= sc- gc/L;\n\n % L1-norm regularized projection\n x=sign(v).*max(abs(v)-lambda / L,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 % aa= - diag(y) * (A * x + c)\n aa=- y.*(Ax+ c);\n\n % fun_x is the logistic loss at the new approximate solution\n bb=max(aa,0);\n fun_x= weight'* ( log( exp(-bb) + exp(aa-bb) ) + bb ) +...\n rsL2/2 * x'*x;\n\n r_sum= (v'*v + (c-sc)^2) / 2;\n l_sum=fun_x - fun_s - v'* g - (c-sc)* gc;\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 fun_x <= fun_s + v'* g + c * gc\n % + L/2 * (v'*v + (c-sc)^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=%e, r_sum=%e',L, r_sum);\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 ValueL(iterStep)=L;\n % store values for L\n \n xxp=x-xp; ccp=c-cp;\n funVal(iterStep)=fun_x + lambda* sum(abs(x));\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 end\nend\n\n\n%% Reformulated problem + Nemirovski's line search scheme\n\n% Original problem: min f(x,c) = - weight_i * log (p_i) + 1/2 rsL2 * ||x||_2^2\n% + z * \\|x\\|_1\n%\n% Reformulated problem: min f(x,c) = - weight_i * log (p_i) + 1/2 rsL2 * ||x||_2^2\n% + z * 1^T t\n% s.t., |x| <=t\n\nif (opts.mFlag==1 && opts.lFlag==0)\n\n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1/m + rsL2; % the intial guess of the Lipschitz continuous gradient\n\n weighty=weight.*y;\n % the product between weight and y\n\n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,1);\n cp=c; ccp=0;\n\n t=abs(x); tp=t;\n % t is the upper bound of absolute value of x\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; sc=c + beta* ccp; s_t= t + beta * (t -tp);\n\n % --------------------------- step 2 ---------------------------\n % line search for L and compute the new approximate solution x\n\n % compute As=A*s\n As=Ax + beta* (Ax-Axp);\n\n % aa= - diag(y) * (A * s + sc)\n aa=- y.*(As+ sc);\n\n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_s= weight' * ( log( exp(-bb) + exp(aa-bb) ) + bb )+...\n rsL2/2 * s'*s;\n\n % compute prob=[p_1;p_2;...;p_m]\n prob=1./( 1+ exp(aa) );\n\n % b= - diag(y.* weight) * (1 - prob)\n b= -weighty.*(1-prob);\n\n gc=sum(b); % the gradient of c\n\n % compute g= AT b, the gradient of x\n if (opts.nFlag==0)\n g=A'*b;\n elseif (opts.nFlag==1)\n g=A'*b - sum(b) * mu'; g=g./nu;\n else\n invNu=b./nu; g=A'*invNu-sum(invNu)*mu';\n end\n\n g=g+ rsL2 * s; % add the squared L2 norm regularization term\n\n % copy x and Ax to xp and Axp\n xp=x; Axp=Ax;\n cp=c; tp=t;\n\n while (1)\n % let s walk in a step in the antigradient of s to get v\n % and then do the Lq/L1-norm regularized projection\n c= sc- gc/L;\n u=s-g/L;\n v= s_t - lambda / L;\n\n % projection\n [x, t]=ep1R(u,v,n);\n\n v=x-s; % the difference between the new approximate solution x\n % and the search point s\n v_t=t-s_t;\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 % aa= - diag(y) * (A * x + c)\n aa=- y.*(Ax+ c);\n\n % fun_x is the logistic loss at the new approximate solution\n bb=max(aa,0);\n fun_x= weight'* ( log( exp(-bb) + exp(aa-bb) ) + bb ) +...\n rsL2/2 * x'*x;\n\n r_sum= (v'*v + (c-sc)^2 + v_t'*v_t) / 2;\n l_sum=fun_x - fun_s - v'* g - (c-sc)* gc;\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 fun_x <= fun_s + v'* g + c * gc\n % + L/2 * (v'*v + (c-sc)^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=%e, r_sum=%e',L, r_sum);\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 ValueL(iterStep)=L;\n % store values for L\n \n xxp=x-xp; ccp=c-cp;\n funVal(iterStep)=fun_x + lambda* sum(t);\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 + norm(t-tp)^2 + (c-cp)^2);\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=sqrt(xp'*xp + cp^2 + tp'*tp); norm_xxp=sqrt(xxp'*xxp + norm(t-tp)^2 + (c-cp)^2);\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 end\nend\n\n\n%% Reformulated problem + adaptive line search scheme\n\n% Original problem: min f(x,c) = - weight_i * log (p_i) + 1/2 rsL2 * ||x||_2^2\n% + z * \\|x\\|_1\n%\n% Reformulated problem: min f(x,c) = - weight_i * log (p_i) + 1/2 rsL2 * ||x||_2^2\n% + z * 1^T t\n% s.t., |x| <=t\n\nif (opts.mFlag==1 && opts.lFlag==1)\n\n bFlag=0; % this flag tests whether the gradient step only changes a little\n\n L=1/m + rsL2; % the intial guess of the Lipschitz continuous gradient\n\n weighty=weight.*y;\n % the product between weight and y\n\n gamma=1;\n % we shall set the value of gamma = L,\n % and L is appropriate for the starting point\n\n % assign xp with x, and Axp with Ax\n xp=x; Axp=Ax; xxp=zeros(n,1);\n cp=c; ccp=0;\n t=abs(x); tp=t;\n % t is the upper bound of absolute value of x\n\n for iterStep=1:opts.maxIter\n while (1)\n if (iterStep~=1)\n alpha= (-gamma+ sqrt(gamma*gamma + 4* L * gamma)) / (2*L);\n beta= (gamma - gamma* alphap) / (alphap * gamma + alphap* L * alpha);\n % beta is the coefficient for generating search point s\n\n s=x + beta* xxp; s_t= t + beta * (t -tp); sc=c + beta* ccp;\n As=Ax + beta* (Ax-Axp);\n else\n alpha= (-1+ sqrt(5)) / 2; beta=0;\n s=x; s_t=t; sc= c;\n As=Ax;\n end\n\n % aa= - diag(y) * (A * s + sc)\n aa=- y.*(As+ sc);\n\n % fun_s is the logistic loss at the search point\n bb=max(aa,0);\n fun_s= weight' * ( log( exp(-bb) + exp(aa-bb) ) + bb )+...\n rsL2/2 * s'*s;\n\n % compute prob=[p_1;p_2;...;p_m]\n prob=1./( 1+ exp(aa) );\n\n % b= - diag(y.* weight) * (1 - prob)\n b= -weighty.*(1-prob);\n\n gc=sum(b); % the gradient of c\n\n % compute g= AT b, the gradient of x\n if (opts.nFlag==0)\n g=A'*b;\n elseif (opts.nFlag==1)\n g=A'*b - sum(b) * mu'; g=g./nu;\n else\n invNu=b./nu; g=A'*invNu-sum(invNu)*mu';\n end\n\n g=g+ rsL2 * s; % add the squared L2 norm regularization term\n\n % let s walk in a step in the antigradient of s to get v\n % and then do the Lq/L1-norm regularized projection\n cnew= sc- gc/L; \n u=s-g/L; \n v= s_t - lambda / L;\n\n % projection\n [xnew, tnew]=ep1R(u,v,n);\n\n v=xnew-s; % the difference between the new approximate solution x\n % and the search point s\n v_t=tnew-s_t;\n\n % compute A xnew\n if (opts.nFlag==0)\n Axnew=A* xnew;\n elseif (opts.nFlag==1)\n invNu=xnew./nu; mu_invNu=mu * invNu;\n Axnew=A*invNu -repmat(mu_invNu, m, 1);\n else\n Axnew=A*xnew-repmat(mu*xnew, m, 1); Axnew=Axnew./nu;\n end\n\n % aa= - diag(y) * (A * x + c)\n aa=- y.*(Axnew+ cnew);\n\n % fun_x is the logistic loss at the new approximate solution\n bb=max(aa,0);\n fun_x= weight'* ( log( exp(-bb) + exp(aa-bb) ) + bb ) +...\n rsL2/2 * xnew'*xnew;\n\n r_sum= (v'*v + (cnew-sc)^2 + v_t'*v_t) / 2;\n l_sum=fun_x - fun_s - v'* g - (cnew-sc)* gc;\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 fun_x <= fun_s + v'* g + c * gc\n % + L/2 * (v'*v + (c-sc)^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=%e, r_sum=%e',L, r_sum);\n end\n end\n\n gamma=L* alpha* alpha; alphap=alpha;\n % update gamma, and alphap\n\n ValueL(iterStep)=L;\n % store values for L\n\n tao=L * r_sum / l_sum;\n if (tao >=5)\n L=L*0.8;\n end\n % decrease the value of L\n\n xp=x; x=xnew; xxp=x-xp;\n Axp=Ax; Ax=Axnew;\n tp=t; t=tnew; \n cp=c; c=cnew; ccp=c-cp;\n % update x, t, c, and Ax\n\n funVal(iterStep)=fun_x + lambda* sum(t);\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 + norm(t-tp)^2 + (c-cp)^2);\n if ( norm_xxp <=opts.tol)\n break;\n end\n case 4\n norm_xp=sqrt(xp'*xp + cp^2 + tp'*tp); norm_xxp=sqrt(xxp'*xxp + norm(t-tp)^2 + (c-cp)^2);\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 end\nend\n\n%%\nif(opts.mFlag==0 && opts.lFlag==1)\n error('\\n The function does not support opts.mFlag=0 & opts.lFlag=1!');\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/L1/L1R/LogisticR.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7084457799082201}} {"text": "function [x,err,it] = perform_conjugate_gradient(A,y,options)\n\n\n% perform_conjugate_gradient - perform (bi)-conjugate gradient\n%\n% [x,err,k] = perform_conjugate_gradient(A,y,options);\n%\n% Solves for A*x=y.\n% Works both for vector x,y and matrix x,y (parralel soving of many\n% linear equations).\n%\n% Important: the algorithm assumes that the matrix is symmetric definite\n% positive. If it is not the case, then you must set options.is_sdp=0,\n% and the algorithm will use a bi-conjugate gradient descent (x2 slower).\n%\n% A can be a matrix or a callback function y=A(x,options).\n% In this case, you have to set options.ncols as the number of columns of\n% A (if it is a callback).\n% In the non-symmetric case, then options.transpose=1 for the computation\n% of A*x and options.transpose=-1 for the computation of A'*x.\n%\n% err monitors the decreasing of |A*x-y|.\n% k is the total number of iterations.\n%\n% You can set:\n% options.x is an initial guess\n% options.epsilon is maximum error\n% options.niter_max is maximum number of iterations\n%\n% Copyright (c) 2007 Gabriel Peyre\n\noptions.null = 0;\nniter = getoptions(options, 'niter_max', 100);\nepsilon = getoptions(options, 'epsilon', 1e-5);\nis_sdp = getoptions(options, 'is_sdp', 1);\n\nuse_callback = 0;\nif not(isnumeric(A))\n use_callback = 1;\nend\nif isfield(options, 'x')\n x = options.x;\nelse\n if use_callback==0\n x = zeros(size(A,2),1);\n else\n if isfield(options, 'ncols')\n x = zeros(options.ncols, 1);\n else\n error('You have to specify options.ncols');\n end\n end\nend\n\n\nif norm(y(:), 'fro') == 0\n normb = epsilon;\nelse\n normb = epsilon; % * sum(y(:).^2);\nend\n\nif use_callback==0\n r = y - A*x;\nelse\n options.transpose = 1;\n r = y - feval(A,x,options); \nend\np = r;\nif is_sdp==0\n rr = r;\n pp = p;\nend\nr0 = sum(r(:).^2);\n\n\nerr = [sum(r0)];\nfor it=1:niter\n \n % auxiliary vector\n if use_callback==0\n w = A*p;\n else\n options.transpose = 1;\n % options.transpose = -1;\n w = feval(A,p,options);\n end\n \n if is_sdp==1\n d = sum(p(:) .* w(:));\n else\n d = sum(pp(:) .* w(:));\n end\n I = find(abs(d): Minor edits\n\n%compatibility with tiffread\nif ( isfield( im, 'data') )\n filename = im.filename;\n im = im(1).data;\nelse\n filename = inputname(1);\nend\n\n% add a plot:\nif nargin < 2\n make_plot = 0;\nend\n\n\nh = image_histogram( im );\n%remove under-exposed pixels, where there might be a peak:\nh(1) = 0;\n\n\n%% calculate a Gaussian filter:\n\nfilt_sig = 20;\nfilt = exp( -( (-2*filt_sig:2*filt_sig) / filt_sig ) .^ 2 );\nfilt = filt ./ sum( filt );\n\n% convolve by the filter to get a smooth profile:\n\nhs = double( conv( h, filt ) );\n\n%crop to the same size as h\nhs = hs( 2*filt_sig+(1:numel(h)) );\n\n\n%% find the maximum in the smoothed histogram\n\n%[ hsmax, upper ] = max(hs);\n\n% iteratively search for the first maximum\n%back = 1;\n%while back < upper && hs(back+1) >= hs(back)\n% back = back + 1;\n%end\n\n[ hsmax, back ] = max(hs);\nupper = back;\n\nif sum( h(1:back) ) < numel(im) / 5\n fprintf([' Background detection might have failed for ', filename, '\\n']);\nend\n\n\n%% Make a figure to debug things\nif make_plot\n \n x = (0:size(h)-1)';\n figure('Name','image_background', 'Position', [100 150 800 300]);\n axes('Position', [0.05 0.1 0.9 0.8] );\n hold on;\n xlim([0 size(h,1)]);\n set(gca, 'ytick', [])\n \n plot(x, h, 'g.' );\n plot(x, hs, 'k:', 'linewidth', 1);\n \n plot([back, back], ylim, 'b-', 'linewidth', 2);\n plot([upper, upper], ylim, 'k:');\n \n text(back, hsmax, sprintf(' %i', back), 'FontSize', 18 );\n title('Histogram of pixel values');\n\nend\n\n\n\n%% Gaussian fit of the distribution of dark pixels\n\n function f = gauss(x, a)\n f = exp( -(x-a(1)).^2 / a(2) );\n end\n\n function err = gauss_err(a)\n f = gauss(rx, a);\n s = sum(ry.*f) / sum(f.*f);\n err = sum( abs(f*s-ry) ); %robust fitting\n %err = norm( f*s-ry ); %least-square fitting\n end\n\nif nargout > 1\n \n % Gaussian fit to obtain the variance of the black pixel values\n \n rwd = fix(back*0.8);\n ri = max(back-rwd, 1) : min(back+rwd, length(hs));\n rh = h(ri);\n \n rx = (ri-1)';\n ry = rh / sum(rh);\n esp = sum(rx.*ry);\n var = sum(rx.*rx.*ry);\n sigma = sqrt(var-esp*esp);\n \n if nargin > 1\n fprintf('Histogram : mean %.2f, sigma %.2f\\n', back, sigma);\n end\n\n [ pamG, pval, flag ] = fminsearch(@gauss_err, [ esp, 2*(var-esp*esp) ]);\n \n %if the fit is successful, we change our estimate of sigma:\n if flag == 1\n f = gauss(rx, pamG);\n fitG = f * ( sum(rh) * sum(ry.*f) / sum(f.*f) );\n\n backG = pamG(1);\n sigma = sqrt(pamG(2)/2);\n\n if nargin > 1\n fprintf('Gauss fit: mean %.2f, sigma %.2f\\n', backG, sigma);\n end\n end\n \n if make_plot\n %make an inset figure:\n axes('Position', [0.5 0.25 0.4 0.62]);\n plot( rx, h(1+rx), 'g.');\n hold on;\n plot( rx, hs(1+rx), 'b--');\n if exist('fitG', 'var')\n plot( rx, fitG, 'k-');\n end\n plot([back, back], ylim, 'k-');\n if exist('sigma', 'var')\n w = sqrt(2) * sigma;\n plot([back-w, back-w], ylim, 'k:');\n plot([back+w, back+w], ylim, 'k:');\n end\n end\nend\n\n\n%% Gamma fit (could be appropriate for low photon counts)\n \n\n function g = gamma_dis(x, a)\n %a is of dimension 2: a = { k, theta }\n %gamma density function\n g = exp( (a(1)-1)*log(x) - x/a(2) - a(1)*log(a(2)) ) / gamma(a(1));\n end\n\n function err = gamma_err(a)\n f = gamma_dis(rx, a);\n s = sum(ry.*f) / sum(f.*f);\n err = sum( abs(f*s-ry) ); %robust fitting\n %err = norm( f*s-ry ); %least-square fitting\n end\n\nif nargout > 1\n \n [ pamP, pval, flag ] = fminsearch(@gamma_err, [ 5, esp/5 ]);\n \n if flag == 1\n\n f = gamma_dis(rx, pamP);\n fitP = f * ( sum(rh) * sum(ry.*f) / sum(f.*f) );\n \n %backP = pamP(1) * pamP(2); %mean-value\n sigmaP = sqrt(pamP(1)) * pamP(2); %sigma\n [v, id] = max(f);\n backP = rx(id); %position of peak\n\n if nargin > 1\n fprintf('Gamma fit: mean %.2f, sigma %.2f\\n', backP, sigmaP);\n end\n \n if make_plot\n plot( rx, fitP, 'r-');\n end\n\n end\n \nend\n\n\n\n%% Poisson fit\n\n function p = poisson(x, a)\n n = x ./ a(2);\n % discrete poisson distribution over n,\n p = exp( n .* ( 1 - log( n ./ a(1) ) ) + 0.5*log(n) );\n end\n\n function err = poisson_err(a)\n f = poisson(rx, a);\n s = sum(ry.*f) / sum(f.*f);\n err = sum( abs(f*s-ry) ); %robust fitting\n %err = norm( f*s-ry ); %least-square fitting\n end\n\nif nargout > 1\n\n [ pamS, pval, flag ] = fminsearch(@poisson_err, [ esp / 10, 10 ]);\n\n \n if flag == 1\n \n grain = pamS(2);\n backS = pamS(2) * pamS(1); %mean\n sigmaS = pamS(2) * sqrt(pamS(1));\n \n f = poisson(rx, pamS);\n fitS = f * ( sum(rh) * sum(ry.*f) / sum(f.*f) );\n\n if nargin > 1\n fprintf('Poisson fit: mean %.2f, sigma %.2f, grain %.2f\\n', backS, sigmaS, grain);\n end\n \n if make_plot\n plot( rx, fitS, 'b-');\n end\n\n end\n\nend\n\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/TiffreadToolbox/image_background.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8104788995148792, "lm_q1q2_score": 0.7084211503303172}} {"text": "function [s, lam] = shcovft(x, shrinkvar)\n% Shrinkage estimate of a covariance matrix, using optimal shrinkage coefficient.\n% INPUT:\n% x is n*p data matrix\n% shrinkvar :\n% 0: corshrink (default)\n% 1: varshrink\n%\n% OUTPUT:\n% s is the posdef p*p cov matrix\n% lam is the shrinkage coefficient\n%\n% See J. Schaefer and K. Strimmer. 2005. A shrinkage approach to\n% large-scale covariance matrix estimation and implications\n% for functional genomics. Statist. Appl. Genet. Mol. Biol. 4:32.\n% This code is based on their original code http://strimmerlab.org/software.html\n% but has been vectorized and simplified by Kevin Murphy.\n% Adapted by Marcel van Gerven\n\nif nargin < 2, shrinkvar = 0; end\n\n[n p] = size(x);\nif p==1, s=var(x); return; end\n\nswitch num2str(shrinkvar)\n\n case '1' % Eqns 10 and 11 of Opgen-Rhein and Strimmer (2007)\n [v, lam] = varshrink(x);\n dsv = diag(sqrt(v));\n r = corshrink(x);\n s = dsv*r*dsv;\n\n otherwise % case 'D' of Schafer and Strimmer\n v = var(x);\n dsv = diag(sqrt(v));\n [r, lam] = corshrink(x);\n s = dsv*r*dsv;\n\nend\n\n%%%%%%%%\n\nfunction [sv, lambda] = varshrink (x)\n% Eqns 10 and 11 of Opgen-Rhein and Strimmer (2007)\n[v, vv] = varcov(x);\nv = diag(v); vv = diag(vv);\nvtarget = median(v);\nnumerator = sum(vv);\ndenominator = sum((v-vtarget).^2);\nlambda = numerator/denominator;\nlambda = min(lambda, 1); lambda = max(lambda, 0);\nsv = (1-lambda)*v + lambda*vtarget;\n\nfunction [Rhat, lambda] = corshrink(x)\n% Eqn on p4 of Schafer and Strimmer 2005\n[n, p] = size(x);\nsx = makeMeanZero(x); sx = makeStdOne(sx); % convert S to R\n[r, vr] = varcov(sx);\noffdiagsumrij2 = sum(sum(tril(r,-1).^2));\noffdiagsumvrij = sum(sum(tril(vr,-1)));\nlambda = offdiagsumvrij/offdiagsumrij2;\nlambda = min(lambda, 1); lambda = max(lambda, 0);\nRhat = (1-lambda)*r;\nRhat(logical(eye(p))) = 1;\n\nfunction [S, VS] = varcov(x)\n% s(i,j) = cov X(i,j)\n% vs(i,j) = est var s(i,j)\n[n,p] = size(x);\nxc = makeMeanZero(x);\nS = cov(xc);\nXC1 = repmat(reshape(xc', [p 1 n]), [1 p 1]); % size p*p*n !\nXC2 = repmat(reshape(xc', [1 p n]), [p 1 1]); % size p*p*n !\nVS = var(XC1 .* XC2, 0, 3) * n/((n-1)^2);\n\nfunction xc = makeMeanZero(x)\n% make column means zero\n[n,p] = size(x);\nm = mean(x);\nxc = x - ones(n, 1)*m;\n\nfunction xc = makeStdOne(x)\n% make column variances one\n[n,p] = size(x);\nsd = ones(n, 1)*std(x);\nxc = x ./ sd;", "meta": {"author": "alexandrebarachant", "repo": "covariancetoolbox", "sha": "f1c088566eda2b2b63857b6563d7be5525ea4768", "save_path": "github-repos/MATLAB/alexandrebarachant-covariancetoolbox", "path": "github-repos/MATLAB/alexandrebarachant-covariancetoolbox/covariancetoolbox-f1c088566eda2b2b63857b6563d7be5525ea4768/lib/estimation/shcovft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.795658104908603, "lm_q1q2_score": 0.7083698237153422}} {"text": "function idx = findClosestCentroids(X, centroids)\n%FINDCLOSESTCENTROIDS computes the centroid memberships for every example\n% idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids\n% in idx for a dataset X where each row is a single example. idx = m x 1 \n% vector of centroid assignments (i.e. each entry in range [1..K])\n%\n\n% Set K\nK = size(centroids, 1);\n\n% You need to return the following variables correctly.\nidx = zeros(size(X,1), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Go over every example, find its closest centroid, and store\n% the index inside idx at the appropriate location.\n% Concretely, idx(i) should contain the index of the centroid\n% closest to example i. Hence, it should be a value in the \n% range 1..K\n%\n% Note: You can use a for-loop over the examples to compute this.\n%\nm = size(X,1);\nfor i = 1:m,\n minDistance = 10^6; % randomly chosen large enough value \n for j = 1:K,\n distance = sum((X(i,:) - centroids(j,:)).^2);\n if distance < minDistance,\n minDistance = distance;\n idx(i) = j;\n end\n end\nend \n\n% =============================================================\n\nend\n\n", "meta": {"author": "anirudhjayaraman", "repo": "Machine-Learning", "sha": "084e9c67ac3853f78461f9d0e46c7b41364da481", "save_path": "github-repos/MATLAB/anirudhjayaraman-Machine-Learning", "path": "github-repos/MATLAB/anirudhjayaraman-Machine-Learning/Machine-Learning-084e9c67ac3853f78461f9d0e46c7b41364da481/Andrew Ng Stanford Coursera/Week 08/ex7/findClosestCentroids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.8902942377652497, "lm_q1q2_score": 0.7083698217174726}} {"text": "function A = matrix(k, n)\n%MATRIX Test matrices accessed by number.\n% MATRIX(K, N) is the N-by-N instance of matrix number K in\n% a set of test matrices comprising those in MATLAB plus those\n% in the Matrix Computation Toolbox,\n% with all other parameters set to their default.\n% N.B. - Only those matrices which are full and take an arbitrary\n% dimension N are included.\n% - Some of these matrices are random.\n% MATRIX(K) is a string containing the name of the K'th matrix.\n% MATRIX(0) is the number of matrices, i.e. the upper limit for K.\n% Thus to set A to each N-by-N test matrix in turn use a loop like\n% for k=1:matrix(0)\n% A = matrix(k, N);\n% Aname = matrix(k); % The name of the matrix\n% end\n% MATRIX(-1) returns the version number and date of the\n% Matrix Computation Toolbox.\n% MATRIX with no arguments lists the names and numbers of the M-files in the\n% collection.\n\n% References:\n% N. J. Higham, Accuracy and Stability of Numerical Algorithms,\n% Second edition, Society for Industrial and Applied Mathematics,\n% Philadelphia, PA, 2002; sec. 20.5.\n\n% Matrices from gallery:\nmatrices = [%\n'cauchy '; 'chebspec'; 'chebvand'; 'chow ';\n'circul '; 'clement '; 'condex ';\n'cycol '; 'dramadah'; 'fiedler ';\n'forsythe'; 'frank '; 'gearmat '; 'grcar ';\n'invhess '; 'invol '; 'ipjfact '; 'jordbloc';\n'kahan '; 'kms '; 'krylov '; 'lehmer ';\n'lesp '; 'lotkin '; 'minij '; 'moler ';\n'orthog '; 'parter '; 'pei '; 'prolate ';\n'randcolu'; 'randcorr'; 'rando '; 'randsvd ';\n'redheff '; 'riemann '; 'ris '; 'smoke ';\n'toeppd '; 'triw ';];\nn_gall = length(matrices);\n\n% Other MATLAB matrices:\nmatrices = [matrices;\n'hilb '; 'invhilb '; 'magic '; 'pascal ';\n'rand '; 'randn ';];\nn_MATLAB = length(matrices);\n\n% Matrices from Matrix Computation Toolbox:\nmatrices = [matrices;\n'augment '; 'gfpp '; 'magic '; 'makejcf ';\n'rschur '; 'vand '];\nn_mats = length(matrices);\n\nif nargin == 0\n\n rows = ceil(n_mats/5);\n temp = zeros(rows,5);\n temp(1:n_mats) = 1:n_mats;\n\n for i = 1:rows\n for j = 1:5\n if temp(i,j) == 0, continue, end\n fprintf(['%2.0f: ' sprintf('%s',matrices(temp(i,j),:)) ' '], ...\n temp(i,j))\n end\n fprintf('\\n')\n end\n fprintf('Matrices 1 to %1.0f are from MATLAB\\.', n_MATLAB)\n\nelseif nargin == 1\n if k == 0\n A = length(matrices);\n elseif k > 0\n A = deblank(matrices(k,:));\n else\n % Version number and date of collection.\n A = 'Version 1.2, September 5 2002';\n end\nelse\n if k <= n_gall\n A = eval( ['gallery(''' deblank(matrices(k,:)) ''',n)'] );\n else\n A = eval( [deblank(matrices(k,:)) '(n)'] );\n end\nend\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/matrixcomp/matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8221891392358015, "lm_q1q2_score": 0.7083473529848902}} {"text": "function [ x, dp2, p1 ] = jacobi_ss_root ( x, n, alpha, beta, b, c )\n\n%*****************************************************************************80\n%\n%% JACOBI_SS_ROOT improves an approximate root of a Jacobi polynomial.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 October 2005\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 approximate root.\n%\n% Input, integer N, the order of the polynomial to be computed.\n%\n% Input, real ALPHA, BETA, the exponents of (1-X) and\n% (1+X) in the quadrature rule.\n%\n% Input, real B(N), C(N), the recursion coefficients.\n%\n% Output, real X, the improved approximate root.\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 maxstep = 10;\n\n for i = 1 : maxstep\n\n [ p2, dp2, p1 ] = jacobi_ss_recur ( x, n, alpha, beta, b, c );\n\n d = p2 / dp2;\n x = x - d;\n\n if ( abs ( d ) <= eps * ( abs ( x ) + 1.0 ) )\n return\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/jacobi_ss_root.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.8221891239865619, "lm_q1q2_score": 0.7083473456930541}} {"text": "function rs = corrdim(s, bins)\n\n%tstoolbox/@signal/corrdim\n% Syntax:\n% * rs = corrdim(s, bins)\n%\n% Input arguments:\n% * s - data points (row vectors)\n% * bins - maximal number of partition per axis (optional)\n%\n% Compute the correlation dimension of a time-delay reconstructed\n% timeseries s for dimensions from 1 to D, where D is the dimension of\n% the input vectors using boxcounting approach. The default number of\n% bins is 100.\n%\n% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt\n\nnarginchk(1,2);\n\nif ndim(s) ~= 2\n error('Signal must contain vector data'); \nend\n\nif nargin<2\n bins = 100; \nend\n\npoints = data(s);\n[N,dim] = size(points);\n\n% scale data to be within 0 and 1\npoints = points - min(min(points));\npoints = points / max(max(points));\n\n% give a sortiment of (integer) partitionsizes with almost exponential behaviour \npar = [2 3 4 5 6 7 8 10 12 14 16 20 23 27 32 39 46 54 64 77 91 108 128 153 182 216 256 ...\n 305 363 431 512 609 725 862 1024 1218 1449 1723 2048 2436 2897 3445 4096 4871 ...\n\t 5793 6889 8192 9742 11586 13778 16384 19484 23171 27555 32768 38968 46341 55109 65536];\n\npartitions = par(find(par<=bins));\t% use no sizes greater than bins\n\n[dummy,dummy2,e] = boxcount(points, partitions);\n\ne = [zeros(1,dim) ; e]; % add zeros for partition size 1\npartitions = [1 ; partitions(:)];\t% add partition size 1\n\nrs = signal(core(e), s);\t\na = achse(-log2(partitions)); \t\t% create axis with arbitrary spacing\na = setname(a, 'ld r');\na2 = setname(achse(unit, 1, 1), 'Embedding dimension');\nrs = setaxis(rs, 1, a);\nrs = setaxis(rs, 2, a2);\nrs = setplothint(rs, 'multigraph');\nrs = addhistory(rs, ['Computed correlation dimension']);\nrs = addcommandlines(rs, 's = corrdim(s', bins);\nrs = setyname(rs, 'ld C(r)');\nrs = setlabel(rs, 'Scaling of D2');\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/OpenTSTOOL/tstoolbox/@signal/corrdim.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7083018743702669}} {"text": "function u = bsv_upwind ( a, b, alpha, beta, nu, n, output )\n\n%*****************************************************************************80\n%\n%% BSV_UPWIND applies Newton's method to a discretized steady viscous Burgers equation.\n%\n% Discussion:\n%\n% An upwind scheme is used to combat the numerical oscillations that\n% can occur otherwise.\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% Input, real A, B, the left and right endpoints.\n%\n% Input, real ALPHA, BETA, the Dirichlet boundary values at the left\n% and right.\n%\n% Input, real NU, the viscosity. Normally, 0 < NU.\n%\n% Input, integer N, the number of nodes to use between A and B.\n%\n% Input, logical OUTPUT, is TRUE if printout is desired.\n%\n% Output, real U(N), the computed discretized solution.\n%\n if ( n < 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BSV_UPWIND - Fatal error!\\n' );\n fprintf ( 1, ' N < 2.\\n' );\n error ( 'BSV_UPWIND - Fatal error!\\n' );\n end\n%\n% Set some iteration parameters.\n%\n newton_step_max = 50;\n newton_resid_tol = sqrt ( eps );\n newton_step_tol = sqrt ( eps );\n%\n% Use equally spaced nodes from A to B.\n%\n dx = ( b - a ) / ( n - 1 );\n%\n% The initial guess will be the linear interpolant to the boundary conditions.\n%\n u = ( linspace ( alpha, beta, n ) )';\n%\n% Prepare for the Newton iteration.\n%\n J = sparse ( [], [], [], n, n, 3 * n );\n newton_step = 0;\n\n if ( output )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Step ||F(U)||\\n' );\n fprintf ( 1, '\\n' );\n end \n\n while ( newton_step <= newton_step_max )\n\n f(1,1) = u(1) - alpha;\n\n f(2:n-1,1) = - nu * ( u(3:n) - 2.0 * u(2:n-1) + u(1:n-2) ) / ( dx^2 );\n%\n% Massaging the results of FIND can be tedious.\n%\n i = find ( 0.0 <= u(2:n-1) );\n i = i + 1;\n j = find ( u(2:n-1) < 0.0 );\n j = j + 1;\n\n f(i,1) = f(i,1) + 0.5 * ( u(i).^2 - u(i-1).^2 ) / dx;\n f(j,1) = f(j,1) + 0.5 * ( u(j+1).^2 - u(j).^2 ) / dx;\n\n f(n,1) = u(n) - beta;\n\n f_norm = norm ( f, inf );\n\n if ( output )\n fprintf ( 1, ' %4d %g\\n', newton_step, f_norm );\n end\n\n if ( f_norm < newton_resid_tol ) \n break\n end\n%\n% Define the Jacobian matrix.\n%\n J(1,1) = 1.0;\n for i = 2 : n - 1\n if ( 0.0 <= u(i) )\n J(i,i-1) = - u(i-1) / dx - nu / dx^2;\n J(i,i) = u(i) / dx + 2.0 * nu / dx^2;\n J(i,i+1) = - nu / dx^2;\n else\n J(i,i-1) = - nu / dx^2;\n J(i,i) = - u(i) / dx + 2.0 * nu / dx^2;\n J(i,i+1) = u(i+1) / dx - nu / dx^2;\n end\n end\n J(n,n) = 1.0;\n%\n% Solve the linear system J * du = -f to get the Newton update.\n%\n du = J \\ f;\n du_norm = norm ( du, inf );\n\n u_norm = norm ( u, inf );\n if ( du_norm < newton_step_tol * ( u_norm + 1.0 ) )\n break\n end\n\n u = u - du;\n newton_step = newton_step + 1;\n\n end\n\n if ( newton_step_max < newton_step )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BSV_UPWIND - Warning!\\n' );\n fprintf ( 1, ' The Newton iteration did not converge.\\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_upwind.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7083018729624813}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Copyright (C) 1995-2020 The Octave Project Developers\n%\n% See the file COPYRIGHT.md in the top-level directory of this\n% distribution or .\n%\n% This file is part of Octave.\n%\n% Octave is free software: you can redistribute it and/or modify it\n% 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% Octave is distributed in the hope that it will be useful, but\n% 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 Octave; see the file COPYING. If not, see\n% .\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% -*- texinfo -*-\n% @deftypefn {} {} cov (@var{x})\n% @deftypefnx {} {} cov (@var{x}, @var{opt})\n% @deftypefnx {} {} cov (@var{x}, @var{y})\n% @deftypefnx {} {} cov (@var{x}, @var{y}, @var{opt})\n% Compute the covariance matrix.\n%\n% If each row of @var{x} and @var{y} is an observation, and each column is\n% a variable, then the @w{(@var{i}, @var{j})-th} entry of\n% @code{cov (@var{x}, @var{y})} is the covariance between the @var{i}-th\n% variable in @var{x} and the @var{j}-th variable in @var{y}.\n% @tex\n% $$\n% \\sigma_{ij} = {1 \\over N-1} \\sum_{i=1}^N (x_i - \\bar{x})(y_i - \\bar{y})\n% $$\n% where $\\bar{x}$ and $\\bar{y}$ are the mean values of @var{x} and @var{y}.\n% @end tex\n% @ifnottex\n%\n% @example\n% cov (@var{x}) = 1/(N-1) * SUM_i (@var{x}(i) - mean(@var{x})) * (@var{y}(i) - mean(@var{y}))\n% @end example\n%\n% @noindent\n% where @math{N} is the length of the @var{x} and @var{y} vectors.\n%\n% @end ifnottex\n%\n% If called with one argument, compute @code{cov (@var{x}, @var{x})}, the\n% covariance between the columns of @var{x}.\n%\n% The argument @var{opt} determines the type of normalization to use.\n% Valid values are\n%\n% @table @asis\n% @item 0:\n% normalize with @math{N-1}, provides the best unbiased estimator of the\n% covariance [default]\n%\n% @item 1:\n% normalize with @math{N}, this provides the second moment around the mean\n% @end table\n%\n% Compatibility Note:: Octave always treats rows of @var{x} and @var{y}\n% as multivariate random variables.\n% For two inputs, however, @sc{matlab} treats @var{x} and @var{y} as two\n% univariate distributions regardless of their shapes, and will calculate\n% @code{cov ([@var{x}(:), @var{y}(:)])} whenever the number of elements in\n% @var{x} and @var{y} are equal. This will result in a 2x2 matrix.\n% Code relying on @sc{matlab}'s definition will need to be changed when\n% running in Octave.\n% @seealso{corr}\n% @end deftypefn\n\nfunction c = cov (x, y, opt)\n\nif (nargin < 2)\n y = [];\nend\nif (nargin < 3)\n opt = 0;\nend\nif (nargin < 1 || nargin > 3)\n error('Usage: c = cov (x, y = [], opt = 0)');\nend\n\nif (~(isnumeric (x) || islogical (x)) || ~(isnumeric (y) || islogical (y)))\n error ('cov: X and Y must be numeric matrices or vectors');\nend\n\nif (ndims (x) ~= 2 || ndims (y) ~= 2)\n error ('cov: X and Y must be 2-D matrices or vectors');\nend\n\nif (nargin == 2 && isscalar (y))\n opt = y;\nend\n\nif (opt ~= 0 && opt ~= 1)\n error ('cov: normalization OPT must be 0 or 1');\nend\n\n% Special case, scalar has zero covariance\nif (isscalar (x))\n if (isa (x, 'single'))\n c = single (0);\n else\n c = 0;\n end\n return;\nend\n\nif (isrow (x))\n x = x.';\nend\nn = size(x,1);\n\nif (nargin == 1 || isscalar (y))\n %x = center (x, 1);\n x = bsxfun(@minus, x, mean (x, 1));\n c = x' * x / (n - 1 + opt);\nelse\n if (isrow (y))\n y = y.';\n end\n if (size(y,1) ~= n)\n error ('cov: X and Y must have the same number of observations');\n end\n %x = center (x, 1);\n %y = center (y, 1);\n x = bsxfun(@minus, x, mean (x, 1));\n y = bsxfun(@minus, y, mean (y, 1));\n c = x' * y / (n - 1 + opt);\nend\n\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/octave/oc_cov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.7082958269965097}} {"text": "function [ f, g, H ] = opt15_fgh ( x, flag )\n\n%*****************************************************************************80\n%\n%% OPT15_FGH evaluates F, G and H for test case #15.\n%\n% Discussion:\n%\n% This example, if started at X = (-1,0), seems to get stuck.\n%\n% Modified:\n%\n% 09 January 2008\n%\n% Author:\n%\n% Jeff Borggaard,\n% Gene Cliff,\n% Virginia Tech.\n%\n% Reference:\n%\n% John Dennis, Robert Schnabel,\n% Numerical Methods for Unconstrained Optimization \n% and Nonlinear Equations,\n% SIAM, 1996,\n% ISBN13: 978-0-898713-64-0,\n% LC: QA402.5.D44.\n%\n% Parameters:\n%\n% Input, real X(2), the evaluation point.\n%\n% Input, string FLAG, indicates what must be computed.\n% 'f' means only the value of F is needed,\n% 'g' means only the value of G is needed,\n% 'all' means F, G and H (if appropriate) are needed.\n% It is acceptable to behave as though FLAG was 'all'\n% on every call.\n%\n% Output, real F, the optimization function.\n%\n% Output, real G(2,1), the gradient column vector.\n%\n% Output, real H(2,2), the Hessian matrix.\n%\n n = length ( x );\n\n if ( n ~= 2 )\n fprintf ( '\\n' );\n fprintf ( 'OPT15_FGH - Fatal error!\\n' );\n fprintf ( ' The input vector X should have length 2.\\n'), \n fprintf ( ' Instead, it has length = %d.\\n', n );\n keyboard\n end\n\n f = - ( x(1) + x(2) ) ...\n + 0.5 * ( 1 - ( x(1)^2 + x(2)^2 ) ) ...\n + 5.0 * ( 1 - ( x(1)^2 + x(2)^2 ) )^2;\n \n g(1,1) = -1 - 21 * x(1) + 20 * x(1) * ( x(1)^2 + x(2)^2 );\n g(2,1) = -1 - 21 * x(2) + 20 * x(2) * ( x(1)^2 + x(2)^2 );\n\n H = zeros(n,n);\n\n H(1,1) = - 21 + 60 * x(1)^2 + 20 * x(2)^2;\n H(1,2) = 40 * x(1) * x(2);\n\n H(2,1) = 40 * x(1) * x(2);\n H(2,2) = - 21 + 20 * x(1)^2 + 60 * x(2)^2;\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/entrust/opt15_fgh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.7082958120206092}} {"text": "function coeffs = ellipseCartesianCoefficients(elli)\n%ELLIPSECARTESIANCOEFFICIENTS Cartesian coefficients of an ellipse.\n%\n% COEFFS = ellipseCartesianCoefficients(ELLI)\n% Computes the cartesian coefficients of the ellipse ELLI, given by:\n% COEFFS = [A B C D E F] \n% such that the points on the ellipse follow:\n% A*X^2 + B*X*Y + C*Y^2 + D*X + E*Y + F = 0\n%\n% Example\n% elli = [30 20 40 20 30];\n% coeffs = ellipseCartesianCoefficients(elli)\n% elli2 = createEllipse(coeffs)\n% elli2 =\n% 30.0000 20.0000 40.0000 20.0000 30.0000\n%\n% See also \n% ellipses2d, createEllipse, equivalentEllipse\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@inrae.fr\n% Created: 2022-09-05, using Matlab 9.12.0.1884302 (R2022a)\n% Copyright 2022 INRAE - BIA Research Unit - BIBS Platform (Nantes)\n\n% retrieve ellipse center and squared radiusses\nxc = elli(1);\nyc = elli(2);\na2 = elli(3)^2;\nb2 = elli(4)^2;\n\n% pre-compute trigonometric functions (angle is in degrees)\ncot = cos(elli(5) * pi / 180);\nsit = sin(elli(5) * pi / 180);\n\n% identification of each parameter\nA = a2 * sit * sit + b2 * cot * cot;\nB = 2 * (b2 - a2) * sit * cot;\nC = a2 * cot * cot + b2 * sit * sit;\nD = - 2 * A * xc - B * yc;\nE = - B * xc - 2 * C * yc;\nF = A * xc * xc + B * xc * yc + C * yc * yc - a2 * b2;\n\n% concatenate into a single row vector\ncoeffs = [A B C D E F];\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/ellipseCartesianCoefficients.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7082860469499398}} {"text": "function A = create_3d_linear_interp_matrix(T, varargin)\n% A = create_2d_bilinear_interp_matrix(T, [szin])\n% T should contain displacements in pixels\n% size(T) = [N1, N2, N3, 2]\n% \n% x_def = A * x(:);\n\nsz = [size(T, 1), size(T, 2), size(T, 3)];\n\nif numel(varargin) == 1\n szin = varargin{1};\nelse\n szin = sz;\nend\n\nnpixin = szin(1) * szin(2) * szin(3);\nnpixout = sz(1) * sz(2) * sz(3);\n\n[m1, m2, m3] = ndgrid(1:sz(1), 1:sz(2), 1:sz(3));\nTT = T + cat(4, m1, m2, m3);\n\nr = cell(3, 1);\nrk = cell(3, 1);\nfor i = 1 : 3\n r{i} = floor(TT(:, :, :, i));\n rk{i} = TT(:,:,:, i) - r{i};\nend\n\n%\nssh = [0, 0, 0, 0, 1, 1, 1, 1;...\n 0, 1, 0, 1, 0, 1, 1, 0;...\n 0, 0, 1, 1, 0, 0, 1, 1;];\nA = sparse(npixout, npixin);\nfor i = 1 : 8\n t = 1 : npixout;\n s = ones(numel(rk{1}), 1);\n rid = cell(3, 1);\n for j = 1 : 3\n rid{j} = r{j} + ssh(j, i);\n if ssh(j, i) == 1\n tmps = rk{j};\n else\n tmps = 1 - rk{j};\n end\n s = s .* tmps(:);\n end\n idx = (rid{1} <= szin(1)) & (rid{1} >= 1) & (rid{2} <= szin(2)) & (rid{2} >= 1) & (rid{3} <= szin(3)) & (rid{3} >= 1);\n for j = 1 : 3\n rid{j} = rid{j}(idx);\n end\n s = s(idx);\n t = t(idx);\n tmp = sparse(t, rid{1} + szin(1) * (rid{2} - 1) + szin(2)*szin(1) * (rid{3} - 1), s, npixout, npixin);\n A = A + tmp;\nend\n\nend", "meta": {"author": "visva89", "repo": "pTVreg", "sha": "c359620e3c8435392db02354274d6c74d682d437", "save_path": "github-repos/MATLAB/visva89-pTVreg", "path": "github-repos/MATLAB/visva89-pTVreg/pTVreg-c359620e3c8435392db02354274d6c74d682d437/mutils/My/deformation_tools_cpp/create_3d_linear_interp_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.708286042026911}} {"text": "function y0 = oddchebser0 ( x, coef, nc )\n\n%*****************************************************************************80\n%\n%% ODDCHEBSER0 evaluates an odd Chebyshev series.\n%\n% Discussion:\n%\n% This function implements Clenshaw's modification of his algorithm\n% for odd series.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 April 2014\n%\n% Author:\n%\n% Manfred Zimmer\n%\n% Reference:\n%\n% Charles Clenshaw,\n% Mathematical Tables, Volume 5,\n% Chebyshev series for mathematical functions,\n% London, 1962.\n%\n% Parameters:\n%\n% Input, real X, the evaluation point.\n% -1 <= X <= +1.\n%\n% Input, real COEF(NC), the Chebyshev series.\n%\n% Input, integer NC, the number of terms in the series.\n% 0 < NC.\n%\n% Output, real Y0, the value of the Chebyshev series at X.\n%\n b0 = coef(nc);\n b1 = 0.0;\n b2 = 0.0;\n\n x2 = 4.0 * x * x - 2.0;\n\n for i = nc - 1 : -1 : 1\n\n b2 = b1;\n b1 = b0;\n b0 = coef(i) - b2 + x2 * b1;\n\n end\n\n y0 = ( b0 - b1 ) * 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/chebyshev_series/oddchebser0.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.7082689428970416}} {"text": "function [y, Fout]=SincResample(xin, npoints, Fin, shift, mode)\n% SincResample resamples signals to arbitrary lengths/frequencies and can\n% timeshift them.\n%\n% SincResample can be faster than INTERP or RESAMPLE when X contains many\n% relatively short data columns.\n%\n%\n% Example:\n% [Y, FOUT]=SincResample(X, NPOINTS, FIN, SHIFT, MODE)\n%\n% X is a vector or M x N matrix where each column represents a signal.\n% NPOINTS is the number of points required in each column after\n% resampling.\n% FIN (if supplied) is the sampling rate in X (default 1 samples/sec).\n% SHIFT (if supplied) is the time (in seconds) to shift the points at which\n% interpolation will be done (default 0). SHIFT should be between ą(1/Fin).\n% SHIFT can be used to synchronize signals separated by up to ą(1/Fin)\n% in time.\n% MODE (if supplied) is a string:\n% 'sinc' to use a hamming-windowed sinc function (default)\n% 'lanczos' for a 3-lobed Lanczos function\n%\n% Y is the resulting M x NPOINTS matrix formed by resampling. The time\n% of the first sample in each column of Y is shifted by SHIFT seconds\n% relative to those in X.\n% FOUT is the effective sample rate for output Y (normalised to FIN=1 if\n% FIN is not supplied on input).\n%\n% If X is a bandlimited (filtered) signal containing components at\n% DC - 0.5Fs where Fs is the sample rate, SincResample will return\n% the signal that would have been seen with a higher sampling rate\n% (and the same filter settings). The algorithm depends on the fact that\n% the bandlimited signal is completely defined when sampling at Fs.\n%\n% SincResample returns the data convolved with a set of time-shifted\n% windowed sinc functions, one for each of the samples [1..size(x,1)]\n% in the input signal. End-effects are reduced by adding a reflected \n% and mirrored copy of the data at the beginning and end of each column\n% before resampling.\n%\n% Note that points at the end of Y (and/or beginning if SHIFT is negative)\n% will be extrapolated beyond the boundaries of X.\n%\n% SincResample is a generalization of the method used in Blanche &\n% Swindale (2006).\n%\n% See also e.g. interp & resample (in the Signal Processing Toolbox) and \n% the sinc online documentation.\n%\n% References:\n% T.Blanche & N.V.Swindale (2006)\n% Nyquist interpolation improves neuron yield in multiunit recordings\n% Journal of Neuroscience Methods 155, 81-91 LinkOut\n%\n% also\n%\n% K. Turkowski, Filters for common resampling tasks LinkOut\n%\n% Toolboxes required: None\n%\n% Author: Malcolm Lidierth 07/06\n% Copyright Š King’s College London 2006-8\n%\n% Acknowledgements: Steve Alty for comments\n%\n% Revisions: 10.07 Argument checks tidied (ML)\n% 02.08 End-effect minimization now relects and mirrors data\n% instead of simply reflecting it. This improves the \n% slopes at the end and reduces the behaviour described at\n% http://www.dsprelated.com/showmessage/79676/2.php\n% (ML)\n% 02.08 Mode option added (ML)\n\n% Argument checks\nif nargin<2\n y=[];\n Fout=0;\n return\nend\n\nif nargin<=2\n % Default\n Fin=1;\nend\n\nif nargin<=3\n % Zero shift default\n shift=0;\nend\n\nif nargin<=4\n % Set sinc as default\n mode='sinc';\nend\n\nif Fin==0\n error('SincResample: Fin specified as zero');\nend\n\nif abs(shift)>=1/Fin\n error('SincResample: shift must be less than 1/Fin');\nend\n\nif rem(npoints,1)~=0\n error('SincResample: npoints must be a whole number');\nend\n\n% Main routine\n% Prepend and append a reflected and mirrored copy of the data\n% to minimize end transients:\n% Change 22.02.08: note change from reflected only\n\nif isvector(xin)\n % Force column vector if row input\n xin=xin(:);\nend\n\nx=zeros(size(xin,1)*3, size(xin,2));\nfor k=1:size(xin,2)\n x(2:end-1,k)=[2*xin(1,k)-xin(end:-1:2,k);...\n xin(:,k);...\n 2*xin(end,k)-xin(end-1:-1:1,k)];\n x(1,k)=2*x(1,k)-x(2,k);\n x(end,k)=2*x(end,k)-x(end-1,k);\nend\nclear('xin');\nnp=npoints*3;\n\n% A column vector of sample times for x - assume unit spacing and zero\n% base\nlen=size(x,1);\nt=(0:len-1)';\n\n% times at which to interpolate data - based on spacing in t.\n% ts will be a [npoints by size(x,1)] matrix\nts=(0:(max(t)+1)/np:(np-1)/(np/len))';\nts=(ts(:,ones(size(t)))-t(:,ones(size(ts)))');\n\n% Hamming window\nN=size(ts,2);\nif N==1 || strcmp(mode, 'lanczos');\n w=1;\nelse\n th=ts+N-1;\n w=0.54-0.46*cos((2*pi*th/max(th(:)))) ;\nend\n\n% Add shift in multiples of a sampling interval i.e. shift/(1/Fin)\nts=ts+(shift*Fin);\n\nswitch mode\n case 'lanczos'\n % Generate Lanczos functions and calculate output\n y=lanczos(ts)*x;\n case 'sinc'\n % Generate sinc functions, apply Hamming window if w~=1 and\n % calculate output.\n y=sinc(ts).*w*x;\n otherwise\n error('mode should be ''sinc'' or ''lanczos''');\nend\n\n% Throw away what is not needed\ny=y(size(y,1)/3+1:(size(y,1)/3)+(size(y,1)/3),:);\nFout=Fin*npoints/(len/3);\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% DEBUG Display the data - UNCOMMENT text below to display results\n% x=x(size(x,1)/3+1:(size(x,1)/3)+(size(x,1)/3),:);\n% debugdisplay(x, y, Fin, Fout, shift)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nreturn\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction y=sinc(x)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ni=find(x==0);\nx(i)=1;\ny=sin(pi*x)./(pi*x);\ny(i)=1;\nreturn\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction y=lanczos(x)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nn=3;\ny=sinc(x).*sinc(x/n);\ny(abs(x)>=n)=0;\nreturn\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction debugdisplay(x, y, Fin, Fout, shift) %#ok\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Interp requires the Signal Processing Toolbox. The output of interp will\n% be shown if Fout is an integer multiple of Fin.\n% Note that shift is not applied to interp\n% Sample times in seconds\nt1= 0 : 1/Fin : (size(x,1)-1)/Fin;\nt2= 0 : 1/Fout : (size(y,1)-1)/Fout;\nif rem(Fout,Fin)==0\n y3=interp(x(:,1),Fout/Fin);\n t3=linspace(0,max(t2),size(y3,1));\nend\nt2=t2+shift;\nhandle=gca(figure);\nxlabel(handle,'Time (seconds)');\nfor i=1:size(x,2)\n if ~ishandle(handle)\n break;\n end\n if rem(Fout,Fin)==0\n y3=interp(x(:,i),Fout/Fin);\n plot(handle,t1,x(:,i),'-bo',t2,y(:,i),'r-x',t3,y3,'g:s');\n xlim([min([0;min(t2)]) max([max(t3);max(t2);max(t1)])]);\n else\n plot(handle,t1,x(:,i),'-bo',t2,y(:,i),'r-x');\n xlim([min([0;min(t2)]) max([max(t2);max(t1)])]);\n end\n xlabel(handle,'Time (seconds)');\n title('Close the figure window to exit this loop');\n if rem(Fout,Fin)==0\n legend('Original','SincResample','MATLAB Interp (no shift)');\n else\n legend('Original','SincResample');\n end\n drawnow();\n pause(.1);\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/12268-sinc-resample/SincResample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.7082689418978148}} {"text": "function [ a, b ] = assemble_fem ( x_num, x, element_num, element_node, ...\n quad_num, t, k_fun, rhs_fun )\n\n%*****************************************************************************80\n%\n%% ASSEMBLE_FEM assembles the finite element stiffness matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer X_NUM, the number of nodes.\n%\n% Input, real X(X_NUM), the coordinates of nodes.\n%\n% Input, integer ELEMENT_NUM, the number of elements.\n%\n% Input, integer ELEMENT_NODE(2,ELEMENT_NUM);\n% ELEMENT_NODE(I,J) is the global index of local node I in element J.\n%\n% Input, integer QUAD_NUM, the number of quadrature points used in assembly.\n%\n% Input, real T, the current time.\n%\n% Input, real K_FUN(), a function to evaluate the heat conductivity.\n%\n% Input, real RHS_FUN(), a function to evaluate the right hand side.\n%\n% Output, sparse real A(X_NUM,X_NUM), the finite element stiffness matrix.\n%\n% Output, real B(X_NUM), the right hand side.\n%\n% Local parameters:\n%\n% Local, real BI, DBIDX, the value of some basis function\n% and its first derivative at a quadrature point.\n%\n% Local, real BJ, DBJDX, the value of another basis\n% function and its first derivative at a quadrature point.\n%\n\n%\n% Initialize the arrays.\n%\n b = zeros ( x_num, 1 );\n a = sparse ( x_num, x_num );\n%\n% Get the quadrature weights and nodes.\n%\n [ reference_w, reference_q ] = quadrature_set ( quad_num );\n%\n% Consider each ELEMENT.\n%\n for element = 1 : element_num\n\n element_x(1:2,1) = x(element_node(1:2,element));\n\n element_q(1:quad_num,1) = reference_to_physical ( element, element_node, ...\n x, quad_num, reference_q );\n\n element_area = element_x(2) - element_x(1);\n\n element_w(1:quad_num,1) = ( element_area / 2.0 ) * reference_w(1:quad_num);\n%\n% Consider the QUAD-th quadrature point in the element.\n%\n k_value = k_fun ( quad_num, element_q, t );\n rhs_value = rhs_fun ( quad_num, element_q, t );\n\n for quad = 1 : quad_num\n%\n% Consider the TEST-th test function.\n%\n% We generate an integral for every node associated with an unknown.\n%\n for i = 1 : 2\n\n test = element_node(i,element);\n\n [ bi, dbidx ] = basis_function ( test, element, x, 1, element_q(quad) );\n\n b(test) = b(test) + element_w(quad) * rhs_value(quad) * bi;\n%\n% Consider the BASIS-th basis function, which is used to form the\n% value of the solution function.\n%\n for j = 1 : 2\n\n basis = element_node(j,element);\n\n [ bj, dbjdx ] = basis_function ( basis, element, x, 1, element_q(quad) );\n\n a(test,basis) = a(test,basis) + element_w(quad) * ( ...\n + k_value(quad) * dbidx * dbjdx );\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/fem1d_heat_explicit/assemble_fem.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.7082689388472241}} {"text": "function val=perm(A,boolRowsSkip,boolColsSkip)\n%%PERM Calculate the matrix permanent allowing for rows and columns to be\n% skipped if desired (operate on a submatrix). The permanent is\n% equivalent to calculating the determininant in the standard\n% summation manner taught in school, except all of the minus signs are\n% replaced with plus signs. Permanents play a role in combinatorics\n% and the ability to skip rows and columns can be useful when using\n% permanents to compute target-measurement association probabilities.\n%\n%INPUTS: A An mXn matrix. If m<=n, then the standard matrix permanent is\n% found. If m>n, then the permanent of A' is found to be consistent\n% with the permanents of A and A' being equal in square matrices.\n% Empty matrices have a permanent of one by definition.\n% boolRowsSkip An optional list of rows in A that should be skipped when\n% computing the matrix permanent. This is an mX1 or 1Xm boolean\n% vector where a 1 means that row should be skipped. If omitted or\n% an empty matrix is passed, no rows are skipped.\n% boolColsSkip An optional list of columns in A that should be skipped when\n% computing the matrix permanent. This is an nX1 or 1Xn boolean\n% vector where a 1 means that column should be skipped. If omitted\n% or an empty matrix is passed, no columns are skipped.\n%\n%OUTPUTS: val The matrix permanent of A, omitting any rows or columns as\n% necessary.\n%\n%Whereas polynomial-time algorithms exist for calculating determinants, it\n%was proven in [1] that matrix permanents can not be computed in polynomial\n%time unless P=NP. However, efficient non-polynomial time algorithms exist.\n%This file implements the method in theorem 4.1 on page 26 in Chapter 2 of\n%[2] when dealing with general rectangular matrices. When dealing with\n%square matrices, an algorithm based on PERMAN from Chapter 23 of [3] is\n%used, because it is more efficient and appears to be less susceptible to\n%finite precision errors. When skipping rows or columns, only Ryser's\n%algorithm is used.\n%\n%EXAMPLE 1:\n%Suppose that one is given a boolean matrix where 1 indicates that a target\n%gates with a measurement and a 0 indicates that it does not gate. To deal\n%with the possibility of missed detections, one often adds dummy\n%measurements, one per target, each gating with only one target. The total\n%number of possible target-measurement (and missed detection) assignments\n%equals the permanent of the matrix.\n% %For 5 targets, 5 measurements (everything gates) and no missed\n% %detections\n% perm(ones(5,5))\n% %One gets 120, there are 120 possible assignments (factorial(5)).\n% %For 5 targets target where everything gates with the possibility of\n% %missed detections, one has\n% perm([ones(5,5),eye(5)])\n% %Leading to 1546 possible assignments to measurements and missed\n% %detections.\n%\n%EXAMPLE 2:\n%This is an example with skip lists.\n% numRow=12;\n% numCol=4;\n% A=magic(max(numRow,numCol));\n% A=A(1:numRow,1:numCol);\n% boolRowsSkip=false(numRow,1);\n% boolColsSkip=false(numCol,1);\n% boolRowsSkip(3)=true;\n% boolColsSkip([1,4])=true;\n% perm(A,boolRowsSkip,boolColsSkip)\n% perm(A',boolColsSkip,boolRowsSkip)\n% %The permanent values should both be 494938.\n%\n%REFERENCES:\n%[1] L. G. Valiant, \"The complexity of computing the permanent,\"\n% Theoretical Computer Science, vol. 8, no. 2, pp. 189-201, 1979.\n%[2] H. J. Ryser, Combinatorial Mathematics, ser. The Carus Mathematical\n% Monographs. The Mathematical Association of America, 1963, no. 14.\n%[3] A. Nijenhuis and H. S. Wilf, Combinatorial Algorithms for Computers\n% and Calculators, 2nd ed. New York: Academic press, 1978.\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n if(isempty(A))\n %Empty matrices have a permanent of 1 by definition.\n val=1;\n return;\n elseif(numel(A)==1)\n %Scalar values have a permanent equal to that value.\n val=A;\n return;\n end\n\n m=size(A,1);\n n=size(A,2);\n \n %Use a modified version of Ryser's algorithm if skip lists are\n %provided.\n if(nargin>1)\n mTotal=m;\n nTotal=n;\n if(nargin<3||isempty(boolColsSkip))\n boolColsSkip=false(nTotal,1);\n end\n \n if(isempty(boolRowsSkip))\n boolRowsSkip=false(mTotal,1); \n end\n \n numRowsSkipped=sum(boolRowsSkip);\n numColsSkipped=sum(boolColsSkip);\n \n m=mTotal-numRowsSkipped;\n n=nTotal-numColsSkipped;\n \n %Empty matrices have a permanent of 1 by definition.\n if(isempty(A)||m==0||n==0)\n val=1;\n return; \n end\n\n if(m>n)\n A=A';\n temp=m;\n m=n;\n n=temp;\n \n temp=mTotal;\n mTotal=nTotal;\n nTotal=temp;\n \n temp=boolRowsSkip;\n boolRowsSkip=boolColsSkip;\n boolColsSkip=temp;\n end\n \n %Set the mapping of indices of the rows in the submatrix to indices in\n %the full matrix.\n rows2Keep=zeros(m,1);%Allocate space\n cumSkip=0;\n curIdx=1;\n for curRow=1:mTotal\n if(boolRowsSkip(curRow)==true)\n cumSkip=cumSkip+1;\n continue;\n else\n rows2Keep(curIdx)=curIdx+cumSkip;\n curIdx=curIdx+1;\n end\n end\n \n %Set the mapping of indices of the columns in the submatrix to indices in\n %the full matrix.\n cols2Keep=zeros(n,1);%Allocate space\n cumSkip=0;\n curIdx=1;\n for curCol=1:nTotal\n if(boolColsSkip(curCol)==true)\n cumSkip=cumSkip+1;\n continue;\n else\n cols2Keep(curIdx)=curIdx+cumSkip;\n curIdx=curIdx+1;\n end\n end\n \n binomTerm=1;\n val=0;\n for x=0:(m-1)\n val=val+SigmaSSkip(A,n-m+x,rows2Keep,cols2Keep)*binomTerm;\n\n binomTerm=binomTerm*(1-m+n+x)/(1+x)*(-1);\n end\n \n return;\n end\n \n if(m~=n)%Use Ryser's algorithm\n if(m>n)\n A=A';\n temp=m;\n m=n;\n n=temp;\n end\n\n binomTerm=1;\n val=0;\n for x=0:(m-1)\n val=val+SigmaS(A,n-m+x)*binomTerm;\n\n binomTerm=binomTerm*(1-m+n+x)/(1+x)*(-1);\n end\n else%If the matrix is square, use the PERMAN algorithm.\n x=zeros(n,1);%Temporary storage space.\n p=0;\n\n for i=1:n\n sumVal=sum(A(i,:));\n x(i)=A(i,n)-sumVal/2;\n end\n\n sgn=-1;\n code=[];\n nCard=n-1;\n while(1)\n sgn=-sgn;\n prodVal=sgn;\n [code,nCard,isLast,j]=getNextGrayCode(code,nCard);\n\n if(nCard~=0)\n z=2*code(j)-1;\n x=x+z*A(:,j);\n end\n for i=1:n\n prodVal=prodVal*x(i);\n end\n p=p+prodVal;\n\n if(isLast)\n break;\n end\n end\n val=2*(2*mod(n,2)-1)*p;\n end\nend\n\nfunction val=S(A)\n%This function gives us the product of the row sums of A.\n val=prod(sum(A,2));\nend\n\nfunction val=SigmaS(A,r)\n %This adds up all of the possible values of S(A) where r columns of A\n %have been replaced by zeros. We shall choose the \n %n-r columns of A that are NOT zero.\n n=size(A,2);\n combLen=n-r;\n curComb=1:combLen;\n val=0;\n while(~isempty(curComb))\n val=val+S(A(:,curComb));\n curComb=getNextCombo(curComb,n,1);\n end\nend\n\nfunction val=SigmaSSkip(A,r,rows2Keep,cols2Keep)\n %This adds up all of the possible values of S(A) where r columns of A\n %have been replaced by zeros. We shall choose the \n %n-r columns of A that are NOT zero.\n n=length(cols2Keep);\n combLen=n-r;\n curComb=0:(combLen-1);\n\n val=0;\n while(~isempty(curComb)) \n val=val+S(A(rows2Keep,cols2Keep(curComb+1)));\n curComb=getNextCombo(curComb,n);\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/Combinatorics/perm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7082598705476914}} {"text": "function [H,S]=create_CHS(A,B,C,N,M);\n% CREATE_CHS Internal function to define matrices for MPC problem\n\n% How many states\nn=length(A);p=size(C,1);\n[dummy,m]=size(B);\n\nH=zeros(N*p,length(A));\nS=zeros(N*p,N*m);\n\nAcum=A;\nfor j=1:N,\n H(1+p*(j-1):p*j,:)=C*Acum;\n Acum=Acum*A;\nend;\n\nfor j=1:N,\n Acum=eye(n);\n for k=j:-1:1,\n S(1+p*(j-1):p*j,1+m*(k-1):k*m)=C*Acum*B;\n Acum=Acum*A;\n end;\nend;\n", "meta": {"author": "yalmip", "repo": "YALMIP", "sha": "f6d5a6d4222a4d722de30bffb43cae4b3e13b860", "save_path": "github-repos/MATLAB/yalmip-YALMIP", "path": "github-repos/MATLAB/yalmip-YALMIP/YALMIP-f6d5a6d4222a4d722de30bffb43cae4b3e13b860/extras/create_CHS.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7082598564729842}} {"text": "function kcoeff = kwiener_train(X,Y,s)\n% FUNCTION kcoeff = kwiener_train(X,Y,param)\n% AUTHOR: Makoto Yamada\n% (myamada@ism.ac.jp)\n% DATE: 12/25/07\n% \n% DESCRIPTION:\n% \n% This function compute the kernel Wiener filter (kernel Dependency\n% Estimation) using Canonical Correlation Analysis (CCA) \n% and outputs it in the abstract object \"kcoeff\".\n% The \"kcoeff\" object can then be used for finding pre-images.\n%\n% INPUTS:\n% \n% X: \"X\" is a (n times N) dimensional input matrix,\n% where \"n\" is the vector dimension and N is the number\n% of samples.\n%\n% Y: \"Y\" is a (m times N) dimensional output matrix.\n% where \"m\" is the vector dimension and N is the number\n% of samples.\n%\n% s: \"s\" is a parameter for Gaussian kernel, \n% exp(-norm(x - y)^2/s).\n% \n% OUTPUTS:\n% \n% kcoeff : The Kernel Wiener Filter object.\n% \n% \n% Example: \n% load usps; %loading USPS data\n% s = 256*0.7; %Gaussian Kernel Parameter\n% %Training Kernel Wiener Filter\n% kcoeff = kwiener_train(X,Y,s);\n% \n% Reference: 1. J. Weston et.al. ``Kernel Dependency Estimation,'' NIPS\n% 2003\n%\n% 2. M. Yamada and M. R. Azimi-Sadjadi, ``Kernel Wiener Filter\n% using Canonical Correlation Analysis Framework,''\n% IEEE SSP'05, Bordeaux, France, July 17-20, 2005. \n%\n% 3. C. Cortes et.al. ``A General Regression Technique for\n% Learning Transductions,'' ICML, Bonn, Germany, Aug 7-11.\n%\n% 4. M. Yamada and M. R. Azimi-Sadjadi, ``Kernel Wiener Filter\n% with Distance Constraint,'' ICASSP, Toulouse, France,\n% May 14-19, 2006\n%\n% 5. Zhe Chen et.al, ``Correlative Learning: A Basis for Brain and Adaptive\n% Systems,'' Wiley, Oct. 2007 (Section 4.6)\n \nn = size(X,2); %Number of Training samples\n\n%Kernel Computation (Gaussian Kernel)\ndisp('Computing the Gram Matrix of X');\nKx = kernelg(X,X,s);\ndisp('Computing the Gram Matrix of Y');\nKy = kernelg(Y,Y,s);\n\n%Centering Matrix\nJ = eye(n) - 1/n*ones(n);\n%Centering Kernel Gram Matrix\nA = J*Kx*J;\n\n%Computing the Kernel Wiener Filter (Kernel Dependency Estimation)\n%Computing the first kernel Canonical Coordinate.\n[F D] = eig(A);\nLambda = sqrt(abs(real(diag(D))));\n[YY I] = sort(-Lambda);\n\n%Normalizing Eigenvectors.\nfor k = 1:n\n if Lambda(k) ~= 0\n F(:,k)=F(:,k)/Lambda(k);\n end\nend\n\nLambda = -YY;\nF = F(:,I);\nkcoeff.Df = F; %First kernel Canonical mapping function.\nkcoeff.lambda = Lambda; %Eigenvalue of kernel CCA.\n\n%Computing the second kernel Canonical Coordinate.\nry = rank(Ky);\n[Uy Wy Vy] = svd(Ky);\ninvKy = Vy(:,1:ry)*inv(Wy(1:ry, 1:ry))*Uy(:,1:ry)';\nkcoeff.Dg = invKy*Kx*J*kcoeff.Df; %Second kernel Canonical mapping function.\n\nkcoeff.Kxt = kcoeff.Df'*Kx;\n\n%Computing rank of kernel Wiener filter.\n[temp1,temp2] = find(kcoeff.lambda > 0);\n\nif sum(temp2) == size(kcoeff.Kxt,2)\n kcoeff.rnk = sum(temp2) -1;\nelse\n kcoeff.rnk = sum(temp2);\nend\n\ndisp('Finished Kernel Wiener Estimation');\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/18764-kernel-wiener-filter-kernel-dependency-estimation/kwiener/kwiener_train.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7081640100939305}} {"text": "function de00 = deltaE2000(Labstd,Labsample)\n% Based on the article:\n% \"The CIEDE2000 Color-Difference Formula: Implementation Notes, \n% Supplementary Test Data, and Mathematical Observations,\", G. Sharma, \n% W. Wu, E. N. Dalal, Color Research and Application, vol. 30. No. 1, pp.\n% 21-30, February 2005.\n% available at http://www.ece.rochester.edu/~/gsharma/ciede2000/\nkl = 1; kc=1; kh =1;\nLstd = Labstd(:,1)';\nastd = Labstd(:,2)';\nbstd = Labstd(:,3)';\nCabstd = sqrt(astd.^2+bstd.^2);\nLsample = Labsample(:,1)';\nasample = Labsample(:,2)';\nbsample = Labsample(:,3)';\nCabsample = sqrt(asample.^2+bsample.^2);\nCabarithmean = (Cabstd + Cabsample)/2;\nG = 0.5* (1 - sqrt( (Cabarithmean.^7)./(Cabarithmean.^7 + 25^7)));\napstd = (1+G).*astd;\napsample = (1+G).*asample; \nCpsample = sqrt(apsample.^2+bsample.^2);\nCpstd = sqrt(apstd.^2+bstd.^2);\nCpprod = (Cpsample.*Cpstd);\nzcidx = find(Cpprod == 0);\nhpstd = atan2(bstd,apstd);\nhpstd = hpstd+2*pi*(hpstd < 0); \nhpstd((abs(apstd)+abs(bstd))== 0) = 0;\nhpsample = atan2(bsample,apsample);\nhpsample = hpsample+2*pi*(hpsample < 0);\nhpsample((abs(apsample)+abs(bsample))==0) = 0;\ndL = (Lsample-Lstd);\ndC = (Cpsample-Cpstd);\ndhp = (hpsample-hpstd);\ndhp = dhp - 2*pi* (dhp > pi );\ndhp = dhp + 2*pi* (dhp < (-pi) );\ndhp(zcidx ) = 0;\ndH = 2*sqrt(Cpprod).*sin(dhp/2);\nLp = (Lsample+Lstd)/2;\nCp = (Cpstd+Cpsample)/2;\nhp = (hpstd+hpsample)/2;\nhp = hp - ( abs(hpstd-hpsample) > pi ) *pi;\nhp = hp+ (hp < 0) *2*pi;\nhp(zcidx) = hpsample(zcidx)+hpstd(zcidx);\nLpm502 = (Lp-50).^2;\nSl = 1 + 0.015*Lpm502./sqrt(20+Lpm502); \nSc = 1+0.045*Cp;\nT = 1 - 0.17*cos(hp - pi/6 ) + 0.24*cos(2*hp) + 0.32*cos(3*hp+pi/30) ...\n -0.20*cos(4*hp-63*pi/180);\nSh = 1 + 0.015*Cp.*T;\ndelthetarad = (30*pi/180)*exp(- ( (180/pi*hp-275)/25).^2);\nRc = 2*sqrt((Cp.^7)./(Cp.^7 + 25^7));\nRT = - sin(2*delthetarad).*Rc;\nklSl = kl*Sl;\nkcSc = kc*Sc;\nkhSh = kh*Sh;\nde00 = sqrt( (dL./klSl).^2 + (dC./kcSc).^2 + (dH./khSh).^2 + ...\n RT.*(dC./kcSc).*(dH./khSh) );\nreturn\n\n\n", "meta": {"author": "mahmoudnafifi", "repo": "WB_sRGB", "sha": "98340313cc7d1728e286ad9ba03e8f9a0e8b82c5", "save_path": "github-repos/MATLAB/mahmoudnafifi-WB_sRGB", "path": "github-repos/MATLAB/mahmoudnafifi-WB_sRGB/WB_sRGB-98340313cc7d1728e286ad9ba03e8f9a0e8b82c5/WB_sRGB_Matlab/evaluation/deltaE2000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.7081611553170062}} {"text": "function [tm,T]=loctime(sig);\n%LOCTIME Time localization caracteristics.\n%\t[TM,T]=LOCTIME(SIG) computes the time localization\n%\tcaracteristics of signal SIG. \n% \n%\tSIG is the signal.\n%\tTM is the averaged time center.\n%\tT is the time spreading.\n%\n%\tExample :\n%\t z=amgauss(160,80,50); [tm,T]=loctime(z)\n%\n%\tSee also LOCFREQ.\n\n%\tF. Auger, 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\n[sigr,sigc]=size(sig);\nif (sigc~=1),\n error('The signal must have 1 column');\nelse\n sig2=abs(sig).^2; sig2=sig2/mean(sig2);\n t=(1:sigr)';\n tm=mean(t.*sig2);\n T=2*sqrt(pi*mean((t-tm).^2 .* sig2)); \nend;\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/loctime.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7081549737252472}} {"text": "function quadrule_test096 ( )\n\n%*****************************************************************************80\n%\n%% QUADRULE_TEST096 tests HERMITE_GK**_SET.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 May 2011\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'QUADRULE_TEST096\\n' );\n fprintf ( 1, ' HERMITE_GK**_SET sets up a nested rule\\n' );\n fprintf ( 1, ' for the Hermite integration problem.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The integration interval is ( -oo, +oo ).\\n' );\n fprintf ( 1, ' The weight function is exp ( - x * x )\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' HERMITE_INTEGRAL determines the exact value of\\n' );\n fprintf ( 1, ' the integal when f(x) = x^m.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Here, we just test the highest order rule.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' HERMITE_GK16_SET:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' M N Estimate Exact Error\\n' );\n fprintf ( 1, '\\n' );\n\n n = 35;\n p = 51;\n\n [ x, w ] = hermite_gk16_set ( n );\n\n for m = 0 : 2 : min ( p + 2, 20 )\n\n exact = hermite_integral ( m );\n\n if ( m == 0 )\n f = ones ( n, 1 );\n else\n f = zeros ( n, 1 );\n f = x.^m;\n end\n\n estimate = w(1:n)' * f(1:n);\n\n error = abs ( exact - estimate );\n\n fprintf ( 1, ' %8d %8d %14.6e %14.6e %14.6e\\n', ...\n m, n, estimate, exact, error );\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' HERMITE_GK18_SET:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' M N Estimate Exact Error\\n' );\n fprintf ( 1, '\\n' );\n\n n = 37;\n p = 55;\n\n [ x, w ] = hermite_gk18_set ( n );\n\n for m = 0 : 2 : min ( p + 2, 20 )\n\n exact = hermite_integral ( m );\n\n if ( m == 0 )\n f = ones ( n, 1 );\n else\n f = zeros ( n, 1 );\n f = x.^m;\n end\n\n estimate = w(1:n)' * f(1:n);\n\n error = abs ( exact - estimate );\n\n fprintf ( 1, ' %8d %8d %14.6e %14.6e %14.6e\\n', ...\n m, n, estimate, exact, error );\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' HERMITE_GK22_SET:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' M N Estimate Exact Error\\n' );\n fprintf ( 1, '\\n' );\n\n n = 41;\n p = 63;\n\n [ x, w ] = hermite_gk22_set ( n );\n\n for m = 0 : 2 : min ( p + 2, 20 )\n\n exact = hermite_integral ( m );\n\n if ( m == 0 )\n f = ones ( n, 1 );\n else\n f = zeros ( n, 1 );\n f = x.^m;\n end\n\n estimate = w(1:n)' * f(1:n);\n\n error = abs ( exact - estimate );\n\n fprintf ( 1, ' %8d %8d %14.6e %14.6e %14.6e\\n', ...\n m, n, estimate, exact, error );\n\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' HERMITE_GK24_SET:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' M N Estimate Exact Error\\n' );\n fprintf ( 1, '\\n' );\n\n n = 43;\n p = 67;\n\n [ x, w ] = hermite_gk24_set ( n );\n\n for m = 0 : 2 : min ( p + 2, 20 )\n\n exact = hermite_integral ( m );\n\n if ( m == 0 )\n f = ones ( n, 1 );\n else\n f = zeros ( n, 1 );\n f = x.^m;\n end\n\n estimate = w(1:n)' * f(1:n);\n\n error = abs ( exact - estimate );\n\n fprintf ( 1, ' %8d %8d %14.6e %14.6e %14.6e\\n', ...\n m, n, estimate, exact, 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/quadrule/quadrule_test096.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7081549710938291}} {"text": "function [e1, e2, E1_l, E2_l] = ahmLinEndpoints(l,t1,t2)\n\n% AHMLINENDPOINTS AHM line endpoints.\n% AHMLINENDPOINTS(L,T) returns the 3D Euclidean endpoint of the\n% AHM line L at abscissa T.\n%\n% [E1,E2] = AHMLINENDPOINTS(L,T1,T2) returns two 3D Euclidean endpoints\n% at abscissas T1 and T2.\n%\n% [e1,e2,E1_l,E2_l] = AHMLINENDPINTS(...) returns the Jacobians of the\n% endopints wrt L.\n%\n% See also AHMLINSEGMENT, AHMLIN2SEG, AHMLIN2IDPPNTS.\n\n% Copyright 2009 Teresa Vidal.\n\nif nargout <= 2\n\n % support segment\n s = ahmLin2seg(l);\n\n % support points\n p1 = s(1:3);\n p2 = s(4:6);\n\n % endpoints\n e1 = (1-t1)*p1 + t1*p2;\n e2 = (1-t2)*p1 + t2*p2;\n\nelse\n \n [s, S_l] = ahmLin2seg(l); % support segment\n \n p1 = s(1:3); % support points\n p2 = s(4:6);\n \n P1_l = S_l(1:3,:); % jacobians of sup points\n P2_l = S_l(4:6,:);\n \n e1 = (1-t1)*p1 + t1*p2; % endpoints\n e2 = (1-t2)*p1 + t2*p2;\n \n E1_p1 = 1-t1; % jacobians of endpoints\n E1_p2 = t1;\n E2_p1 = 1-t2;\n E2_p2 = t2;\n \n E1_l = E1_p1*P1_l + E1_p2*P2_l; % chain rule\n E2_l = E2_p1*P1_l + E2_p2*P2_l;\n\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/Lines/ahmLinEndpoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875225, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7081549663328108}} {"text": "function d = p09_fd ( p )\n\n%*****************************************************************************80\n%\n%% P09_FD is a signed distance function for problem 9.\n%\n% Discussion:\n%\n% Notice that the V1 and V2 arrays, which define hexagons, contain SEVEN\n% points, not six. This is necessary in order for DPOLY to carry out its\n% calculations correctly.\n%\n% Licensing:\n%\n% (C) 2004 Per-Olof Persson. \n% See COPYRIGHT.TXT for details.\n%\n% Modified:\n%\n% 11 March 2006\n%\n% Parameters:\n%\n% Input, real P, one or more points.\n%\n% Output, real D, the signed distance of each point to the boundary of the region.\n%\n v1 = [ 0.15, 0.75;\n 0.20, 0.6634;\n 0.30, 0.6634;\n 0.35, 0.75;\n 0.30, 0.8366;\n 0.20, 0.8366;\n 0.15, 0.75 ];\n\n d1 = dpoly ( p, v1 );\n\n v2 = [ 0.50, 0.40;\n 0.55, 0.3134;\n 0.65, 0.3134;\n 0.70, 0.40;\n 0.65, 0.4866;\n 0.55, 0.4866;\n 0.50, 0.40 ];\n\n d2 = dpoly ( p, v2 );\n\n d3 = dunion ( d1, d2 );\n\n d4 = drectangle ( p, 0.0, 1.0, 0.0, 1.0 );\n\n d = ddiff ( d4, d3 );\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/distmesh/p09_fd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7081549642032107}} {"text": "function gb=gabor_fn(sigma,theta,lambda,psi,gamma)\n \nsigma_x = sigma;\nsigma_y = sigma/gamma;\n \n% Bounding box\nnstds = 3;\nxmax = max(abs(nstds*sigma_x*cos(theta)),abs(nstds*sigma_y*sin(theta)));\nxmax = ceil(max(1,xmax));\nymax = max(abs(nstds*sigma_x*sin(theta)),abs(nstds*sigma_y*cos(theta)));\nymax = ceil(max(1,ymax));\nxmin = -xmax; ymin = -ymax;\n[x,y] = meshgrid(xmin:xmax,ymin:ymax);\n \n% Rotation \nx_theta=x*cos(theta)+y*sin(theta);\ny_theta=-x*sin(theta)+y*cos(theta);\n \ngb= 1/(2*pi*sigma_x *sigma_y) * exp(-.5*(x_theta.^2/sigma_x^2+y_theta.^2/sigma_y^2)).*cos(2*pi/lambda*x_theta+psi);\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/28751-gabor-filtering-on-an-image/gab/gabor_fn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.7081357704558997}} {"text": "function x = triangle_cdf_inv ( cdf, a, b, c )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_CDF_INV inverts the Triangle CDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 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% Input, real A, B, C, the parameters of the PDF.\n% A <= B <= C and A < C.\n%\n% Output, real X, the corresponding argument.\n%\n if ( cdf < 0.0 | 1.0 < cdf )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_CDF_INV - Fatal error!\\n' );\n fprintf ( 1, ' CDF < 0 or 1 < CDF.\\n' );\n error ( 'TRIANGLE_CDF_INV - Fatal error!' );\n end\n\n d = 2.0 / ( c - a );\n cdf_mid = 0.5 * d * ( b - a );\n\n if ( cdf <= cdf_mid )\n x = a + sqrt ( cdf * ( b - a ) * ( c - a ) );\n else\n x = c - sqrt ( ( c - b ) * ( ( c - b ) - ( cdf - cdf_mid ) * ( c - a ) ) );\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/prob/triangle_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8311430394931456, "lm_q1q2_score": 0.7080946350842034}} {"text": "function Speciation\n% Speciation \n% using MATLAB \n%\n% $Ekkehard Holzbecher $Date: 2006/05/03 $\n%--------------------------------------------------------------------------\ntoll = 1.e-15; % tolerance\nnmax = 50; % max. no. of iterations \nSe = [-1 -1 1]; % reaction matrix\nlogc = [1.e-10; 1.e-10; 0]; % initial guess (log)\nlogK = [-0.93]; % equilibrium constants (log)\nlogu = [-0.301; 0]; % total concentrations (log)\n \nln10 = 2.3026;\nn=size(Se,1); m=size(Se,2);\nS1 = Se(:,1:m-n); \nS2 = Se(:,m-n+1:m); \nS1star = -S2\\S1; \nU = [eye(m-n),S1star'];\n\nc=exp(ln10*logc);\nu(1:m-n,1) = exp(ln10*logu); \nerr = toll+1; nit = 0;\nwhile (nit < nmax && err > toll),\n nit = nit+1;\n F = [U*c-u; Se*logc-logK];\n DF = [U; Se*diag((1/ln10)./c)]; \n dc = -DF\\F; \n cn = max(c+dc,0.005*abs(c));\n err = max(abs(cn-c));\n c = cn;\nend\ndisplay (['Species concentrations obtained after ' num2str(nit) ' iterations:']);\nc\nexp(ln10*logK)-c(3)/c(1)/c(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/41147-environmental-modeling-using-matlab/Speciation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.7080793988730306}} {"text": "function C=tprod(A,B)\n% Computes the tensor-product of two P dimensional tensors (A & B)\n% All dimensions of the inputed tensor except for the 2nd must be the same.\n% The algorithm follows from paper by ...\n%\n% INPUTS:\n%\n% A - n1 x n2 x n3 .... nP tensor\n% B - n2 x n4 x n3 .... nP tensor\n%\n% OUTPUTS: \n%\n% C - n1 x n4 x n3 .... nP tensor\n%\n% Original author : Misha Kilmer, Ning Hao\n% Edited by : G. Ely, S. Aeron, Z. Zhang, ECE, Tufts Univ. 03/16/2015\n\n\nsa = size(A);\nsb = size(B);\n\nfaces = length(sa);\n\nnfaces = prod(sb(3:end));\n\nfor i = 3:faces\n A = fft(A,[],i);\n B = fft(B,[],i);\nend\nsc = sa;\nsc(2) = sb(2);\nC = zeros(sc);\nfor i = 1:nfaces\n C(:,:,i) = A(:,:,i)*B(:,:,i);\nend\nfor i = 3:faces\n C = ifft(C,[],i);\nend\n\n\n\n", "meta": {"author": "andrewssobral", "repo": "mctc4bmi", "sha": "fbcbcd25654b818646387c3d6a64304fb60e12dd", "save_path": "github-repos/MATLAB/andrewssobral-mctc4bmi", "path": "github-repos/MATLAB/andrewssobral-mctc4bmi/mctc4bmi-fbcbcd25654b818646387c3d6a64304fb60e12dd/algs_tc/tSVD/tSVD/tprod.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.7080268245257632}} {"text": "function [mappedX, mapping] = charting(X, no_dims, no_analyzers, max_iterations, eig_impl)\n%CHARTING Performs manifold charting on dataset X \n%\n% [mappedX, mapping] = charting(X, no_dims, no_analyzers, max_iterations, eig_impl)\n%\n% Performs manifold charting on dataset X to reduce its dimensionality to\n% no_dims dimensions. The variable no_analyzers determines the number of\n% local factor analyzers that is used in the mixture of factor analyzers\n% (default = 40). The variable max_iterations sets the maximum number of\n% iterations that is employed in the EM algorithm (default = 200).\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n\n if ~exist('no_dims', 'var')\n no_dims = 2;\n end\n if ~exist('no_analyzers', 'var')\n no_analyzers = 40;\n end\n if ~exist('max_iterations', 'var')\n max_iterations = 200;\n end\n \n % Initialize some parameters\n tol = 1e-10; % regularization parameter\n min_std = 1e-3; % minimum STD of Gaussians\n kf = no_analyzers * (no_dims + 1);\n\n % Construct MFA model on the data\n disp('Running EM algorithm and compute local factor analyzers...');\n [LX, MX, PX] = mppca(X', no_dims, no_analyzers, tol, max_iterations, min_std);\n [R, Z] = infermfa(X', LX, MX, PX);\n \n % Adds last entry = 1 in posterior mean to handle means of factor analyzers\n Z(no_dims + 1,:,:) = 1; \n Z = permute(Z, [1 3 2]);\n \n % Construct blockdiagonal matrix D\n disp('Performing manifold charting...');\n D = zeros((no_dims + 1) * no_analyzers, (no_dims + 1) * no_analyzers);\n for i=1:no_analyzers\n Ds = zeros(no_dims + 1, no_dims + 1);\n for j=1:size(X, 1)\n Ds = Ds + R(i, j) .* (Z(:,i,j) * Z(:,i,j)');\n end\n D((i - 1) * (no_dims + 1) + 1:i * (no_dims + 1), (i - 1) * (no_dims + 1) + 1:i * (no_dims + 1)) = Ds;\n end\n \n % Construct responsibility weighted local representation matrix U\n R = reshape(R, [1 no_analyzers size(X, 1)]);\n U = reshape(bsxfun(@times, R, Z), [kf size(X, 1)])';\n \n % Solve generalized eigenproblem\n if strcmp(eig_impl, 'Matlab')\n options.disp = 0;\n options.isreal = 1;\n options.issym = 1;\n [V, lambda] = eigs(D - U' * U, U' * U, no_dims + 1, 'SM', options);\n else\n options.Disp = 0;\n options.LSolver = 'bicgstab';\n [V, lambda] = jdqz(D - U' * U, U' * U, no_dims + 1, 'SM', options);\n end\n [lambda, ind] = sort(diag(lambda));\n V = V(:,ind(2:end));\n \n % Compute final lowdimensional data representation\n mappedX = U * V;\n \n % Store mapping data for out-of-sample extension\n if nargout > 1\n mapping.LX = LX;\n mapping.MX = MX;\n mapping.PX = PX;\n mapping.V = V;\n end\n ", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/charting.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7080268180023753}} {"text": "function [parent_pop] = osy(parent_pop)\n% This procedure implements Osyczka and Kundu's function.\n% The canonical zdt1 function is defined as below --\n% f_1 = -25.0 * ((x_1 - 2)^2 - (x_2 - 2)^2 - (x_3 - 1)^2 \n% - (x_4 - 4)^2 - (x_5 - 1)^2)\n% f_2 = sum_{i=1}^n x_i^2.0\n% s.t.\n% c_1(x) = x_1 + x_2 - 2 >= 0\n% c_2(x) = 6 - x_1 - x_2 >= 0\n% c_3(x) = 2 - x_2 + x_1 >= 0\n% c_4(x) = 2 - x_1 + 3x_2 >= 0\n% c_5(x) = 4 - (x_3 - 3)^2 - x_4 >= 0\n% c_6(x) = (x_5 - 3)^2 + x_6 - 4 >= 0\n% where,\n% 0 <= x_1 <= 10.0\n% 0 <= x_2 <= 10.0\n% 1 <= x_3 <= 5.0\n% 0 <= x_4 <= 6.0\n% 1 <= x_5 <= 5.0\n% 0 <= x_6 <= 10.0\n\nglobal nreal ;\nglobal ncon ;\nglobal nobj ;\n\ncindex = nreal + nobj + 1 : nreal + nobj + ncon ;\n\n% disp(parent_pop(1,:))\n\nx = parent_pop(:,1:nreal);\nf1 = -(25.0 .* ((x(:,1) - 2.0) .^ 2.0) + ((x(:,2) - 2.0) .^ 2.0) ...\n + ((x(:,3) - 1.0) .^ 2.0) + ((x(:,4) - 4.0) .^ 2.0) ... \n + ((x(:,5) - 1.0) .^ 2.0));\nf2 = sum((x .^ 2.0), 2) ;\n\nc = parent_pop(:,cindex) ;\n% disp(c(1,:))\nc(:,1) = ((x(:,1) + x(:,2)) ./ 2.0) - 1.0 ;\nc(:,2) = 1.0 - ((x(:,1) + x(:,2)) ./ 6.0);\nc(:,3) = 1.0 - (x(:,2) ./ 2.0) + (x(:,1) ./ 2.0);\nc(:,4) = 1.0 - (x(:,1) ./ 2.0) + (3.0 .* (x(:,2) ./ 2.0));\nc(:,5) = 1.0 - (((x(:,3) - 3.0) .^ 2.0) ./ 4.0) - (x(:,4) ./ 4.0);\nc(:,6) = (((x(:,5) - 3.0) .^ 2.0) ./ 4.0) + (x(:,6) ./ 4.0) - 1.0;\nparent_pop(:, (nreal+1)) = f1;\nparent_pop(:, (nreal+2)) = f2;\nparent_pop(:,cindex) = c ;\nend", "meta": {"author": "chudur-budur", "repo": "nsga2-matlab", "sha": "58c2ca3729c1c871dcd3bda310693f19cf181a9e", "save_path": "github-repos/MATLAB/chudur-budur-nsga2-matlab", "path": "github-repos/MATLAB/chudur-budur-nsga2-matlab/nsga2-matlab-58c2ca3729c1c871dcd3bda310693f19cf181a9e/problemdef/osy.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7080140815577108}} {"text": "function k = calcWaveNumber(omega,waterDepth,g,deepWater)\n% Solves the wave dispersion relation :math:`\\omega^2 = g k*tanh(k h)` for\n% the wave number\n% \n% Parameters\n% ----------\n% omega : float\n% Wave frequency [rad/s]\n% \n% waterDepth : float\n% Water depth [m]\n% \n% g : float\n% Gravitational acceleration [m/s^2]\n% \n% deepWater : integar\n% waveClass flag inidicating a deep water wave [-]\n% \n% Returns\n% ------------\n% k : float\n% Wave number [m]\n% \n\narguments\n omega\n waterDepth\n g = 9.81;\n deepWater = 0;\nend\n\n% Deep water approximation, initial guess \nk = omega.^2./g;\n\n% Iterate for shallow and intermediate water, full dispersion relationship\nif deepWater == 0\n for i = 1:100\n k = omega.^2./g./tanh(k.*waterDepth);\n end\nend\n\nend\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/functions/BEMIO/calcWaveNumber.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741241296943, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.7079226094666693}} {"text": "function op = proj_l1( q, d )\n%PROJ_L1 Projection onto the scaled 1-norm ball.\n% OP = PROJ_L1( Q ) returns an operator implementing the \n% indicator function for the 1-norm ball of radius q,\n% { X | norm( X, 1 ) <= q }. Q is optional; if omitted,\n% Q=1 is assumed. But if Q is supplied, it must be a positive\n% real scalar.\n%\n% OP = PROJ_L1( Q, D ) uses a scaled 1-norm ball of radius q,\n% { X | norm( D.*X, 1 ) <= 1 }. D should be the same size as X\n% and non-negative (some zero entries are OK).\n%\n% Dual: prox_linf.m\n% See also: prox_linf, prox_l1, proj_linf\n\nif nargin == 0,\n\tq = 1;\nelseif ~isnumeric( q ) || ~isreal( q ) || numel( q ) ~= 1 || q <= 0,\n\terror( 'Argument must be positive.' );\nend\nif nargin < 2 || isempty(d) || numel(d)==1\n if nargin>=2 && ~isempty(d)\n % d is a scalar, so norm( d*x ) <= q is same as norm(x)<=q/d\n if d==0\n error('If d==0 in proj_l1, the set is just {0}, so use proj_0');\n elseif d < 0\n error('Require d >= 0');\n end\n q = q/d;\n end\n op = @(varargin)proj_l1_q(q, varargin{:} );\nelse\n if any(d<0)\n error('All entries of d must be non-negative');\n end\n op = @(varargin)proj_l1_q_d(q, d, varargin{:} );\nend\n\nfunction [ v, x ] = proj_l1_q( q, x, t )\nv = 0;\nswitch nargin,\ncase 2,\n\tif nargout == 2,\n\t\terror( 'This function is not differentiable.' );\n\telseif norm( x(:), 1 ) > q,\n\t\tv = Inf;\n\tend\ncase 3,\n s = sort(abs(nonzeros(x)),'descend');\n cs = cumsum(s);\n % ndx = find( cs - (1:numel(s))' .* [ s(2:end) ; 0 ] >= q, 1 );\n ndx = find( cs - (1:numel(s))' .* [ s(2:end) ; 0 ] >= q+2*eps(q), 1 ); % For stability\n if ~isempty( ndx )\n thresh = ( cs(ndx) - q ) / ndx;\n x = x .* ( 1 - thresh ./ max( abs(x), thresh ) ); % May divide very small numbers\n end\notherwise,\n error( 'Not enough arguments.' );\nend\n\n% Allows scaling. Added Feb 21 2014\nfunction [ v, x ] = proj_l1_q_d( q, d, x, t )\nv = 0;\nswitch nargin,\ncase 3,\n\tif nargout == 2,\n\t\terror( 'This function is not differentiable.' );\n\telseif norm( d(:).*x(:), 1 ) > q,\n\t\tv = Inf;\n\tend\ncase 4,\n [lambdas,srt] = sort(abs(nonzeros(x./d)),'descend');\n s = abs(x(:).*d(:)); s = s(srt);\n dd = d(:).^2; dd= dd(srt);\n cs = cumsum(s);\n cd = cumsum(dd);\n ndx = find( cs - lambdas.*cd >= q+2*eps(q), 1, 'first');\n if ~isempty( ndx )\n ndx = ndx - 1;\n lambda = ( cs(ndx) - q )/cd(ndx);\n x = sign(x).*max( 0, abs(x) - lambda*d );\n end\notherwise,\n error( 'Not enough arguments.' );\nend\n\n% TFOCS v1.3 by Stephen Becker, Emmanuel Candes, and Michael Grant.\n% Copyright 2013 California Institute of Technology and CVX Research.\n% See the file LICENSE for full license information.\n", "meta": {"author": "cvxr", "repo": "TFOCS", "sha": "164ada20401cd445930673e42bb3d2a5489f2030", "save_path": "github-repos/MATLAB/cvxr-TFOCS", "path": "github-repos/MATLAB/cvxr-TFOCS/TFOCS-164ada20401cd445930673e42bb3d2a5489f2030/proj_l1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7078890445286207}} {"text": "function [ n_data, x, fx ] = psi_values ( n_data )\n\n%*****************************************************************************80\n%\n%% PSI_VALUES returns some values of the Psi or Digamma function.\n%\n% Discussion:\n%\n% In Mathematica, the function can be evaluated by:\n%\n% PolyGamma[x]\n%\n% or\n%\n% PolyGamma[0,x]\n%\n% PSI(X) = d ln ( Gamma ( X ) ) / d X = Gamma'(X) / Gamma(X)\n%\n% PSI(1) = -Euler's constant.\n%\n% PSI(X+1) = PSI(X) + 1 / X.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 June 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Milton Abramowitz and Irene Stegun,\n% Handbook of Mathematical Functions,\n% US Department of Commerce, 1964.\n%\n% Stephen Wolfram,\n% The Mathematica Book,\n% Fourth Edition,\n% Wolfram Media / Cambridge University Press, 1999.\n%\n% Parameters:\n%\n% Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n% first call. On each call, the routine increments N_DATA by 1, and\n% returns the corresponding data; when there is no more data, the\n% output value of N_DATA will be 0 again.\n%\n% Output, real X, the argument of the function.\n%\n% Output, real FX, the value of the function.\n%\n n_max = 20;\n\n fx_vec = [ ...\n -10.42375494041108E+00, ...\n -5.289039896592188E+00, ...\n -3.502524222200133E+00, ...\n -2.561384544585116E+00, ...\n -1.963510026021423E+00, ...\n -1.540619213893190E+00, ...\n -1.220023553697935E+00, ...\n -0.9650085667061385E+00, ...\n -0.7549269499470514E+00, ...\n -0.5772156649015329E+00, ...\n -0.4237549404110768E+00, ...\n -0.2890398965921883E+00, ...\n -0.1691908888667997E+00, ...\n -0.6138454458511615E-01, ...\n 0.3648997397857652E-01, ...\n 0.1260474527734763E+00, ...\n 0.2085478748734940E+00, ...\n 0.2849914332938615E+00, ...\n 0.3561841611640597E+00, ...\n 0.4227843350984671E+00 ];\n\n x_vec = [ ...\n 0.1E+00, ...\n 0.2E+00, ...\n 0.3E+00, ...\n 0.4E+00, ...\n 0.5E+00, ...\n 0.6E+00, ...\n 0.7E+00, ...\n 0.8E+00, ...\n 0.9E+00, ...\n 1.0E+00, ...\n 1.1E+00, ...\n 1.2E+00, ...\n 1.3E+00, ...\n 1.4E+00, ...\n 1.5E+00, ...\n 1.6E+00, ...\n 1.7E+00, ...\n 1.8E+00, ...\n 1.9E+00, ...\n 2.0E+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 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/psi_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.8198933447152497, "lm_q1q2_score": 0.7078890349004874}} {"text": "function out = bicubic_interpolation_cell(p, x, y)\nv(1) = cubic_interpolation_cell(p(1,:), y); \nv(2) = cubic_interpolation_cell(p(2,:), y);\n v(3) = cubic_interpolation_cell(p(3,:), y);\n v(4) = cubic_interpolation_cell(p(4,:), y);\n out = cubic_interpolation_cell(v, x);\n \nend", "meta": {"author": "zhangqianqianQQ", "repo": "MachineVisionAlgorithm", "sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee", "save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm", "path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/去噪算法/SPTWO_matlab-master/bicubic_interpolation_cell.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.7078834637750799}} {"text": "function [cc,c0]=lpcpf2cc(pf,np,f)\n%LPCPF2CC Convert power spectrum to complex cepstrum CC=(PF,NP)\n%\n% Inputs: pf(nf,n) Power spectrum, uniformly spaced DC to Nyquist\n% np Number of cepstral coefficients to calculate [n-1]\n% f(1,n) Frequencies of pf columns [linspace(0,0.5,n)]\n%\n% Outputs: cc(nf,np) Complex spectrum from DC to Nyquist\n% c0(nf,1) The zeroth cepstral coefficient, c(0)\n%\n% Note since the log spectrum is not normally bandlimited, this conversion is not exact unless n >> np\n\n% Copyright (C) Mike Brookes 1998-2014\n% Version: $Id: lpcpf2cc.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,nq]=size(pf);\nif nargin<2 || ~numel(np) np=nq-1; end\nif nargin<3 || ~numel(f)\n cc=rsfft(log(pf.')).'/(2*nq-2);\n c0=cc(:,1)*0.5;\n cc(:,nq)=cc(:,nq)*0.5;\n if np>nq-1\n cc=[cc(:,2:nq) zeros(nf,np-nq+1)];\n else\n cc=cc(:,2:np+1);\n end\nelse\n cc=0.5*(log(pf)/cos(2*pi*f(:)*(0:min(np,nq-1))));\n c0=cc(:,1);\n cc=cc(:,2:end);\n if np>nq-1\n cc(1,np)=0;\n end\nend\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/lpcpf2cc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7078431747500011}} {"text": "function [stats, TABLE] = SummStats(TEMP,p)\n% =======================================================================\n% Computes descriptive stats of a time series (or a matrix of time series)\n% =======================================================================\n% [stats, TABLE] = SummStats(TEMP,p)\n% -----------------------------------------------------------------------\n% INPUT\n% - TEMP : T obs (rows) x N series (columns)\n% - p = order of time polynomial in the ADF null-hypothesis.\n% p ~exist, does not perform ADF test \n% p = -1, no deterministic part\n% p = 0, for constant term\n% p = 1, for constant plus time-trend\n% p > 1, for higher order polynomial\n% -----------------------------------------------------------------------\n% OUTPUT\n% - stats: [Obs, mean, median, max, min, StDev, AutoCorr, Skew, Kurt,...\n% ADF(4), ADF(4) Conf, ADF(8), ADF(8) Conf]\n% - TABLE: cell, matrix with the names of the stats & the stats\n% =======================================================================\n% Ambrogio Cesa Bianchi, March 2015\n\n[~, c] = size(TEMP);\n\n% Compute summary statistics NaN are not considered (like in Excel)\nmean = nanmean(TEMP);\nmedian = nanmedian(TEMP);\nmax = nanmax(TEMP);\t\nmin = nanmin(TEMP);\t\nStDev = nanstd(TEMP);\nCV = StDev./mean;\n\n% Compute autocorrelation coefficient AutoCorr on the maximum number of\n% observation available per series\nfor i=1:c\n X = TEMP(:,i);\n if isnan(X)==1\n Obs(1,i) = NaN;\n AutoCorr(1,i) = NaN;\n Skew(1,i) = NaN;\n Kurt(1,i) = NaN;\n ADF4(1,i) = NaN;\n ADF4conf(1,i) = NaN;\n ADF8(1,i) = NaN;\n ADF8conf(1,i) = NaN;\n else\n X(any(isnan(X),2),:) = [];\n size_X = size(X);\n Obs(1,i) = size_X(1);\n AutoCorr(1,i) = corr(X(2:end),X(1:end-1));\n Skew(1,i) = skewness(X);\n Kurt(1,i) = kurtosis(X);\n % If less than 20 observations don't do ADF4\n if length(X)<20 || ~exist('p','var')\n ADF4(1,i) = NaN;\n ADF4conf(1,i) = NaN;\n else\n test = adf(X,p,4);\n ADF4(1,i) = test.adf;\n if test.adf I(1)\n ADF4conf(1,i) = 0;\n end\n end\n % If less than 40 observations don't do ADF8\n if length(X)<40 || ~exist('p','var')\n ADF8(1,i) = NaN;\n ADF8conf(1,i) = NaN;\n else\n test = adf(X,p,8);\n ADF8(1,i) = test.adf;\n if test.adf 1 | min(size(Mem2)) > 1\n error('Contingency: Requires two vector arguments')\n return\nend\n\nCont=zeros(max(Mem1),max(Mem2));\n\nfor i = 1:length(Mem1);\n Cont(Mem1(i),Mem2(i))=Cont(Mem1(i),Mem2(i))+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/32994-the-mincentropy-algorithm-for-alternative-clustering/minCEntropy/Contingency.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.707843172647763}} {"text": "function b = isPointOnRay(point, ray, varargin)\n%ISPOINTONRAY Test if a point belongs to a ray.\n%\n% B = isPointOnRay(PT, RAY);\n% Returns 1 if point PT belongs to the ray RAY.\n% PT is given by [x y] and RAY by [x0 y0 dx dy].\n%\n% If PT is a N-by-2 array, and RAY is a M-by-4 array, then the result is\n% a N-by-M array containing the result of each pair-wise test.\n%\n% B = isPointOnRay(PT, RAY, TOL);\n% Specifies the tolerance to use for testing if point is on the ray.\n%\n% Example\n% ray = [10 20 3 4];\n% % test for a point on the ray\n% p1 = [16 28]; \n% isPointOnRay(p1, ray)\n% ans =\n% logical\n% 0\n% % test for a point on the supporting line but \"before\" the origin\n% p2 = [7 16];\n% isPointOnRay(p1, ray)\n% ans =\n% logical\n% 0\n% \n% See also \n% rays2d, points2d, isPointOnLine, isPointOnEdge\n%\n\n% ------\n% Author: David Legland \n% E-mail: david.legland@inrae.fr\n% Created: 2003-10-31\n% Copyright 2003-2022 INRA - TPV URPOI - BIA IMASTE\n\n% extract computation tolerance\ntol = 1e-14;\nif ~isempty(varargin)\n tol = varargin{1};\nend\n\n% number of rays and points\nNr = size(ray, 1);\nNp = size(point, 1);\n\n% if several rays or several points, adapt sizes of arrays\nx0 = repmat(ray(:,1)', Np, 1);\ny0 = repmat(ray(:,2)', Np, 1);\ndx = repmat(ray(:,3)', Np, 1);\ndy = repmat(ray(:,4)', Np, 1);\nxp = repmat(point(:,1), 1, Nr);\nyp = repmat(point(:,2), 1, Nr);\n\n% test if points belongs to the supporting line\nb1 = abs((xp-x0).*dy - (yp-y0).*dx) ./ (dx.*dx + dy.*dy) < tol;\n\n% check if points lie the good direction on the rays\nind = abs(dx) > abs(dy);\nt = zeros(size(b1));\nt(ind) = (xp(ind) - x0(ind)) ./ dx(ind);\nt(~ind) = (yp(~ind) - y0(~ind)) ./ dy(~ind);\n\n% combine the two tests\nb = b1 & (t >= 0);\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/isPointOnRay.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8289388125473629, "lm_q1q2_score": 0.7078414296143494}} {"text": "function t = bal_seq_unrank ( rank, n )\n\n%*****************************************************************************80\n%\n%% BAL_SEQ_UNRANK unranks a balanced sequence.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 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 RANK, the rank of the balanced sequence.\n%\n% Input, integer N, the number of 0's (and 1's) in the sequence.\n% N must be positive.\n%\n% Output, integer T(2*N), a balanced sequence.\n%\n\n%\n% Check.\n%\n if ( n < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BAL_SEQ_UNRANK - Fatal error!\\n' );\n fprintf ( 1, ' Input N is illegal.\\n' );\n error ( 'BAL_SEQ_UNRANK - Fatal error!' );\n end\n\n nseq = bal_seq_enum ( n );\n\n if ( rank < 0 || nseq < rank )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'BAL_SEQ_UNRANK - Fatal error!\\n' );\n fprintf ( 1, ' The input rank is illegal.\\n' );\n error ( 'BAL_SEQ_UNRANK - Fatal error!' );\n end\n\n y = 0;\n low = 0;\n\n for x = 1 : 2 * n\n\n m = mountain ( n, x, y + 1 );\n\n if ( rank <= low + m - 1 )\n y = y + 1;\n t(x) = 0;\n else\n low = low + m;\n y = y - 1;\n t(x) = 1;\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/combo/bal_seq_unrank.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7078414208959115}} {"text": "function btv_test09 ( )\n\n%*****************************************************************************80\n%\n%% BTV_TEST09 tests BURGERS_TIME_VISCOUS with the spike 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_TEST09\\n' );\n fprintf ( 1, ' Test BURGERS_TIME_VISCOUS with the spike initial condition.\\n' );\n\n nx = 81;\n nt = 400;\n t_max = 4.0;\n nu = 0.01;\n bc = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Initial condition: spike\\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_spike, nx, nt, t_max, nu, bc );\n\n x = linspace ( -1.0, +1.0, nx );\n\n figure ( 9 )\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 spike' )\n\n filename = 'btv_test09.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_test09.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7078414095433075}} {"text": "function [Du,area,Dlambda] = gradu(node,elem,u,Dlambda)\n%% GRADU gradient of a finite element function.\n%\n% Du = GRADU(node,elem,u) compute the gradient of a finite element function\n% u on a mesh representing by (node,elem).\n% \n% [Du,area,Dlambda] = GRADU(node,elem,u) also outputs area and Dlambda\n% which is the gradient of P1 basis. \n%\n% Du = GRADU(node,elem,u,Dlambda) compute the gradient with Dlambda. It\n% will save time when Dlambda is available. See recovery.m\n%\n% See also gradu3, gradbasis\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\nif ~exist('Dlambda','var')\n [Dlambda,area] = gradbasis(node,elem);\nend\ndudx = u(elem(:,1)).*Dlambda(:,1,1) + u(elem(:,2)).*Dlambda(:,1,2) ...\n + u(elem(:,3)).*Dlambda(:,1,3);\ndudy = u(elem(:,1)).*Dlambda(:,2,1) + u(elem(:,2)).*Dlambda(:,2,2) ...\n + u(elem(:,3)).*Dlambda(:,2,3); \nDu = [dudx, dudy];", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/fem/gradu.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.707753690246431}} {"text": "function [p P_u P_pol] = omni_retro(u, pol)\n% \n% OMNI_RETRO Retroproject pixel into 3D space.\n% P = OMNI_RETRO(UP, pol) retro-projects the point UP of the image\n% plane into the point P at depth S in 3D space\n%\n% based on M=cam2world(m, ocam_model) from DAVIDE SCARAMUZZA\n% \"Omnidirectional camera calibration toolbox\" CAM2WORLD Project a give\n% pixel point onto the unit sphere M=CAM2WORLD=(m, ocam_model) returns\n% the 3D coordinates of the vector emanating from the single effective\n% viewpoint on the unit sphere\n%\n%\n% Notes\n% - pol: polynom coeff (vec) -> \"distortion\" parametes in a0..an order, not polyval() order\n% we have 4th order polynome \n%\n% Author: Davide Scaramuzza - email: davide.scaramuzza@ieee.org\n% Author: Grigory Abuladze - email: ryhor.a@google.com\n\n% Copyright (C) 2012 Grigory Abuladze @ ASL-vision. \n% Copyright (C) 2008 DAVIDE SCARAMUZZA, ETH Zurich \n\n if nargout == 1 % only points\n % Given an image point it returns the 3D coordinates of its correspondent optical ray \n r = (u(1,:).^2 + u(2,:).^2).^0.5;\n p = [u(1,:);\n u(2,:);\n polyval(pol(end:-1:1), r)];\n p = normc(p); % normalizes coordinates so that they have unit length (projection onto the unit sphere) \n\n else % nargout > 2 -> Jacobians\n \n if size(u,2) > 1\n error('Jacobians not available for multiple points');\n end\n \n r = (u(1)^2 + u(2)^2)^0.5;\n n = numel(pol);\n nn = 0:n-1; % orders vector\n r2n = r.^nn; % powers vector\n p3 = r2n*pol; % \n p = [u(1);\n u(2);\n p3];\n \n [p,P_p] = normvec(p,1);\n \n a0 = pol(1); a1 = pol(2); a2 = pol(3); a3 = pol(4); a4 = pol(5);\n u1 = u(1);\n u2 = u(2);\n r2 = (u1^2 + u2^2);\n r = r2^(1/2);\n \n % all before normalization \n P_u = [...\n [ 1, 0]\n [ 0, 1]\n [ 2*a2*u1 + 4*a4*u1*r2 + (a1*u1)/r + 3*a3*u1*r, 2*a2*u2 + 4*a4*u2*r2 + (a1*u2)/r + 3*a3*u2*r]\n ];\n\n P_pol = [...\n [ 0, 0, 0, 0, 0]\n [ 0, 0, 0, 0, 0]\n [ 1, r, r2, r2^(3/2), r2^2]\n ];\n\n % add normalization\n % f = norm(g()) -> use chain rule\n P_u = P_p * P_u;\n\n \n end\n\nreturn\n\n\n%% Jacobian\nsyms a0 a1 a2 a3 a4 real\nsyms u1 u2 s real\n\n\nu = [u1 u2]';\npol = [a0 a1 a2 a3 a4]';\n\np = omni_retro(u, s, pol);\n\nP_u = simplify(jacobian(p,u))\nP_s = simplify(jacobian(p,s))\nP_pol = simplify(jacobian(p,pol))\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/omni_retro.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.707718658292259}} {"text": "%ZSSD Sum of squared differences\n%\n% M = ZSSD(I1, I2) is the zero-mean sum of squared differences between the \n% two equally sized image patches I1 and I2. The result M is a scalar that\n% indicates image similarity, a value of 0 indicates identical pixel patterns\n% and is increasingly positive as image dissimilarity increases.\n%\n% Notes::\n% - The ZSSD similarity measure is invariant to changes in image brightness\n% offset.\n%\n% See also SDD, SAD, NCC, ISIMILARITY.\n\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB 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% MVTB 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 MVTB. If not, see .\n\nfunction m = zssd(w1, w2)\n\n\tw1 = w1 - mean(w1(:));\n\tw2 = w2 - mean(w2(:));\n\n\tm = (w1-w2).^2;\n m = sum(m(:));\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/zssd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7077186571792592}} {"text": "function c=ref_dft(f)\n%REF_DFT Reference Discrete Fourier Transform\n% Usage: c=ref_dft(f);\n%\n% REF_DFT(f) computes the unitary discrete Fourier transform of f.\n%\n% AUTHOR: Jordy van Velthoven\n\nL=size(f,1);\nW=size(f,2);\nc= zeros(L,W);\n\nfor w=1:W\nfor k=0:L-1\n for l=0:L-1\n c(k+1,w) = c(k+1,w) + f(l+1,w) * exp(-2*pi*i*k*l/L);\n end;\nend;\nend\n\nc = c./sqrt(L);\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_dft.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7077186524248485}} {"text": "function result = cone_unit_3d ( func )\n\n%*****************************************************************************80\n%\n%% CONE_UNIT_3D approximates an integral inside a unit cone in 3D.\n%\n% Integration Region:\n%\n% X**2 + Y**2 <= 1 - Z\n% 0 <= Z <= 1.\n%\n% Discussion:\n%\n% An 48 point degree 7 formula, Stroud CN:S2:7-1, is used.\n%\n% (There is a typographical error in the S2:7-1 formula for B3.)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 May 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Arthur Stroud,\n% Approximate Calculation of Multiple Integrals,\n% Prentice Hall, 1971, page 339.\n%\n% Parameters:\n%\n% Input, external FUNC, the name of the user supplied function which\n% evaluates F(X,Y,Z), of the form\n% function value = func ( x, y, z )\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n u = [ 0.04850054945E+00, 0.2386007376E+00, 0.5170472951E+00, 0.7958514179E+00 ];\n w1 = [ 0.1108884156E+00, 0.1434587878E+00, 0.06863388717E+00, 0.01035224075E+00 ];\n\n a = sqrt ( 3.0E+00 ) / 2.0E+00;\n b = sqrt ( ( 27.0E+00 - 3.0E+00 * sqrt ( 29.0E+00 ) ) / 104.0E+00 );\n c = sqrt ( ( 27.0E+00 + 3.0E+00 * sqrt ( 29.0E+00 ) ) / 104.0E+00 );\n w2(1:3) = 3.0E+00 * [ ...\n 2.0E+00 / 27.0E+00, ...\n ( 551.0E+00 + 4.0E+00 * sqrt ( 29.0E+00 ) ) / 6264.0E+00, ...\n ( 551.0E+00 - 4.0E+00 * sqrt ( 29.0E+00 ) ) / 6264.0E+00 ];\n\n quad = 0.0E+00;\n\n for i = 1 : 4\n\n x = a * ( 1.0E+00 - u(i) );\n y = 0.0E+00;\n z = u(i);\n quad = quad + w1(i) * w2(1) * feval ( func, x, y, z );\n\n x = - a * ( 1.0E+00 - u(i) );\n y = 0.0E+00;\n z = u(i);\n quad = quad + w1(i) * w2(1) * feval ( func, x, y, z );\n\n x = 0.0E+00;\n y = a * ( 1.0E+00 - u(i) );\n z = u(i);\n quad = quad + w1(i) * w2(1) * feval ( func, x, y, z );\n\n x = 0.0E+00;\n y = - a * ( 1.0E+00 - u(i) );\n z = u(i);\n quad = quad + w1(i) * w2(1) * feval ( func, x, y, z );\n\n end\n\n for i = 1 : 4\n\n x = b * ( 1.0E+00 - u(i) );\n y = b * ( 1.0E+00 - u(i) );\n z = u(i);\n quad = quad + w1(i) * w2(2) * feval ( func, x, y, z );\n\n x = - b * ( 1.0E+00 - u(i) );\n y = b * ( 1.0E+00 - u(i) );\n z = u(i);\n quad = quad + w1(i) * w2(2) * feval ( func, x, y, z );\n\n x = - b * ( 1.0E+00 - u(i) );\n y = - b * ( 1.0E+00 - u(i) );\n z = u(i);\n quad = quad + w1(i) * w2(2) * feval ( func, x, y, z );\n\n x = b * ( 1.0E+00 - u(i) );\n y = - b * ( 1.0E+00 - u(i) );\n z = u(i);\n quad = quad + w1(i) * w2(2) * feval ( func, x, y, z );\n\n x = c * ( 1.0E+00 - u(i) );\n y = c * ( 1.0E+00 - u(i) );\n z = u(i);\n quad = quad + w1(i) * w2(3) * feval ( func, x, y, z );\n\n x = - c * ( 1.0E+00 - u(i) );\n y = c * ( 1.0E+00 - u(i) );\n z = u(i);\n quad = quad + w1(i) * w2(3) * feval ( func, x, y, z );\n\n x = - c * ( 1.0E+00 - u(i) );\n y = - c * ( 1.0E+00 - u(i) );\n z = u(i);\n quad = quad + w1(i) * w2(3) * feval ( func, x, y, z );\n\n x = c * ( 1.0E+00 - u(i) );\n y = - c * ( 1.0E+00 - u(i) );\n z = u(i);\n quad = quad + w1(i) * w2(3) * feval ( func, x, y, z );\n\n end\n\n r = 1.0E+00;\n h = 1.0E+00;\n\n volume = cone_volume_3d ( r, h );\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/cone_unit_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7076970909750693}} {"text": "function PoiseuilleFlow( varargin )\n%POISOILLEFLOW Summary of this function goes here\n% Detailed explanation goes here\nclose all; % closes all figures\naddpath('../Functions');\n\nh=4; % height of the channel\ndPdx=-0.01; % pressure gradient in x direction\nmu=0.001; % dynamic viscosity\n\n% function for the analytical solution\nu_analFunc=@(y) -0.5*h^2/mu*dPdx*(1-(y/h).^2);\n\n% create mesh\nm=createMesh2D(20,20,2*h,2*h);\n\n%% Boundary Conditions\nU_BC = createBC(m); % all Neumann boundary condition structure \n\n% Assign boundary conditions\nU_BC.left.a(:) = 1; U_BC.left.b(:)=0; U_BC.left.c(:)=0; % Dirichlet for the left boundary \nU_BC.right.a(:) = 1; U_BC.right.b(:)=0; U_BC.right.c(:)=0; % Dirichlet for the left boundary \nU_BC.top.a(:) = 0; U_BC.top.b(:)=1; U_BC.top.c(:)=0; % Dirichlet for the left boundary \nU_BC.bottom.a(:) = 0; U_BC.bottom.b(:)=1; U_BC.bottom.c(:)=0; % Dirichlet for the left boundary \n\nV_BC = createBC(m); % all Neumann boundary condition structure \n\n% Assign boundary conditions\nV_BC.top.a(:) = 0; V_BC.top.b(:)=1; V_BC.top.c(:)=0; % Dirichlet for the left boundary \nV_BC.bottom.a(:) = 0; V_BC.bottom.b(:)=1; V_BC.bottom.c(:)=0; % Dirichlet for the left boundary \nV_BC.left.a(:) = 0; V_BC.left.b(:)=1; V_BC.left.c(:)=0; % Dirichlet for the left boundary \nV_BC.right.a(:) = 0; V_BC.right.b(:)=1; V_BC.right.c(:)=0; % Dirichlet for the left boundary \n\nBC_pressureCorrection = createBC(m);\nBC_pressureCorrection.left.a(:) = 1; BC_pressureCorrection.left.b(:)=0; BC_pressureCorrection.left.c(:)=0;\nBC_pressureCorrection.right.a(:) = 1; BC_pressureCorrection.right.b(:)=0; BC_pressureCorrection.right.c(:)=0;\nBC_pressureCorrection.bottom.a(:) = 1; BC_pressureCorrection.bottom.b(:)=0; BC_pressureCorrection.bottom.c(:)=0;\nBC_pressureCorrection.bottom.a(end/2) = 0; BC_pressureCorrection.bottom.b(end/2)=1; BC_pressureCorrection.bottom.c(end/2)=1;\nBC_pressureCorrection.top.a(:) = 1; BC_pressureCorrection.top.b(:)=0; BC_pressureCorrection.top.c(:)=0;\n\n% constant pressure - so there is no gradient\np_cellVar=createCellVariable(m,1,BC_pressureCorrection);\n\nmu_cellVar=createCellVariable(m,0.001);\nmu_faceVar=createFaceVariable(m,0.001);\n\nrho=1000;\nrho_cellVar=createCellVariable(m,rho);\nrho_faceVar=createFaceVariable(m,rho);\n\nU_cellVar=createCellVariable(m,0,U_BC);\nV_cellVar=createCellVariable(m,0,V_BC);\nfaceVelocity=createFaceVariable(m,[0 0]);\n\npGradMat = gradientCellTerm(p_cellVar);\nhelpVarx = createCellVariable(m,dPdx);\nhelpVary = createCellVariable(m,0);\npGradMat.xvalue=helpVarx.value(2:end-1,2:end-1);\npGradMat.yvalue=helpVary.value(2:end-1,2:end-1);\n\n% solve momentum equation Momentum equation\n[U_cellVar,~,~,~]=MomentumEq(1,m,pGradMat,mu_faceVar,faceVelocity,U_cellVar,V_cellVar,U_BC,V_BC,rho,'SIMPLE');\n\ny_anal=linspace(0,h,100);\nu_anal=u_analFunc(y_anal);\n\nfigure;\nplot(u_anal,y_anal); % plot analytical solution\nhold on;\nplot(U_cellVar.value(3,2:end-1),U_cellVar.domain.cellcenters.y-h,'o');\nhold off;\nfigure;\nvisualizeCells(U_cellVar);\n\n\nend\n\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Examples/External/SteadyLidDrivenCavityProblem/Testcases/PoiseuilleFlow.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7076970870653102}} {"text": "function stats = grayrlprops(varargin)\n\n%GRAYCOPROPS Properties of gray-level run-length matrix.\n% -------------------------------------------\n% STATS = GRAYCOPROPS(GLRLM,PROPERTIES) Each element in GLRLM, (r,c),\n% is the probability occurrence of pixel having gray level values r, run-length c in the image.\n% GRAYCOPROPS is to calculate PROPERTIES.\n% -------------------------------------------\n% Requirements:\n% -------------------------------------------\n% GLRLM mustbe an cell array of valid gray-level run-length\n% matrices.Recall that a valid glrlm must be logical or numerical.\n% -------------------------------------------\n% Current supported statistics include:\n% -------------------------------------------\n% Short Run Emphasis (SRE)\n% Long Run Emphasis (LRE)\n% Gray-Level Nonuniformity (GLN)\n% Run Length Nonuniformity (RLN)\n% Run Percentage (RP)\n% Low Gray-Level Run Emphasis (LGRE)\n% High Gray-Level Run Emphasis (HGRE)\n% Short Run Low Gray-Level Emphasis (SRLGE)\n% Short Run High Gray-Level Emphasis (SRHGE)\n% Long Run Low Gray-Level Emphasis (LRLGE)\n% Long Run High Gray-Level Emphasis (LRHGE)\n% --------------------------------------------\n% Reference:\n% --------------------------------------------\n% Xiaoou Tang,Texture Information in Run-Length Matrices\n% IEEE TRANSACTIONS ON IMAGE PROCESSING, VOL.7, NO.11,NOVEMBER 1998\n% ---------------------------------------------\n% See also GRAYRLMATRIX.\n% ---------------------------------------------\n% Author:\n% ---------------------------------------------\n% (C)Xunkai Wei \n% Beijing Aeronautical Technology Research Center\n% Beijing %9203-12,10076\n% ---------------------------------------------\n% History:\n% ---------------------------------------------\n% Creation: beta Date: 01/10/2007\n% Revision: 1.0 Date: 12/11/2007\n% 1.Accept cell input now\n% 2.Using MATLAB file style\n% 3.Fully vectorized programming\n% 4.Fully support the IEEE reference\n% 5. ...\n\n\n% Check GLRLM\n[GLRLM numGLRLM] = ParseInputs(varargin{:});\n\n% Initialize output stats structure.\n% 11 statistics for each GLRLM\nnumStats = 11;\n\n% % count number of GLRLM\n% numGLRLM = length(GLRLM);\n\n% Initialization default 4*11 matrix\nstats = zeros(numGLRLM,numStats);\n\nfor p = 1 : numGLRLM\n %N-D indexing not allowed for sparse.\n\n if numGLRLM ~= 1\n % transfer to double matrix\n tGLRLM = GLRLM{p};\n else\n tGLRLM = GLRLM;\n end\n % if numGLRLM ~= 1\n % % transfer to double matrix\n % tGLRLM = normalizeGLRL(GLRLM{p});\n % else\n % tGLRLM = normalizeGLRL(GLRLM);\n % end\n % Get row and column subscripts of GLRLM. These subscripts correspond to the\n % pixel values in the GLRLM.\n s = size(tGLRLM);\n % colum indicator\n c_vector =1:s(1);\n % row indicator\n r_vector =1:s(2);\n % matrix element indicator\n % Matrix form col and row: using meshgrid, you should transpose before using\n % i.e. if tGLRLM is m*n, then this function return c_matrix n*m,\n % r_matrix n*m.\n [c_matrix,r_matrix] = meshgrid(c_vector,r_vector);\n\n % Total number of runs\n N_runs = sum(sum(tGLRLM));\n\n % total number of elements\n N_tGLRLM = s(1)*s(2);\n\n %--------------------Prepare four matrix for speedup--------------\n % 1.Gray Level Run-Length Pixel Number Matrix\n % p_p = calculate_p_p(tGLRLM,c_matrix');\n\n % 2.Gray-Level Run-Number Vector\n % This vector represents the sum distribution of the number of runs\n % with gray level i.\n p_g = sum(tGLRLM);\n\n % 3.Run-Length Run-Number Vector\n % This vector represents the sum distribution of the number of runs\n % with run length j.\n p_r = sum(tGLRLM,2)';\n\n % 4.Gray-Level Run-Length-One Vector\n %\n % p_o = tGLRLM(:,1); % Not used yet\n % ----------------------End four matrix---------------------------\n %\n %------------------------Statistics-------------------------------\n % 1. Short Run Emphasis (SRE)\n SRE = sum(p_r./(c_vector.^2))/N_runs;\n % 2. Long Run Emphasis (LRE)\n LRE = sum(p_r.*(c_vector.^2))/N_runs;\n % 3. Gray-Level Nonuniformity (GLN)\n GLN = sum(p_g.^2)/N_runs;\n % 4. Run Length Nonuniformity (RLN)\n RLN = sum(p_r.^2)/N_runs;\n % 5. Run Percentage (RP)\n RP = N_runs/N_tGLRLM;\n % 6. Low Gray-Level Run Emphasis (LGRE)\n LGRE = sum(p_g./(r_vector.^2))/N_runs;\n % 7. High Gray-Level Run Emphasis (HGRE)\n HGRE = sum(p_g.*r_vector.^2)/N_runs;\n % 8. Short Run Low Gray-Level Emphasis (SRLGE)\n SGLGE =calculate_SGLGE(tGLRLM,r_matrix',c_matrix',N_runs);\n % 9. Short Run High Gray-Level Emphasis (SRHGE)\n SRHGE =calculate_SRHGE(tGLRLM,r_matrix',c_matrix',N_runs);\n % 10. Long Run Low Gray-Level Emphasis (LRLGE)\n LRLGE =calculate_LRLGE(tGLRLM,r_matrix',c_matrix',N_runs);\n % 11.Long Run High Gray-Level Emphasis (LRHGE\n LRHGE =calculate_LRHGE(tGLRLM,r_matrix',c_matrix',N_runs);\n %----------------insert statistics----------------------------\n stats(p,:)=[SRE LRE GLN RLN RP LGRE HGRE SGLGE SRHGE LRLGE LRHGE ];\nend % end all run length matrixs\n\n% ----------------------Utility functions--------------------\n%-----------------------------------------------------------------------------\n% function glrl = normalizeGLRL(glrl)\n%\n% % Normalize glcm so that sum(glcm(:)) is one.\n% if any(glrl(:))\n% glrl = glrl ./ sum(glrl(:));\n% end\n% function p_p = calculate_p_p(GLRLM,c) % Note: currently not used\n%\n% % p_p(i; j) = GLRLM(i,j)*j\n% % Each element of the matrix represents the number of pixels of run length\n% % j and gray-level i. Compared to the original matrix, the new matrix gives\n% % equal emphasis to all length of runs in an image.\n%\n% term1 = c; % j index in matrix size\n% term2 = GLRLM;\n% p_p = term1 .* term2;\n%---------------------------------\nfunction SGLGE =calculate_SGLGE(tGLRLM,r_matrix,c_matrix,N_runs)\n% Short Run Low Gray-Level Emphasis (SRLGE):\n\nterm = tGLRLM./((r_matrix.*c_matrix).^2);\nSGLGE= sum(sum(term))./N_runs;\n\n%------------------------------------\nfunction SRHGE =calculate_SRHGE(tGLRLM,r_matrix,c_matrix,N_runs)\n% Short Run High Gray-Level Emphasis (SRHGE):\n%\nterm = tGLRLM.*(r_matrix.^2)./(c_matrix.^2);\nSRHGE = sum(sum(term))/N_runs;\n%------------------------------------\nfunction LRLGE =calculate_LRLGE(tGLRLM,r_matrix,c_matrix,N_runs)\n% Long Run Low Gray-Level Emphasis (LRLGE):\n%\nterm = tGLRLM.*(c_matrix.^2)./(r_matrix.^2);\nLRLGE = sum(sum(term))/N_runs;\n%---------------------------------------\nfunction LRHGE =calculate_LRHGE(tGLRLM,r_matrix,c_matrix,N_runs)\n% Long Run High Gray-Level Emphasis (LRHGE):\n%\nterm = tGLRLM.*(c_matrix.^2).*(r_matrix.^2);\nLRHGE = sum(sum(term))/N_runs;\n%----------------------------------------\n\n%-----------------------------------------------------------------------------\nfunction [glrlm num_glrlm] = ParseInputs(varargin)\n% check stability of inputs\n%\n% first receive all inputs\nglrlm = varargin{:};\n% get numbers total\nnum_glrlm=length(glrlm);\n% then for each element, check its stability\nfor i=1:num_glrlm\n % The 'nonnan' and 'finite' attributes are not added to iptcheckinput because the\n % 'integer' attribute takes care of these requirements.\n % iptcheckinput(glrlm,{'cell'},{'real','nonnegative','integer'}, ...\n % mfilename,'GLRLM',1);\n iptcheckinput(glrlm{i},{'logical','numeric'},{'real','nonnegative','integer'},...\n mfilename,'GLRLM',1);\n % Cast GLRLM to double to avoid truncation by data type. Note that GLRLM is not an\n % image.\n if ~isa(glrlm,'double')\n glrlm{i}= double(glrlm{i});\n end\nend\n", "meta": {"author": "mvallieres", "repo": "radiomics", "sha": "d3a61737730e1b2b46d04c9e22a3fcc390912f1a", "save_path": "github-repos/MATLAB/mvallieres-radiomics", "path": "github-repos/MATLAB/mvallieres-radiomics/radiomics-d3a61737730e1b2b46d04c9e22a3fcc390912f1a/TextureToolbox/Textures/GLRLM/Wei_Toolbox/grayrlprops.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.8080672158638528, "lm_q1q2_score": 0.7076947638900453}} {"text": "function[varargout]=materncov(varargin)\n%MATERNCOV Autocovariance of the Matern random process and variations.\n%\n% [TAU,R]=MATERNCOV(DT,N,SIGMA,ALPHA,LAMBDA) returns the autocovariance \n% function R of a length N complex-valued Matern random process having \n% variance SIGMA^2, slope parameter ALPHA, and damping parameter LAMBDA.\n%\n% [TAU,R]=MATERNCOV(...,'real') instead forms the covariance of a real-\n% valued Matern process.\n%\n% DT is the sample interval. Note that LAMBDA is understood to have the\n% same units as the inverse sample interval 1/DT.\n%\n% TAU is an array of time lags at which R is computed, and is given by \n% TAU=DT*[0,1,...,N-1].\n%\n% By definition, R is one-sided theoretical autocovariance at \n% non-negative time lags. See below for the relationship between this \n% and the full, length (2N-1) theoretical autocovariance function. \n%\n% Note that for LAMBDA=0, the case of fractional Brownian motion, R will \n% contain only INFs because the autocovariance function is unbounded.\n%\n% The input parameters SIGMA, ALPHA, and LAMBDA, may all either be \n% scalars or arrays of the same length M. If the latter, then the output \n% autocovariance function R will be a matrix with N rows and M columns. \n%\n% [TAU,R]=MATERNCOV(DT,N,SIGMA,ALPHA,LAMBDA,NU,MU) returns the \n% autocovariance function of various extensions of the Matern process. \n% MATERNOISE(...,'composite') also works. See MATERNSPEC for details.\n%\n% See MATERNSPEC for a more thorough discussion of the Matern process.\n%\n% For details on the Matern process and its autocovariance function, see:\n%\n% Lilly, Sykulski, Early, and Olhede, (2017). Fractional Brownian\n% motion, the Matern process, and stochastic modeling of turbulent \n% dispersion. Nonlinear Processes in Geophysics, 24: 481--514.\n% __________________________________________________________________\n%\n% Relationship to full autocovariance\n%\n% For a time series of length N, the full autocovariance function RF is \n% length 2N-1, defined at time lags -N+1,-N+2...,-1,0,1,...,N-2,N-1.\n%\n% The one-sided autocovariance R contains the full autocovariance RF at \n% positive time lags. Negative lags are given by Hermitian symmetry.\n%\n% [TAUF,RF]=MATERNCOV(...,'full') returns the full (two-sided)\n% autocovariance RF and the corresponding two-sided time array TAUF. \n%\n% RF is constructed from R as RF=[FLIPUD(CONJ(R(2:end,:));R]. \n% __________________________________________________________________\n%\n% Real-valued processes\n%\n% By default MATERNCOV returns the autocovariance of a complex-valued\n% process. \n%\n% MATERNCOV(...,'real') instead returns the autocovariance of a real-\n% valued process. This also works with any of extended versions.\n% __________________________________________________________________\n%\n% Computational notes\n%\n% The autocovariances for the generalized and composite Matern spectra do\n% not have analytic forms. Rather, these are approximated to high\n% precision by inverse Fourier transforming the oversampled spectrum with \n% 10 x oversampling over a 10 x longer time period, and then decimating. \n%\n% MATERNCOV(...,'general',M,P) or MATERNCOV(...,'composite',M,P) \n% specifies the numerical oversampling parameters in the calculation. \n%\n% The spectrum is then computed over a time window of M times the\n% required duration, and P times the required sampling density, for a\n% total of M*P time more points. These values may set to optimize the\n% tradeoff between speed and accuracy. \n%\n% This computation method is expected to minimize aliasing effects and\n% resolution errors. \n% __________________________________________________________________\n%\n% See also MATERNSPEC, MATERNIMP, MATERNOISE, MATERNFIT.\n%\n% 'materncov --t' runs some tests.\n%\n% Usage: [tau,R]=materncov(dt,N,sigma,alpha,lambda);\n% [tau,R]=materncov(dt,N,sigma,alpha,lambda,nu);\n% [tau,R]=materncov(dt,N,sigma,alpha,lambda,mu,'composite');\n% __________________________________________________________________\n% This is part of JLAB --- type 'help jlab' for more information\n% (C) 2013--2021 J.M. Lilly --- type 'help jlab_license' for details\n\n% No longer supported, sorry\n% __________________________________________________________________\n%\n% Reverse Matern\n%\n% [TAU,R]=MATERNCOV(N,SIGMA,ALPHA,LAMBDA,'reverse') returns the autocovariance \n% of the reverse Matern process, in which the roles of the spectrum and \n% the autocovariance functions are swapped. The autocovariance is \n%\n% R(TAU) = SIGMA^2 / (1+LAMBDA^2*TAU^2)^ALPHA \n%\n% Note that the parameter LAMBDA has been inverted so that it still has units\n% of frequency, as in the case of the forward Matern process. \n\n\n% __________________________________________________________________\n%\n% Extensions\n%\n% Several extensions of the basic Matern form are supported, all of which\n% are discussed in more detail in MATERNSPEC.\n%\n% Oscillatory Matern\n% [F,SPP,SNN]=MATERNCOV(DT,N,SIGMA,ALPHA,LAMBDA,NU)\n% Generalized Matern (+ optional oscillations)\n% [F,SPP,SNN]=MATERNCOV(DT,N,SIGMA,ALPHA,LAMBDA,GAMMA,'general') \n% [F,SPP,SNN]=MATERNCOV(DT,N,SIGMA,ALPHA,LAMBDA,GAMMA,NU,'general') \n% Extended Matern (+ optional oscillations)\n% [F,SPP,SNN]=MATERNCOV(DT,N,SIGMA,ALPHA,LAMBDA,MU,'extended')\n% [F,SPP,SNN]=MATERNCOV(DT,N,SIGMA,ALPHA,LAMBDA,MU,NU,'extended')\n% Composite Matern \n% [F,SPP,SNN]=MATERNCOV(DT,N,SIGMA,ALPHA,LAMBDA,MU,NU,'composite')\n\nif strcmpi(varargin{1}, '--t')\n materncov_test,return\nend\n\nsid='one';\nmodel='standard';\nflag='complex';\n\nM=10; %Specifying oversampling rates for numerical computations\nP=10;\nfor i=1:3\n if ischar(varargin{end})\n if strcmpi(varargin{end}(1:3),'rev')||strcmpi(varargin{end}(1:3),'com')||strcmpi(varargin{end}(1:3),'gen')||strcmpi(varargin{end}(1:3),'ext')\n model=varargin{end}(1:3);\n elseif strcmpi(varargin{end}(1:3),'rea')\n flag=varargin{end};\n else\n sid=varargin{end};\n end\n varargin=varargin(1:end-1);\n elseif ischar(varargin{end-2}) %For inputting M and P for testing\n if strcmpi(varargin{end-2}(1:3),'com')||strcmpi(varargin{end-2}(1:3),'gen')\n model=varargin{end-2};\n M=varargin{end-1};\n P=varargin{end};\n varargin=varargin(1:end-3);\n end\n end\nend\n\nif strcmpi(model(1:3),'com')&&strcmpi(model(1:3),'rev')\n error('Sorry, the COMPOSITE and REVERSE options cannot be used together.')\nend\n\ndt=double(varargin{1});\nN=floor(varargin{2});\nvarargin=varargin(3:end);\n\nif length(varargin)==1\n params=varargin{1}; %for input from materfit\nelse\n %this will be easier as a matrix\n Ncell=max(cellength(varargin));\n params=zeros(Ncell,length(varargin));\n for i=1:length(varargin)\n params(:,i)=varargin{i};\n end\nend\n\ntau=dt*[0:N-1]';\nR=zeros(N,size(params,1));\nfor i=1:size(params,1)\n R(:,i)=materncov_one(tau,params(i,:),model,M,P,flag);\nend\n\nif strcmpi(sid(1:3),'ful')\n tau=[-flipud(tau(2:end,:));tau];\n R=[flipud(conj(R(2:end,:)));R];\nend\nvarargout{1}=tau;\nvarargout{2}=R;\n\n\nfunction[R]=materncov_one(tau,params,model,M,P,flag)\n\nsigma=params(1);\nalpha=params(2);\nlambda=params(3);\n\nnu=0;\nif strcmpi(model(1:3),'com')\n mu=params(4);\n nu=params(5);\n \n N=length(tau);\n dt=tau(2)-tau(1);\n [f,Spp,Snn]=maternspec(dt,M*N*P,sigma,alpha,lambda/P,mu/P,nu/P,'composite',flag);\n S=[flipud(Snn(2:end));Spp];%figure,plot(S)\n Ri=ifft(ifftshift(S))./dt; %Make sure it's ifftshift not fftshift\n Ri=Ri(1:P:end);\n R=Ri(1:N);\n R=R./R(1);\nelseif strcmpi(model(1:3),'gen')\n %Generalized Matern form\n gamma=params(4);\n if length(params)==5\n nu=params(5);\n end\n %sigma,alpha,lambda/P,gamma,nu,flag\n N=length(tau);\n dt=tau(2)-tau(1);\n [f,Spp,Snn]=maternspec(dt,M*N*P,sigma,alpha,lambda/P,gamma,'generalized',flag);\n S=[flipud(Snn(2:end));Spp];%figure,plot(S)\n %figure,plot(f,[Spp Snn]),xlog,ylog,aresame(Spp,Snn,1e-13)\n Ri=ifft(ifftshift(S))./dt; %Make sure it's ifftshift not fftshift\n %figure,plot(Ri)\n Ri=Ri(1:P:end);\n R=Ri(1:N);\n R=R./R(1);\nelseif strcmpi(model(1:3),'ext')\n %Extended Matern, reduces to the standard Matern form for mu=0\n mu=params(4);\n if length(params)==5\n nu=params(5);\n end\n t=lambda.*sqrt(tau.^2+mu.^2); %This is to support the extended Matern form\n R=frac(maternfun(alpha,t),maternfun(alpha,mu*lambda));\nelseif strcmpi(model(1:3),'sta')\n %Standard Matern form\n if length(params)==4\n nu=params(4);\n end\n t=lambda.*tau;\n R=maternfun(alpha,t);\nend\nif nu~=0 && ~strcmpi(model(1:3),'com')\n R=R.*exp(sqrt(-1)*tau.*nu);\nend\nR=R.*sigma.^2;\n\nif strcmpi(flag(1:3),'rea')\n R=real(R);\nend\n\n% Extended Matern form reduces to this Bessel function form, test is below\n% if alpha=-1/2\n% tnorm=sqrt(tau.^2+mu.^2);\n% fact=besselk(1,lambda.*mu);\n% R1=frac(1,fact).*frac(1,tnorm./mu).*besselk(1,lambda.*tnorm);\n% end\n\n% function[]=maternfun_fig\n% \n% alpha=[-4:0.1:4];\n% [tau,R]=materncov(dt,10000,1,alpha,0,0,1000);\n% figure,plot(tau,R)\n% \n% hold on,h=plot(r1,xi(:,1)); linestyle -h h 3D\n% hold on,h=plot(r1,xi(:,end)); linestyle -h h 3k\n% title('The Matern function from \\alpha = 1/2 (gray) to \\alpha = 4 (black)')\n\nfunction[]=materncov_test\n\ntic\nalpha=1.5;\nh=0.1;\nsigma=1;\n\nN=1000;\n[tau,R]=materncov(1,N,sigma,alpha,h);\n[f,Spp,Snn]=maternspec(1,N,sigma,alpha,h);\n[f,Spp2,Snn2]=blurspec(1,R,'aliased');\n\nb1=aresame(Spp2./maxmax(Spp),Spp./maxmax(Spp),1e-4);\nb2=aresame(Snn2./maxmax(Snn),Snn./maxmax(Snn),1e-4);\n\nreporttest('MATERNCOV Fourier transforms to MATERNSPEC for case with negligible aliasing, even N',b1&&b2)\n\n\nN=1000;\n[tau,R]=materncov(1,N,sigma,alpha,h,h/2);\n[f,Spp,Snn]=maternspec(1,N,sigma,alpha,h,h/2);\n[f,Spp2,Snn2]=blurspec(1,R,'aliased');\n\nb1=aresame(Spp2./maxmax(Spp),Spp./maxmax(Spp),1e-4);\nb2=aresame(Snn2./maxmax(Snn),Snn./maxmax(Snn),1e-4);\n\nreporttest('MATERNCOV Fourier transforms to MATERNSPEC for oscillatory Matern with negligible aliasing, even N',b1&&b2)\n\nN=1000;\n[tau,R]=materncov(1,N,sigma,alpha,h,h/2,'real');\n[f,Spp,Snn]=maternspec(1,N,sigma,alpha,h,h/2,'real');\n[f,Spp2,Snn2]=blurspec(1,R,'aliased');\n\nb1=aresame(Spp2./maxmax(Spp),Spp./maxmax(Spp),1e-4);\nb2=aresame(Snn2./maxmax(Snn),Snn./maxmax(Snn),1e-4);\n\nreporttest('MATERNCOV Fourier transforms to MATERNSPEC for real-valued oscillatory Matern with negligible aliasing, even N',b1&&b2)\n\nN=1000;\ndt=7;\n[tau,R]=materncov(dt,N,sigma,alpha,h/dt);\n[f,Spp,Snn]=maternspec(dt,N,sigma,alpha,h/dt);\n[f,Spp2,Snn2]=blurspec(dt,R,'aliased');\n\nb1=aresame(Spp2./maxmax(Spp),Spp./maxmax(Spp),1e-4);\nb2=aresame(Snn2./maxmax(Snn),Snn./maxmax(Snn),1e-4);\n\nreporttest('MATERNCOV Fourier transforms to MATERNSPEC ..., even N, non-unit sample rate',b1&&b2)\n\nN=1000;\n[f,Spp,Snn]=maternspec(2,N,sigma,alpha,h/5,h,h*5,'composite');\n[tau,R]=materncov(2,N,sigma,alpha,h/5,h,h*5,'composite');\n[f,Spp2,Snn2]=blurspec(2,R,'aliased');\n\n%[tau,R]=materncov(2,N,sigma,alpha,h/5,h*5,h,'composite');\n%[f,Spp3,Snn3]=blurspec(2,R,'aliased');\n\n%z=maternoise(N,sigma,alpha,h/5-1i*h*5,h,'composite');\n\n%fact=2*sigma.^2.*(h/5).*((h*5).^2+h.^2).^alpha;\n%2*sigma.^2.*H.*(nu.^2+G.^2).^alpha;\n\nb1=aresame(Spp2./maxmax(Spp),Spp./maxmax(Spp),2e-2);\nb2=aresame(Snn2./maxmax(Snn),Snn./maxmax(Snn),2e-2);\n\n%this test is currently not working ... Spp2 is off by a factor of sqrt(3),\n%related to the fact that R(1) is not unity in the above code after calling mspec\n%reporttest('MATERNCOV Fourier transforms to MATERNSPEC for case composite Matern with negligible aliasing, even N',b1&&b2)\n\nN=1000;\n[tau,R]=materncov(1,N,sigma,-1/2,h,alpha*10,'extended');\n[f,Spp,Snn]=maternspec(1,N,sigma,-1/2,h,alpha*10,'extended');\n[f,Spp2,Snn2]=blurspec(1,R,'aliased');\n\nb1=aresame(Spp2./maxmax(Spp),Spp./maxmax(Spp),1e-4);\nb2=aresame(Snn2./maxmax(Snn),Snn./maxmax(Snn),1e-4);\n\nreporttest('MATERNCOV Fourier transforms to MATERNSPEC for case with negligible aliasing, even N, exponential',b1&&b2)\n\n\nN=1000;\ndt=7;\n[tau,R]=materncov(dt,N,sigma,-1/2,h/dt,(alpha*10*dt),'extended');\n[f,Spp,Snn]=maternspec(dt,N,sigma,-1/2,h/dt,(alpha*10*dt),'extended');\n[f,Spp2,Snn2]=blurspec(dt,R,'aliased');\n\nb1=aresame(Spp2./maxmax(Spp),Spp./maxmax(Spp),1e-4);\nb2=aresame(Snn2./maxmax(Snn),Snn./maxmax(Snn),1e-4);\n\nreporttest('MATERNCOV Fourier transforms to MATERNSPEC ..., even N, exponential, non-unit sample rate',b1&&b2)\n\n\n[tau,R]=materncov(1,1000,7,1.5,1/10,20,'extended');\n[f,Spp,Snn]=maternspec(1,1000,7,1.5,1/10,20,'extended');\n[f,Spp2,Snn2]=blurspec(1,R,'aliased');\n\n\nb1=aresame(Spp2./maxmax(Spp),Spp./maxmax(Spp),1e-10);\nb2=aresame(Snn2./maxmax(Snn),Snn./maxmax(Snn),1e-10);\n\nreporttest('MATERNCOV Fourier transforms to MATERNSPEC for case with negligible aliasing, even N, extended Matern',b1&&b2)\n\ndt=1.3;\n[tau,R]=materncov(dt,1000,7,1.5,1/10/dt,20/dt,'extended');\n[f,Spp,Snn]=maternspec(dt,1000,7,1.5,1/10/dt,20/dt,'extended');\n%[f,Spp2,Snn2]=blurspec(dt,R);\n[f,Spp2,Snn2]=blurspec(dt,R,'aliased');\n\nb1=aresame(Spp2./maxmax(Spp),Spp./maxmax(Spp),1e-10);\nb2=aresame(Snn2./maxmax(Snn),Snn./maxmax(Snn),1e-10);\n\nreporttest('MATERNCOV Fourier transforms to MATERNSPEC ..., even N, extended Matern, non-unit sample rate',b1&&b2)\n\n\nN=1000-1;\n[tau,R]=materncov(1,N,sigma,alpha,h,2*h,'extended');\n[f,Spp,Snn]=maternspec(1,N,sigma,alpha,h,2*h,'extended');\n[f,Spp2,Snn2]=blurspec(1,R,'aliased');\n\nb1=aresame(Spp2./maxmax(Spp),Spp./maxmax(Spp),1e-4);\nb2=aresame(Snn2./maxmax(Spp),Snn./maxmax(Spp),1e-4);\n\nreporttest('MATERNCOV Fourier transforms to MATERNSPEC for case with negligible aliasing, frequency shift case, odd N',b1&&b2)\n\nN=1000;\ndt=7;\nlambda=h/dt;\nmu=(alpha*10*dt);\n[tau,R]=materncov(dt,N,sigma,-1/2,lambda,mu,'extended');\ntnorm=sqrt(tau.^2+mu.^2);\nfact=besselk(1,lambda.*mu);%See notes for this form\nR1=frac(1,fact).*frac(1,tnorm./mu).*besselk(1,lambda.*tnorm);\nreporttest('MATERNCOV ALPHA = -1/2 case matches expected form',aresame(R,R1,1e-10))\n\ntoc\n% [tau,R]=materncov(1,N,sigma,alpha,h,'reverse');\n% [f,Spp,Snn]=maternspec(1,N,sigma,alpha,h,'reverse');\n% R(1)=R(1)/2;\n% S=2*real(fft(R));\n% Spp2=S(1:length(Spp));\n% S=flipud(S);\n% Snn2=[S(end);S(1:length(Snn)-1)];\n% \n% b1=aresame(Spp2./maxmax(Spp),Spp./maxmax(Spp),1e-4);\n% b2=aresame(Snn2./maxmax(Snn),Snn./maxmax(Snn),1e-4);\n% \n% reporttest('MATERNCOV Fourier transforms to MATERNSPEC for case with negligible aliasing, even N, reverse Matern',b1&&b2)\n\n\n%Playing around with asymptotic results... which don't work for alpha > 3/2\n% sigma=7;\n% alpha=[0.6 3/4 1.001 1.25 3/2-0.001 1.75];% 1.75 2 3 4 10];\n% %alpha=[1.75 2 3 4 10];% 1.75 2 3 4 10];\n% lambda=1/10000;\n% N=10000;\n% [tau,R]=materncov(N,sigma,alpha,lambda);\n% Rapprox=zeros(size(R));\n% for i=1:length(alpha)\n% %numer=(lambda.*tau).^(2*alpha(i)-1);\n% %denom=2*materncfun(alpha(i)).*cos(pi.*alpha(i)).*gamma(2*alpha(i));\n% numer1=-(lambda.*tau/2).^(2*alpha(i)-1)*gamma(3/2-alpha(i));\n% denom1=gamma(1/2+alpha(i));\n% numer2=(lambda.*tau/2).^2*gamma(3/2-alpha(i));\n% denom2=gamma(5/2-alpha(i));\n% Rapprox1(:,i)=sigma.^2.*(1+frac(numer,denom));\n% %Rapprox2(:,i)=sigma.^2.*(1+frac(numer1,denom2)+frac(numer2,denom2));\n% end\n% Rapprox(Rapprox<0)=nan;\n% Rapprox(Rapprox>2*sigma.^2)=nan;\n\n% alpha=1.5;\n% h=0.1;\n% sigma=1;\n% nu=0.1;\n% \n% N=1000;\n% figure\n% [tau,R]=materncov(N,sigma,1,h-1i*nu);\n% [f,Spp,Snn]=blurspec(R);\n% plot(-f,Snn),hold on,plot(f,Spp)\n% [tau,R]=materncov(N,sigma,1,h+1i*nu);\n% [f,Spp,Snn]=blurspec(R);\n% plot(-f,Snn),hold on,plot(f,Spp)\n% \n% [f,Spp,Snn]=maternspec(N,sigma,alpha,h);\n\n% N=1000;\n% r1=[0:.00001:0.00001]';\n% alpha=[1/2:0.1:4];\n% R=materncov(r1,1,alpha(:),1/100);\n% dr=(R(2,:)-R(1,:))./(r1(2)-r1(1));\n% dr2=-frac(gamma(abs(alpha-3/2)),gamma(alpha-1/2)).*frac(1/100,2);\n% %dr2(alpha==1)=-1/100;\n% \n% plot(alpha,-dr,'r*'),hold on,plot(alpha,-dr2,'o')\n% \n% dxi=-frac(r,2).*frac(gamma(alpha-1),gamma(alpha)).*maternfun(alpha-1,r);\n% reporttest('MATERNFUN iterative expression for derivative matches direct expression',aresame(xi1(2:end,:),dxi(2:end,:),1e-10))\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/jmatern/materncov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.7076800642203988}} {"text": "%% Hough Lines Transform\n% An example using the Hough line detector.\n%\n% This program demonstrates line finding with the Hough transform.\n% We show how to use the OpenCV functions |cv.HoughLines| and |cv.HoughLinesP|\n% to detect lines in an image.\n%\n% Sources:\n%\n% * \n% * \n% * \n% * \n% * \n%\n\n%% Theory\n%\n% The explanation below belongs to the book *Learning OpenCV* by\n% Bradski and Kaehler.\n%\n% The Hough Line Transform is a transform used to detect straight lines. To\n% apply the Transform, first an edge detection pre-processing is desirable.\n%\n% As you know, a line in the image space can be expressed with two variables.\n% For example:\n%\n% * In the *Cartesian coordinate system:* Parameters: $(m,b)$.\n% * In the *Polar coordinate system:* Parameters: $(r,\\theta)$\n%\n% <>\n%\n% For Hough Transforms, we will express lines in the _Polar system_. Hence, a\n% line equation can be written as:\n%\n% $$y = \\left ( -\\frac{\\cos \\theta}{\\sin \\theta} \\right ) x +\n% \\left ( \\frac{r}{\\sin \\theta} \\right )$$\n%\n% Arranging the terms: $r = x \\cos \\theta + y \\sin \\theta$\n%\n% In general for each point $(x_{0}, y_{0})$, we can define the family of\n% lines that goes through that point as:\n%\n% $$r_{\\theta} = x_{0} \\cdot \\cos \\theta + y_{0} \\cdot \\sin \\theta$$\n%\n% Meaning that each pair $(r_{\\theta},\\theta)$ represents each line that\n% passes by $(x_{0}, y_{0})$.\n%\n% If for a given $(x_{0}, y_{0})$ we plot the family of lines that goes\n% through it, we get a sinusoid. For instance, for $x_{0} = 8$ and $y_{0} = 6$\n% we get the following plot (in a plane $\\theta$ - $r$):\n%\n% <>\n%\n% We consider only points such that $r > 0$ and $0< \\theta < 2 \\pi$.\n%\n% We can do the same operation above for all the points in an image. If the\n% curves of two different points intersect in the plane $\\theta$ - $r$, that\n% means that both points belong to a same line. For instance, following with\n% the example above and drawing the plot for two more points:\n% $x_{1} = 4$, $y_{1} = 9$ and $x_{2} = 12$, $y_{2} = 3$, we get:\n%\n% <>\n%\n% The three plots intersect in one single point $(0.925, 9.6)$, these\n% coordinates are the parameters ($\\theta, r$) or the line in which\n% $(x_{0}, y_{0})$, $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ lay.\n%\n% What does all the stuff above mean? It means that in general, a line can be\n% _detected_ by finding the number of intersections between curves. The more\n% curves intersecting means that the line represented by that intersection\n% have more points. In general, we can define a _threshold_ of the minimum\n% number of intersections needed to _detect_ a line.\n%\n% This is what the Hough Line Transform does. It keeps track of the\n% intersection between curves of every point in the image. If the number of\n% intersections is above some _threshold_, then it declares it as a line with\n% the parameters $(\\theta, r_{\\theta})$ of the intersection point.\n%\n%% Standard and Probabilistic Hough Line Transform\n%\n% OpenCV implements two kind of Hough Line Transforms:\n%\n% 1) *The Standard Hough Transform*\n%\n% * It consists in pretty much what we just explained in the previous section.\n% It gives you as result a vector of couples $(\\theta, r_{\\theta})$\n% * In OpenCV it is implemented with the function |cv.HoughLines|\n%\n% 2) *The Probabilistic Hough Line Transform*\n%\n% * A more efficient implementation of the Hough Line Transform. It gives as\n% output the extremes of the detected lines $(x_{0}, y_{0}, x_{1}, y_{1})$\n% * In OpenCV it is implemented with the function |cv.HoughLinesP|\n%\n\n%% Code\n%\n% This program:\n%\n% * Loads an image\n% * Applies either a _Standard Hough Line Transform_ or a\n% _Probabilistic Line Transform_.\n% * Display the original image and the detected line in two windows.\n%\n% You may observe that the number of lines detected vary while you change the\n% _threshold_. The explanation is sort of evident: If you establish a higher\n% threshold, fewer lines will be detected (since you will need more points to\n% declare a line detected).\n%\n\n%%\n% Input image\nif true\n fname = fullfile(mexopencv.root(), 'test', 'sudoku.jpg');\n thresh = 200;\n threshP = 100;\n minlen = 100;\nelse\n fname = fullfile(mexopencv.root(), 'test', 'pic1.png');\n thresh = 85;\n threshP = 50;\n minlen = 50;\nend\nsrc = cv.imread(fname, 'Color',true);\n\n%%\n% Edge Detection\ngray = cv.cvtColor(src, 'RGB2GRAY');\nedges = cv.Canny(gray, [50, 150], 'ApertureSize',3);\nimshow(edges), title('Edges')\n\n%%\n% HoughLines: Standard Hough Line Transform\ntic\nlines = cv.HoughLines(edges, 'Rho',1, 'Theta',pi/180, 'Threshold',thresh);\ntoc\n\n%%\n% draw the lines, and display the result\nlines = cat(1, lines{:});\nrho = lines(:,1);\ntheta = lines(:,2);\na = cos(theta); b = sin(theta);\nx0 = a.*rho; y0 = b.*rho;\npt1 = round([x0 + 1000*(-b), y0 + 1000*(a)]);\npt2 = round([x0 - 1000*(-b), y0 - 1000*(a)]);\nout = cv.line(src, pt1, pt2, ...\n 'Color',[0 255 0], 'Thickness',2, 'LineType','AA');\nfigure, imshow(out), title('Detected Lines')\n\n%%\n% HoughLinesP: Probabilistic Hough Line Transform\ntic\nlinesP = cv.HoughLinesP(edges, 'Rho',1, 'Theta',pi/180, ...\n 'Threshold',threshP, 'MinLineLength',minlen, 'MaxLineGap',10);\ntoc\n\n%%\n% draw the line segments, and display the result\nlinesP = cat(1, linesP{:});\noutP = cv.line(src, linesP(:,1:2), linesP(:,3:4), ...\n 'Color',[0 255 0], 'Thickness',2, 'LineType','AA');\nfigure, imshow(outP), title('Detected Line Segments')\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/samples/hough_lines_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7075422417261175}} {"text": "%\n% This code calculates the interevent distances and the correlation integral\n% of a given earthquake distribution.\n% Calculation of the 3D distances between all possible pairs\n% (combination of n epicenters taken 2 at a time) of earthquakes of\n% the given dataset.\n% Francesco Pacchiani 1/2000\n%\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((N-1),N);\ndepth = zeros((N-1),N);\nk = 1;\n%E.Latitude= (max(Da(:,2))+min(Da(:,2)))/2;\n\n\n%Ho_Wb = waitbar(0,'Calculating the fractal dimension D');\n%Hf_Cfig = gcf;\n%Hf_child = get(groot,'children');\n%set(Hf_child,'pointer','watch','papertype','A4');\n%\n%\n% Calculation of the interevent distances in 2D plus the depths differences.\n%\n%\nfor i = 1:(N-1)\n\n lon1 = repmat(E(i,1), [(N-1),1]);\n lat1 = repmat(E(i,2), [(N-1),1]);\n depth1 = repmat(E(i,7), [(N-1),1]);\n\n E(i,:) = [];\n\n lon2 = E.Longitude;\n lat2 = E.Latitude;\n depth2 = E.Depth;\n\n pairdist(1:(N-1),k) = distance(lat1,lon1,lat2,lon2);\n depth(1:(N-1),k) = depth1-depth2;\n\n k = k + 1;\n E = newt2;\n\n %Waitbar((0.75/(N-1))*i, Ho_Wb);\n\nend\n\nclear i j k;\n%\n%\n% Conversion of the interevent distances from degrees to kilometers and calculates\n% the interevent distances in three dimensions.\n%\n%\nif dtokm == 1\n pairdist = pairdist.*111;\nend\n\npairdist = (pairdist.^2 + depth.^2).^0.5;\t\t% pairdist = Interevent distances (vector).\nclear depth;\n%\n%\n% Calculation of the correlation integral using as input the\n% pair distances computed above.\n%\n%\n% Variables\n%\nd = 3;\t\t\t\t\t\t%d = the dimension of the embedding volume.\nrmax1 = max(pairdist);\nrmin1 = min(pairdist);\nrmax = max(rmax1);\nrmin = min(rmin1);\n\nclear rmax1 rmin1;\n\nif rmin == 0\n rmin = 0.01;\nend\n\nlrmin = log10(rmin);\nlrmax = log10(rmax);\n\n%u = (log10(rmin):0.15:log10(rmax))';\n%\n% Defining the distance vector r in order that on the\n% log-log graph all the points plot at equal distances from one another.\n%\nr = (logspace(lrmin, lrmax, 50))';\n%r = zeros(size(u,1),1);\n%r = 10.^u;\n%\n%\ncorint = [];\t\t\t\t\t\t% corint= Vector of ?cumulative? correlation integral values for increasing interevent radius\ncor = zeros(size(r,1),N);\ni = 1;\n\nfor k = 1:50\n\n l = [];\n l = pairdist < r(k);\n test(k,1) = sum(l);\n %cor(1:size(r,1),i) = (sum(l));\n %i=i+1;\n\n %Waitbar(0.75 + (0.25/size(r,1))*k,Ho_Wb);\nend\n\nsumcor = sum(cor,2);\nsumcor1 = sumcor./N;\n\nfor j = 0:20\n\n corint1(1:50,1,(j+1)) = sumcor1(:,1,(j+1)).^(1/(j-1));\nend\n\ncorint = corint1(1:50, 1:21);\n\nclear i j j1 k l cor sumcor;\nclose(Ho_Wb);\nHf_child = get(groot,'children');\nset(Hf_child,'pointer','arrow');\n%\n%\n% Plotting of the correlation integral in function of the interevent\n% distance r.\n%\n%\nHf_Fig = figure_w_normalized_uicontrolunits('Numbertitle','off','Name','Fractal Dimension');\nHl_gr1 = loglog(r, corint,'ko', 'MarkerSize',5);\nset(Hl_gr1,'MarkerSize',5);\ntitle(sprintf('Correlation Integral versus %.0fD Interevent Distances', d));\n\nHf_Fig = figure_w_normalized_uicontrolunits('Numbertitle','off','Name','Fractal Dimension');\nHl_gr1 = loglog(r, cor,'r+');\nset(Hl_gr1,'MarkerSize',7);\ntitle(sprintf('Correlation Integral versus %.0fD Interevent Distances', d));\n%\n%\ndofd = 'fd';\ndofdim;\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/testpdc3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.7075144593007467}} {"text": "function [coeff, score, latent, tsquared, explained, mu] = pca(x,varargin)\n%PCA Principal Component Analysis (PCA) on raw data.\n% COEFF = PCA(X) returns the principal component coefficients for the N\n% by P data matrix X. Rows of X correspond to observations and columns to\n% variables. Each column of COEFF contains coefficients for one principal\n% component. The columns are in descending order in terms of component\n% variance (LATENT). PCA, by default, centers the data and uses the\n% singular value decomposition algorithm. For the non-default options,\n% use the name/value pair arguments.\n% \n% [COEFF, SCORE] = PCA(X) returns the principal component score, which is\n% the representation of X in the principal component space. Rows of SCORE\n% correspond to observations, columns to components. The centered data\n% can be reconstructed by SCORE*COEFF'.\n%\n% [COEFF, SCORE, LATENT] = PCA(X) returns the principal component\n% variances, i.e., the eigenvalues of the covariance matrix of X, in\n% LATENT.\n%\n% [COEFF, SCORE, LATENT, TSQUARED] = PCA(X) returns Hotelling's T-squared\n% statistic for each observation in X. PCA uses all principal components\n% to compute the TSQUARED (computes in the full space) even when fewer\n% components are requested (see the 'NumComponents' option below). For\n% TSQUARED in the reduced space, use MAHAL(SCORE,SCORE).\n%\n% [COEFF, SCORE, LATENT, TSQUARED, EXPLAINED] = PCA(X) returns a vector\n% containing the percentage of the total variance explained by each\n% principal component.\n%\n% [COEFF, SCORE, LATENT, TSQUARED, EXPLAINED, MU] = PCA(X) returns the\n% estimated mean, MU, when 'Centered' is set to true; and all zeros when\n% set to false.\n%\n% [...] = PCA(..., 'PARAM1',val1, 'PARAM2',val2, ...) specifies optional\n% parameter name/value pairs to control the computation and handling of\n% special data types. Parameters are:\n% \n% 'Algorithm' - Algorithm that PCA uses to perform the principal\n% component analysis. Choices are:\n% 'svd' - Singular Value Decomposition of X (the default).\n% 'eig' - Eigenvalue Decomposition of the covariance matrix. It\n% is faster than SVD when N is greater than P, but less\n% accurate because the condition number of the covariance\n% is the square of the condition number of X.\n% 'als' - Alternating Least Squares (ALS) algorithm which finds\n% the best rank-K approximation by factoring a X into a\n% N-by-K left factor matrix and a P-by-K right factor\n% matrix, where K is the number of principal components.\n% The factorization uses an iterative method starting with\n% random initial values. ALS algorithm is designed to\n% better handle missing values. It deals with missing\n% values without listwise deletion (see {'Rows',\n% 'complete'}).\n%\n% 'Centered' - Indicator for centering the columns of X. Choices are: \n% true - The default. PCA centers X by subtracting off column\n% means before computing SVD or EIG. If X contains NaN\n% missing values, NANMEAN is used to find the mean with\n% any data available.\n% false - PCA does not center the data. In this case, the original\n% data X can be reconstructed by X = SCORE*COEFF'. \n%\n% 'Economy' - Indicator for economy size output, when D the degrees of\n% freedom is smaller than P. D, is equal to M-1, if data\n% is centered and M otherwise. M is the number of rows\n% without any NaNs if you use 'Rows', 'complete'; or the\n% number of rows without any NaNs in the column pair that\n% has the maximum number of rows without NaNs if you use\n% 'Rows', 'pairwise'. When D < P, SCORE(:,D+1:P) and\n% LATENT(D+1:P) are necessarily zero, and the columns of\n% COEFF(:,D+1:P) define directions that are orthogonal to\n% X. Choices are:\n% true - This is the default. PCA returns only the first D\n% elements of LATENT and the corresponding columns of\n% COEFF and SCORE. This can be significantly faster when P\n% is much larger than D. NOTE: PCA always returns economy\n% size outputs if 'als' algorithm is specifed.\n% false - PCA returns all elements of LATENT. Columns of COEFF and\n% SCORE corresponding to zero elements in LATENT are\n% zeros.\n%\n% 'NumComponents' - The number of components desired, specified as a\n% scalar integer K satisfying 0 < K <= P. When specified,\n% PCA returns the first K columns of COEFF and SCORE.\n%\n% 'Rows' - Action to take when the data matrix X contains NaN\n% values. If 'Algorithm' option is set to 'als, this\n% option is ignored as ALS algorithm deals with missing\n% values without removing them. Choices are:\n% 'complete' - The default action. Observations with NaN values\n% are removed before calculation. Rows of NaNs are\n% inserted back into SCORE at the corresponding\n% location.\n% 'pairwise' - If specified, PCA switches 'Algorithm' to 'eig'. \n% This option only applies when 'eig' method is used.\n% The (I,J) element of the covariance matrix is\n% computed using rows with no NaN values in columns I\n% or J of X. Please note that the resulting covariance\n% matrix may not be positive definite. In that case,\n% PCA terminates with an error message.\n% 'all' - X is expected to have no missing values. All data\n% are used, and execution will be terminated if NaN is\n% found.\n% \n% 'Weights' - Observation weights, a vector of length N containing all\n% positive elements.\n%\n% 'VariableWeights' - Variable weights. Choices are:\n% - a vector of length P containing all positive elements.\n% - the string 'variance'. The variable weights are the inverse of\n% sample variance. If 'Centered' is set true at the same time,\n% the data matrix X is centered and standardized. In this case,\n% PCA returns the principal components based on the correlation\n% matrix.\n%\n% The following parameter name/value pairs specify additional options\n% when alternating least squares ('als') algorithm is used.\n%\n% 'Coeff0' - Initial value for COEFF, a P-by-K matrix. The default is\n% a random matrix.\n%\n% 'Score0' - Initial value for SCORE, a N-by-K matrix. The default is\n% a matrix of random values.\n%\n% 'Options' - An options structure as created by the STATSET function.\n% PCA uses the following fields:\n% 'Display' - Level of display output. Choices are 'off' (the\n% default), 'final', and 'iter'.\n% 'MaxIter' - Maximum number of steps allowed. The default is\n% 1000. Unlike in optimization settings, reaching\n% MaxIter is regarded as convergence.\n% 'TolFun' - Positive number giving the termination tolerance for\n% the cost function. The default is 1e-6.\n% 'TolX' - Positive number giving the convergence threshold\n% for relative change in the elements of L and R. The\n% default is 1e-6.\n%\n%\n% Example:\n% load hald;\n% [coeff, score, latent, tsquared, explained] = pca(ingredients);\n%\n% See also PPCA, PCACOV, PCARES, BIPLOT, BARTTEST, CANONCORR, FACTORAN,\n% ROTATEFACTORS.\n\n% References:\n% [1] Jolliffe, I.T. Principal Component Analysis, 2nd ed.,Springer,2002. \n% [2] Krzanowski, W.J., Principles of Multivariate Analysis, Oxford\n% University Press, 1988.\n% [3] Seber, G.A.F., Multivariate Observations, Wiley, 1984. \n% [4] Jackson, J.E., A User's Guide to Principal Components, Wiley, 1988. \n% [5] Sam Roweis, EM algorithms for PCA and SPCA, In Proceedings of the\n% 1997 conference on Advances in neural information processing\n% systems 10 (NIPS '97), MIT Press, Cambridge, MA, USA, 626-632,1998.\n% [6] Alexander Ilin and Tapani Raiko. Practical Approaches to Principal\n% Component Analysis in the Presence of Missing Values. J. Mach.\n% Learn. Res. 11 (August 2010), 1957-2000, 2010.\n\n% Copyright 2012 The MathWorks, Inc.\n\n\n\n[n, p] = size(x);\ninternal.stats.checkSupportedNumeric('X',x,false,false,true); % complex is accepted here\n\n% Parse arguments and check if parameter/value pairs are valid \nparamNames = {'Algorithm','Centered','Economy','NumComponents','Rows',...\n 'Weights','VariableWeights','Coeff0','Score0','Options'};\ndefaults = {'svd', true, true, p, 'complete',...\n ones(1,n,'like',x) ,ones(1,p,'like',x), [], [], statset('pca')};\n\n[vAlgorithm, vCentered, vEconomy, vNumComponents, vRows,vWeights,...\n vVariableWeights, c0, s0, opts, setFlag]...\n = internal.stats.parseArgs(paramNames, defaults, varargin{:});\n% Validate String value for Algorithm value\nAlgorithmNames = {'svd','eig','als'};\nvAlgorithm = internal.stats.getParamVal(vAlgorithm,AlgorithmNames,...\n '''Algorithm''');\n% Validate boolean value for 'Centered' option\nvCentered = internal.stats.parseOnOff(vCentered,'''Centered''');\n% Validate boolean value for 'Economy' option\nvEconomy = internal.stats.parseOnOff(vEconomy,'''Economy''');\n% Validate the number of components option 'NumComponents'\nif ~isempty(x) && ~internal.stats.isScalarInt(vNumComponents,1,p)\n error(message('stats:pca:WrongNumComponents',p));\nend\n% Validate value for 'Rows' option\nRowsNames = {'complete','pairwise','all'};\nvRows = internal.stats.getParamVal(vRows,RowsNames,'''Rows''');\n\nswitch vAlgorithm\n case 'svd'\n % Switch 'Algorithm' to 'eig' if 'Rows' set to 'pairwise'\n if strcmp(vRows,'pairwise')\n if setFlag.Algorithm\n warning(message('stats:pca:NoPairwiseSVD'));\n end\n vAlgorithm = 'eig';\n end \n % Switch algorithm to 'als' if user specify 'Coeff0' and 'Score0'.\n if setFlag.Coeff0 || setFlag.Score0\n vAlgorithm = 'als';\n end\n case 'als'\n % If 'als' is chosen, force PCA to use ALS and to ignore the\n % Rows' option\n if setFlag.Rows\n warning(message('stats:pca:NoALSRows'));\n end\nend\n\n% Validate Weights Vectors\nif isvector(vWeights) && isequal(numel(vWeights),n)\n vWeights = reshape(vWeights,1,n); % make sure it is a row vector\nelse\n error(message('stats:pca:WrongObsWeights', n));\nend\n\nif internal.stats.isString(vVariableWeights)\n WeightsNames = {'variance'};\n internal.stats.getParamVal(vVariableWeights,WeightsNames,...\n '''VariableWeights''');\n vVariableWeights = 1./classreg.learning.internal.wnanvar(x,vWeights,1);\nelseif isnumeric(vVariableWeights) && isvector(vVariableWeights)...\n && (isequal(numel(vVariableWeights), p))\n vVariableWeights = reshape(vVariableWeights,1,p);\nelse\n error(message('stats:pca:WrongVarWeights', p));\nend\n\nif any(vWeights <= 0) || any(vVariableWeights <= 0)\n error(message('stats:pca:NonPositiveWeights'));\nend\n% end of checking input arguments\n\n\n% Handling special empty case\nif isempty(x)\n pOrZero = ~vEconomy * p;\n coeff = zeros(p, pOrZero); \n coeff(1:p+1:end) = 1;\n score = zeros(n, pOrZero);\n latent = zeros(pOrZero, 1);\n tsquared = zeros(n, 1);\n explained = [];\n mu = [];\n return;\nend\n\nnanIdx = isnan(x);\nnumNaN = sum(nanIdx, 2); % number of NaNs in each row\nwasNaN = any(numNaN,2); % Rows that contain NaN\n\n% Handling special cases where X is all NaNs:\nif all(nanIdx(:))\n coeff = NaN;\n score = NaN;\n latent = NaN;\n tsquared = NaN;\n explained = NaN;\n mu = NaN;\n return;\nend\n% Handling special scalar case;\nif isscalar(x)\n coeff = 1;\n score = (~vCentered)*x;\n latent = (~vCentered)*x^2;\n tsquared = ~vCentered;\n explained = 100;\n mu = vCentered*x;\n return;\nend\n\nif strcmp(vRows,'all') && (~strcmp(vAlgorithm,'als'))\n if any(wasNaN)\n error(message('stats:pca:RowsAll'));\n else\n vRows = 'complete';\n end\nend\n\nif strcmp(vRows,'complete')\n % Degrees of freedom (DOF) is n-1 if centered and n if not centered,\n % where n is the numer of rows without any NaN element.\n DOF = max(0,n-vCentered-sum(wasNaN));\nelseif strcmp(vRows,'pairwise') \n % DOF is the maximum number of element pairs without NaNs\n notNaN = double(~nanIdx);\n nanC = notNaN'*notNaN;\n nanC = nanC.*(~eye(p));\n DOF = max(nanC(:));\n DOF = DOF-vCentered;\nelse\n DOF = max(0,n-vCentered);\nend\n\nif vCentered\n % Weighted sample mean:\n mu = classreg.learning.internal.wnanmean(x, vWeights);\nelse\n mu = zeros(1,p,'like',x);\nend\n\n% Compute by EIG if no weights are given\nswitch vAlgorithm\ncase 'eig'\n % Center the data if 'Centered' is true.\n if vCentered\n x = bsxfun(@minus,x,mu);\n end\n \n % Use EIG to compute.\n [coeff, eigValues] = localEIG(x, vCentered, vRows, vWeights,...\n vVariableWeights);\n \n % When 'Economy' value is true, nothing corresponding to zero\n % eigenvalues should be returned.\n if (DOF 1\n score = x/coeff';\n latent = eigValues; % Output Eigenvalues\n if nargout > 3\n tsquared = localTSquared(score, latent, n, p);\n end\n end\n \ncase 'svd' % Use SVD to compute\n % Center the data if 'Centered' is true.\n if vCentered\n x = bsxfun(@minus,x,mu);\n end\n \n [U,sigma, coeff, wasNaN] = localSVD(x, n,...\n vEconomy, vWeights, vVariableWeights);\n if nargout > 1\n score = bsxfun(@times,U,sigma');\n latent = sigma.^2./DOF;\n if nargout > 3\n tsquared = localTSquared(score,latent,DOF,p);\n end\n %Insert NaNs back\n if any(wasNaN)\n score = internal.stats.insertnan(wasNaN, score);\n if nargout >3\n tsquared = internal.stats.insertnan(wasNaN,tsquared);\n end\n end\n end\n \n if DOF < p\n % When 'Economy' value is true, nothing corresponding to zero\n % eigenvalues should be returned.\n if vEconomy\n coeff(:, DOF+1:end) = [];\n if nargout > 1\n score(:, DOF+1:end)=[];\n latent(DOF+1:end, :)=[];\n end\n elseif nargout > 1\n % otherwise, eigenvalues and corresponding outputs need to pad\n % zeros because svd(x,0) does not return columns of U corresponding\n % to components of (DOF+1):p.\n score(:, DOF+1:p) = 0;\n latent(DOF+1:p, 1) = 0;\n end\n end\n \ncase 'als' % Alternating Least Square Algorithm\n \n vNumComponents = min([vNumComponents,n-vCentered,p]); % ALS always return economy sized outputs \n \n if isempty(s0);\n s0 = randn(n,vNumComponents,'like',x);\n elseif ~isequal(size(s0),[n,vNumComponents])|| any(isnan(s0(:)))\n error(message('stats:pca:BadInitialValues','Score0',n,vNumComponents));\n end\n if isempty(c0);\n c0 = randn(p,vNumComponents,'like',x);\n elseif ~isequal(size(c0),[p,vNumComponents]) || any(isnan(c0(:)))\n error(message('stats:pca:BadInitialValues','Coeff0',p,vNumComponents));\n end\n \n [score,coeff,mu,latent]=alsmf(x,vNumComponents,'L0',s0,'R0',c0,...\n 'Weights',vWeights,'VariableWeights',vVariableWeights,...\n 'Orthonormal',true,'Centered',vCentered,'Options',opts);\n \n if nargout > 3 \n % T-squared values are in reduced space.\n tsquared = localTSquared(score, latent,n-vCentered, vNumComponents); \n end \nend % end of switch vAlgorithm\n\n% Calcuate the percentage of the total variance explained by each principal\n% component.\nif nargout > 4\n explained = 100*latent/sum(latent);\nend\n\n% Output only the first k principal components\nif (vNumComponents 1\n score(:, vNumComponents+1:end) = [];\n end\nend\n\n\n% Enforce a sign convention on the coefficients -- the largest element in\n% each column will have a positive sign.\n[~,maxind] = max(abs(coeff), [], 1);\n[d1, d2] = size(coeff);\ncolsign = sign(coeff(maxind + (0:d1:(d2-1)*d1)));\ncoeff = bsxfun(@times, coeff, colsign);\nif nargout > 1\n score = bsxfun(@times, score, colsign); % scores = score\nend\n\nend % End of main function\n\n\n%----------------Subfucntions--------------------------------------------\n\nfunction [coeff, eigValues]=localEIG(x,vCentered, vRows,vWeights,...\n vVariableWeights)\n% Compute by EIG. vRows are the options of handing NaN when compute\n% covariance matrix\n\n% Apply observation and variable weights\nOmegaSqrt = sqrt(vWeights);\nPhiSqrt = sqrt(vVariableWeights);\nx = bsxfun(@times, x, OmegaSqrt');\nx = bsxfun(@times, x, PhiSqrt);\n\nxCov = ncnancov(x, vRows, vCentered);\n\n[coeff, eigValueDiag] = eig(xCov);\n[eigValues, idx] = sort(diag(eigValueDiag), 'descend');\ncoeff = coeff(:, idx);\n\ncoeff = bsxfun(@times, coeff,1./PhiSqrt');\nend\n\n\nfunction [U,sigma, coeff, wasNaN] = localSVD(x, n,...,\n vEconomy, vWeights, vVariableWeights)\n% Compute by SVD. Weights are supplied by vWeights and vVariableWeights.\n\n% Remove NaNs missing data and record location\n[~,wasNaN,x] = internal.stats.removenan(x);\nif n==1 % special case because internal.stats.removenan treats all vectors as columns\n wasNaN = wasNaN';\n x = x';\nend\n\n% Apply observation and variable weights\nvWeights(wasNaN) = [];\nOmegaSqrt = sqrt(vWeights);\nPhiSqrt = sqrt(vVariableWeights);\nx = bsxfun(@times, x, OmegaSqrt');\nx = bsxfun(@times, x, PhiSqrt);\n \nif vEconomy\n [U,sigma,coeff] = svd(x,'econ');\nelse\n [U,sigma, coeff] = svd(x, 0);\nend\n\nU = bsxfun(@times, U, 1./OmegaSqrt');\ncoeff = bsxfun(@times, coeff,1./PhiSqrt');\n\nif n == 1 % sigma might have only 1 row\n sigma = sigma(1);\nelse\n sigma = diag(sigma);\nend\nend\n\nfunction tsquared = localTSquared(score, latent,DOF, p)\n% Subfunction to calulate the Hotelling's T-squared statistic. It is the\n% sum of squares of the standardized scores, i.e., Mahalanobis distances.\n% When X appears to have column rank < r, ignore components that are\n% orthogonal to the data.\n\nif isempty(score)\n tsquared = score;\n return;\nend\n\nr = min(DOF,p); % Max possible rank of x;\nif DOF > 1\n q = sum(latent > max(DOF,p)*eps(latent(1)));\n if q < r\n warning(message('stats:pca:ColRankDefX', q)); \n end\nelse\n q = 0;\nend\nstandScores = bsxfun(@times, score(:,1:q), 1./sqrt(latent(1:q,:))');\ntsquared = sum(standScores.^2, 2);\nend\n\nfunction c = ncnancov(x,Rows,centered)\n% C = NCNANCOV(X) returns X'*X/N, where N is the number of observations\n% after removing rows missing values. \n%\n% C = NCNANCOV(...,'pairwise') computes C(I,J) using rows with no NaN\n% values in columns I or J. The result may not be a positive definite\n% matrix. C = NCNANCOV(...,'complete') is the default, and it omits rows\n% with any NaN values, even if they are not in column I or J.\n%\n% C = NCNANCOV(...,true), C is normalized by N-1 if data X is already\n% centered. The default is false.\n\nif nargin <2\n Rows = 'complete';\nend\n\nd = 0;\nif nargin>2\n d = d + centered;\nend\n\nidxnan = isnan(x);\n\n[n, p] = size(x);\n\n\nif ~any(any(idxnan))\n c = x'*x/(n-d);\nelseif strcmp(Rows,'complete')\n nanrows = any(idxnan,2);\n xNotNaN = x((~nanrows),:);\n denom = max(0, (size(xNotNaN,1)-d) );\n c = xNotNaN'*xNotNaN/denom;\nelseif strcmp(Rows,'pairwise')\n c = zeros(p,class(x));\n for i = 1:p\n for j = 1:i\n NonNaNRows = ~any(idxnan(:,[i, j]),2);\n denom = max(0,(sum(NonNaNRows)-d));\n c(i,j) = x(NonNaNRows,i)'*x(NonNaNRows,j)/denom;\n end\n end\n c = c + tril(c,-1)';\nend\nend", "meta": {"author": "Daikenan", "repo": "ASRCF", "sha": "5dedd83105a547be97ec4d914154439cbfd6ee9b", "save_path": "github-repos/MATLAB/Daikenan-ASRCF", "path": "github-repos/MATLAB/Daikenan-ASRCF/ASRCF-5dedd83105a547be97ec4d914154439cbfd6ee9b/feature/pca_.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.8031737892899221, "lm_q1q2_score": 0.7074331317413328}} {"text": "function partners=assignStableRoommates(prefLists)\n%%ASSIGNSTABLEROOMMATES Solve the basic form of the stable roommates \n% problem. In this problem, an even number of individuals rank their\n% preferences for each other. The algorithm then finds a stable \n% pairing of individuals, if one exists. An assignment is stable if\n% there is no pair of (non-assigned) members where BOTH prefer each \n% other over their current assignment. This function finds one\n% solutions; though multiple solutions may exist. If no solutions\n% exist, an empty matrix is returned.\n%\n%INPUTS: prefLists An NX(N-1) matrix where prefLists(n,i) is the ith\n% preferred roommate for person n. N must be an even\n% number. The \"roommate\" is just a number from 1 to N that\n% cannot equal n. Alternatively, an NXN matrix can be\n% passed, where the last column is equal to the row\n% number. This is allowed as this algorithm just augments\n% any NX(N-1) matrix to have that format before proceeding\n% (it plays a role in identifying infeasible assignments).\n%\n%OUTPUTS: partners An NX1 vector listing which each partner of the N\n% individuals is assigned to share a room in a stable\n% assignment (thus, partners is a permutation vector). If\n% no stable assignment exists, then an empty matrix is\n% returned.\n%\n%The O(N^2) algorithm of [1] is used to solve the problem.\n% \n%Example with a solution (from [1]):\n% prefLists=[4,6,2,5,3;\n% 6,3,5,1,4;\n% 4,5,1,6,2;\n% 2,6,5,1,3;\n% 4,2,3,6,1;\n% 5,1,4,2,3];\n% partners=assignStableRoommates(prefLists)\n%The solution should be partners=[6;3;2;5;4;1] for pairs of (1,6), (2,3),\n%and (4,5)\n%\n%Example without a solution (from [1]):\n% prefLists=[2,6,4,3,5;\n% 3,5,1,6,4;\n% 1,6,2,5,4;\n% 5,2,3,6,1;\n% 6,1,3,4,2;\n% 4,2,5,1,3];\n% partners=assignStableRoommates(prefLists)\n%The solution in this instance is an empty matrix, because no stable\n%solution exists.\n% \n%Example with multiple solutions (from [1]). Only 1 solution is found by\n%this function, though.\n% prefLists=[2,5,4,6,7,8,3;\n% 3,6,1,7,8,5,4;\n% 4,7,2,8,5,6,1;\n% 1,8,3,5,6,7,2;\n% 6,1,8,2,3,4,7;\n% 7,2,5,3,4,1,8;\n% 8,3,6,4,1,2,5;\n% 5,4,7,1,2,3,6];\n% partners=assignStableRoommates(prefLists)\n%The solution that will be found by this algorithm is\n%partners=[4;3;2;1;6;5;8;7]. However, the other two possible solutions are\n%[1,2,3,4,8,7,6,5] and [5,6,7,8,1,2,3,4].\n% \n%REFERENCES:\n%[1] R. W. Irving, \"An Efficient Algorithm for the 'Stable Rommates'\n% Problem,\" Journal of Algorithms, vol. 6, no. 4, pp. 577-595, Dec.\n% 1985.\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n \n numPeople=size(prefLists,1);\n \n %If the preference lists do not already contain \"self\" (sentinel) as\n %the last column, then add it.\n if(size(prefLists,2)numPeople)\n solutionFound=true;\n break;\n else\n [cycle,firstInCycle,lastInCycle,firstUnmatched,second,tail]=seekCycle(prefLists,ranking,cycle,firstInCycle,firstUnmatched,second,tail,rightmost);\n \n [solutionPossible,leftmost,second,rightmost]=phase2Reduce(prefLists,ranking,cycle,leftmost,second,rightmost,firstInCycle,lastInCycle);\n end\n end\n \n if(solutionFound)\n partners=zeros(numPeople,1);\n \n for curPerson=1:numPeople\n partners(curPerson)=prefLists(curPerson,leftmost(curPerson));\n end\n else\n partners=[];%No solution found.\n end\nend\n\nfunction [solutionPossible,leftmost,rightmost]=phase1Reduce(prefLists,ranking,leftmost,rightmost)\n numPeople=size(prefLists,1);\n \n %Initially, no one proposed to (all zeros).\n setProposedTo=zeros(numPeople,1);\n for curPerson=1:numPeople\n proposer=curPerson;\n while(1)\n %Best potential partner\n nextChoice=prefLists(proposer,leftmost(proposer));\n %nextChoice holds current\n current=prefLists(nextChoice,rightmost(nextChoice));\n \n while(ranking(nextChoice,proposer)>ranking(nextChoice,current))\n %Proposer is rejected by nextChoice \n leftmost(proposer)=leftmost(proposer)+1;\n nextChoice=prefLists(proposer,leftmost(proposer));\n current=prefLists(nextChoice,rightmost(nextChoice));\n end\n %nextChoice holds proposer\n rightmost(nextChoice)=ranking(nextChoice,proposer);\n %and rejects current\n proposer=current;\n \n if(setProposedTo(nextChoice)==0)\n break;\n end\n end\n setProposedTo(nextChoice)=1;\n end\n \n solutionPossible=(proposer==nextChoice);\nend\n\nfunction firstUnmatched=find1stwithMoteThan1Potential(firstUnmatched,leftmost,rightmost)\n%%Find the first person with more than one potential partner.\n while(leftmost(firstUnmatched)==rightmost(firstUnmatched))\n firstUnmatched=firstUnmatched+1;\n end\nend\n\nfunction [cycle,firstInCycle,lastInCycle,firstUnmatched,second,tail]=seekCycle(prefLists,ranking,cycle,firstInCycle,firstUnmatched,second,tail,rightmost)\n numPeople=size(prefLists,1);\n \n if(firstInCycle>1)\n %Last person in previous tail.\n person=cycle(firstInCycle-1);\n %His second choice may have to be updated\n posInCycle=firstInCycle-1;\n cycleSet=tail;\n else\n cycleSet=zeros(numPeople,1);%Nothing in the cycle set\n posInCycle=1;\n person=firstUnmatched;\n end\n \n %Generate sequence\n while(1)\n cycleSet(person)=1;%Add person to the cycle set.\n \n cycle(posInCycle)=person;\n posInCycle=posInCycle+1;\n posInList=second(person);\n \n while(1)%Update second choice for current person\n nextChoice=prefLists(person,posInList);\n posInList=posInList+1;\n \n if(ranking(nextChoice,person)<=rightmost(nextChoice))\n break;\n end; \n end\n \n second(person)=posInList-1;\n person=prefLists(nextChoice,rightmost(nextChoice));\n \n %If sequence starts to cycle.\n if(cycleSet(person)==1)\n break;\n end\n end\n lastInCycle=posInCycle-1;\n tail=cycleSet;\n \n %Work back to the beginning of the cycle\n while(1)\n posInCycle=posInCycle-1;\n tail(cycle(posInCycle))=0;\n \n if(cycle(posInCycle)==person)\n break;\n end\n end\n firstInCycle=posInCycle;\nend\n\nfunction [solutionPossible,leftmost,second,rightmost]=phase2Reduce(prefLists,ranking,cycle,leftmost,second,rightmost,firstInCycle,lastInCycle) \n for rank=firstInCycle:lastInCycle\n %Allow next person in cycle to be rejected\n proposer=cycle(rank);\n leftmost(proposer)=second(proposer);\n %Proper update unnaecessary at this stage\n second(proposer)=leftmost(proposer)+1;\n \n nextChoice=prefLists(proposer,leftmost(proposer));\n rightmost(nextChoice)=ranking(nextChoice,proposer);\n %nextChoice holds proposer.\n end\n \n rank=firstInCycle;\n solutionPossible=true;\n while(rank<=lastInCycle&&solutionPossible)\n %Check that no one has run out of potential partners\n proposer=cycle(rank);\n solutionPossible=(leftmost(proposer)<=rightmost(proposer));\n rank=rank+1;\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/Assignment_Algorithms/2D_Assignment/Game_Theoretic_Assignment/assignStableRoommates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.8807970701552505, "lm_q1q2_score": 0.7074331183571958}} {"text": "function zscoredData = BF_zscore(inputData)\n% BF_zscore z-score the input data vector (without a Statistics Toolbox licence)\n%\n%---INPUT:\n% inputData, the input time series (or any vector).\n%\n%---OUTPUT:\n% zscoredData, the z-scored transformation of the input.\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% Check for NaNs:\nif any(isnan(inputData))\n error('inputData contains NaNs');\nend\n\n% By default, z-score twice to reduce the numerical error:\nzscoredData = (inputData - mean(inputData)) / std(inputData);\nzscoredData = (zscoredData - mean(zscoredData)) / std(zscoredData);\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/PeripheryFunctions/BF_zscore.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7073851222572082}} {"text": "function [res,err] = Dot_(varargin)\n%DOT_ Dot products in K-fold precision\n%\n% res = Dot_(A1,x1,...,An,xn,K)\n%\n% [res,err] = Dot_(A1,x1,...,An,xn,K)\n%\n% res or res+err is sum(Ai*xi)\n% K optional, default K=2\n% K >0 approximate result as if computed in K-fold precision\n% <0 inclusion of result as if computed in |K|-fold precision\n%\n% First factor Ai may be either matrix or scalar; in the latter case\n% res is of the size of xi.\n% Second factor xi must be vector or scalar.\n% All factors may be complex, but must be non-interval. \n% Sizes of every product Ai*xi must be the same.\n%\n% Precision K must be at least 2.\n%\n% Interval input makes only sense, if all intervals are degenerated (point intervals); \n% therefore omitted.\n%\n% For speed and to fight interpretation overhead, 2 extra matrices are necessary; for\n% the product of to nxn matrices this would be n^3 memory, therefore this is not allowed.\n%\n% Examples are\n%\n% res = Dot_(x',y); Approximate scalar product x'*y in quadruple precision\n% res = Dot_(A,x,-1,b); Approximate residual A*x-b in quadruple precision\n% res = Dot_(A,x,-1,b,-2); Inclusion of residual A*x-b in quadruple precision\n% res = Dot_(A,x1,A,x2,-1,b,3); Approximate residual A*x1+A*x2-b in 3-fold precision\n%\n%For randomly generated full matrices of dimension n with b=a*randn(n,1) the following\n% table lists the computing times\n% t1 for ordinary residual b - A*x\n% t2 with improved residual by lssresidual\n% t3 with quadruple precision residual by Dot_\n%as well as the ratios to t1. All times are in seconds on a 800 MHz Pentium III Laptop.\n%\n% n t1 t2 t3 t2/t1 t3/t1 approximation of b-A*x\n%--------------------------------------------\n% 50 0.0002 0.001 0.003 3.1 14.6\n% 100 0.0002 0.003 0.010 13.7 45.7\n% 200 0.0005 0.010 0.045 20.5 89.5\n% 500 0.0064 0.089 0.416 13.7 64.6\n% 1000 0.0246 0.347 1.698 14.1 68.9\n%\n%The same table for verified inclusion of the residual b-A*x is as follows.\n%\n% n t1 t2 t3 t2/t1 t3/t1 inclusion of b-A*x\n%--------------------------------------------\n% 50 0.0012 0.001 0.004 0.9 3.0\n% 100 0.0013 0.002 0.010 1.9 7.5\n% 200 0.0020 0.012 0.048 6.1 23.8\n% 500 0.0138 0.103 0.381 7.5 27.5\n% 1000 0.0505 0.421 1.863 8.3 36.9\n%\n%Finally we display the achieved accuracy of the three methods for \n% matrices of dimension 100 and different condition numbers, a randomly\n% generated right hand side b and computed solution x=A\\b. \n% We treat 100 test cases each and display the median and maximum componentwise\n% relative error of the results. Matrices are normed to 1.\n%\n% A*x-b lssresidual Dot_\n%condition median maximum median maximum median maximum\n%---------------------------------------------------------------\n% 1e2 6.8e-16 1.0e+0 5.0e-21 8.9e-16 0.0e+0 4.7e-30 \n% 1e5 1.8e-01 1.0e+0 1.8e-18 3.0e-01 5.0e-29 1.7e-27 \n% 1e10 2.9e-01 1.0e+0 2.4e-06 6.8e-01 3.3e-24 1.8e-22 \n% 1e14 2.8e-01 1.0e+0 2.1e-06 1.0e+0 2.7e-20 2.6e-18 \n%\n%The more we pay, the more we get.\n%\n% Implements algorithms Dot2 and DotK from\n% T. Ogita, S.M. Rump, S. Oishi: Accurate Sum and Dot Product, \n% SIAM Journal on Scientific Computing (SISC), 26(6):1955-1988, 2005\n%\n\n% written 11/08/03 S.M. Rump\n% modified 11/30/03 S.M. Rump complex data allowed\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% modified 08/08/04 S.M. Rump sparse input\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 11/20/05 S.M. Rump fast check for rounding to nearest\n% modified 12/12/05 S.M. Rump apapted to paper, improved performance\n% modified 05/30/07 S.M. Rump typo\n% modified 08/07/10 S.M. Rump upper case Dot_\n% modified 06/06/11 S.M. Rump result in two parts\n% modified 08/26/12 S.M. Rump global variables removed, rounding\n% modified 09/05/12 S.M. Rump sparse complex (thanks to M. Lange)\n% modified 10/17/12 S.M. Rump comments\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 % detect parameters\n len = length(varargin);\n if even(len) % default precision\n K = 2;\n else\n K = varargin{len};\n end\n idim = 0;\n \n % check precision K\n if abs(K)<2\n error('invalid parameter K for Dot_')\n end\n \n % detect dimension of result\n if prod(size(varargin{1}))==1\n [m n] = size(varargin{2});\n else\n m = size(varargin{1},1); % m or n must be 1\n n = size(varargin{1},2);\n end\n \n % Initialization\n factor = 134217729; % splitting factor 2^27+1\n if abs(K)==2\n res = zeros(m,1);\n if K>0\n s = 0;\n else\n sinf = 0;\n ssup = 0;\n end\n else\n res = [];\n S = [];\n end\n \n % Compute array to sum up\n for i=1:floor(nargin/2)\n \n % compute next product A*x\n A = varargin{2*i-1};\n x = varargin{2*i};\n sA = size(A);\n sx = size(x);\n if sx(2)~=1\n error('second factor in Dot_ must be vector')\n end\n \n if ( prod(sA)==1 ) & ( sx(1)~=m )\n error('dimensions of summands in Dot_ do not match')\n end\n\n if ( prod(sA)==1 ) & ( abs(A)==1 ) % first factor A scalar +/- 1\n \n % TwoProduct(A,x)\n if A==1\n [res,q] = sumK([res x],2);\n else\n [res,q] = sumK([res -x],2);\n end\n if abs(K)==2\n if K>0\n s = s + q;\n else\n setround(-1)\n sinf = sinf + q;\n setround(1)\n ssup = ssup + q;\n setround(0)\n end\n else\n S = [S q];\n end\n idim = idim + 1;\n \n else % first factor non-scalar or ~= +/- 1\n \n % matrix-vector product or dot product\n if ( prod(sA)~=1 ) & ( sA(2)~=sx(1) )\n error('inner dimensions in Dot_ do not match')\n end\n if issparse(A)\n [iA,jA,ssA] = find(A);\n end\n C = factor*A;\n A1 = C - ( C - A ); % upper part of A\n A2 = A - A1; % A = A1+A2 exact splitting\n \n C = factor*x;\n x1 = C - ( C - x ); % upper part of x\n x2 = x - x1; % x = x1+x2 exact splitting\n \n I = sqrt(-1);\n if sA(1)~=1 % m~=1: matrix-vector product\n if issparse(A) % factors s.t. A*x = sum( (A1+A2).*(x1+x2) , 2 )\n x1 = sparse(iA,jA,x1(jA),m,sA(2));\n x2 = sparse(iA,jA,x2(jA),m,sA(2));\n else\n x1 = x1(:,ones(1,m)).';\n x2 = x2(:,ones(1,m)).';\n end\n if isreal(A) | isreal(x) % A or x real\n if issparse(A)\n h = sparse(iA,jA,ssA.*x(jA),m,sA(2));\n else\n h = A .* ( x(:,ones(1,m)).' );\n end\n idim = idim + sx(1);\n else % both A and x complex\n if issparse(A)\n h = [ sparse(iA,jA,ssA.*real(x(jA)),m,sA(2)) , sparse(iA,jA,I*(ssA.*imag(x(jA))),m,sA(2)) ];\n else\n xx = x(:,ones(1,m)).';\n h = [ A.*real(xx) , A.*(I*imag(xx)) ];\n end\n idim = idim + 2*sx(1);\n end\n elseif sA(2)~=1\n if isreal(A) | isreal(x) % A or x real\n h = A .* x.';\n x1 = x1.';\n x2 = x2.';\n idim = idim + sx(1);\n else % both A and x complex\n h = [ A.*real(x).' , A.*(I*imag(x)).' ];\n x1 = x1.';\n x2 = x2.';\n idim = idim + 2*sx(1);\n end\n else\n if isreal(A) | isreal(x) % A or x real\n h = A * x;\n idim = idim + 1;\n else % both A and x complex\n h = [ A*real(x) , A*(I*imag(x)) ];\n idim = idim + 2;\n end\n end\n \n % TwoProduct(A,x): A*x = h + r\n if isreal(A) | isreal(x) % A or x real\n r = A2.*x2 - ((( h - A1.*x1 ) - A2.*x1 ) - A1.*x2 );\n else % both A and x complex\n r = [A2.*real(x2),A2.*(I*imag(x2))] - ((( h - [A1.*real(x1),A1.*(I*imag(x1))] ) - ...\n [A2.*real(x1),A2.*(I*imag(x1))] ) - [A1.*real(x2),A1.*(I*imag(x2))] );\n end\n \n if issparse(h) % compress h\n h = compress(h);\n end\n if issparse(r) % compress r\n r = compress(r);\n end\n \n % Summation vector and partial summation for |K|=2\n if abs(K)==2\n [res,q] = sumK([res h],2); % error-free\n sq2 = size(q,2);\n sr2 = size(r,2);\n if sq2>sr2\n r = [r zeros(size(r,1),sq2-sr2)];\n elseif sq2>sr2\n q = [q zeros(size(q,1),sr2-sq2)];\n end\n if K>0\n s = s + sum(q+r,2);\n else\n setround(-1)\n sinf = sinf + sum(q+r,2);\n setround(1)\n ssup = ssup + sum(q+r,2);\n setround(0)\n end\n else\n [res,q] = sumK([res h],2);\n S = [S q r];\n end\n \n end\n \n end\n\n % Compute result in K-fold precision\n if abs(K)==2 % quadruple precision\n if K>0\n res = res + s;\n else\n INTLAB_INTVAL_ETA = realmin*eps; % smallest positive denormalized fl-pt\n setround(-1)\n resinf = sinf - 5*idim*INTLAB_INTVAL_ETA;\n setround(1)\n ressup = ssup + 5*idim*INTLAB_INTVAL_ETA;\n err = infsup(resinf,ressup);\n if nargout==1\n res = res + err;\n end\n end\n else % |K|-fold precision\n if K>0\n res = Sum_([S res],K,2);\n else\n INTLAB_INTVAL_ETA = realmin*eps; % smallest positive denormalized fl-pt\n [res,q] = sumK([S res],-K); % error-free transformation\n setround(-1)\n resinf = sum(q,2) - 5*idim*INTLAB_INTVAL_ETA;\n setround(1)\n ressup = sum(q,2) + 5*idim*INTLAB_INTVAL_ETA;\n err = infsup(resinf,ressup);\n if nargout==1\n res = res + err;\n end\n end\n end\n \n if rndold\n setround(rndold)\n end\n\n \nfunction [res,q] = sumK(a,K)\n%SUM Summation of \"a\" in K-fold precision along 2nd dimension\n% res is approximate sum, sum of errors in q\n% res + sum(q,2) = sum(a,2) in exact arithmetic\n\n % number of summands\n N = size(a,2);\n \n % summation (i.e. quadruple for K==2)\n for i=1:K-1\n pi = cumsum(a,2);\n z = diff(pi,1,2);\n q = ( pi(:,1:N-1) - ( pi(:,2:N) - z ) ) + ( a(:,2:N) - z );\n res = pi(:,N);\n if i~=K-1\n a = [q res];\n end\n end\n\nfunction a = compress(a)\n%COMPRESS horizontal compress of array \"a\" such that sum(a,2) remains unchanged\n\n [i,j,s]=find(a.'); \n rows = sum(spones(a),2);\n m = max(rows);\n if m==0\n a = sparse([],[],[],size(a,1),m);\n return\n end\n rows = nonzeros(rows);\n index = cumsum([1;rows(1:end-1)]);\n h = ones(size(i));\n h(index(2:end))=-rows(1:end-1)+1;\n a = sparse(j,cumsum(h),s,size(a,1),m);", "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/Dot_.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.8175744761936438, "lm_q1q2_score": 0.7073851204204357}} {"text": "% HOMOTRANS - 2D homogeneous transformation of points/lines.\n%\n% Function to perform a transformation on 2D homogeneous points/lines\n% The resulting points/lines are normalised to lie in the z = 1 plane\n%\n% Usage:\n% t = homoTrans(P,v);\n%\n% Arguments:\n% P - 3 x 3 transformation matrix\n% v - 3 x n matrix of points/lines\n\n% Peter Kovesi\n% School of Computer Science & Software Engineering\n% The University of Western Australia\n% pk @ csse uwa edu au\n% http://www.csse.uwa.edu.au/~pk\n%\n% April 2000\n\nfunction t = homoTrans(P,v);\n\nt = P*v;\nt(1,:) = t(1,:)./t(3,:); % Now normalise\nt(2,:) = t(2,:)./t(3,:);\nt(3,:) = ones(1,size(v,2));\n", "meta": {"author": "christianwengert", "repo": "calib_toolbox_addon", "sha": "d4220bde1d17acc9ea03c88433f13eaad94ddccd", "save_path": "github-repos/MATLAB/christianwengert-calib_toolbox_addon", "path": "github-repos/MATLAB/christianwengert-calib_toolbox_addon/calib_toolbox_addon-d4220bde1d17acc9ea03c88433f13eaad94ddccd/homoTrans.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.79053032607222, "lm_q1q2_score": 0.7073582106219649}} {"text": "%TPOLY Generate scalar polynomial trajectory\n%\n% [S,SD,SDD] = TPOLY(S0, SF, M) is a scalar trajectory (Mx1) that varies\n% smoothly from S0 to SF in M steps using a quintic (5th order) polynomial.\n% Velocity and acceleration can be optionally returned as SD (Mx1) and SDD\n% (Mx1) respectively.\n%\n% TPOLY(S0, SF, M) as above but plots S, SD and SDD versus time in a single\n% figure.\n%\n% [S,SD,SDD] = TPOLY(S0, SF, T) as above but the trajectory is computed at\n% each point in the time vector T (Mx1).\n%\n% [S,SD,SDD] = TPOLY(S0, SF, T, QD0, QD1) as above but also specifies the\n% initial and final velocity of the trajectory.\n%\n% Notes::\n% - If M is given\n% - Velocity is in units of distance per trajectory step, not per second.\n% - Acceleration is in units of distance per trajectory step squared, not\n% per second squared. \n% - If T is given then results are scaled to units of time.\n% - The time vector T is assumed to be monotonically increasing, and time\n% scaling is based on the first and last element.\n%\n% Reference:\n% Robotics, Vision & Control\n% Chap 3\n% Springer 2011\n%\n% See also LSPB, JTRAJ.\n\n\n\n% Copyright (C) 1993-2017, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\n% [S,SD,SDD] = TPOLY(S0, SF, N, SD0, SDF) as above but specifies initial \n% and final joint velocity for the trajectory.\n%\n% [S,SD,SDD] = TPOLY(S0, SF, T, SD0, SDF) as above but specifies initial \n% and final joint velocity for the trajectory and time vector T.\n%\n% Notes::\n% - In all cases if no output arguments are specified S, SD, and SDD are plotted \n% against time.\n%\n% See also LSPB, JTRAJ.\n\nfunction [s,sd,sdd] = tpoly(q0, qf, t, qd0, qdf)\n\n t0 = t;\n if isscalar(t)\n\t\tt = (0:t-1)';\n else\n t = t(:);\n end\n if nargin < 4\n qd0 = 0;\n end\n if nargin < 5\n qdf = 0;\n end\n \n plotsargs = {'.-', 'Markersize', 16};\n \n tf = max(t);\n % solve for the polynomial coefficients using least squares\n X = [\n 0 0 0 0 0 1\n tf^5 tf^4 tf^3 tf^2 tf 1\n 0 0 0 0 1 0\n 5*tf^4 4*tf^3 3*tf^2 2*tf 1 0\n 0 0 0 2 0 0\n 20*tf^3 12*tf^2 6*tf 2 0 0\n ];\n coeffs = (X \\ [q0 qf qd0 qdf 0 0]')';\n\n % coefficients of derivatives \n coeffs_d = coeffs(1:5) .* (5:-1:1);\n coeffs_dd = coeffs_d(1:4) .* (4:-1:1);\n\n % evaluate the polynomials\n p = polyval(coeffs, t);\n pd = polyval(coeffs_d, t);\n pdd = polyval(coeffs_dd, t);\n\n switch nargout\n case 0\n if isscalar(t0)\n % for scalar time steps, axis is labeled 1 .. M\n xt = t+1;\n else\n % for vector time steps, axis is labeled by vector M\n xt = t;\n end\n\n\n clf\n subplot(311)\n plot(xt, p, plotsargs{:}); grid; ylabel('$s$', 'FontSize', 16, 'Interpreter','latex');\n\n subplot(312)\n plot(xt, pd, plotsargs{:}); grid; \n if isscalar(t0)\n ylabel('$ds/dk$', 'FontSize', 16, 'Interpreter','latex');\n else\n ylabel('$ds/dt$', 'FontSize', 16, 'Interpreter','latex');\n end\n \n subplot(313)\n plot(xt, pdd, plotsargs{:}); grid;\n if isscalar(t0)\n ylabel('$ds^2/dk^2$', 'FontSize', 16, 'Interpreter','latex');\n else\n ylabel('$ds^2/dt^2$', 'FontSize', 16, 'Interpreter','latex');\n end\n \n if ~isscalar(t0)\n xlabel('t (seconds)')\n else\n xlabel('k (step)');\n for c=findobj(gcf, 'Type', 'axes')\n set(c, 'XLim', [1 t0]);\n end\n end\n shg\n case 1\n s = p;\n case 2\n s = p;\n sd = pd;\n case 3\n s = p;\n sd = pd;\n sdd = pdd;\n end\n", "meta": {"author": "petercorke", "repo": "robotics-toolbox-matlab", "sha": "bd7a9d75176c660f43fc799b24d838f70b02250c", "save_path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-robotics-toolbox-matlab/robotics-toolbox-matlab-bd7a9d75176c660f43fc799b24d838f70b02250c/tpoly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.7073582039581329}} {"text": "% Calculate Pearson cross correlation between two firing rate maps\n%\n% The size of return variable corrValue depends on input parameter 'output':\n% *) 'single', corrValue is a single number. Maps are reshaped in a vector and\n% correlation is calculated.\n% *) 'vector', corrValue is a vector. Maps are processed row- or column-wise.\n% corrValue(i) is a correlation coeeficient for row/column i.\n% Row/column selection is done by parameter 'processBy'.\n%\n% USAGE\n% corrValue = analyses.spatialCrossCorrelation(map1, map2, )\n% map1 2D matrix, rate map\n% map2 2D matrix, rate map\n% optional list of property-value pairs (see table below)\n%\n% =========================================================================\n% Properties Values\n% -------------------------------------------------------------------------\n% 'output' 'single' or 'vector'. Default is 'single'.\n%\n% 'processBy' 'r' or 'c'. The parameter specifies how maps are processed.\n% 'r' means iteration over y-axis (rows) and calculation of correlation per row.\n% 'c' means iteration over x-axis (columns) and calculation of correlation\n% per column. Default is 'c'. This only makes difference for 'vector' output.\n% Single value is independent of processing order.\n% =========================================================================\n%\n% corrValue Correlation value(s). Can be either a single number or a vector.\n%\nfunction corrValue = spatialCrossCorrelation(map1, map2, varargin)\n columnWise = 0;\n rowWise = 1;\n single = 'single';\n\n inp = inputParser;\n defaultProcessBy = 'c';\n defaultReturnFormat = single;\n\n checkProcessBy = @(x) strcmpi(x, 'c') || strcmpi(x, 'r');\n checkReturnFormat = @(x) strcmpi(x, 'single') || strcmpi(x, 'vector');\n\n addRequired(inp, 'map1');\n addRequired(inp, 'map2');\n addParamValue(inp, 'processBy', defaultProcessBy, checkProcessBy);\n addParamValue(inp, 'output', defaultReturnFormat, checkReturnFormat);\n\n parse(inp, map1, map2, varargin{:});\n\n % get parsed arguments\n if strcmpi(inp.Results.processBy, 'c')\n orientation = columnWise;\n else\n orientation = rowWise;\n end\n returnFormat = inp.Results.output;\n\n if ~isequal(size(map1), size(map2))\n warning('BNT:mapsSize', 'Maps are of different size. This is suspicious. Correlation won''t be calculated');\n corrValue = nan;\n return;\n end\n\n if strcmpi(returnFormat, single)\n % Transform the 2-D maps to 1-D arrays by assembling the columns/rows from the maps\n A = reshape(map1, numel(map1), 1);\n B = reshape(map2, numel(map2), 1);\n\n % Remove the bins with NaN in A from both maps\n nansA = isnan(A);\n A = A(~nansA);\n B = B(~nansA);\n\n % Remove the bins with NaN in B from both maps\n nansB = isnan(B);\n A = A(~nansB);\n B = B(~nansB);\n\n % Calculate the correlation for the two rate maps.\n if isempty(A) || isempty(B)\n corrValue = NaN; % Cannot do calculation on empty arrays\n else\n corrValue = corr(A, B);\n end\n else\n nansLeft = isnan(map1);\n map1(nansLeft) = [];\n map2(nansLeft) = [];\n\n nansRight = isnan(map2);\n map1(nansRight) = [];\n map2(nansRight) = [];\n\n if orientation == columnWise\n corrMatrix = corr(map1, map2);\n corrValue = diag(corrMatrix)'; % make a row\n else\n corrMatrix = corr(map1', map2');\n corrValue = diag(corrMatrix); % make a column\n end\n end\nend\n", "meta": {"author": "kavli-ntnu", "repo": "MINI2P_toolbox", "sha": "83311a49baea69ecf027e19390e608fd4eaeae8d", "save_path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox", "path": "github-repos/MATLAB/kavli-ntnu-MINI2P_toolbox/MINI2P_toolbox-83311a49baea69ecf027e19390e608fd4eaeae8d/Analysis/+SpatialTuning_BNT/spatialCrossCorrelation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.7073581995623763}} {"text": "function value = r8_cbrt ( x )\n\n%*****************************************************************************80\n%\n%% R8_CBRT computes the cube root of an R8.\n%\n% Discussion:\n%\n% The approximation is a generalized Chebyshev series converted\n% to polynomial form. The approximation is nearly best in the\n% sense of relative error with 4.085 digits accuracy.\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 number whose square root is desired.\n%\n% Output, real VALUE, the cube root of X.\n%\n persistent cbrt2\n persistent niter\n\n if ( isempty ( niter ) )\n\n cbrt2 = [ ...\n 0.62996052494743658238360530363911, ...\n 0.79370052598409973737585281963615, ...\n 1.0, ...\n 1.25992104989487316476721060727823, ...\n 1.58740105196819947475170563927231 ]';\n\n niter = r8_aint ( 1.443 * log ( - 0.106 ...\n * log ( 0.1 * r8_mach ( 3 ) ) ) + 1.0 );\n\n end\n\n value = 0.0;\n\n if ( x ~= 0.0 )\n\n [ y, n ] = r8_upak ( abs ( x ) );\n ixpnt = floor ( n / 3 );\n irem = n - 3 * ixpnt + 3;\n\n value = 0.439581 + y * ( ...\n 0.928549 + y * ( ...\n - 0.512653 + y * ...\n 0.144586 ) );\n\n for iter = 1 : niter\n vsq = value * value;\n value = value + ( y - value * vsq ) / ( 3.0 * vsq );\n end\n\n if ( x < 0.0 )\n value = - abs ( value );\n else\n value = + abs ( value );\n end\n\n value = r8_pak ( cbrt2(irem) * value, ixpnt );\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_cbrt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.70735819954232}} {"text": "%% Laplacian Eigen maps and MDS\n close all; clear all;\n\t%[X, labels] = generate_data('swiss', 2000);\n \n % 1st group of points\n X1=[1 1\n 1 0.5\n 1 1.5\n 0.5 1\n 1.5 1\n ]\n [N1,r]=size(X1);\n labels([1:N1])=1; % Labels of the class - 3 classes here\n \n % 2nd group of points\n X2=[-1 -1\n -1 -0.8\n -1 -1.2\n -0.8 -1\n -1.2 -1\n ]\n [N2,r]=size(X2);\n labels([N1+1:N1+N2])=2;\n\n \n % 3rd group of points (overlap with one and two)\n% X3=[-0.9 -1\n% -0.2 -0.8\n% -0.5 -0.5\n% 0.5 0.8\n% 0.2 0.0\n% 0.1 -0.1\n% 0.2 -0.2\n% % ]\n X3=X1;\n [N3,r]=size(X3);\n labels([N1+N2+1:N1+N2+N3])=3;\n\n figure; hold on;\n plot(X1(:,1),X1(:,2),'b*');\n plot(X2(:,1),X2(:,2),'r*');\n plot(X3(:,1),X3(:,2),'k*');\n legend('Class 1', 'Class 2', 'Class 3');\naxis([-2 2 -2 2]);\n\nX=[X1' X2' X3']'; %% Construct the entire matrix made of the 3 subgroups of points\n\n[L,r]=size(X);\nfor i=1:L\n if labels(i)==1 c(i,:)=[0 0 1];\n elseif labels(i)==2; c(i,:)=[1 0 0];\n else c(i,:)=[0 0 0];\n end;\nend;\n%%\nfigure; hold on;\n\n%% Perform MDS\n % [mappedX, mapping] = compute_mapping(X, 'MDS', 3);\t\n \n disp('Computing kernel matrix...'); \n kernel = 'gauss';\n param1 = 1; % sigma\n param2 = 0; % not used\n K = gram(X, X, kernel, param1, param2);\n dims_keep = 2;\n \n [mappedX, mapping] = cmdscale(K,dims_keep);\n \n subplot(2,2,1), scatter(mappedX(:,1), mappedX(:,2), 25, c, 'filled'); title(['Result of MDS']); drawnow\n \n%% Perform PCA\n [mappedX, mapping] = compute_mapping(X, 'PCA', 2);\t\n\tsubplot(2,2,2), scatter(mappedX(:,1), mappedX(:,2), 25, c, 'filled'); title(['Result of ' mapping.name]); drawnow\n \n\n %% Perform Laplacian\n [mappedX, mapping] = compute_mapping(X, 'Laplacian', 4);\t\n\tsubplot(2,2,3), scatter(mappedX(:,1), mappedX(:,2), 25, c, 'filled'); title(['Result of ' mapping.name]); drawnow\n %% Isomap\n [mappedX, mapping] = compute_mapping(X, 'Isomap', 2);\t\n\tsubplot(2,2,4), scatter(mappedX(:,1), mappedX(:,2), 25, c, 'filled'); title(['Result of ' mapping.name]); drawnow\nreturn; \n\n \n\tfigure, scatter3(X(:,1), X(:,2), X(:,3), 5, labels); title('Original dataset'), drawnow\n\tno_dims = round(intrinsic_dim(X, 'MLE'));\n\tdisp(['MLE estimate of intrinsic dimensionality: ' num2str(no_dims)]);\n\n % This does not seem to be implemented in the toolbox, -> use matlab \n % dimensionality reduction: http://uk.mathworks.com/help/stats/dimensionality-reduction.html\n [mappedX, mapping] = compute_mapping(X, 'MDS', 2);\t\n\tfigure, scatter(mappedX(:,1), mappedX(:,2), 5); title(['Result of ' mapping.name]); drawnow\n\n [mappedX, mapping] = compute_mapping(X, 'LaplacianEigenmaps', no_dims, 7);\t\n\tfigure, scatter(mappedX(:,1), mappedX(:,2), 5, labels(mapping.conn_comp)); title('Result of Laplacian Eigenmaps'); drawnow \n \n %% Multi-dimensional scaling from matlab\n \n % Generate some points in 4-D space, but close to 3-D space, then reduce them to distances only.\n X = [normrnd(0,1,10,3) normrnd(0,.1,10,1)];\n D = pdist(X,'euclidean');\n \n [Y,e] = cmdscale(D);\n \n % Four, but fourth one small\n dim = sum(e > eps^(3/4));\n \n % Poor reconstruction\n maxerr2 = max(abs(pdist(X)-pdist(Y(:,1:2))))\n\n % Good reconstruction\n maxerr3 = max(abs(pdist(X)-pdist(Y(:,1:3)))) \n\n % Exact reconstruction\n maxerr4 = max(abs(pdist(X)-pdist(Y)))\n \n %% Try matlab MDS with Swiss role data set\n \t\n [X, labels] = generate_data('swiss', 1000);\n \n % Use the euclidean distance metrix, rows of X should correspond to\n % observations\n D = pdist(X,'euclidean');\n \n disp(['D: ' num2str(size(D,1)) ' x ' num2str(size(D,2))]);\n \n \n [Y,e] = cmdscale(D);\n \tfigure, scatter(Y(:,1), Y(:,2), 5,labels); title(['Result of Matlab MDS']); drawnow\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/manifold_learning/laplace_eigen_demo_simple.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.7073581951565913}} {"text": "%% HODGELAPMGRATE test multigrid solver for Hodge Laplacian\n%\n% Reference \n%\n% L. Chen, Y. Wu, L. Zhong and J. Zhou. Multigrid Preconditioners for Mixed\n% Finite Element Methods of Vector Laplacian. Journal of Scientific\n% Computing, 77:101?128, 2018. https://doi.org/10.1007/s10915-018-0697-7\n%\n% See also HodgeLap3mgrate\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details.\n\n%%\nclose all; clear variables;\npde = HodgeLaplacianEdata1;\n% bdFlag = setboundary(node,elem,'Dirichlet','x==0','Neumann','~(x==0)');\noption.elemType = 'ND0';\n\n%% Options\n% option.N0 = 10; % number of nodes in the coarsest mesh\noption.maxIt = 4;\noption.rateflag = 0;\n% option.mg.solver = 'VCYCLE'; % V,W;\n% option.mg.coarsematrix = 'G'; % Galerkin formulation\noption.mg.smoothingstep = 2; % Smoothing step.\noption.mg.smoothingratio = 1.5; % ratio of variable smoothing\noption.mg.Vit = 1; % number of cycles for Schur complement \n\n%% Square\ndisp('Square Domain')\noption.L0 = 3; % refine to a finer mesh\n[node,elem] = squaremesh([0,1,0,1],1/4);\nbdFlag = setboundary(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\n\n%% Diagonal Preconditioner\noption.solver = 'sdiag';\nmfemHodgeLap(mesh,pde,option);\n\n%% Triangular Preconditioner\noption.solver = 'tri';\nmfemHodgeLap(mesh,pde,option);\n\n%% Approximated Factorization Preconditioner\noption.solver = 'appf';\nmfemHodgeLap(mesh,pde,option);\n\n%% Lshape domain\ndisp('Lshape Domain')\noption.L0 = 2; % refine to a finer mesh\npde = fveconedata;\n[node,elem] = squaremesh([-1,1,-1,1],0.25);\n[node,elem] = delmesh(node,elem,'x>0 & y<0');\nbdFlag = setboundary(node,elem,'Dirichlet');\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\n\n%% Diagonal Preconditioner\noption.solver = 'sdiag';\nmfemHodgeLap(mesh,pde,option);\n\n%% Triangular Preconditioner\noption.solver = 'tri';\nmfemHodgeLap(mesh,pde,option);\n\n%% Approximated Factorization Preconditioner\noption.solver = 'appf';\nmfemHodgeLap(mesh,pde,option);\n\n\n%% Crack domain\ndisp('Crack Domain')\npde = fveconedata;\nnode = [1,0; 0,1; -1,0; 0,-1; 0,0; 1,0]; % nodes\nelem = [5,1,2; 5,2,3; 5,3,4; 5,4,6]; % elements\nelem = label(node,elem); % label the mesh\n[node,elem ] = uniformrefine(node,elem);\nbdFlag = setboundary(node,elem,'Dirichlet');\noption.L0 = 3; % refine to a finer mesh\nmesh = struct('node',node,'elem',elem,'bdFlag',bdFlag);\n\n%% Diagonal Preconditioner\noption.solver = 'sdiag';\nmfemHodgeLap(mesh,pde,option);\n\n%% Triangular Preconditioner\noption.solver = 'tri';\nmfemHodgeLap(mesh,pde,option);\n\n%% Approximated Factorization Preconditioner\noption.solver = 'appf';\nmfemHodgeLap(mesh,pde,option);", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/example/solver/HodgeLapmgrate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.7073581885128156}} {"text": "% Fugacity coeficient calculation using Soave equation of state \n% Author: Arnulfo Rosales-Quintero\n% Email: arnol122@gmail.com \n% This function calculates either liquid or vapor fugacity coeficients\n%-------------------------------------------------------------------------%\nfunction [Phi,Vmix]=Phi(P,T,xy,a,b,phase01)\n%-------------------------------------------------------------------------%\n global delta1 delta2 R\n global Kij\n%-----------------------------------------------------------------------%\nnc = length(xy);\n%Mixture rule\namix=0.;\tbmix=0.;\nfor i=1:nc\n dda=0.;\n for j=1:nc\n aij(i,j)= sqrt(a(i)*a(j))*(1.0-Kij(i,j));\n dda = 2.0 * xy(j) * aij(i,j) + dda;\n amix = xy(i)*xy(j) * aij(i,j) + amix;\t%\"a\" mixture constant\n end\n dna(i) = dda;\t\t\t\t\t\t%First derivative d(an)/dni\n dnb(i) = b(i);\t\t\t\t\t\t%First derivative d(bn)/dni\n bmix = xy(i)*b(i) + bmix; %\"b\" mixture constant\nend\n%-------------------------------------------------------------------------%\n%Mixture Volume\n Bb = (P*bmix*(delta1+delta2-1.0) - R*T)/P;\n Cc = (amix - (P*bmix^2+R*T*bmix)*(delta1+delta2) + P*bmix^2*delta1*delta2)/P;\n Dd = (-amix*bmix - (P*bmix^3 + R*T*bmix^2)*delta1*delta2)/P;\n \nswitch phase01 \n case ('vapor')\n Vmix = max(roots([1 Bb Cc Dd]));\n case ('liquid')\n Vmix = min(roots([1 Bb Cc Dd]));\nend\n%-------------------------------------------------------------------------%\n%Fugacity calculation\nfor i=1:nc\n\tPhi(i) = dnb(i)/bmix*(P*Vmix/R/T-1.) - log(P*(Vmix-bmix)/R/T);\n Phi(i) = Phi(i) - amix/bmix*(dna(i)/amix-dnb(i)/bmix)/R/T*log((Vmix+delta1*bmix)/(Vmix+delta2*bmix))/(delta1-delta2);\nend\n\tPhi = exp(Phi);\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/22364-isothermal-flash-calculation-using-soave-equation-of-state/Isothermal_Flash/Phi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776495, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.7073486080633082}} {"text": "classdef SMMOP6 < PROBLEM\n% \n% Sparse multi-modal multi-objective optimization problem\n% theta --- 0.1 --- Sparsity of the Pareto sets\n% np --- 4 --- Number of the Pareto sets\n\n%------------------------------- Reference --------------------------------\n% Y. Tian, R. Liu, X. Zhang, H. Ma, K. C. Tan, and Y. Jin, A\n% multipopulation evolutionary algorithm for solving large-scale multimodal\n% multiobjective optimization problems, IEEE Transactions on Evolutionary\n% Computation, 2021, 25(3): 405-418.\n%------------------------------- Copyright --------------------------------\n% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for\n% research purposes. All publications which use this platform or any code\n% in the platform should acknowledge the use of \"PlatEMO\" and reference \"Ye\n% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform\n% for evolutionary multi-objective optimization [educational forum], IEEE\n% Computational Intelligence Magazine, 2017, 12(4): 73-87\".\n%--------------------------------------------------------------------------\n\n properties(Access = private)\n theta = 0.1; % Sparsity of the Pareto sets\n np = 4; \t% Number of the Pareto sets\n POS; % Pareto optimal set for IGDX calculation\n end \n methods\n %% Default settings of the problem\n function Setting(obj)\n [obj.theta,obj.np] = obj.ParameterSet(0.1,4);\n if isempty(obj.M); obj.M = 2; end\n if isempty(obj.D); obj.D = 100; end\n obj.lower = [zeros(1,obj.M-1)+0,zeros(1,obj.D-obj.M+1)-1];\n obj.upper = [zeros(1,obj.M-1)+1,zeros(1,obj.D-obj.M+1)+2];\n obj.encoding = ones(1,obj.D);\n end\n %% Calculate objective values\n function PopObj = CalObj(obj,X)\n [N,D] = size(X);\n M = obj.M; \n S = ceil(obj.theta*(D-M));\n g = zeros(N,obj.np);\n for i = 1 : obj.np\n g(:,i) = sum(g2(X(:,M+(i-1)*S:M+i*S-1),pi/3),2)+sum(g4(X(:,[M:M+(i-1)*S-1,M+i*S:end]),0),2);\n end\n PopObj = repmat(1+min(g,[],2)/(D-M+1),1,M).*fliplr(cumprod([ones(N,1),1-cos(X(:,1:M-1)*pi/2)],2)).*[ones(N,1),1-sin(X(:,M-1:-1:1)*pi/2)];\n end\n %% Generate Pareto optimal solutions\n function R = GetOptimum(obj,N)\n % Generate points in Pareto optimal set\n A = GetPS(obj.D-obj.M+1,obj.np,ceil(obj.theta*(obj.D-obj.M)));\n X = UniformPoint(N/size(A,1),obj.M-1,'grid');\n obj.POS = [repmat(X,size(A,1),1),A(repmat(1:end,size(X,1),1),:)];\n % Generate points on Pareto front\n R = UniformPoint(N,obj.M);\n c = ones(size(R,1),obj.M);\n for i = 1 : size(R,1) \n for j = 2 : obj.M\n temp = R(i,j)/R(i,1)*prod(1-c(i,obj.M-j+2:obj.M-1));\n c(i,obj.M-j+1) = (temp^2-temp+sqrt(2*temp))/(temp^2+1);\n end\n end\n x = acos(c)*2/pi;\n R = fliplr(cumprod([ones(size(x,1),1),1-cos(x(:,1:end-1)*pi/2)],2)).*[ones(size(x,1),1),1-sin(x(:,end-1:-1:1)*pi/2)];\n end\n %% Generate the image of Pareto front\n function R = GetPF(obj)\n if obj.M == 2\n a = linspace(0,pi/2,100)';\n R = [1-cos(a),1-sin(a)];\n elseif obj.M == 3\n a = linspace(0,pi/2,10)';\n R = {(1-cos(a))*(1-cos(a')),(1-cos(a))*(1-sin(a')),(1-sin(a))*ones(size(a'))};\n else\n R = [];\n end\n end\n %% Calculate the metric value\n function score = CalMetric(obj,metName,Population)\n switch metName\n case 'IGDX'\n score = feval(metName,Population,obj.POS);\n otherwise\n score = feval(metName,Population,obj.optimum);\n end\n end\n %% Display a population in the objective space\n function DrawObj(obj,Population)\n PopDec = Population.decs;\n A = GetPS(obj.D-obj.M+1,obj.np,ceil(obj.theta*(obj.D-obj.M)));\n [~,Label] = min(pdist2(PopDec(:,obj.M:end),A),[],2);\n tempStream = RandStream('mlfg6331_64','Seed',2);\n if obj.M == 2\n for i = 1 : size(A,1)\n color = rand(tempStream,1,3);\n Draw(Population(Label==i).objs+(i-1)*0.05,'o','MarkerSize',6,'Marker','o','Markerfacecolor',sqrt(color),'Markeredgecolor',color,{'\\it f\\rm_1','\\it f\\rm_2',[]});\n Draw(obj.PF+(i-1)*0.05,'-','LineWidth',1,'Color',color);\n end\n elseif obj.M == 3\n for i = 1 : size(A,1)\n color = rand(tempStream,1,3);\n ax = Draw(Population(Label==i).objs+(i-1)*0.05,'o','MarkerSize',8,'Marker','o','Markerfacecolor',sqrt(color),'Markeredgecolor',color,{'\\it f\\rm_1','\\it f\\rm_2','\\it f\\rm_3'});\n surf(ax,obj.PF{1}+(i-1)*0.05,obj.PF{2}+(i-1)*0.05,obj.PF{3}+(i-1)*0.05,'EdgeColor',color,'FaceColor','none');\n end\n else\n for i = 1 : size(A,1)\n Draw(Population(Label==i).objs,'-','Color',rand(tempStream,1,3),'LineWidth',2);\n end\n end\n end\n end\nend\n\nfunction g = g2(x,t)\n g = 2*(x-t).^2 + sin(2*pi*(x-t)).^2;\nend\n\nfunction g = g4(x,t)\n g = sqrt((x-t).^2)+sin(2*pi*(x-t)).^2;\nend\n\nfunction PS = GetPS(D,np,S)\n PS = zeros(np,D);\n for i = 1 : np\n PS(i,(i-1)*S+1:i*S) = 1;\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/SMMOP/SMMOP6.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.7073221273041915}} {"text": "% \n% LibQPEP: A Library for Globally Optimal Solving Quadratic Pose Estimation Problems (QPEPs),\n% It also gives highly accurate uncertainty description of the solutions.\n%\n%\n% Article: \n% Wu, J., Zheng, Y., Gao, Z., Jiang, Y., Hu, X., Zhu, Y., Jiao, J., Liu, M. (2020)\n% Quadratic Pose Estimation Problems: Globally Optimal Solutions, \n% Solvability/Observability Analysis and Uncertainty Description.\n% IEEE Transactions on Robotics.\n% https://doi.org/10.1109/TRO.2022.3155880\n%\n%\n% Authors: Jin Wu and Ming Liu\n% Affiliation: Hong Kong University of Science and Technology (HKUST)\n% Emails: jin_wu_uestc@hotmail.com; eelium@ust.hk\n% Websites: https://zarathustr.github.io\n% https://ram-lab.com\n%\n%\n% syms_pnp.m: Generating symbolic expressions for solving PnP problem\n\n\n\n\nclear all\nclose all\nclc\n\naddpath('func_files');\naddpath('utils');\n\nsyms b1 b2 real\nsyms r1 r2 r3 real\n\nimage_pt = [b1, b2];\nworld_pt = [r1, r2, r3];\n\nsyms fx fy cx cy real\nK = [fx, 0, 0;\n 0, fy, 0;\n cx, cy, 1];\n \nsyms q0 q1 q2 q3 real\nsyms t1 t2 t3 lambda scale real\nq = [q0; q1; q2; q3];\ntt = [t1; t2; t3];\nRR = q2R(q);\nXX = [\n RR, tt;\n zeros(1, 3), 1];\nJ_pure = J_pnp_loss(image_pt, world_pt, K, RR, tt) * scale;\n[coef_J_pure, mon_J_pure] = coeffs(J_pure, [q; tt]);\ngenerateFuncFile(coef_J_pure, fullfile('func_files', 'coef_J_pure_pnp_func_new.m'), {image_pt, world_pt, [fx, fy, cx, cy], scale});\ngenerateFuncFile(mon_J_pure, fullfile('func_files', 'mon_J_pure_pnp_func_new.m'), {q, tt});\nJ = J_pure - 0.5 * lambda * (q.' * q - 1);\nx = [q; tt; lambda];\nJacob = jacobian(J, x);\nJacob = expand(Jacob.');\n\ncoef_len = length(coef_J_pure);\nstr = sprintf('coef_J = sym(''coef_J'', [1, %d]);', coef_len);\neval(str);\nshowSyms(symvar(coef_J));\nJ = coef_J * mon_J_pure.' - 0.5 * lambda * (q.' * q - 1);\nx = [q; tt; lambda];\nJacob = jacobian(J, x);\nJacob = expand(Jacob.');\n\nts = solveSyms(Jacob(5 : 7), tt);\nss = Jacob(1 : 4);\nss = subs(ss, q0^3, (q0 * (1 - q1^2 - q2^2 - q3^2)));\nss = subs(ss, q0^2, (1 - q1^2 - q2^2 - q3^2));\nJacob(1 : 4) = ss;\n\nss = subs(ss, t1, ts.t1);\nss = subs(ss, t2, ts.t2);\nss = subs(ss, t3, ts.t3);\n\n\n[coeft1, mont1] = coeffs(Jacob(5), tt);\ng1_ = coeft1(1 : 3).';\ng1 = vpa(zeros(3, 1));\nfor i = 1 : 3\n idx = sscanf(char(mont1(i)), 't%d');\n if(~isempty(idx))\n g1(idx) = g1_(i);\n end\nend\n[coeft2, mont2] = coeffs(Jacob(6), tt);\ng2_ = coeft2(1 : 3).';\ng2 = vpa(zeros(3, 1));\nfor i = 1 : 3\n idx = sscanf(char(mont2(i)), 't%d');\n if(~isempty(idx))\n g2(idx) = g2_(i);\n end\nend\n[coeft3, mont3] = coeffs(Jacob(7), tt);\ng3_ = coeft3(1 : 3).';\ng3 = vpa(zeros(3, 1));\nfor i = 1 : 3\n idx = sscanf(char(mont3(i)), 't%d');\n if(~isempty(idx))\n g3(idx) = g3_(i);\n end\nend\n\n[coeftq1, montq1] = coeffs(expand(Jacob(5) - g1.' * tt ), q);\ngenerateFuncFile(coeftq1, fullfile('func_files', 'coeftq1_pnp_func_new.m'), {coef_J});\n[coeftq2, montq2] = coeffs(expand(Jacob(6) - g2.' * tt ), q);\ngenerateFuncFile(coeftq2, fullfile('func_files', 'coeftq2_pnp_func_new.m'), {coef_J});\n[coeftq3, montq3] = coeffs(expand(Jacob(7) - g3.' * tt ), q);\ngenerateFuncFile(coeftq3, fullfile('func_files', 'coeftq3_pnp_func_new.m'), {coef_J});\nG = - [g1.'; g2.'; g3.'];\ngenerateFuncFile(G, fullfile('func_files', 'G_pnp_func_new.m'), {coef_J});\n\npinvG = sym('pinvG', [3, 3]);\nshowSyms(symvar(pinvG));\ncoefs_tq = sym('coefs_tq', [3, 10]);\nshowSyms(symvar(coefs_tq));\nts = pinvG * coefs_tq * montq1.';\nt1 = ts(1);\nt2 = ts(2);\nt3 = ts(3);\ngenerateFuncFile(t1, fullfile('func_files', 't1_pnp_func_new.m'), {pinvG, coefs_tq, q});\ngenerateFuncFile(t2, fullfile('func_files', 't2_pnp_func_new.m'), {pinvG, coefs_tq, q});\ngenerateFuncFile(t3, fullfile('func_files', 't3_pnp_func_new.m'), {pinvG, coefs_tq, q});\n\n[coef_Jacob1_qt, mon_Jacob1_qt] = coeffs(Jacob(1) + lambda * q0, [q; tt]);\ngenerateFuncFile(coef_Jacob1_qt, fullfile('func_files', 'coef_Jacob1_qt_pnp_func_new.m'), {coef_J});\n[coef_Jacob2_qt, mon_Jacob2_qt] = coeffs(Jacob(2) + lambda * q1, [q; tt]);\ngenerateFuncFile(coef_Jacob2_qt, fullfile('func_files', 'coef_Jacob2_qt_pnp_func_new.m'), {coef_J});\n[coef_Jacob3_qt, mon_Jacob3_qt] = coeffs(Jacob(3) + lambda * q2, [q; tt]);\ngenerateFuncFile(coef_Jacob3_qt, fullfile('func_files', 'coef_Jacob3_qt_pnp_func_new.m'), {coef_J});\n[coef_Jacob4_qt, mon_Jacob4_qt] = coeffs(Jacob(4) + lambda * q3, [q; tt]);\ngenerateFuncFile(coef_Jacob4_qt, fullfile('func_files', 'coef_Jacob4_qt_pnp_func_new.m'), {coef_J});\n\ncoef_Jacob1_qt_syms = sym('coef_Jacob1_qt_syms', [1, 32]);\ncoef_Jacob2_qt_syms = sym('coef_Jacob2_qt_syms', [1, 32]);\ncoef_Jacob3_qt_syms = sym('coef_Jacob3_qt_syms', [1, 32]);\ncoef_Jacob4_qt_syms = sym('coef_Jacob4_qt_syms', [1, 32]);\nshowSyms(symvar(coef_Jacob1_qt_syms));\nshowSyms(symvar(coef_Jacob2_qt_syms));\nshowSyms(symvar(coef_Jacob3_qt_syms));\nshowSyms(symvar(coef_Jacob4_qt_syms));\ncoef_Jacob_qt_syms = [\n coef_Jacob1_qt_syms;\n coef_Jacob2_qt_syms;\n coef_Jacob3_qt_syms;\n coef_Jacob4_qt_syms;\n ];\nJacob_ = coef_Jacob_qt_syms * mon_Jacob1_qt.';\n \neqs = expand(eval([Jacob_; Jacob(8)]));\n\neqs_ = eqs;\neqs_(1 : 4) = eval(subs(eqs_(1 : 4), q0^2, (1 - q3 * q3 - q1 * q1 - q2 * q2)));\neqs_(1 : 4) = eval(subs(eqs_(1 : 4), q0^3, q0 * (1 - q3 * q3 - q1 * q1 - q2 * q2)));\n\nf0 = eqs(1);\nf1 = eqs(2);\nf2 = eqs(3);\nf3 = eqs(4);\n[coef_f0_q, mon_f0_q] = coeffs(f0, q);\n[coef_f1_q, mon_f1_q] = coeffs(f1, q);\n[coef_f2_q, mon_f2_q] = coeffs(f2, q);\n[coef_f3_q, mon_f3_q] = coeffs(f3, q);\ncoef_f0_q_sym = sym('coef_f0_q_sym', [1, 24]);\ncoef_f1_q_sym = sym('coef_f1_q_sym', [1, 24]);\ncoef_f2_q_sym = sym('coef_f2_q_sym', [1, 24]);\ncoef_f3_q_sym = sym('coef_f3_q_sym', [1, 24]);\nshowSyms(symvar(coef_f0_q_sym));\nshowSyms(symvar(coef_f1_q_sym));\nshowSyms(symvar(coef_f2_q_sym));\nshowSyms(symvar(coef_f3_q_sym));\nf0 = coef_f0_q_sym * mon_f0_q.';\nf1 = coef_f1_q_sym * mon_f1_q.';\nf2 = coef_f2_q_sym * mon_f2_q.';\nf3 = coef_f3_q_sym * mon_f3_q.';\ncoef_f_q_sym = [\n coef_f0_q;\n coef_f1_q;\n coef_f2_q;\n coef_f3_q;\n ];\ngenerateFuncFile(coef_f_q_sym, fullfile('func_files', 'coef_f_q_sym_pnp_func_new.m'), {pinvG, coefs_tq, coef_Jacob_qt_syms});\n\neq = expand([\n f0 * q1 - f1 * q0;\n f0 * q2 - f2 * q0;\n f0 * q3 - f3 * q0;\n q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3 - 1;\n ]);\ngenerateFuncFile(eq, fullfile('func_files', 'eq_pnp_func_new.m'), {coef_f0_q_sym, coef_f1_q_sym, coef_f2_q_sym, coef_f3_q_sym, q});\n\n\neq_ = eq;\n[coefeq1, moneq1] = coeffs(eq_(1), q); \n[coefeq2, moneq2] = coeffs(eq_(2), q); \n[coefeq3, moneq3] = coeffs(eq_(3), q); \n\nv1 = moneq1.';\ngenerateFuncFile(v1, fullfile('func_files', 'v1_func_pnp_new.m'), {q});\nv2 = moneq2.';\ngenerateFuncFile(v2, fullfile('func_files', 'v2_func_pnp_new.m'), {q});\nv3 = moneq3.';\ngenerateFuncFile(v3, fullfile('func_files', 'v3_func_pnp_new.m'), {q});\n\nD = [\n coefeq1;\n coefeq2;\n coefeq3;\n ];\ngenerateFuncFile(D, fullfile('func_files', 'D_func_pnp_new.m'), {coef_f0_q_sym, coef_f1_q_sym, coef_f2_q_sym, coef_f3_q_sym});\n\nHH = jacobian(eq, q);\ngenerateFuncFile(HH, fullfile('func_files', 'Jacob_pnp_func_new.m'), {coef_f0_q_sym, coef_f1_q_sym, coef_f2_q_sym, coef_f3_q_sym, q});\ngradient = expand(HH.' * eq);\n\n[coef1, mon1] = coeffs(eqs_(1), x);\n[coef2, mon2] = coeffs(eqs_(2), x);\n[coef3, mon3] = coeffs(eqs_(3), x);\n[coef4, mon4] = coeffs(eqs_(4), x);\n\nQ_sym = [\n coef1(7), coef1(14), coef1(18), coef1(20);\n coef2(7), coef2(14), coef2(18), coef2(20);\n coef3(7), coef3(14), coef3(18), coef3(20);\n coef4(7), coef4(14), coef4(18), coef4(20);\n ];\ngenerateFuncFile(Q_sym, fullfile('func_files', 'Q_pnp_func_new.m'), {pinvG, coefs_tq, coef_Jacob_qt_syms});\n\nres = expand(eqs_(1 : 4) - Q_sym * q);\nH = jacobian(res, q);\nh1 = H(:, 1);\nh2 = H(:, 2);\nh3 = H(:, 3);\nh4 = H(:, 4);\nP1 = jacobian(h1, q);\nP2 = jacobian(h2, q);\nP3 = jacobian(h3, q);\nP4 = jacobian(h4, q);\n\nfor i = 1 : 4\n for j = 1 : 4\n str = sprintf('W%d%d = [jacobian(P%d(1, :), q%d).''; jacobian(P%d(2, :), q%d).''; jacobian(P%d(3, :), q%d).''; jacobian(P%d(4, :), q%d).''];', ...\n i, j, i, j - 1, i, j - 1, i, j - 1, i, j - 1);\n eval(str);\n end\nend\n\n\nW1 = [W11, W12, W13, W14];\nW2 = [W21, W22, W23, W24];\nW3 = [W31, W32, W33, W34];\nW4 = [W41, W42, W43, W44];\nv = kron(q, q);\nu = kron(v, q);\nW = - [W1, W2, W3, W4] / 6;\ngenerateFuncFile(W, fullfile('func_files', 'W_pnp_func_new.m'), {pinvG, coefs_tq, coef_Jacob_qt_syms});\n\n\n\n\n\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/syms_pnp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.7073221268324634}} {"text": "%DEMO_REGRESSION1 Regression problem demonstration for 2-input \n% function with Gaussian process\n%\n% Description\n% The regression problem consist of a data with two input\n% variables and one output variable with Gaussian noise. The\n% model constructed is following:\n%\n% The observations y are assumed to satisfy\n%\n% y = f + e, where e ~ N(0, s^2)\n%\n% where f is an underlying function, which we are interested in. \n% We place a zero mean Gaussian process prior for f, which\n% implies that at the observed input locations latent values\n% have prior\n%\n% f ~ N(0, K),\n%\n% where K is the covariance matrix, whose elements are given as\n% K_ij = k(x_i, x_j | th). The function k(x_i, x_j | th) is\n% covariance function and th its parameters.\n%\n% Since both likelihood and prior are Gaussian, we obtain a\n% Gaussian marginal likelihood\n%\n% p(y|th) = N(0, K + I*s^2).\n% \n% By placing a prior for parameters, p(th), we can find\n% the maximum a posterior (MAP) estimate for them by maximizing\n%\n% argmax log p(y|th) + log p(th).\n% th\n% \n% An approximation for the posterior of the parameters, can be\n% found using Markov chain Monte Carlo (MCMC) methods. We can\n% integrate over the parameters also with other integration\n% approximations such as grid integration.\n%\n% After finding MAP estimate or posterior samples of\n% parameters, we can use them to make predictions for f_new:\n%\n% p(f_new | y, th) = N(m, S),\n%\n% m = K_nt*(K + I*s^2)^(-1)*y\n% S = K_new - K_nt*(K + I*s^2)^(-1)*K_tn\n% \n% where K_new is the covariance matrix of new f, and K_nt between\n% new f and training f.\n%\n% For more detailed discussion of Gaussian process regression see,\n% for example, Rasmussen and Williams (2006) or Vanhatalo and\n% Vehtari (2008)\n%\n% The demo is organised in three parts:\n% 1) data analysis with MAP estimate for the parameters\n% 2) data analysis with grid integration over the parameters\n% 3) data analysis with MCMC integration over the parameters\n%\n% See also DEMO_*\n%\n% References:\n% Rasmussen, C. E. and Williams, C. K. I. (2006). Gaussian\n% Processes for Machine Learning. The MIT Press.\n%\n% Vanhatalo, J. and Vehtari, A. (2008). Modelling local and global\n% phenomena with sparse Gaussian processes. Proceedings of the 24th\n% Conference on Uncertainty in Artificial Intelligence,\n\n% Copyright (c) 2008-2010 Jarno Vanhatalo\n% Copyright (c) 2010 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% PART 1 data analysis with full GP model\n%========================================================\ndisp('GP 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\n% Now 'x' consist of the inputs and 'y' of the output. \n% 'n' and 'nin' are the number of data points and the \n% dimensionality of 'x' (the number of inputs).\n\n% ---------------------------\n% --- Construct the model ---\n% \n% First create structures for Gaussian likelihood and squared\n% exponential covariance function with ARD\nlik = lik_gaussian('sigma2', 0.2^2);\ngpcf = gpcf_sexp('lengthScale', [1.1 1.2], 'magnSigma2', 0.2^2)\n\n% Set some priors\npn = prior_logunif();\nlik = lik_gaussian(lik,'sigma2_prior', pn);\npl = prior_unif();\npm = prior_sqrtunif();\ngpcf = gpcf_sexp(gpcf, 'lengthScale_prior', pl, 'magnSigma2_prior', pm);\n\n% Following lines do the same since the default type is FULL\n%gp = gp_set('type','FULL','lik',lik,'cf',gpcf);\ngp = gp_set('lik', lik, 'cf', gpcf);\n\n% Demostrate how to evaluate covariance matrices. \n% K contains the covariance matrix without noise variance \n% at the diagonal (the prior covariance)\n% C contains the covariance matrix with noise variance at \n% the diagonal (the posterior covariance)\nexample_x = [-1 -1 ; 0 0 ; 1 1];\n[K, C] = gp_trcov(gp, example_x)\n\n% What has happend this far is the following\n% - we created structures 'gpcf' and 'lik', which describe \n% the properties of the covariance function and Gaussian likelihood (see\n% gpcf_sexp and lik_gaussian for more details)\n% - we created structures that describe the prior of the length-scale \n% and magnitude of the squared exponential covariance function and\n% the prior of the noise variance. These structures were set into\n% 'gpcf' and 'lik' (see prior_* for more details)\n% - we created a GP structure 'gp', which has among others 'gpcf' \n% and 'lik' structures. (see gp_set for more details)\n\n% -----------------------------\n% --- Conduct the inference ---\n%\n% We will make the inference first by finding a maximum a posterior\n% estimate for the parameters via gradient based optimization. \n% After this we will use grid integration and Markov chain Monte\n% Carlo sampling to integrate over the parameters.\n \n\n% --- MAP estimate ---\ndisp(' MAP estimate for the parameters')\n% Set the options for the optimization\nopt=optimset('TolFun',1e-3,'TolX',1e-3);\n% Optimize with the scaled conjugate gradient method\ngp=gp_optim(gp,x,y,'opt',opt);\n\n% get optimized parameter values for display\n[w,s]=gp_pak(gp);\n% display exp(w) and labels\ndisp(s), disp(exp(w))\n\n% For last, make predictions of the underlying function on a dense\n% grid and plot it. Below Eft_map is the predictive mean and\n% Varf_map the predictive variance.\n[xt1,xt2]=meshgrid(-1.8:0.1:1.8,-1.8:0.1:1.8);\nxt=[xt1(:) xt2(:)];\n[Eft_map, Varft_map] = gp_pred(gp, x, y, xt);\n\n% Plot the prediction and data\nfigure(1)\nclf\nmesh(xt1, xt2, reshape(Eft_map,37,37));\nhold on\nplot3(x(:,1), x(:,2), y, '*')\naxis on;\ntitle('The predicted underlying function and the data points (MAP solution)');\n\n% --- Grid integration ---\ndisp(' Grid integration over the parameters')\n% Perform the grid integration and make predictions\n% We can also get predictions for marginals of f, which are not\n% Gaussian due to integration over the hyperparameters\n[gp_array, P_TH, th, Eft_ia, Varft_ia, fx_ia, x_ia] = ...\n gp_ia(gp, x, y, xt, 'int_method', 'grid');\n\n% Plot the predictions for two input locations\nfigure(2)\nclf\nsubplot(2,1,1)\nplot(x_ia(100,:), fx_ia(100,:))\ntitle('p(f|D) at input location (-1.6, 0.7)');\nsubplot(2,1,2)\nplot(x_ia(400,:), fx_ia(400,:))\ntitle('p(f|D) at input location (-0.8, 1.1)');\n\n% --- MCMC ---\ndisp(' MCMC integration over the parameters')\n[gp_rec,g,opt] = gp_mc(gp, x, y, 'nsamples', 220,'display',20);\n\n% After sampling we delete the burn-in and thin the sample chain\ngp_rec = thin(gp_rec, 21, 2);\n\n% Make the predictions\n[Eft_mc, Varft_mc] = gp_pred(gp_rec, x, y, xt);\n\nfigure(1)\nclf\nsubplot(1,2,1)\nmesh(xt1, xt2, reshape(Eft_map,37,37));\nhold on\nplot3(x(:,1), x(:,2), y, '*')\naxis on;\ntitle(['The predicted underlying function ';\n 'and the data points (MAP solution)']);\nsubplot(1,2,2)\nmesh(xt1, xt2, reshape(Eft_mc,37,37));\nhold on\nplot3(x(:,1), x(:,2), y, '*')\naxis on;\ntitle(['The predicted underlying function ';\n 'and the data points (MCMC solution)']);\nset(gcf,'pos',[93 511 1098 420])\n\n% We can compare the posterior samples of the parameters to the MAP\n% estimate that we got from optimization\nfigure(3)\nclf\nsubplot(1,2,1)\nplot(gp_rec.cf{1}.lengthScale)\ntitle('The sample chain of length-scales')\nsubplot(1,2,2)\nplot(gp_rec.cf{1}.magnSigma2)\ntitle('The sample chain of magnitude')\nset(gcf,'pos',[93 511 1098 420])\n\nfigure(4)\nclf\nsubplot(1,4,1)\nhist(gp_rec.cf{1}.lengthScale(:,1))\nhold on\nplot(gp.cf{1}.lengthScale(1), 0, 'rx', 'MarkerSize', 11, 'LineWidth', 2)\ntitle('Length-scale 1')\nsubplot(1,4,2)\nhist(gp_rec.cf{1}.lengthScale(:,2))\nhold on\nplot(gp.cf{1}.lengthScale(2), 0, 'rx', 'MarkerSize', 11, 'LineWidth', 2)\ntitle('Length-scale 2')\nsubplot(1,4,3)\nhist(gp_rec.cf{1}.magnSigma2)\nhold on\nplot(gp.cf{1}.magnSigma2, 0, 'rx', 'MarkerSize', 11, 'LineWidth', 2)\ntitle('magnitude')\nsubplot(1,4,4)\nhist(gp_rec.lik.sigma2)\nhold on\nplot(gp.lik.sigma2, 0, 'rx', 'MarkerSize', 11, 'LineWidth', 2)\ntitle('Noise variance')\nlegend('MCMC samples', 'MAP estimate')\nset(gcf,'pos',[93 511 1098 420])\n\n\n% Sample from two posterior marginals and plot them alongside \n% with the MAP and grid integration results\n% gpmc_preds returns the predictive mean of the latent function\n% with every sampled parameter value.\n[Eft_mcs, Varft_mcs] = gpmc_preds(gp_rec, x, y, xt);\nsf = normrnd(Eft_mcs(100,:), sqrt(Varft_mcs(100,:)));\nsf2 = normrnd(Eft_mcs(400,:), sqrt(Varft_mcs(400,:)));\n\nfigure(2)\nsubplot(1,2,1)\n[N,X] = hist(sf);\nhist(sf)\nhold on\nplot(x_ia(100,:), max(N)/max(fx_ia(100,:))*fx_ia(100,:), 'k')\nff = norm_pdf(x_ia(100,:)', Eft_map(100), sqrt(Varft_map(100)));\nplot(x_ia(100,:), max(N)/max(ff)*ff, 'r', 'lineWidth', 2)\nset(gca, 'Ytick', [])\ntitle('p(f|D) at input location (-1.6, 0.7)');\nxlim([0 1])\n\nsubplot(1,2,2)\n[N,X] = hist(sf2);\nhist(sf2)\nhold on\nplot(x_ia(400,:), max(N)/max(fx_ia(400,:))*fx_ia(400,:), 'k')\nff = norm_pdf(x_ia(400,:)', Eft_map(400), sqrt(Varft_map(400)));\nplot(x_ia(400,:), max(N)/max(ff)*ff, 'r', 'lineWidth', 2)\nset(gca, 'Ytick', [])\ntitle('p(f|D) at input location (-0.8, 1.1)');\nxlim([-1.2 -0.6])\n\ndisp('Done')\n\n\n% ========================\n% Print figures for manual\n% ========================\n% $$$ sf = normrnd(Eft_mc(100,:), sqrt(Varft_mc(100,:)));\n% $$$ sf2 = normrnd(Eft_mc(400,:), sqrt(Varft_mc(400,:)));\n% $$$ \n% $$$ figure\n% $$$ subplot(1,2,1)\n% $$$ [N,X] = hist(sf);\n% $$$ hist(sf)\n% $$$ h = findobj(gca,'Type','patch');\n% $$$ set(h,'FaceColor','w','EdgeColor','k')\n% $$$ hold on\n% $$$ plot(x_ia(100,:), max(N)/max(fx_ia(100,:))*fx_ia(100,:), 'k')\n% $$$ ff = norm_pdf(x_ia(100,:)', Eft_map(100), sqrt(Varft_map(100)));\n% $$$ plot(x_ia(100,:), max(N)/max(ff)*ff, 'k', 'lineWidth', 2)\n% $$$ set(gca, 'Ytick', [])\n% $$$ xlim([0 1])\n% $$$ ylim([0 110])\n% $$$ \n% $$$ subplot(1,2,2)\n% $$$ [N,X] = hist(sf2);\n% $$$ hist(sf2)\n% $$$ h = findobj(gca,'Type','patch');\n% $$$ set(h,'FaceColor','w','EdgeColor','k')\n% $$$ hold on\n% $$$ plot(x_ia(400,:), max(N)/max(fx_ia(400,:))*fx_ia(400,:), 'k')\n% $$$ ff = norm_pdf(x_ia(400,:)', Eft_map(400), sqrt(Varft_map(400)));\n% $$$ plot(x_ia(400,:), max(N)/max(ff)*ff, 'k', 'lineWidth', 2)\n% $$$ set(gca, 'Ytick', [])\n% $$$ xlim([-1.2 -0.5])\n% $$$ \n% $$$ \n% $$$ set(gcf,'units','centimeters');\n% $$$ set(gcf,'pos',[15 14 7 5])\n% $$$ set(gcf,'paperunits',get(gcf,'units'))\n% $$$ set(gcf,'paperpos',get(gcf,'pos'))\n% $$$ print -depsc2 /proj/bayes/jpvanhat/software/doc/GPstuffDoc/pics/demo_regression1_fig3.eps\n% $$$ \n% $$$ \n% $$$ figure(4)\n% $$$ clf, subplot(1,4,1)\n% $$$ hist(gp_rec.cf{1}.lengthScale(:,1))\n% $$$ h = findobj(gca,'Type','patch');\n% $$$ set(h,'FaceColor','w','EdgeColor','k')\n% $$$ hold on\n% $$$ plot(gp.cf{1}.lengthScale(1), 0, 'kx', 'MarkerSize', 11, 'LineWidth', 2)\n% $$$ xlabel('Length-s 1')\n% $$$ xlim([0.3 1.6])\n% $$$ \n% $$$ subplot(1,4,2)\n% $$$ hist(gp_rec.cf{1}.lengthScale(:,2))\n% $$$ h = findobj(gca,'Type','patch');\n% $$$ set(h,'FaceColor','w','EdgeColor','k')\n% $$$ hold on\n% $$$ plot(gp.cf{1}.lengthScale(2), 0, 'kx', 'MarkerSize', 11, 'LineWidth', 2)\n% $$$ xlabel('Length-s 2')\n% $$$ xlim([0.4 1.4])\n% $$$ \n% $$$ subplot(1,4,3)\n% $$$ hist(gp_rec.cf{1}.magnSigma2)\n% $$$ h = findobj(gca,'Type','patch');\n% $$$ set(h,'FaceColor','w','EdgeColor','k')\n% $$$ hold on\n% $$$ plot(gp.cf{1}.magnSigma2, 0, 'kx', 'MarkerSize', 11, 'LineWidth', 2)\n% $$$ xlabel('magnitude')\n% $$$ xlim([0.5 6])\n% $$$ \n% $$$ subplot(1,4,4)\n% $$$ hist(gp_rec.lik.sigma2)\n% $$$ h = findobj(gca,'Type','patch');\n% $$$ set(h,'FaceColor','w','EdgeColor','k')\n% $$$ hold on\n% $$$ plot(gp.lik.sigma2, 0, 'kx', 'MarkerSize', 11, 'LineWidth', 2)\n% $$$ xlabel('Noise variance')\n% $$$ xlim([0.03 0.06])\n% $$$ set(gca, 'Xtick', [0.03 0.06])\n% $$$ \n% $$$ set(gcf,'units','centimeters');\n% $$$ set(gcf,'pos',[15 14 11 5])\n% $$$ set(gcf,'paperunits',get(gcf,'units'))\n% $$$ set(gcf,'paperpos',get(gcf,'pos'))\n% $$$ \n% $$$ print -depsc2 /proj/bayes/jpvanhat/software/doc/GPstuffDoc/pics/demo_regression1_fig2.eps\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/gp/demo_regression1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.7073221249117608}} {"text": "function value = r8poly_value ( n, a, x )\n\n%*****************************************************************************80\n%\n%% R8POLY_VALUE evaluates an R8 polynomial.\n%\n% Discussion:\n%\n% For sanity's sake, the value of N indicates the NUMBER of \n% coefficients, or more precisely, the ORDER of the polynomial,\n% rather than the DEGREE of the polynomial. The two quantities\n% differ by 1, but cause a great deal of confusion.\n%\n% Given N and A, the form of the polynomial is:\n%\n% p(x) = a(1) + a(2) * x + ... + a(n-1) * x^(n-2) + a(n) * x^(n-1)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 April 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of the polynomial.\n%\n% Input, real A(1:N), the coefficients of the polynomial.\n% A(1) is the constant term.\n%\n% Input, real X, the point at which the polynomial is to be evaluated.\n%\n% Output, real VALUE, the value of the polynomial at X.\n%\n value = 0.0;\n for i = n : -1 : 1\n value = value * x + a(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/asa241/r8poly_value.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.787931188173138, "lm_q1q2_score": 0.7073221224407081}} {"text": "% Isoparametric Formulation Implementation\n% clear memory\nclear all\nclose all\nclc\n% E: modulus of elasticity\n% A: area of cross section\n% L: length of bar\nE=2e5; A=12.5e-4; L=1.5;\ns_exact=@(x)1/2*(80000*x)*x/(A);\nhold on;\nezplot(s_exact,[0 1.5])\ntitle('Exact solution v.s. FEM','interpreter','latex');\nxlabel('x','interpreter','latex');\nylabel('Axial stress, Pa','interpreter','latex');\n\nfor i=1:4 %For NEL = 1, 2, 4, 8 \nNNOD=3;\nfprintf( '\\nNumber of elements:%d\\n\\n',2^(i-1) );\n% numberElements: number of elements\nnumberElements=2^(i-1); \n% numberNodes: number of nodes\nnumberNodes=2*numberElements+1;\n% generation of coordinates and connectivities \n \nnodeCoordinates=linspace(0,L,numberNodes); \n%Generate element length vector\nfor i=1:numberElements\n Le(i)=L/numberElements;\n elementNodes(i,:)=[(i-1)*2+1 (i-1)*2+2 (i-1)*2+3];\nend\n% for structure:\n % displacements: displacement vector\n % force : force vector\n % stiffness: stiffness matrix\nforce=zeros(numberNodes,1);\nstiffness=zeros(numberNodes,numberNodes); \n% computation of the system stiffness matrix and force vector\nfor e=1:numberElements; \n % elementDof: element degrees of freedom (Dof)\n elementDof=elementNodes(e,:) ;\n detJacobian=Le(e)/2;\n invJacobian=1/detJacobian;\n ngp = 3;\n [w,xi]=gauss1d(ngp);\n xc=0.5*(nodeCoordinates(elementDof(1))+nodeCoordinates(elementDof(3)));\n for ip=1:ngp;\n [shape,naturalDerivatives]=shapeFunctionL3(xi(ip)); \n B=naturalDerivatives*invJacobian;\n stiffness(elementDof,elementDof)=...\n stiffness(elementDof,elementDof)+ B'*B*w(ip)*detJacobian*E*A;\n force(elementDof)=force(elementDof)+...\n -80000*(xc+detJacobian*xi(ip))*shape'*detJacobian*w(ip);\n end\nend \n \n% boundary conditions and solution\n% prescribed dofs\nprescribedDof=[numberNodes];\n% solution\nGDof=numberNodes;\ndisplacements=solution(GDof,prescribedDof,stiffness,force);\n% output displacements/reactions\noutputDisplacementsReactionsPretty(displacements,stiffness, ...\n numberNodes,prescribedDof,force)\nfprintf('Axial stress\\n')\nfprintf('element\\t\\taxial stress\\n')\n%Stress and strain recovery\nngp = 2;\n\nelementNodeCoor=zeros(numberElements*NNOD,1);\nelementNodeStr=zeros(numberElements*NNOD,1);\nfor e=1:numberElements; \n % elementDof: element degrees of freedom (Dof)\n elementDof=elementNodes(e,:);\n detJacobian=Le(e)/2;\n invJacobian=1/detJacobian;\n xi=[-1 0 1];\n for ip=1:NNOD;\n [shape,naturalDerivatives]=shapeFunctionL3(xi(ip));\n B=naturalDerivatives*invJacobian;\n elementNodeCoor(ip+(e-1)*NNOD,1)=nodeCoordinates(elementDof(ip));\n elementNodeStr(ip+(e-1)*NNOD,1)=E*B*displacements(elementDof,1);\n fprintf('%2.0f\\t%2.0fth node\\t%10.4e\\n', e, ip,elementNodeStr(ip+(e-1)*NNOD,1))\n end\nend \n\n\n%post process\nswitch numberElements\n case 1\n str='rs--';\n case 2\n str='gs--';\n case 4\n str='ks--';\n case 8\n str='ms--';\nend\nswitch numberElements\n case 1\n strg='r*';\n case 2\n strg='g*';\n case 4\n strg='k*';\n case 8\n strg='m*';\nend\nplot(elementNodeCoor,elementNodeStr,str)\nhold on;\n%plot(elementIpCoor,elementAxiStr,strg)\nend\nlegend('Exact solution','NEL=1','NEL=2','NEL=4','NEL=8');\ntitle('Stress','interpreter','latex','FontSize',18);\nxlabel('$\\it{x}$','interpreter','latex','FontSize',14);\nylabel({'Stress, $\\it{\\sigma}$'},'interpreter','latex','FontSize',14);\nbox on;", "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/FEM/BarSimple_solution/Prob_3/Prob_3_stress.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7073190390585661}} {"text": "function b = r83_vxm ( n, a, x )\n\n%*****************************************************************************80\n%\n%% R83_VXM multiplies a vector by an R83 matrix.\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% 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% 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, real A(3,N), the R83 matrix.\n%\n% Input, real X(N), the vector to be multiplied by A'.\n%\n% Output, real B(N), the product A' * x.\n%\n b(1:n) = a(2,1:n) .* x(1:n);\n b(1:n-1) = b(1:n-1) + a(3,1:n-1) .* x(2:n);\n b(2:n) = b(2:n) + a(1,2:n) .* x(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/linplus/r83_vxm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7073006383463988}} {"text": "function ydot = lorenzeq(t,y)\n%LORENZEQ Equation of the Lorenz chaotic attractor.\n% ydot = lorenzeq(t,y).\n% The differential equation is written in almost linear form.\n\nSIGMA = 10.;\nRHO = 28.;\nBETA = 8./3.;\n\n\nA = [ -BETA 0 y(2)\n 0 -SIGMA SIGMA\n -y(2) RHO -1 ];\n\nydot = A*y;\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/24320-algorithmic-trading-with-matlab-2009-update/lorenzeq.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7072788973783577}} {"text": "function [Series, Sigmas] = garchsim(parameters, model, distr, p, q, H, y, NumSamples, NumPaths)\n%{\n-----------------------------------------------------------------------\n PURPOSE: \n Simulation of GARCH models\n-----------------------------------------------------------------------\n USAGE:\n [Series, Sigmas] = garchsim(parameters, model, distr, p, q, H, NumSamples, NumPaths)\n \n INPUTS:\n parameters: a vector of parameters (i.e. constant, ARCH, GARCH, Gamma, Delta, DoF)\n model: 'GARCH', 'GJR', 'EGARCH', 'NARCH', 'NGARCH, 'AGARCH', 'APGARCH',\n 'NAGARCH'\n distr: 'GAUSSIAN', 'T', 'GED', 'CAUCHY', 'HANSEN' and 'GC' \n p: positive scalar integer representing the order of ARCH\n q: positive scalar integer representing the order of GARCH\n H: a vector of time series of positive pre-sample \n conditional standard deviations.\n y: a vector of factors for the volatility process, must be positive!\n NumSamples: The number of samples. If is left empty 100 samples will be generated.\n NumPaths: The number of paths. If it is left empty 1 path will be estimated.\n\n\n OUTPUTS:\n Series: (NumSamples x NumPaths) simulated series with GARCH variances\n Sigmas: (NumSamples x NumbPaths) vector of conditional standard deviations.\n \n-----------------------------------------------------------------------\n Author:\n Alexandros Gabrielsen, a.gabrielsen@city.ac.uk\n Date: 08/2011\n-----------------------------------------------------------------------\n%}\n\nif nargin == 0 \n error('Parameters, GARCH Model, Distribution, ARCH, GARCH, Sigmas, Number of Samples, Number of Paths') \nend\n\nif nargin < 8 | isempty(NumPaths)\n NumPaths=1;\nend\n\n% Verifying that the vector of parameters is a column vector\n[r,c]=size(parameters);\nif r 0. D is the first\n% difference matrix. Uses hot-restarts from each value of lambda to speed\n% up convergence for subsequent values: best use of this feature is made by\n% ensuring that the chosen lambda values are close to each other.\n%\n% Usage:\n% [x, E, s] = tvdip(y, lambda, display, stoptol, maxiter)\n%\n% Input arguments:\n% - y Original signal to denoise, size N x 1.\n% - lambda A vector of positive regularization parameters, size L x 1.\n% TVD will be applied to each value in the vector.\n% - display (Optional) Set to 0 to turn off progress display, 1 to turn\n% on. If not specifed, defaults to progress display on.\n% - stoptol (Optional) Precision as determined by duality gap tolerance,\n% if not specified, defaults to 1e-3.\n% - maxiter (Optional) Maximum interior-point iterations, if not\n% specified defaults to 60.\n%\n% Output arguments:\n% - x Denoised output signal for each value of lambda, size N x L.\n% - E Objective functional at minimum for each lambda, size L x 1.\n% - s Optimization result, 1 = solved, 0 = maximum iterations\n% exceeded before reaching duality gap tolerance, size L x 1.\n% - lambdamax Maximum value of lambda for the given y. If\n% lambda >= lambdamax, the output is the trivial constant\n% solution x = mean(y).\n%\n% (c) Max Little, 2010. Based around code originally written by \n% S.J. Kim, K. Koh, S. Boyd and D. Gorinevsky. If you use this code for\n% your research, please cite:\n% M.A. Little, Nick S. Jones (2010)\n% \"Sparse Bayesian Step-Filtering for High-Throughput Analysis of Molecular\n% Machine Dynamics\", in 2010 IEEE International Conference on Acoustics,\n% Speech and Signal Processing, 2010, ICASSP 2010 Proceedings.\n%\n% This code is released under the terms of GNU General Public License as\n% published by the Free Software Foundation; version 2 or later.\n\nerror(nargchk(2,5,nargin));\nif (nargin < 3)\n display = 1;\nend\nif (nargin < 4)\n stoptol = 1e-3;\nend\nif (nargin < 5)\n maxiter = 60;\nend\n\ny = y(:);\n\n% Search tuning parameters\nALPHA = 0.01; % Backtracking linesearch parameter (0,0.5]\nBETA = 0.5; % Backtracking linesearch parameter (0,1)\nMAXLSITER = 20; % Max iterations of backtracking linesearch\nMU = 2; % t update\n\nN = length(y); % Length of input signal y\nM = N-1; % Size of Dx\n\n% Construct sparse operator matrices\nI1 = speye(M,M);\nO1 = spalloc(M,1,M);\nD = [I1 O1]-[O1 I1];\n\nDDT = D*D';\nDy = D*y;\n\n% Find max value of lambda\nlambdamax = max(abs(DDT\\Dy));\n\nif (display)\n fprintf('lambda_max=%5.2e\\n', lambdamax);\nend\n\nL = length(lambda);\nx = zeros(N, L);\ns = zeros(L, 1);\nE = zeros(L, 1);\n\n% Optimization variables set up once at the start\nz = zeros(M,1); % Dual variable\nmu1 = ones(M,1); % Dual of dual variable\nmu2 = ones(M,1); % Dual of dual variable\n\n% Work through each value of lambda, with hot-restart on optimization\n% variables\nfor l = 1:L\n \n t = 1e-10; \n step = Inf;\n f1 = z-lambda(l);\n f2 = -z-lambda(l);\n\n % Main optimization loop\n s(l) = 1;\n\n if (display)\n fprintf('Solving for lambda=%5.2e, lambda/lambda_max=%5.2e\\nIter# Primal Dual Gap\\n', ...\n lambda(l), lambda(l)/lambdamax);\n end\n for iters = 0:maxiter\n\n DTz = (z'*D)';\n DDTz = D*DTz;\n w = Dy-(mu1-mu2);\n\n % Calculate objectives and primal-dual gap\n pobj1 = 0.5*w'*(DDT\\w)+lambda(l)*sum(mu1+mu2);\n pobj2 = 0.5*DTz'*DTz+lambda(l)*sum(abs(Dy-DDTz));\n pobj = min(pobj1,pobj2);\n dobj = -0.5*DTz'*DTz+Dy'*z;\n gap = pobj - dobj;\n\n if (display)\n fprintf('%5d %7.2e %7.2e %7.2e\\n', iters, pobj, dobj, gap);\n end\n\n % Test duality gap stopping criterion\n if (gap <= stoptol)\n s(l) = 1;\n break;\n end\n\n if (step >= 0.2)\n t = max(2*M*MU/gap, 1.2*t);\n end\n\n % Do Newton step\n rz = DDTz - w;\n S = DDT-sparse(1:M,1:M,mu1./f1+mu2./f2);\n r = -DDTz + Dy + (1/t)./f1 - (1/t)./f2;\n dz = S\\r;\n dmu1 = -(mu1+((1/t)+dz.*mu1)./f1);\n dmu2 = -(mu2+((1/t)-dz.*mu2)./f2);\n\n resDual = rz;\n resCent = [-mu1.*f1-1/t; -mu2.*f2-1/t];\n residual= [resDual; resCent];\n\n % Perform backtracking linesearch\n negIdx1 = (dmu1 < 0); \n negIdx2 = (dmu2 < 0);\n step = 1;\n if (any(negIdx1))\n step = min( step, 0.99*min(-mu1(negIdx1)./dmu1(negIdx1)) );\n end\n if (any(negIdx2))\n step = min( step, 0.99*min(-mu2(negIdx2)./dmu2(negIdx2)) );\n end\n\n for liter = 1:MAXLSITER\n newz = z + step*dz;\n newmu1 = mu1 + step*dmu1;\n newmu2 = mu2 + step*dmu2;\n newf1 = newz - lambda(l);\n newf2 = -newz - lambda(l);\n\n % Update residuals\n newResDual = DDT*newz - Dy + newmu1 - newmu2;\n newResCent = [-newmu1.*newf1-1/t; -newmu2.*newf2-1/t];\n newResidual = [newResDual; newResCent];\n\n if ((max(max(newf1),max(newf2)) < 0) && ...\n (norm(newResidual) <= (1-ALPHA*step)*norm(residual)))\n break;\n end\n step = BETA*step;\n end\n\n % Update primal and dual optimization parameters\n z = newz;\n mu1 = newmu1;\n mu2 = newmu2;\n f1 = newf1;\n f2 = newf2;\n end\n\n x(:,l) = y-D'*z;\n E(l) = 0.5*sum((y-x(:,l)).^2)+lambda(l)*sum(abs(D*x(:,l)));\n\n % We may have a close solution that does not satisfy the duality gap\n if (iters >= maxiter)\n s(l) = 0;\n end\n \n if (display)\n if (s(l))\n fprintf('Solved to precision of duality gap %5.2e\\n', gap);\n else\n fprintf('Max iterations exceeded - solution may be inaccurate\\n');\n end\n end\n\nend\n", "meta": {"author": "beckel", "repo": "nilm-eval", "sha": "83a2cd5fb911299cc267bd9998636934af781915", "save_path": "github-repos/MATLAB/beckel-nilm-eval", "path": "github-repos/MATLAB/beckel-nilm-eval/nilm-eval-83a2cd5fb911299cc267bd9998636934af781915/Matlab/lib/TVDIP/tvdip.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7071937638585589}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n\n% Inverse DFT of X(k)=[6, -1-j,0,-1+j], k=0,1,2,3\n\n\nclear; \nXk=[6, -1-j,0,-1+j];\nN=length(Xk);\nfor n=0:N-1\nfor k=0:N-1\nxn(k+1)=Xk(k+1)*exp(j*2*pi*n*k/N);\nend\nx(n+1)=sum(xn);\nend\nx=(1/N)*x\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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/7/c76.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.7071481334269345}} {"text": "\nclassdef Quad < handle\n %QUAD Summary of this class goes here\n % Detailed explanation goes here\n \n properties\n V00,V01,V10,V11;\n end\n \n methods\n function obj =Quad(V00,V01,V10,V11)\n obj.V00 = V00;\n obj.V01 = V01;\n obj.V10 = V10;\n obj.V11 = V11;\n end\n function a = isPointIn(obj,pt)\n in1 = isPointInTriangular(pt,obj.V00,obj.V01,obj.V11);\n in2 = isPointInTriangular(pt,obj.V00,obj.V10,obj.V11);\n if in1==1 || in2==1\n a = 1;\n else\n a = 0; \n end\n end\n \n function a = isPointsIn(obj,pts)\n in1 = isPointsInTriangular(pts(:,1),pts(:,2),obj.V00,obj.V01,obj.V11);\n in2 = isPointsInTriangular(pts(:,1),pts(:,2),obj.V00,obj.V10,obj.V11);\n \n a = double(in1|in2);\n \n end\n \n function [coefficients,bool] = getBilinearCoordinates(obj,pt)\n \t\n\n a_x = obj.V00.x - obj.V01.x - obj.V10.x + obj.V11.x;\n b_x = -obj.V00.x + obj.V01.x;\n c_x = -obj.V00.x + obj.V10.x;\n d_x = obj.V00.x - pt.x;\n \n a_y = obj.V00.y - obj.V01.y - obj.V10.y + obj.V11.y;\n b_y = -obj.V00.y + obj.V01.y;\n c_y = -obj.V00.y + obj.V10.y;\n d_y = obj.V00.y - pt.y;\n \n bigA = -a_y*b_x + b_y*a_x;\n bigB = -a_y*d_x - c_y*b_x + d_y*a_x +b_y*c_x;\n bigC = -c_y*d_x + d_y*c_x;\n \n tmp1 = -1;\n tmp2 = -1;\n tmp3 = -1;\n tmp4 = -1;\n\n if bigB*bigB - 4*bigA*bigC >= 0.0\n if abs(bigA) >= 0.000001\n tmp1 = ( -bigB + sqrt(bigB*bigB - 4*bigA*bigC) ) / ( 2*bigA );\n tmp2 = ( -bigB - sqrt(bigB*bigB - 4*bigA*bigC) ) / ( 2*bigA );\n else\n tmp1 = -bigC/bigB;\n end\n \n if ( tmp1 >= -0.999999 && tmp1 <= 1.000001)\n \n tmp3 = -(b_y*tmp1 + d_y) / (a_y*tmp1 + c_y);\n tmp4 = -(b_x*tmp1 + d_x) / (a_x*tmp1 + c_x);\n if tmp3 >= -0.999999 && tmp3 <= 1.000001\n k1 = tmp1;\n k2 = tmp3;\n else if tmp4 >= -0.999999 && tmp4 <= 1.000001\n k1 = tmp1;\n k2 = tmp4;\n end\n end\n end\n if ( tmp2 >= -0.999999 && tmp2 <= 1.000001)\n \n if tmp3 >= -0.999999 && tmp3 <= 1.000001\n k1 = tmp2;\n k2 = tmp3;\n else if tmp4 >= -0.999999 && tmp4 <= 1.000001\n k1 = tmp2;\n k2 = tmp4;\n end\n end\n end\n end\n\t\n if k1>=-0.999999 && k1<=1.000001 && k2>=-0.999999 && k2<=1.000001\n \n coe1 = (1.0-k1)*(1.0-k2);\n coe2 = k1*(1.0-k2);\n coe3 = (1.0-k1)*k2;\n coe4 = k1*k2;\n \n coefficients(1) = coe1;\n coefficients(2) = coe2;\n coefficients(3) = coe3;\n coefficients(4) = coe4;\n \n bool = 1;\n else\n bool = 0;\n end\n \n end\n \n function minx = getMinX(obj)\n minx = min(obj.V00.x,obj.V01.x);\n minx = min(minx, obj.V10.x);\n minx = min(minx,obj.V11.x);\n end\n function maxx = getMaxX(obj)\n maxx = max(obj.V00.x,obj.V01.x);\n maxx = max(maxx,obj.V10.x);\n maxx = max(maxx,obj.V11.x);\n end\n function miny = getMinY(obj)\n miny = min(obj.V00.y,obj.V01.y);\n miny = min(miny,obj.V10.y);\n miny = min(miny,obj.V11.y);\n end\n function maxy = getMaxY(obj)\n maxy = max(obj.V00.y,obj.V01.y);\n maxy = max(maxy,obj.V10.y);\n maxy = max(maxy,obj.V11.y);\n end\n \n \n end\nend\n\n\nfunction a = isPointInTriangular(pt,V0,V1,V2)\n lambda1 = ((V1.y-V2.y)*(pt.x-V2.x) + (V2.x-V1.x)*(pt.y-V2.y)) / ((V1.y-V2.y)*(V0.x-V2.x) + (V2.x-V1.x)*(V0.y-V2.y));\n\tlambda2 = ((V2.y-V0.y)*(pt.x-V2.x) + (V0.x-V2.x)*(pt.y-V2.y)) / ((V2.y-V0.y)*(V1.x-V2.x) + (V0.x-V2.x)*(V1.y-V2.y));\n lambda3 = 1-lambda1-lambda2;\n if lambda1 >= 0.0 && lambda1 <= 1.0 && lambda2 >= 0.0 && lambda2 <= 1.0 && lambda3 >= 0.0 && lambda3 <= 1.0\n a = 1; %true\n else\n a = 0; %false\n end\nend\n\nfunction a = isPointsInTriangular(ptx,pty,V0,V1,V2)\n y12 = V1.y - V2.y;\n x21 = V2.x - V1.x;\n x02 = V0.x - V2.x;\n x21 = V2.x - V1.x;\n y02 = V0.y - V2.y;\n y20 = V2.y - V0.y;\n x12 = V1.x - V2.x;\n s1 = y12*x02 + x21*y02;\n s2 = y20*x12 + x02*y12;\n \n lambda1 = (y12.*(ptx-V2.x) + x21.*(pty-V2.y)) ./ s1;\n lambda2 = (y20.*(ptx-V2.x) + x02.*(pty-V2.y)) ./ s2;\n lambda3 = 1-lambda1-lambda2;\n \n condition1 = lambda1>=0.0;\n condition2 = lambda1<=1.0;\n condition3 = lambda2>=0.0;\n condition4 = lambda2<=1.0;\n condition5 = lambda3>=0.0;\n condition6 = lambda3<=1.0;\n \n a = condition1 & condition2 & condition3 & condition4 & condition5 & condition6;\n\nend\n\n\n\n\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/mesh/Quad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7956581000631541, "lm_q1q2_score": 0.7071481330446293}} {"text": "%ROTX Rotation about X axis\n%\n% R = ROTX(THETA) is an SO(3) rotation matrix (3x3) representing a rotation of THETA \n% radians about the x-axis.\n%\n% R = ROTX(THETA, 'deg') as above but THETA is in degrees.\n%\n% See also ROTY, ROTZ, ANGVEC2R, ROT2.\n\n\n\n% Copyright (C) 1993-2015, by Peter I. Corke\n%\n% This file is part of The Robotics Toolbox for MATLAB (RTB).\n% \n% RTB is free software: you can redistribute it and/or modify\n% it under the terms of the GNU Lesser General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% RTB is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU Lesser General Public License for more details.\n% \n% You should have received a copy of the GNU Leser General Public License\n% along with RTB. If not, see .\n%\n% http://www.petercorke.com\n\nfunction R = rotx(t, deg)\n\n if nargin > 1 && strcmp(deg, 'deg')\n t = t *pi/180;\n end\n \n ct = cos(t);\n st = sin(t);\n R = [\n 1 0 0\n 0 ct -st\n 0 st ct\n ];\n", "meta": {"author": "Allopart", "repo": "rbpf-gmapping", "sha": "affe0adc25fa446fc7af4902d699d92864bdba1b", "save_path": "github-repos/MATLAB/Allopart-rbpf-gmapping", "path": "github-repos/MATLAB/Allopart-rbpf-gmapping/rbpf-gmapping-affe0adc25fa446fc7af4902d699d92864bdba1b/rvctools/robot/rotx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.7071481244317586}} {"text": "function I_d = Akashi2016(I)\n%Akashi2016 I_d = Akashi2016(I)\n% The core mechanism is herein implemented fully in accordance with their\n% paper. I have not implemented the repeated score trials. It is pending.\n% This is because this method is somewhat slow.\n%\n% Convergence criterion is based on Yamamoto and Nakazawa (exp(-15)), you\n% can change it:\n% edit Akashi2016.m\n% Search 'eps' and change it.\n%\n% Also, because of random initialization, I believe averaging the\n% estimated diffuse component over many applications of the method will\n% greatly improve the quality.\n%\n% See also SIHR.\n\nassert(isa(I, 'float'), 'SIHR:I:notTypeSingleNorDouble', ...\n 'Input I is not type single nor double.')\nassert(min(I(:)) >= 0 && max(I(:)) <= 1, 'SIHR:I:notWithinRange', ...\n 'Input I is not within [0, 1] range.')\n[n_row, n_col, n_ch] = size(I);\nassert(n_row > 1 && n_col > 1, 'SIHR:I:singletonDimension', ...\n 'Input I has a singleton dimension.')\nassert(n_ch == 3, 'SIHR:I:notRGB', ...\n 'Input I is not a RGB image.')\n\nI = 255 * I;\nM = 3; % = number of color channels\nN = n_row * n_col; % = number of pixels\nR = 7; % = number of color clusters - 1\nI = reshape(I, [N, M])';\ni_s = ones(3, 1, class(I)) / sqrt(3);\nH = 254 * rand(R, N, class(I)) + 1;\nW_d = 254 * rand(3, R-1, class(I)) + 1;\nW_d = my_normc(W_d); % W_d ./ vecnorm(W_d, 2, 1); % normalize(W_d,1,'norm');\nW = [i_s, W_d];\nA = ones(M, class(I));\nlambda = 3;\neps = exp(-15);\nF_t_1 = Inf;\niter = uint16(0);\nmax_iter = uint16(10e3); % change for later convergence (takes way longer)\n% tic\nwhile true\n W_bar = my_normc(W);\n H = H .* ((W_bar') * I) ./ ...\n ((W_bar') * W_bar * H + lambda);\n H_d = H(2:end, :);\n Vl = max(0, I-i_s*H(1, :));\n % W_d = W(:,2:end); % not sure\n W_d_bar = W_bar(:, 2:end);\n W_d = W_d_bar .* (Vl * (H_d') + W_d_bar .* (A * W_d_bar * H_d * (H_d'))) ./ ...\n (W_d_bar * H_d * (H_d') + W_d_bar .* (A * Vl * (H_d')));\n W = [i_s, W_d];\n F_t = 0.5 * norm((I - W * H), 'fro') + lambda * sum(H(:));\n if abs(F_t-F_t_1) < eps * abs(F_t) || iter >= max_iter\n break\n end\n F_t_1 = F_t;\n iter = iter + 1;\nend\n% toc\nW_d = W(:, 2:end);\n% h_s = H(1, :);\nH_d = H(2:end, :);\n% I_s = i_s * h_s;\nI_d = W_d * H_d;\n% I_s = reshape(full(I_s)', [n_row, n_col, n_ch]) / 255;\nI_d = reshape(full(I_d)', [n_row, n_col, n_ch]) / 255;\n\n% figure(1), imshow(I_s)\n% figure(2), imshow(I_d)\n\nend\n", "meta": {"author": "vitorsr", "repo": "SIHR", "sha": "8f0a2d67307298019a45901ac09a9d827fd40efe", "save_path": "github-repos/MATLAB/vitorsr-SIHR", "path": "github-repos/MATLAB/vitorsr-SIHR/SIHR-8f0a2d67307298019a45901ac09a9d827fd40efe/Akashi2016/Akashi2016.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7070932551326317}} {"text": "function [Xi W] = SigmaPoints(xm, P, kappa)\n%\n%\nn = numel(xm);\nXi = zeros(n, 2*n+1); % sigma points = col of Xi\nW = zeros(n, 1);\n\nXi(:, 1) = xm;\nW(1) = kappa / (n + kappa);\n\nU = chol((n+kappa)*P); % U'*U = (n+kappa)*P\n\nfor k=1:n\n Xi(:, k+1) = xm + U(k, :)'; % row of U\n W(k+1) = 1 / (2*(n+kappa));\nend\n\nfor k=1:n\n Xi(:, n+k+1) = xm - U(k, :)';\n W(n+k+1) = 1 / (2*(n+kappa));\nend", "meta": {"author": "philbooks", "repo": "Kalman-Filter-for-Beginners", "sha": "5190a723dcbf96eacda71ed56abddb3a11779a82", "save_path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners", "path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners/Kalman-Filter-for-Beginners-5190a723dcbf96eacda71ed56abddb3a11779a82/15.UKF/RadarUKF/SigmaPoints.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7070932366776185}} {"text": "function res = isCounterClockwise(p1, p2, p3, varargin)\n%ISCOUNTERCLOCKWISE Compute relative orientation of 3 points\n%\n% CCW = isCounterClockwise(P1, P2, P3);\n% Computes the orientation of the 3 points. The returns is:\n% +1 if the path P1->P2->P3 turns Counter-Clockwise (i.e., the point P3\n% is located \"on the left\" of the line P1-P2)\n% -1 if the path turns Clockwise (i.e., the point P3 lies \"on the right\"\n% of the line P1-P2) \n% 0 if the point P3 is located on the line segment [P1 P2].\n%\n% This function can be used in more complicated algorithms: detection of\n% line segment intersections, convex hulls, point in triangle...\n%\n% CCW = isCounterClockwise(P1, P2, P3, EPS);\n% Specifies the threshold used for detecting colinearity of the 3 points.\n% Default value is 1e-12 (absolute).\n%\n% Example\n% isCounterClockwise([0 0], [10 0], [10 10])\n% ans = \n% 1\n% isCounterClockwise([0 0], [0 10], [10 10])\n% ans = \n% -1\n% isCounterClockwise([0 0], [10 0], [5 0])\n% ans = \n% 0\n%\n% See also\n% points2d, isPointOnLine, isPointInTriangle\n%\n% References\n% Algorithm adapated from Sedgewick's book.\n%\n% ------\n% Author: David Legland\n% e-mail: david.legland@grignon.inra.fr\n% Created: 2010-04-09\n% Copyright 2011 INRA - Cepia Software Platform.\n\n\n% HISTORY\n% 2011-05-16 change variable names, add support for point arrays\n\n\n% get threshold value\neps = 1e-12;\nif ~isempty(varargin)\n eps = varargin{1};\nend\n\n% ensure all data have same size\nnp = max([size(p1, 1) size(p2, 1) size(p3,1)]);\nif np > 1\n if size(p1,1) == 1\n p1 = repmat(p1, np, 1);\n end\n if size(p2,1) == 1\n p2 = repmat(p2, np, 1);\n end\n if size(p3,1) == 1\n p3 = repmat(p3, np, 1);\n end \nend\n\n% init with 0\nres = zeros(np, 1);\n\n% extract vector coordinates\nx0 = p1(:, 1);\ny0 = p1(:, 2);\ndx1 = p2(:, 1) - x0;\ndy1 = p2(:, 2) - y0;\ndx2 = p3(:, 1) - x0;\ndy2 = p3(:, 2) - y0;\n\n% check non colinear cases\nres(dx1 .* dy2 > dy1 .* dx2) = 1;\nres(dx1 .* dy2 < dy1 .* dx2) = -1;\n\n% case of colinear points\nind = abs(dx1 .* dy2 - dy1 .* dx2) < eps;\nres(ind( (dx1(ind) .* dx2(ind) < 0) | (dy1(ind) .* dy2(ind) < 0) )) = -1;\nres(ind( hypot(dx1(ind), dy1(ind)) < hypot(dx2(ind), dy2(ind)) )) = 1;\n", "meta": {"author": "rpng", "repo": "lips", "sha": "a97157e586b509c9c2e3e01e64e4347f36d0b63e", "save_path": "github-repos/MATLAB/rpng-lips", "path": "github-repos/MATLAB/rpng-lips/lips-a97157e586b509c9c2e3e01e64e4347f36d0b63e/lips_matlab/matlab/functions/matGeom/geom2d/isCounterClockwise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969193, "lm_q2_score": 0.8104789155369047, "lm_q1q2_score": 0.7070191568904054}} {"text": "% Mathematics Q2410741\n% https://math.stackexchange.com/questions/2410741\n% Matrix differentiation on ∥A−B∘X∥2F+λ∥X∥2F\n% References:\n% 1. aa\n% Remarks:\n% 1. sa\n% TODO:\n% \t1. ds\n% Release Notes\n% - 1.0.000 30/08/2017\n% * First release.\n\n\n%% General Parameters\n\nrun('InitScript.m');\n\nfigureIdx = 0; %=0, parameter\n% opts - Structure value in Matlab. The fields are\n% opts.tol - termination tolerance\n% opts.max_iter - maximum number of iterations\n% opts.mu - stepsize for dual variable updating in ADMM\n% opts.max_mu - maximum stepsize\n% opts.rho - rho>=1, ratio used to increase mu\n% opts.DEBUG - 0 or 1\n%\n% Output:\n% x - n*1 vector\n% obj - objective function value\n% err - residual\n% iter - number of iterations\n%\n% version 1.0 - 20/06/2016\n%\n% Written by Canyi Lu (canyilu@gmail.com)\n% \n\ntol = 1e-8; \nmax_iter = 500;\nrho = 1.1;\nmu = 1e-4;\nmax_mu = 1e10;\nDEBUG = 0;\n\nif ~exist('opts', 'var')\n opts = [];\nend \nif isfield(opts, 'tol'); tol = opts.tol; end\nif isfield(opts, 'max_iter'); max_iter = opts.max_iter; end\nif isfield(opts, 'rho'); rho = opts.rho; end\nif isfield(opts, 'mu'); mu = opts.mu; end\nif isfield(opts, 'max_mu'); max_mu = opts.max_mu; end\nif isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end\n\n\n[d,n] = size(A);\nx = zeros(n,1);\n\nz = x;\nY1 = zeros(d,1);\nY2 = x;\n\nAtb = A'*b;\nI = eye(n);\ninvAtAI = (A'*A+I)\\I;\n\n% parameters for \"flsa\" (from SLEP package)\ntol2 = 1e-10; % the duality gap for termination\nmax_step = 50; % the maximal number of iterations\nx0 = zeros(n-1,1); % the starting point\n\niter = 0;\nfor iter = 1 : max_iter\n xk = x;\n zk = z;\n % update x. \n % flsa solves min_x 1/2||x-v||_2^2+lambda1*||x||_1+lambda2*\\sum_{i=2}^p |x_i-x_{i-1}|\n x = flsa(z-Y2/mu,x0,1/mu,lambda/mu,n,max_step,tol2,1,6);\n % update z\n z = invAtAI*(-A'*Y1/mu+Atb+Y2/mu+x); \n dY1 = A*z-b;\n dY2 = x-z;\n chgx = max(abs(xk-x));\n chgz = max(abs(zk-z));\n chg = max([chgx chgz max(abs(dY1(:))) max(abs(dY2(:)))]);\n if DEBUG \n if iter == 1 || mod(iter, 10) == 0\n obj = comp_fusedl1(x,1,lambda);\n err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2);\n disp(['iter ' num2str(iter) ', mu=' num2str(mu) ...\n ', obj=' num2str(obj) ', err=' num2str(err)]); \n end\n end\n \n if chg < tol\n break;\n end \n Y1 = Y1 + mu*dY1;\n Y2 = Y2 + mu*dY2;\n mu = min(rho*mu,max_mu); \nend\nobj = comp_fusedl1(x,1,lambda);\nerr = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2);\n\nfunction f = comp_fusedl1(x,lambda1,lambda2)\n% compute f = lambda1*||x||_1 + lambda2*\\sum_{i=2}^p |x_i-x_{i-1}|.\n% x - p*1 vector\nf = 0;\np = length(x);\nfor i = 2 : p\n f = f+abs(x(i)-x(i-1)); \nend\nf = lambda1*norm(x,1)+lambda2*f;\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "canyilu", "repo": "LibADMM-toolbox", "sha": "fa9bc9458b8fbe22ac264c6008b26e7e41e70742", "save_path": "github-repos/MATLAB/canyilu-LibADMM-toolbox", "path": "github-repos/MATLAB/canyilu-LibADMM-toolbox/LibADMM-toolbox-fa9bc9458b8fbe22ac264c6008b26e7e41e70742/algorithms/fusedl1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.7068993419894479}} {"text": "function [idp,IDP_p,IDP_p0] = p2idp(p,p0)\n\n% P2IDP Point to inverse-depth point conversion.\n% P2IDP(P,P0) is the inverse depth point anchored at P0 corresponding to\n% the Euclidean point P.\n%\n% An inverse-depth point (idp) is a 6-vector: \n%\n% idp = [x0 y0 z0 el az rho]',\n%\n% where:\n% x0, z0, y0: anchor: the 3D point P0 where where distance is referred to.\n% el, az: azimuth and elevation of the ray through P that starts at P0.\n% rho: inverse of the distance from point P to P0.\n%\n% [idp,IDP_p,IDP_p0] returns the Jacobians wrt P and P0.\n%\n% See also IDP2P.\n\n% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.\n\nif nargout == 1\n m = p-p0;\n rho = 1/sqrt(dot(m,m));\n py = vec2py(m);\n\n idp = [p0;py;rho];\nelse\n\n m = p-p0;\n M_p = 1;\n M_p0 = -1;\n [mn2,MN2_m] = dotJ(m,m);\n rho = 1/mn2;\n RHO_mn2 = -1/mn2^2;\n [py,PY_m] = vec2py(m);\n\n idp = [p0;py;rho];\n\n RHO_m = RHO_mn2*MN2_m;\n \n IDP_p = [zeros(3);PY_m*M_p;RHO_m*M_p];\n IDP_p0 = [eye(3);PY_m*M_p0;RHO_m*M_p0];\n\nend\n\n\nreturn\n\n%% Jac\n\nsyms x y z x0 y0 z0 real\np = [x;y;z];\np0 = [x0;y0;z0];\n\nidp = p2idp(p,p0);\n\nsimplify(IDP_p - jacobian(idp,p))\nsimplify(IDP_p0 - jacobian(idp,p0))\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/Points/p2idp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.7068993392964135}} {"text": "function [plane, inlier_count, inliers] = ransac_depth_plane(x, depth, alpha,...\n iter, p)\n%RANSAC_DEPTH_PLANE Fit a 3D depth plane to a set of input points using RANSAC.\n%The distance of a point from the plane is defined as the vertical offset.\n%\n% INPUTS:\n%\n% -|x|: |P|-by-2 matrix with image-plane coordinates of input points.\n%\n% -|depth|: |P|-by-1 vector with depth values for input points.\n%\n% -|alpha|: positive constant regulating the inlier threshold used in RANSAC.\n%\n% -|iter|: maximum number of RANSAC iterations.\n%\n% -|p|: target probability for having obtained a pure inlier set, used to cut\n% down on number of RANSAC iterations.\n%\n% OUTPUTS:\n%\n% -|plane|: 3-by-1 vector holding the parameters of the fitted plane, so that\n% for each point [x, y, d] it holds d = [x, y, 1] * plane.\n%\n% -|inlier_count|: cardinality of the final inlier set.\n%\n% -|inliers|: |inlier_count|-by-1 vector with indices of the members of the\n% final inlier set. \n\n% Determine inlier threshold |theta| based on the depth values. Goal: invariance\n% to range of depth values.\ntheta = alpha * median(depth);\n\n% Number of plane parameters.\nN = 3;\n\n% Total number of points.\nP = length(depth);\n\n% Represent pixel coordinates homogeneously.\nx_h = [x, ones(P, 1)];\n\n% Initialize variables to save the best fit across iterations.\ninliers = [];\ninlier_count = 0;\ninlier_ratio = 0;\n\n% Main RANSAC loop.\nfor i = 1:iter\n colinear = true;\n while colinear\n % Select a sample at random.\n permut = randperm(P);\n sample = permut(1:N);\n x_h_sample = x_h(sample, :);\n \n % Proceed to plane fitting only if the points of the sample are not\n % colinear, i.e. square matrix with homogeneous coordinates of\n % points in the sample is of full rank.\n if rank(x_h_sample) == N\n colinear = false;\n end\n end\n \n % Fit a plane to the current sample.\n plane_tmp = fit_depth_plane(x_h_sample, depth(sample));\n \n % Identify inliers for current fit.\n \n % Vertical distance.\n inliers_tmp = abs(x_h * plane_tmp - depth) <= theta;\n % Orthogonal distance.\n % plane_tmp_normal = [plane_tmp(1:N-1); 1];\n % inliers_tmp = abs([points(known_pixels_finite, :), depth_known_finite] *...\n % plane_tmp_normal - plane_tmp(N)) / norm(plane_tmp_normal) <= theta;\n inlier_tmp_count = nnz(inliers_tmp);\n \n % Update best fit.\n if inlier_tmp_count > inlier_count\n inlier_count = inlier_tmp_count;\n inlier_ratio = inlier_count / P;\n inliers = find(inliers_tmp);\n end\n \n % An adaptive version of RANSAC is implemented. If a pure inlier sample\n % has been already examined with probability greater that |p|, avoid\n % performing more iterations.\n p_bound = 1 - (1 - inlier_ratio ^ N) ^ i;\n if p <= p_bound\n break;\n end\nend\n\n% Perform a final least squares fit to compute the best depth plane with respect\n% to all points in the maximum inlier set that has been found with RANSAC.\nplane = fit_depth_plane(x_h(inliers, :), depth(inliers));\n\nend\n\n", "meta": {"author": "sakaridis", "repo": "fog_simulation-SFSU_synthetic", "sha": "8048e2ea208bd797ef2298e6b50f0d4e3a1b77a3", "save_path": "github-repos/MATLAB/sakaridis-fog_simulation-SFSU_synthetic", "path": "github-repos/MATLAB/sakaridis-fog_simulation-SFSU_synthetic/fog_simulation-SFSU_synthetic-8048e2ea208bd797ef2298e6b50f0d4e3a1b77a3/source/Depth_processing/ransac_depth_plane.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.7068993344775547}} {"text": "function y = atan(x)\n%ATAN Implements atan(x) for intervals\n%\n% y = atan(x)\n%\n%interval standard function implementation\n%\n\n% written 12/30/98 S.M. Rump\n% modified 08/31/99 S.M. Rump complex allowed, sparse input,\n% major revision, improved accuracy\n% modified 09/02/00 S.M. Rump rounding unchanged after use\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% accelaration for sparse input\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 09/06/07 S.M. Rump approximate std fcts removed\n% modified 09/28/08 S.M. Rump check for rounding to nearest improved\n%\n\n if issparse(x)\n [ix,jx,sx] = find(x);\n [m,n] = size(x);\n y = sparse(ix,jx,atan(full(sx)),m,n);\n return\n end\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 x.complex\n y = log( 2./(1-j*x) - 1) / (2*j);\n if rndold\n setround(rndold)\n end\n return\n end\n\n y = x;\n\n xinf = x.inf(:);\n xsup = x.sup(:);\n\n IndexInfPos = ( xinf>=0 );\n len1 = sum(IndexInfPos);\n IndexSupNeg = ( xsup<=0 );\n\n Y = atan_pos( [ xinf(IndexInfPos) ; -xsup(IndexSupNeg) ] , -1 );\n y.inf(IndexInfPos) = Y(1:len1);\n y.sup(IndexSupNeg) = -Y( len1+1 : end );\n\n IndexInfNeg = ( xinf<0 );\n len1 = sum(IndexInfNeg);\n IndexSupPos = ( xsup>0 );\n\n Y = atan_pos( [ -xinf(IndexInfNeg) ; xsup(IndexSupPos) ] , 1 );\n y.inf(IndexInfNeg) = -Y(1:len1);\n y.sup(IndexSupPos) = Y( len1+1 : end );\n\n setround(rndold)\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/intval/@intval/atan.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7068993278164774}} {"text": "function [M]=gen_MassMatrix(q,Pcii,Icii,mcii)\n%% This function is used to calculate the mass matrix of the KUKA iiwa 7 R 800 manipulator\n\n% Arreguments:\n%--------------------\n% q: is 1x7 vector, joint nagles vector of the manipulator\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% M: 7x7 matrix, the mass matrix of the KUKA iiwa 7 R 800.\n\n% Copyright: Mohammad SAFEEA\n\nT=kukaGetKenimaticModelAccelerated(q);\n[M]=GetInertiaMatrix5(T,Pcii,Icii,mcii);", "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/Matlab_client/gen_MassMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809827, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.706877948644529}} {"text": "function combo_test11 ( )\n\n%*****************************************************************************80\n%\n%% COMBO_TEST11 tests KNAPSACK_REORDER and KNAPSACK_01.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 25 January 2011\n%\n% Author:\n%\n% John Burkardt\n%\n n = 5;\n mass_limit = 26.0;\n p = [ 24.0, 13.0, 23.0, 15.0, 16.0 ]';\n w = [ 12.0, 7.0, 11.0, 8.0, 9.0 ]';\n\n fprintf ( 1, ' \\n' );\n fprintf ( 1, 'COMBO_TEST11\\n' );\n fprintf ( 1, ' KNAPSACK_REORDER reorders the knapsack data.\\n' );\n fprintf ( 1, ' KNAPSACK_01 solves the 0/1 knapsack problem.\\n' );\n\n fprintf ( 1, ' \\n' );\n fprintf ( 1, ' Object, Profit, Mass, \"Profit Density\"\\n' );\n fprintf ( 1, ' \\n' );\n for i = 1 : n\n fprintf ( 1, ' %6d %7.3f %7.3f %7.3f\\n', i, p(i), w(i), p(i) / w(i) );\n end\n\n [ p, w ] = knapsack_reorder ( n, p, w );\n\n fprintf ( 1, ' \\n' );\n fprintf ( 1, ' After reordering by Profit Density:\\n' );\n fprintf ( 1, ' \\n' );\n fprintf ( 1, ' Object, Profit, Mass, \"Profit Density\"\\n' );\n fprintf ( 1, ' \\n' );\n for i = 1 : n\n fprintf ( 1, ' %6d %7.3f %7.3f %7.3f\\n', i, p(i), w(i), p(i) / w(i) );\n end\n\n fprintf ( 1, ' \\n' );\n fprintf ( 1, ' Total mass restriction is %f\\n', mass_limit );\n\n [ x, mass, profit ] = knapsack_01 ( n, mass_limit, p, w );\n\n fprintf ( 1, ' \\n' );\n fprintf ( 1, ' Object, Density, Choice, Profit, Mass\\n' );\n fprintf ( 1, ' \\n' );\n for i = 1 : n\n fprintf ( 1, '%6d %7.3f %7.3f %7.3f %7.3f\\n', ...\n i, p(i) / w(i), x(i), x(i) * p(i), x(i) * w(i) );\n end\n\n fprintf ( 1, ' \\n' );\n fprintf ( 1, ' Total: %7.3f %7.3f\\n', profit, mass );\n\n return\nend\n", "meta": {"author": "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/combo_test11.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.7068633965670311}} {"text": "function jac = p36_jac ( neqn, t, y )\n\n%*****************************************************************************80\n%\n%% P36_JAC evaluates the jacobian for problem p36.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 23 February 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer NEQN, the number of equations.\n%\n% Input, real T, Y(NEQN), the arguments of the jacobian.\n%\n% Output, real JAC(NEQN,NEQN), the jacobian matrix.\n%\n jac = zeros ( neqn, neqn );\n\n jac(1,1) = 0.0;\n jac(1,2) = 1.0;\n\n jac(2,1) = 1.0 - 3.0 * y(1).^2;\n jac(2,2) = 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/test_ode/p36_jac.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7068633928819188}} {"text": "function Sest = cosamp_cgls(Phi,u,K,tol,maxiterations, err_tol)\n\n% Cosamp algorithm\n% Input\n% K : sparsity of Sest\n% Phi : measurement matrix\n% u: measured vector\n% tol : tolerance for approximation between successive solutions. \n% Output\n% Sest: Solution found by the algorithm\n%\n% Algorithm as described in \"CoSaMP: Iterative signal recovery from \n% incomplete and inaccurate samples\" by Deanna Needell and Joel Tropp.\n% \n\n\n% This implementation was written by David Mary, \n% but modified 20110707 by Bob L. Sturm to make it much clearer,\n% and corrected multiple times again and again.\n% To begin with, see: http://media.aau.dk/null_space_pursuits/2011/07/ ...\n% algorithm-power-hour-compressive-sampling-matching-pursuit-cosamp.html\n%\n% This script/program is released under the Commons Creative Licence\n% with Attribution Non-commercial Share Alike (by-nc-sa)\n% http://creativecommons.org/licenses/by-nc-sa/3.0/\n% Short Disclaimer: this script is for educational purpose only.\n% Longer Disclaimer see http://igorcarron.googlepages.com/disclaimer\n\n%%Code modified by Praneeth 14March2017 to include case when there is no\n%%signal to estimate;replaced pinv() by A\\b syntax for speed.\n% Initialization\nSest = zeros(size(Phi,2),1);\nv = u;\nt = 1; \nnumericalprecision = 1e-12;\nT = [];\nwhile ((t <= maxiterations) && (norm(v)/norm(u) > tol) ...\n && (norm(Phi'*v) > err_tol))\n \n y = abs(Phi'*v);\n [vals,z] = sort(y,'descend');\n Omega = find(y >= vals(2*K) & y > numericalprecision);\n \n T = union(Omega,T);\n x = v(T);\n %b = pinv(Phi(:,T))*u;\n% b = Phi(:,T) \\ u; %% edit PKN -- 3/3/17\n b = cgls(Phi(:, T), u, 0, err_tol, 3, 0, x);\n [vals,z] = sort(abs(b),'descend');\n Kgoodindices = (abs(b) >= vals(K) & abs(b) > numericalprecision);\n T = T(Kgoodindices);\n Sest = zeros(size(Phi,2),1);\n b = b(Kgoodindices);\n Sest(T) = b;\n v = u - Phi(:,T)*b;\n t = t+1;\nend", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/algorithms/st/MEDRoP/cosamp_cgls.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7068357163101044}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% s10.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% function s10(x)\n% Shekel10 function\nfunction f = s10(x)\na = [4, 1, 8, 6, 3, 2, 5, 8, 6, 7;\n 4, 1, 8, 6, 7, 9, 5, 1, 2, 3.6;\n 4, 1, 8, 6, 3, 2, 3, 8, 6, 7;\n 4, 1, 8, 6, 7, 9, 3, 1, 2, 3.6];\nc = [ 0.1, 0.2, 0.2, 0.4, 0.4, 0.6, 0.3, 0.7, 0.5, 0.5];\nif size(x,1) == 1\n x = x';\nend\nfor i=1:10\n b = (x - a(:,i)).^2;\n d(i) = sum(b);\nend\nf = -sum((c+d).^(-1));\n", "meta": {"author": "lacerbi", "repo": "optimviz", "sha": "2cc41c19ffeaaa9a23239f53d80691cf3599357d", "save_path": "github-repos/MATLAB/lacerbi-optimviz", "path": "github-repos/MATLAB/lacerbi-optimviz/optimviz-2cc41c19ffeaaa9a23239f53d80691cf3599357d/utils/mcs/jones/s10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.7068266612719812}} {"text": "function [PC, powers] = powercentersPD(T, E, wts)\n% function [PC, powers] = powercentersPD(T, E, wts)\n%\n% T: triangulation\n% E: set of points\n% wts: weights of points in E\n%\n% The output array PC contains the power centers of the triangles in T.\n% That is, row i of PC contains the point that is equidistant from each\n% vertex of the triangle specified by row i of T, with respect to the power\n% of each vertex. The output array powers contains the power of each power\n% center.\n\n[m, n] = size(T);\nPC = zeros(m,n-1);\npowers = zeros(m,1);\n\nfor i=1:m\n tr = E(T(i,:),:);\n wt = wts(T(i,:));\n p = tr(1,:);\n Rp = repmat(p, n-1, 1);\n Pts = tr(2:n,:);\n Ac = 2*(Pts - Rp);\n \n Rw1 = repmat(wt(1), n-1, 1);\n Wts = wt(2:n);\n Sp1 = repmat(sum(p.^2), n-1, 1);\n SPts = sum(Pts.^2, 2);\n Bc = Rw1 - Wts - Sp1 + SPts;\n \n pc = Ac \\ Bc;\n \n PC(i,:) = pc;\n powers(i,1) = norm(pc - p')^2 - wt(1);\nend", "meta": {"author": "optimaltransport", "repo": "optimaltransport.github.io", "sha": "2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203", "save_path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io", "path": "github-repos/MATLAB/optimaltransport-optimaltransport.github.io/optimaltransport.github.io-2fa6db6e6a48ab9bd6676088db00bd7c5c8b4203/_site/code/semi-discrete/power_diagrams/powercentersPD.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913343093499, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.7068266574747915}} {"text": "function value = p23_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P23_F evaluates the integrand for problem 23.\n%\n% Dimension:\n%\n% DIM_NUM is arbitrary.\n%\n% Region:\n%\n% The interior of the unit simplex, for which all X's are nonnegative,\n% and sum ( X(1:N) ) <= 1.\n%\n% Integral Parameters:\n%\n% C defaults to 1.0. \n% Call P23_R8 to get or set this value.\n%\n% E(1:DIM_NUM) defaults to (/ 2, 2, ..., 2 /). \n% Call P23_I4VEC to get or set this value.\n%\n% Integrand:\n%\n% F(X) = C * X1^E1 * X2^E2 * ... * Xn^En\n%\n% C is real, all exponents E are nonnegative integers.\n%\n% Exact Integral:\n%\n% C * Gamma(E1+1) * Gamma(E2+1) * ... * Gamma(En+1) / Gamma(E1+E2+...+En+1)\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% 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 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 c = 0.0;\n c = p23_r8 ( 'G', 'C', c );\n\n e = [];\n e = p23_i4vec ( 'G', 'E', dim_num, e );\n\n value(1:point_num) = c;\n\n for point = 1 : point_num\n\n for dim = 1 : dim_num\n value(point) = value * x(dim,point)^e(dim);\n end\n\n end\n\n p23_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/p23_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7067709844657378}} {"text": "function [Z] = MCWNNM_ADMM2( 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\nW = 1 ./ (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);\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 || stopC end.\n%\n% zFieldV must be specified as a list of coordinates for each slice in\n% field3M.\n%\n% xInterpV, yInterpV, zInterpV are vectors of equal length indicating the\n% x,y,z, coordinates to interpolate from original data field3M.\n%\n% Based on code by J.O.Deasy.\n%\n%JRA 1/13/05\n%\n%Usage:\n% function [interpV] = finterp3(xInterpV, yInterpV, zInterpV, field3M, xFieldV, yFieldV, zFieldV, outOfBoundsVal)\n\nsiz = size(field3M);\n\nif ~exist('OOBV')\n OOBV = NaN;\nend\n\nxDelta = xFieldV(2);\nyDelta = yFieldV(2);\n\n%Get r,c,s indices.\n% cols = interp1q(reshape(xFieldV, [], 1), reshape(1:length(xFieldV),[], 1), reshape(xInterpV, [], 1));\n% rows = interp1q(reshape(yFieldV, [], 1), reshape(1:length(yFieldV),[], 1), reshape(yInterpV, [], 1));\ncols = (xInterpV-(xFieldV(1)-xDelta))/xDelta;\nrows = (yInterpV-(yFieldV(1)-yDelta))/yDelta;\nif length(zFieldV) > 1;\n slcs = interp1(zFieldV,1:length(zFieldV),zInterpV);\nelse\n slcs = ones(size(cols)); %This effectively negates Z. All values are in plane. Bad idea? \nend\n\nclear xInterpV yInterpV zInterpV\nclear xFieldV yFieldV zFieldV\n\n%Find indices out of bounds.\ncolNaN = cols >= siz(2) | cols < 1;\nrowNaN = rows >= siz(1) | rows < 1; \n% slcNaN = slcs >= siz(3) | slcs < 1; \n\n% colNaN = isnan(cols);\n% rowNaN = isnan(rows);\nslcNaN = isnan(slcs) | slcs < 1 | slcs >= siz(3);\n\n%Set those to a proxy 1.\nrows(rowNaN) = 1;\ncols(colNaN) = 1;\nslcs(slcNaN) = 1;\n\ncolFloor = floor(cols);\ncolMod = cols - colFloor;\noneMinusColMod = (1-colMod);\n\nrowFloor = floor(rows);\nrowMod = rows - rowFloor;\noneMinusRowMod = (1-rowMod); \n\nslcFloor = floor(slcs);\nslcMod = slcs - slcFloor;\noneMinusSlcMod = (1-slcMod); \n\nclear rows cols slcs\n\n%Linear indices of lower bound contributing points.\nINDEXLIST = rowFloor + (colFloor-1)*siz(1) + (slcFloor-1)*siz(1)*siz(2);\n\nclear rowFloor colFloor slcFloor\n\n%Linear offsets when moving in 3D matrix.\noneRow = 1;\noneCol = siz(1);\noneSlc = siz(1)*siz(2);\n\n%Accumulate contribution from each voxel surrounding x,y,z point.\ninterpV = double(field3M(INDEXLIST)) .* oneMinusRowMod .* oneMinusColMod .* oneMinusSlcMod;\ninterpV = interpV + double(field3M(INDEXLIST+(oneRow))) .* rowMod .* oneMinusColMod .* oneMinusSlcMod;\ninterpV = interpV + double(field3M(INDEXLIST+(oneCol))) .* oneMinusRowMod .* colMod .* oneMinusSlcMod;\ninterpV = interpV + double(field3M(INDEXLIST+(oneCol+oneRow))) .* rowMod .* colMod .* oneMinusSlcMod;;\ninterpV = interpV + double(field3M(INDEXLIST+(oneSlc))) .* oneMinusRowMod .* oneMinusColMod .* slcMod;\ninterpV = interpV + double(field3M(INDEXLIST+(oneSlc+oneRow))) .* rowMod .* oneMinusColMod .* slcMod;\ninterpV = interpV + double(field3M(INDEXLIST+(oneSlc+oneCol))) .* oneMinusRowMod .* colMod .* slcMod;\ninterpV = interpV + double(field3M(INDEXLIST+(oneSlc+oneCol+oneRow))) .* rowMod .* colMod .* slcMod;\n\n%Replace proxy 1s with out of bounds vals.\ninterpV(rowNaN | colNaN | slcNaN) = OOBV;\n\nreturn;", "meta": {"author": "cerr", "repo": "CERR", "sha": "d320754abad9dcb78508ab69f33ae9f644202114", "save_path": "github-repos/MATLAB/cerr-CERR", "path": "github-repos/MATLAB/cerr-CERR/CERR-d320754abad9dcb78508ab69f33ae9f644202114/IMRTP/recompDose/MC/finterp3_plnChk.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7066656163548656}} {"text": "function r_size = nwspgr_size ( type, dim, k, sym, compress )\n\n%*****************************************************************************80\n%\n%% NWSPGR_SIZE determines the size of a sparse grid rule.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 June 2012\n%\n% Author:\n%\n% Original MATLAB version by Florian Heiss, Viktor Winschel.\n% This MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Florian Heiss, Viktor Winschel,\n% Likelihood approximation by numerical integration on sparse grids,\n% Journal of Econometrics,\n% Volume 144, 2008, pages 62-80.\n%\n% Parameters:\n% \n% Input, string TYPE, selects the 1D integration rule:\n% \"kpu\": Nested rule for unweighted integral over [0,1];\n% \"kpn\": Nested rule for integral with Gaussian weight;\n% \"gqu\": Gaussian quadrature for unweighted integral over [0,1] \n% (Gauss-Legendre);\n% \"gqn\": Gaussian quadrature for integral with Gaussian weight \n% (Gauss-Hermite);\n% func: any function name. Function must accept level l and return nodes N \n% and weights W for univariate quadrature rule with polynomial exactness \n% 2*L-1 as [n, w] = feval(func,level)\n%\n% Input, integer DIM, the dimension of the integration problem.\n%\n% Input, integer K, the level. When using the built in 1D rules, the \n% resulting sparse grid will be exact for polynomials up to total order\n% 2*K-1. When using the built-in quadrature rules, the maximum value of K \n% that is available is 25.\n%\n% Input, integer SYM. This is only useful when the user has \n% chosen to supply the 1D quadrature rule. In that case, if the rule is \n% symmetric, specifying SYM to be 1 will allow the code to run faster.\n% But this also requires that the user quadrature rule function only \n% return the nonnegative abscissas and their weights.\n%\n% Input, integer COMPRESS,\n% 0, do not compress the rule ( = do not merge duplicate points.)\n% 1, compress the rule.\n%\n% Output, integer R_SIZE, the \"size\" of the rule.\n%\n\n%\n% Interpret the inputs. Use STRCMPI so that case is ignored.\n%\n builtinfct = ( strcmpi ( type, 'gqu' ) || ...\n strcmpi ( type, 'gqn' ) || ...\n strcmpi ( type, 'kpu' ) || ...\n strcmpi ( type, 'kpn' ) );\n\n sym = logical ( sym );\n%\n% Retrieve the 1D rules of levels 1 to K.\n% Create cell arrays X1D and W1D containing the node and weight information.\n% The array N1D stores the length or order of each rule.\n%\n% The built in functions already return only the positive orthant.\n%\n% If the rule is being supplied by the user, and the user indicates that\n% it's a symmetric rule, then similarly keep only the positive orthant.\n%\n% The result will be that if SYM is true, whether for built in or user-supplied\n% functions, we have only the positive orthant data stored.\n%\n n1d = zeros ( 1, k );\n x1d = cell ( k, 1 ); \n w1d = cell ( k, 1 ); \n\n for level = 1 : k\n\n [ x, w ] = feval ( type, level );\n\n if ( ( ~ builtinfct ) && sym )\n [ numnew, dummy ] = size ( x );\n [ x, sortvec ] = sortrows ( x );\n w = w ( sortvec );\n x = x((floor(numnew/2)+1):numnew,:);\n w = w((floor(numnew/2)+1):numnew,:);\n end\n\n n1d(level) = length ( w );\n x1d{level} = x;\n w1d{level} = w;\n\n end\n%\n% Initialization.\n%\n minq = max ( 0, k - dim );\n maxq = k - 1;\n nodes = [];\n weights = [];\n%\n% Loop for max ( 0, K - DIM ) <= Q <= K - 1.\n%\n for q = minq : maxq\n\n r = length ( weights );\n%\n% BQ is the combinatorial coefficient applied to the component\n% product rules which have level Q.\n%\n bq = ( -1 )^( maxq - q ) * nchoosek ( dim - 1, dim + q - k );\n%\n% Compute the D-dimensional row vectors that sum to DIM+Q.\n%\n is = get_seq ( dim, dim + q );\n%\n% Preallocate new rows for nodes and weights.\n%\n Rq = prod ( n1d(is), 2 );\n sRq = sum ( Rq );\n nodes = [ nodes; zeros(sRq,dim) ];\n weights = [ weights; zeros(sRq,1) ];\n%\n% Generate each of the product rules indicated by IS, and\n% insert them into NODES and WEIGHTS.\n%\n for j = 1 : size(is,1)\n midx = is(j,:);\n [ newn, neww ] = tensor_product ( x1d(midx), w1d(midx) );\n nodes((r+1):(r+Rq(j)),:) = newn;\n weights((r+1):(r+Rq(j))) = bq .* neww;\n r = r + Rq(j);\n end\n%\n% Sort the nodes and merge repeated values.\n%\n [ nodes, sortvec ] = sortrows ( nodes );\n weights = weights(sortvec);\n keep = 1; \n lastkeep = 1;\n\n for j = 2 : size(nodes,1)\n if ( compress )\n\n if ( nodes(j,:) == nodes(j-1,:) ) \n weights(lastkeep) = weights(lastkeep) + weights(j);\n else\n lastkeep = j;\n keep = [ keep ; j ];\n end\n else\n lastkeep = j;\n keep = [ keep ; j ];\n end\n end\n\n nodes = nodes(keep,:);\n weights = weights(keep);\n\n end\n%\n% The rule has been computed.\n% If we used symmetry, we now have to extend the rule.\n%\n if ( sym )\n\n nr = length ( weights );\n m = x1d{1};\n\n for j = 1 : dim\n\n keep = zeros(nr,1);\n numnew = 0;\n\n for r = 1 : nr \n if ( nodes(r,j) ~= m )\n numnew = numnew + 1;\n keep(numnew) = r;\n end\n end\n\n if ( 0 < numnew )\n nodes = [nodes ; nodes(keep(1:numnew),:)];\n nodes(nr+1:nr+numnew,j) = 2*m - nodes(nr+1:nr+numnew,j);\n weights = [weights ; weights(keep(1:numnew))]; \n nr = nr + numnew;\n end\n\n end\n\n [ nodes, sortvec ] = sortrows ( nodes );\n weights = weights(sortvec);\n\n end\n\n r_size = length ( weights );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/sparse_grid_hw/nwspgr_size.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7066656163548656}} {"text": "function fem1d_pack_test01 ( )\n\n%*****************************************************************************80\n%\n%% FEM1D_PACK_TEST01 tests LOCAL_BASIS_1D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 March 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% None\n%\n node_num = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FEM1D_PACK_TEST01:\\n' );\n fprintf ( 1, ' LOCAL_BASIS_1D evaluates the local basis functions\\n' );\n fprintf ( 1, ' for a 1D element.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Test that the basis functions, evaluated at the nodes,\\n' );\n fprintf ( 1, ' form the identity matrix.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of nodes = %d\\n', node_num );\n\n node_x(1:node_num) = [ 1.0, 2.0, 4.0, 4.5 ];\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Node coordinates:\\n' );\n fprintf ( 1, '\\n' );\n for j = 1 : node_num\n fprintf ( 1, ' %8d %7.3f\\n', j, node_x(j) );\n end\n\n for j = 1 : node_num\n x = node_x(j);\n phi_matrix(1:node_num,j) = local_basis_1d ( node_num, node_x, x );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' A(I,J) = PHI(I) at node (J):\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : node_num\n for j = 1 : node_num\n fprintf ( 1, ' %7.3f', phi_matrix(i,j) );\n end\n fprintf ( 1, '\\n' );\n end\n\n seed = 123456789;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The PHI functions should sum to 1 at random X values:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X Sum ( PHI(:)(X) )\\n' );\n fprintf ( 1, '\\n' );\n\n for j = 1 : 5\n [ x, seed ] = r8_uniform_ab ( 1.0, 4.5, seed );\n phi = local_basis_1d ( node_num, node_x, x );\n fprintf ( 1, ' %14.6g %14.6g\\n', x, sum ( phi(1:node_num) ) );\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/fem1d_pack/fem1d_pack_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.706632399001291}} {"text": "function [x1,lun,err] = perform_douglas_rachford(A,y,options)\n\n% perform_douglas_rachford - \n%\n% [x1,lun,err] = perform_douglas_rachford(A,y,options);\n%\n% Solve noiseless Basis Pursuit\n% x1 = argmin_x \\sum |x[k]| subj.to A*x=y\n%\n% A can be a matrix or an operator A(x,dir,options)\n% with dir=1 for A*x and dir=-2 for A^{+}*x (pseudo inverse).\n%\n% options.x can be an initial guess\n%\n% options.niter is the number of iterations\n%\n% Special thanks to Jalal Fadili for useful helps on this algorithm.\n%\n% Copyright (c) 2008 Gabirel Peyre\n\nniter = getoptions(options, 'niter', 100);\nmu = getoptions(options, 'mu', 3);\n\nif isnumeric(A)\n pA = getoptions(options, 'pseudo_inv', []);\n if isempty(pA)\n pA = pinv(A);\n end\nend\n\n% initial guess\nx = getoptions(options, 'x', [] );\nif isempty(x)\n if isnumeric(A)\n x = pA*y;\n else\n x = feval(A, y, -2, options);\n end\nend\n\n% target result (error monitoring\nx0 = getoptions(options, 'x0', [] );\n\ndrawiter = getoptions(options, 'drawiter',0);\nverb = getoptions(options, 'verb', 1);\nisreal = getoptions(options, 'isreal', 0);\n\nsolve_tv = getoptions(options, 'solve_tv', 0);\n\nlun = [];\nerr = [];\nif isnumeric(A)\n x1 = x + pA*(y-A*x);\nelse\n x1 = y - feval(A,x, +1, options);\n x1 = x + feval( A, x1, -2, options);\nend\nif drawiter\n clf;\nend\n\nnrefresh = 100;\nndisp = max(2, ceil(niter/nrefresh) );\n\nfor i=1:niter\n if verb\n progressbar(i,niter);\n end\n % compute the intermediary point\n % x <- x-x1 + thresh( 2*x1-x )\n \n u = 2*x1-x;\n \n% sparse_weight = getoptions(options, 'sparse_weight', 0,1);\n% u = u./sparse_weight;\n if not(solve_tv)\n % L1 regularization\n u = perform_thresholding( u, mu, 'soft' );\n else\n % TV regularization\n opts.method = 'gradient';\n opts.lambda = mu;\n opts.niter = getoptions(options, 'niter_tv', 50);\n opts.niter_inner = 1;\n opts.display = 0;\n opts.verb = 0;\n [u1,err,tv,lalist,Err] = perform_tv_denoising(u,opts);\n % u1 = u - mu*div( xi, options )\n% opts.xi = grad( (u1-u)/mu, options );\n u = u1;\n end\n% u = u.*sparse_weight;\n \n x = x-x1 + u;\n \n % perform projection step on the constraints\n if isnumeric(A)\n x1 = x + pA*(y-A*x);\n else\n x1 = y - feval(A,x,+1, options);\n x1 = x + feval( A, x1, -2, options);\n end\n \n if isreal\n % x1 = real(x1); % force real signal\n end\n % check for error decay\n if nargout>=3 && not(isempty(x0))\n err(end+1) = norm(x0-x1, 'fro')^2;\n end\n if nargout>=2\n if not(solve_tv)\n lun(end+1) = sum(abs(x1(:))); % mean(sum(abs(x1)));\n else\n lun(end+1) = compute_total_variation(x1,options);\n end\n end\n if drawiter && mod(i,ndisp)==1 % && ntest==1\n if nb_dims(x1)==1\n n = size(x1,1);\n plot( real(x1(:,1:min(end,3))) ); \n axis([1,n,-1,1]); \n axis tight;\n drawnow;\n else\n clf; imageplot(x1); drawnow;\n end\n end\nend\n% x1 = real(x1);\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_sparsity/perform_douglas_rachford.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.706552949196347}} {"text": "function [ result, seed ] = sphere01_triangle_quad_00 ( n, v1, v2, v3, f, ...\n seed )\n\n%*****************************************************************************80\n%\n%% SPHERE01_TRIANGLE_QUAD_00: quadrature over a triangle on the unit sphere.\n%\n% Discussion:\n%\n% This is a Monte Carlo approach.\n%\n% The integral is approximated by averaging the values at N random points,\n% multiplied by the area.\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% Parameters:\n%\n% Input, integer N, the number of sample points.\n%\n% Input, real V1(3), V2(3), V3(3), the XYZ coordinates of\n% the vertices of the triangle.\n%\n% Input, function v = f ( x ), evaluates the integrand at X.\n%\n% Input/output, integer SEED, a seed for the random\n% number generator.\n%\n% Output, real RESULT, the approximate integral.\n%\n area = sphere01_triangle_vertices_to_area ( v1, v2, v3 );\n\n [ vc, seed ] = sphere01_triangle_sample ( n, v1, v2, v3, seed );\n\n quad = 0.0;\n for j = 1 : n\n quad = quad + f ( vc(1:3,j) );\n end\n\n result = quad * area / 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_triangle_quad/sphere01_triangle_quad_00.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.7065529347194072}} {"text": "\nfunction [Rz] = R_z(psi)\n\n% Input sanity check\nif nargin < 1\n psi = sym('psi_t','real');\nend\nassert(numel(psi) == 1,'Angle must be a scalar [1x1].');\nassert(isa(psi,'sym') || isnumeric(psi),'Angle must be a symbolic or numeric value.');\n\n% Rotate about the z-axis (yaw)\nRz = [cos(psi) -sin(psi) 0;\n sin(psi) cos(psi) 0;\n 0 0 1];\nend", "meta": {"author": "douthwja01", "repo": "OpenMAS", "sha": "962f321f82167db78066b2c88c783423ecc3b73a", "save_path": "github-repos/MATLAB/douthwja01-OpenMAS", "path": "github-repos/MATLAB/douthwja01-OpenMAS/OpenMAS-962f321f82167db78066b2c88c783423ecc3b73a/environment/common/R_z.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.7065529322437003}} {"text": "%% ALS optimization for CP and Tucker tensor decompositions\n\n%% Alternating least squares for PARAFAC/CANDECOMP\n% The function |parafac_als| computes an estimate of the best rank-R\n% PARAFAC model of a tensor X using an alternating least-squares\n% algorithm. The input X can be a tensor, sptensor, ktensor, or\n% ttensor. The result P is a ktensor.\nrand('state',0);\nX = sptenrand([5 4 3], 10)\n%%\nP = parafac_als(X,2)\n%%\nP = parafac_als(X,2,struct('dimorder',[3 2 1]))\n%%\nP = parafac_als(X,2,struct('dimorder',[3 2 1],'init','nvecs'))\n%%\nU0 = {rand(5,2),rand(4,2),[]}; %<-- Initial guess for factors of P\nP = parafac_als(X,2,struct('dimorder',[3 2 1],'init',{U0}))\n%% Alternating least squares for Tucker model \n% The function |tucker_als| computes the best rank(R1,R2,..,Rn)\n% approximation of tensor X, according to the specified dimensions in\n% vector R. The input X can be a tensor, sptensor, ktensor, or\n% ttensor. The result returned in T is a ttensor.\nX = sptenrand([5 4 3], 10)\n%%\nT = tucker_als(X,2) %<-- best rank(2,2,2) approximation \n%%\nT = tucker_als(X,[2 2 1]) %<-- best rank(2,2,1) approximation \n%%\nT = tucker_als(X,2,struct('dimorder',[3 2 1]))\n%%\nT = tucker_als(X,2,struct('dimorder',[3 2 1],'init','eigs'))\n%%\nU0 = {rand(5,2),rand(4,2),[]}; %<-- Initial guess for factors of T\nT = tucker_als(X,2,struct('dimorder',[3 2 1],'init',{U0}))\n", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/libs/tensor_toolbox_2.5/doc/T1_algorithms_doc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7064628447482003}} {"text": "function [coeff,variance]=OLSPriorTheta(y,timetrend,f)\n% OLSPriorTheta(y,timetrend,f) computes the prior for coefficients of the\n% deterministic trends in the TVE-VAR approach. The prior is normally\n% distributed with mean \"coeff\" and variance \"variance\". The prior\n% parameters are computed regressing the data y on timetrend. Then, coeff is\n% the OLS estimate, and variance is the asymptotic variance of the OLS,\n% scaled up of a factor f.\n\n\n%% Prepare data: make sure the dimensions of the inputs are correct\nif size(y,1)>size(y,2)\n y=y';\nend\nif size(timetrend,1)>size(timetrend,2)\n timetrend=timetrend';\nend\n\n%% Run OLS\nT=size(y,2); % number of data available\nk=size(timetrend,1); % number of regressors\n\nP=y*timetrend'*inv(timetrend*timetrend'); % the OLS coefficients\nresid=y-P*timetrend; % the residuals from the regression\nO=1/(T-k)*resid*resid';\nQ=timetrend*timetrend';\nvarpar=kron(O,Q^-1); % the asymptotic variance\n\n%% The output\nvariance=varpar*f;\ncoeff=P';\n\nend", "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/OLSPriorTheta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.7063850072520371}} {"text": "function [pos vel alt] = RadarUKF(z, dt)\n%\n%\npersistent Q R\npersistent x P\npersistent n m\npersistent firstRun\n\n\nif isempty(firstRun)\n Q = [ 0.01 0 0;\n 0 0.01 0;\n 0 0 0.01 ];\n \n R = 100;\n\n x = [0 90 1100]'; \n P = 100*eye(3);\n\n n = 3;\n m = 1;\n \n firstRun = 1; \nend\n\n\n[Xi W] = SigmaPoints(x, P, 0);\n\nfXi = zeros(n, 2*n+1);\nfor k = 1:2*n+1\n fXi(:, k) = fx(Xi(:,k), dt);\nend\n\n[xp Pp] = UT(fXi, W, Q);\n%norm(xp - fx(x, dt))\n\n\nhXi = zeros(m, 2*n+1);\nfor k = 1:2*n+1\n hXi(:, k) = hx(fXi(:,k));\nend\n\n[zp Pz] = UT(hXi, W, R);\n%norm(zp - hx(xp))\n\nPxz = zeros(n, m);\nfor k = 1:2*n+1\n Pxz = Pxz + W(k)*(fXi(:, k) - xp)*(hXi(:, k) - zp)';\nend\n\nK = Pxz*inv(Pz);\n\nx = xp + K*(z - zp);\nP = Pp - K*Pz*K';\n\n\npos = x(1);\nvel = x(2);\nalt = x(3);\n\n\n%------------------------------\nfunction xp = fx(x, dt)\n%\n%\nA = eye(3) + dt*[ 0 1 0;\n 0 0 0;\n 0 0 0 ]; \n\nxp = A*x;\n\n\n\n%------------------------------\nfunction yp = hx(x)\n%\n%\nyp = sqrt(x(1)^2 + x(3)^2);", "meta": {"author": "philbooks", "repo": "Kalman-Filter-for-Beginners", "sha": "5190a723dcbf96eacda71ed56abddb3a11779a82", "save_path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners", "path": "github-repos/MATLAB/philbooks-Kalman-Filter-for-Beginners/Kalman-Filter-for-Beginners-5190a723dcbf96eacda71ed56abddb3a11779a82/15.UKF/RadarUKF/RadarUKF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7063850069648995}} {"text": "% Build a spectrum-like harmonic model using a given sinusoids set\n%\n% Input\n% sins : Nx3 (or Nx4), frequency[Hz], amplitude, phase, (harmnb)\n% Only positive frequencies, with DC.\n% opt : Options (see below)\n%\n% Output\n% M : Spectrum built from sins.\n% (With same format as a DFT result)\n%\n% Copyright (c) 2012 University of Crete - Computer Science Department\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% TODO\n% Manage holes in the harmonic structure\n%\n\nfunction [M, opt] = sin2shm(sins, opt)\n\n if nargin<2\n opt.nbh = Inf; % Number of harmonics to be use in the model\n % (excluding DC).\n opt.max_freq = 8000;% Consider harmonics up to this limit.\n\n opt.prevpow2 = false;% if true, reduce the harmonic model to the\n % biggest possible power of 2 length\n opt.dc_extrap = 1; % 0: Use the current value\n % 1; Copy the amplitude of the first harm\n % 2: Use linear extrapolation on log scale\n % both 1 and 2 assume angle(DC)=0\n end\n if nargin==0; M=opt; return; end\n\n % TODO manage holes in the harmonic structure\n\n if ~isempty(opt.max_freq) && opt.max_freq>0\n inds = sins(1,:)<=opt.max_freq;\n sins = sins(:,inds);\n end\n sins = sins(:,1:min(size(sins,2), 1+opt.nbh));\n if opt.prevpow2\n % in order to speed up the computation of the min phase\n harmsize = 2^(nextpow2(size(sins,2))-1) + 1;\n sins = sins(:,1:min(size(sins,2), harmsize));\n end\n\n M = [sins(2,:).'.*exp(1i*sins(3,:).')];\n\n M(1) = sign(real(M(1)))*abs(M(1)); % set DC phase to 0 or pi\n\n M(end) = sign(real(M(end)))*abs(M(end)); % set the Nyquist phase to 0 or pi\n\n M = hspec2spec(M);\n\n % Extrapolate the model DC\n % Doesn't keep the DC phase !\n % Angle(DC) never makes sens in acoustic measurement\n % For technical reasons, we can therefore assume any constant (here zero).\n if opt.dc_extrap==1; M(1) = abs(M(2));\n elseif opt.dc_extrap==2; M(1) = db2lin(lin2db(M(2))+(lin2db(M(2))-lin2db(M(3)))); end\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/sinusoidal/sin2shm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.7063849889486968}} {"text": "function writeDoublePendulumDynamics(f,M)\n\n%This function writes the dynamics file for the double pendulum.\n\nfilename = 'doublePendulumDynamics';\n\ncomments{1} = ['DZ = ' upper(filename) '(T,Z,P)'];\ncomments{2} = ' ';\ncomments{3} = 'FUNCTION: This function computes the dynamics of a double';\ncomments{4} = ' pendulum, and is designed to be called from ode45. The';\ncomments{5} = ' model allows for arbitrary mass and inertia for each';\ncomments{6} = ' link, but no friction or actuation';\ncomments{7} = ' ';\ncomments{8} = 'INPUTS: ';\ncomments{9} = ' t = time. Dummy input for ode45. Not used.';\ncomments{10} = ' z = [4xn] matrix of states.';\ncomments{12} = ' P = struct of parameters';\ncomments{13} = 'OUTPUTS: ';\ncomments{14} = ' dz = [4xn] matrix of state derivatives';\ncomments{15} = ' ';\ncomments{16} = 'NOTES:';\ncomments{17} = [' This file was automatically generated by ' mfilename]; \n\nparams{1} = {'m1','link one mass'};\nparams{2} = {'m2','link two mass'};\nparams{3} = {'g ','gravity'};\nparams{4} = {'l1','link one length'};\nparams{5} = {'l2','link two length'};\nparams{6} = {'I1','link one moment of inertia about its center of mass'};\nparams{7} = {'I2','link two moment of inertia about its center of mass'};\nparams{8} = {'d1','distance between link one center of mass and parent joint'};\nparams{9} = {'d2','distance between link two center of mass and parent joint'};\n\nstates{1} = {'th1','link one absolute angle'};\nstates{2} = {'dth1','link one angular rate'};\nstates{3} = {'th2','link two absolute angle'};\nstates{4} = {'dth2','link two angular rate'};\n\ndstates{1} = {'dth1','derivative of link one absolute angle'};\ndstates{2} = {'ddth1','derivative of link one angular rate'};\ndstates{3} = {'dth2','derivative of link two absolute angle'};\ndstates{4} = {'ddth2','derivative of link two angular rate'};\n\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\n% write file %\n%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%\nfid = fopen([filename '.m'],'w');\n\nfprintf(fid, ['function dz = ' filename '(~,z,P) \\n']);\n\nfor i=1:length(comments)\n fprintf(fid,['%%' comments{i} '\\n']);\nend\nfprintf(fid,'\\n');\n\nfor i=1:length(params)\n fprintf(fid,[params{i}{1} ' = P.' params{i}{1} '; %%' params{i}{2} '\\n']);\nend\nfprintf(fid,'\\n');\n\nfor i=1:length(states)\n fprintf(fid,[states{i}{1} ' = z(' num2str(i) ',:); %%' states{i}{2} '\\n']);\nend\nfprintf(fid,'\\n');\n\nfor i=1:2;\n fprintf(fid,['f' num2str(i) ' = ' vectorize(char(f(i))) ';\\n']);\nend\nfprintf(fid,'\\n');\n\nfor i=1:2\n for j=1:2\n fprintf(fid,['M' num2str(i) num2str(j) ' = ' vectorize(char(M(i,j))) ';\\n']);\n end\nend\nfprintf(fid,'\\n');\n\nfprintf(fid,'D = M11.*M22 - M12.*M21;\\n\\n');\n\nfprintf(fid,'ddth1 = (f2.*M12 - f1.*M22)./D;\\n');\nfprintf(fid,'ddth2 = -(f2.*M11 - f1.*M21)./D;\\n');\nfprintf(fid,'\\n');\n\nfprintf(fid,'dz = [...\\n');\nfor i=1:length(dstates)\n fprintf(fid,[' ' dstates{i}{1} '; %%' dstates{i}{2} '\\n']);\nend\nfprintf(fid,'];\\n');\n\nfprintf(fid,'end \\n');\n\nfclose(fid);\nend\n\n\n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/LagrangeMechanics/doublePendulum/writeDoublePendulumDynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.7063694288219903}} {"text": "function result = cube_unit_3d ( func )\n\n%*****************************************************************************80\n%\n%% CUBE_UNIT_3D approximates an integral inside the unit cube in 3D.\n%\n% Integration region:\n%\n% Points (X,Y,Z) such that:\n%\n% -1 <= X <= 1,\n% -1 <= Y <= 1,\n% -1 <= Z <= 1.\n%\n% Discussion:\n%\n% An 8 point third degree formula is used.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 21 May 2004\n%\n% Author:\n%\n% 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(X,Y,Z), of the form\n% function value = func ( x, y, z )\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n s = 1.0E+00 / sqrt ( 3.0E+00 );\n w = 1.0E+00 / 8.0E+00;\n\n x = s;\n y = s;\n z = s;\n\n quad = w * ( ...\n feval ( func, x, y, z ) ...\n + feval ( func, x, y, -z ) ...\n + feval ( func, x, -y, z ) ...\n + feval ( func, x, -y, -z ) ...\n + feval ( func, -x, y, z ) ...\n + feval ( func, -x, y, -z ) ...\n + feval ( func, -x, -y, z ) ...\n + feval ( func, -x, -y, -z ) );\n\n volume = cube_unit_volume_nd ( 3 );\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/cube_unit_3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.7063131664521597}} {"text": "function y = inverseGammaPdf(x,alpha,beta)\n% The inverse Gamma PDF.\n% INPUT\n% x (>0)\n% alpha - shape parameter\n% beta - scale parameter\n% OUTPUT\n% y = the pdf [nrX nrBeta]\n% BK - 2018\n\n[nrX,nrBetaInX] = size(x);\n[nrBeta,nrXInBeta] = size(beta);\nif nrXInBeta1\n x = repmat(x,[1 nrBeta]);\nend\n\nz = x<0;\nx(z) =NaN;\ny = (beta.^alpha)./gamma(alpha).*(1./x).^(alpha+1).*exp(-beta./x);\ny(z) = 0;\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/bayesFactor/+bf/+internal/inverseGammaPdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.7062685736811207}} {"text": "%% RPCA demo using TFOCS\n% This is a demo of Robust PCA (RPCA) using . Since 2009,\n% there has been much interest in this specific RPCA formulation\n% (RPCA can refer to many different formulations; we will state\n% our formulation precisely below), but most solvers\n% assume equality constraints. One great feature of TFOCS\n% is how easy it is to prototype new formulations, so we show\n% here a formulation using inequality constraints.\n% \n% The basic (equality constraint) RPCA formulation is:\n% ( see \n% for references )\n% \n% $$ \\min_{S,L} \\|L\\|_* + \\lambda \\|S\\|_{\\ell_1} \\quad\\textrm{subject to}\\;L+S = X $$\n% \n% The idea is that some object $X$ can be broken into two components $X=L+S$,\n% where $L$ is low-rank and $S$ is sparse. To tease out this separation,\n% RPCA penalizes $\\|L\\|_*$ (the nuclear norm of $L$), which is a proxy for\n% the rank of $L$. We also penalizes $\\|S\\|_{\\ell_1}$ which is just the sum\n% of the absolute value of all the entries of the matrix $S$; this is a proxy\n% for the number of non-zero entries of $S$.\n%\n% The parameter $\\lambda$ is important, as it controls how much weight\n% to put on $S$ relative to $L$. This parameter is not overly sensitive,\n% and we picked the value used in this demo by a few quick rounds of trial-and-error.\n%\n% _Code by Stephen Becker, May 2011_\n\n%% Inequality constraints\n% In this demo, $X$ is a video. In particular, each column of $X$ is the set\n% of $m n$ pixels from a $m \\times n$ pixel frame of the video, reshaped\n% so that it is now a vector instead of a matrix.\n%\n% The particular video we use is not compressed using a video codec, so\n% each frame of the video is stored. This leads to huge files, so to save\n% a bit of space, the value of each pixel is stored as an 8 bit number,\n% which means we can think of it as a value from $0,1,2,\\ldots,255$. Now,\n% we may imagine that there is some \"true\" video where each pixel\n% is a _real_ number between $[0,255]$, and that we see a quantized version of it.\n% It would be nice to apply RPCA to this true version instead of applying \n% it to the quantized version. In particular, it is unlikely that the quantized\n% version can be split nicely into a low-rank and sparse component.\n% To account for this quantization, we will ask that $S+L$ is not exactly equal\n% to $X$, but rather that $S+L$ agrees with $X$ up to the precision\n% of the quantization. The quantization can induce at most an error of .5 in\n% the pixel value (e.g. true value is 5.6, which is rounded to 6.0, so an error of .4;\n% or a true value of 6.4, which is also rounded to 6.0, so also an error of 0.4).\n% A nice way to capture this is via the $\\ell_\\infty$ norm.\n%\n% So, the inequality constrained version of RPCA uses the same objective\n% function, but instead of the constraints $L+S=X$, the constraints are\n%\n% $$ \\|L+S-X\\|_{\\ell_\\infty} \\le 0.5. $$\n\n%% Numerical demo\n% We demonstrate this on a video clip taken from a surveillance\n% camera in a subway station. Not only is there a background\n% and a foreground (i.e. people), but there is an escalator\n% with periodic motion. Conventional background subtraction\n% algorithms would have difficulty with the escalator, but \n% this RPCA formulation easily captures it as part of the low-rank\n% structure.\n% The clip is taken from the data at this website (after\n% a bit of processing to convert it to grayscale):\n% http://perception.i2r.a-star.edu.sg/bk_model/bk_index.html\n\n% Load the data:\nload escalator_data % contains X (data), m and n (height and width)\nX = double(X);\n\n% addpath ~/Dropbox/TFOCS/ % add TFOCS to your path, so change this to suit your computer\n\n\n%%\nnFrames = size(X,2);\n\nlambda = 1e-2;\n\nopts = [];\nopts.stopCrit = 4;\nopts.printEvery = 1;\nopts.tol = 1e-4;\n\nopts.maxIts = 25;\n\nopts.errFcn{1} = @(f,d,p) norm(p{1}+p{2}-X,'fro')/norm(X,'fro');\n\nlargescale = false;\n\nfor inequality_constraints = 0:1\n\n \n if inequality_constraints\n % if we already have equality constraint solution,\n % it would make sense to \"warm-start\":\n% x0 = { LL_0, SS_0 };\n % but it's more fair to start all over:\n x0 = { X, zeros(size(X)) };\n z0 = [];\n else\n x0 = { X, zeros(size(X)) };\n z0 = [];\n end\n \n \n obj = { prox_nuclear(1,largescale), prox_l1(lambda) };\n affine = { 1, 1, -X };\n \n mu = 1e-4;\n if inequality_constraints\n epsilon = 0.5;\n dualProx = prox_l1(epsilon);\n else\n dualProx = proj_Rn;\n end\n \n tic\n % call the TFOCS solver:\n [x,out,optsOut] = tfocs_SCD( obj, affine, dualProx, mu, x0, z0, opts);\n toc\n \n % save the variables\n LL = x{1};\n SS = x{2};\n if ~inequality_constraints\n z0 = out.dual;\n LL_0 = LL;\n SS_0 = SS;\n end\n \nend % end loop over \"inequality_constriants\" variable\n\n%% show all together in movie format\n% If you run this in your own computer, you can see the movie. On the webpage,\n% we have a youtube version of the video.\n% The top row is using equality constraints, and the bottom row\n% is using inequality constraints.\n% The first column of both rows is the same (i.e. it is the original image).\nmat = @(x) reshape( x, m, n );\nfigure();\ncolormap( 'Gray' );\nk = 1;\nfor k = 1:nFrames\n \n imagesc( [mat(X(:,k)), mat(LL_0(:,k)), mat(SS_0(:,k)); ...\n mat(X(:,k)), mat(LL(:,k)), mat(SS(:,k)) ] );\n \n axis off\n axis image\n \n drawnow;\n pause(.05); \n \n if k == round(nFrames/2)\n snapnow; % Take a single still snapshot for publishing the m file to html format\n end\nend\n\n%% Is there a difference between the two versions?\n% Compare the equality constrained version and the inequality\n% constrained version. To do this, we can check whether\n% the \"L\" components are really low rank\n% and whether the \"S\" components are really sparse.\n% Even if the two versions appear visually similar, the variables\n% may behave quite differently with respect to low-rankness\n% and sparsity.\n\nfprintf('\"S\" from equality constrained version has \\t%.1f%% nonzero entries\\n',...\n 100*nnz(SS_0)/numel(SS_0) );\nfprintf('\"S\" from inequality constrained version has \\t%.1f%% nonzero entries\\n',...\n 100*nnz(SS)/numel(SS) );\n\ns = svd(LL); % inequality constraints\ns0 = svd(LL_0); % equality constraints\n\nfprintf('\"L\" from equality constrained version has numerical rank\\t %d (of %d possible)\\n',...\n sum( s0>1e-6), min( m*n, nFrames) );\nfprintf('\"L\" from inequality constrained version has numerical rank\\t %d (of %d possible)\\n',...\n sum( s > 1e-6), min( m*n, nFrames) );\n\nfigure();\nsemilogy( s0 ,'o-') \nhold all;\nsemilogy( s ,'o-')\nlegend('Equality constraints','Inequality constraints');\nxlabel('sorted singular value location');\nylabel('value of singular value');\ntitle('Comparison of RPCA using equality and inequality constraints');\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/rpca/TFOCS/SIAM_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276107, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.7062408975795014}} {"text": "function hpp_test03 ( )\n\n%*****************************************************************************80\n%\n%% HPP_TEST03 tests HEPP_VALUE.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 22 October 2014\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'HPP_TEST03:\\n' );\n fprintf ( 1, ' HePP_VALUE evaluates a Hermite product polynomial.\\n' );\n fprintf ( 1, ' POLYNOMIAL_VALUE evaluates a polynomial.\\n' );\n\n m = 3;\n n = 1;\n seed = 123456789;\n [ x, seed ] = r8vec_uniform_ab ( m, -1.0, +1.0, seed );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Evaluate at X = ( %g, %g, %g )\\n', x(1:3) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Rank I1 I2 I3: He(I1,X1)*He(I2,X2)*He(I3,X3) P(X1,X2,X3)\\n' );\n fprintf ( 1, '\\n' );\n\n for rank = 1 : 20\n\n l = comp_unrank_grlex ( m, rank );\n%\n% Evaluate the HePP directly.\n%\n v1 = hepp_value ( m, n, l, x );\n%\n% Convert the HePP to a polynomial, and reevaluate.\n%\n o_max = prod ( floor ( ( l(1:m) + 2 ) / 2 ) );\n\n [ o, c, e ] = hepp_to_polynomial ( m, l, o_max );\n\n v2 = polynomial_value ( m, o, c, e, n, x );\n%\n% Compare results.\n%\n fprintf ( 1, ' %4d %2d %2d %2d %12g %12g\\n', rank, l(1:m), v1, v2 );\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_product_polynomial/hpp_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7062408932355472}} {"text": "function point_num = levels_index_size_own ( dim_num, level_max )\n\n%*****************************************************************************80\n%\n%% LEVELS_INDEX_SIZE_OWN sizes a sparse grid made from OWN 1D rules.\n%\n% Discussion:\n%\n% The sparse grid is presumed to have been created from products\n% of OPEN WEAKLY NESTED 1D quadrature rules.\n%\n% OWN rules include Gauss Hermite and Gauss Legendre.\n%\n% The sparse grid is the logical sum of product grids with total LEVEL\n% between LEVEL_MIN and LEVEL_MAX.\n%\n% Oddly enough, in order to count the number of points, we will\n% behave as though LEVEL_MIN was zero. This is because our computation\n% concentrates on throwing away all points generated at lower levels,\n% but, in fact, if we start at a nonzero level, we need to include\n% on that level all the points that would have been generated on lower\n% levels.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 July 2008\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 number of points in the grid.\n%\n\n% Special case.\n%\n if ( level_max == 0 )\n point_num = 1;\n return\n end\n%\n% The outer loop generates LEVELs from LEVEL_MIN to LEVEL_MAX.\n%\n% The normal definition of LEVEL_MIN:\n%\n% level_min = max ( 0, level_max + 1 - dim_num )\n%\n% Our somewhat artificial temporary local definition of LEVEL_MIN:\n%\n if ( dim_num == 1 )\n level_min = level_max;\n point_num = 1;\n else\n level_min = 0;\n point_num = 0;\n end\n\n for level = level_min : level_max\n%\n% The middle loop generates the next partition that adds up to LEVEL.\n%\n level_1d = [];\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% Transform each 1D level to a corresponding 1D order.\n%\n order_1d = level_to_order_open ( dim_num, level_1d );\n\n for dim = 1 : dim_num\n%\n% Account for the repetition of the center point.\n%\n if ( 1 < order_1d(dim) )\n order_1d(dim) = order_1d(dim) - 1;\n end\n\t\t\n end\n\n point_num = point_num + prod ( order_1d(1:dim_num) );\n\n if ( ~more )\n break\n end\n\t\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/sandia_sparse/levels_index_size_own.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7062408857444304}} {"text": "function a = chow_inverse ( alpha, beta, n )\n\n%*****************************************************************************80\n%\n%% CHOW_INVERSE returns the inverse of the CHOW 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, 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 A(N,N), the matrix.\n%\n a = zeros ( n, n );\n\n if ( 0.0 == alpha & beta == 0.0 )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHOW_INVERSE - Fatal error!\\n' );\n fprintf ( 1, ' The Chow matrix is not invertible, because\\n' );\n fprintf ( 1, ' ALPHA = 0 and BETA = 0.\\n' );\n error ( 'CHOW_INVERSE - Fatal error!' );\n\n elseif ( 0.0 == alpha & beta ~= 0.0 )\n\n for i = 1 : n\n for j = 1 : n\n\n if ( i <= j )\n a(i,j) = (-1)^(j-i) / beta^(j+1-i);\n else\n a(i,j) = 0.0;\n end\n\n end\n end\n\n return\n\n elseif ( 0.0 ~= alpha & beta == 0.0 )\n\n if ( 1 < n )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHOW_INVERSE - Fatal error!\\n' );\n fprintf ( 1, ' The Chow matrix is not invertible, because\\n' );\n fprintf ( 1, ' BETA = 0 and 1 < N.\\n' );\n error ( 'CHOW_INVERSE - Fatal error!' );\n end\n\n a(1,1) = 1.0 / alpha;\n\n return\n\n end\n\n d(0+1) = 1.0;\n d(1+1) = beta;\n for i = 2 : n\n d(i+1) = beta * d(i-1+1) + alpha * beta * d(i-2+1);\n end\n\n dp(-1+2) = 1.0 / beta;\n dp(0+2) = 1.0;\n dp(1+2) = alpha + beta;\n for i = 2 : n\n dp(i+2) = d(i+1) + alpha * d(i-1+1);\n end\n\n for i = 1 : n\n for j = 1 : i-1\n a(i,j) = - alpha * ( alpha * beta )^(i-j) * dp(j-2+2) * d(n-i+1) ...\n / dp(n+2);\n end\n for j = i : n\n a(i,j) = (-1)^(i+j) * dp(i-1+2) * d(n+1-j+1) / ( beta * dp(n+2) );\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/chow_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7062167243456566}} {"text": "function det = r8plu_det ( n, pivot, lu )\n\n%*****************************************************************************80\n%\n%% R8PLU_DET computes the determinant of an R8PLU matrix.\n%\n% Discussion:\n%\n% The matrix should have been factored by R8MAT_TO_R8PLU.\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% 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, integer PIVOT(N), the pivot vector computed by R8MAT_TO_R8PLU.\n%\n% Input, real LU(N,N), the LU factors computed by R8MAT_TO_R8PLU.\n%\n% Output, real DET, the determinant of the matrix.\n%\n det = 1.0;\n\n for i = 1 : n\n det = det * lu(i,i);\n if ( pivot(i) ~= i )\n det = -det;\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/r8lib/r8plu_det.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.7061844114703603}} {"text": "% this function solves the odometry calibration problem\n% given a measurement matrix Z.\n% We assume that the information matrix is the identity\n% for each of the measurements\n% Every row of the matrix contains\n% z_i = [u'x, u'y, u'theta, ux, uy, ytheta]\n% Z:\tThe measurement matrix\n% X:\tthe calibration matrix\n% returns the correction matrix X\nfunction X = ls_calibrate_odometry(Z)\n % initial solution (the identity transformation)\n X = eye(3); \n\n % TODO: initialize H and b of the linear system \n H = zeros(9);\n b = zeros(9,1);\n omega = eye(3);\n\n % TODO: loop through the measurements and update H and b\n % You may call the functions error_function and jacobian, see below\n % We assume that the information matrix is the identity.\n for i=1:size(Z,1)\n\tH = H + jacobian(i,Z)'*omega*jacobian(i,Z);\n\tb = b + jacobian(i,Z)'*omega'*error_function(i,X,Z);\n endfor\n % TODO: solve and update the solution\n delX = -H\\b;\n X = X + [delX(1:3)';delX(4:6)';delX(7:9)']; \nend\n\n% this function computes the error of the i^th measurement in Z\n% given the calibration parameters\n% i:\tthe number of the measurement\n% X:\tthe actual calibration parameters\n% Z:\tthe measurement matrix, each row contains first the scan-match result\n% and then the motion reported by odometry\n% e:\tthe error of the ith measurement\nfunction e = error_function(i, X, Z)\n % TODO compute the error of each measurement\n e = Z(i,1:3)' - X*Z(i,4:6)';\nend\n\n% derivative of the error function for the ith measurement in Z\n% i:\tthe measurement number\n% Z:\tthe measurement matrix\n% J:\tthe jacobian of the ith measurement\nfunction J = jacobian(i, Z)\n % TODO compute the Jacobian\n J = -[Z(i,4) Z(i,5) Z(i,6) zeros(1,6); zeros(1,3) Z(i,4) Z(i,5) Z(i,6) zeros(1,3); zeros(1,6) Z(i,4) Z(i,5) Z(i,6)];\nend\n", "meta": {"author": "kiran-mohan", "repo": "SLAM-Algorithms-Octave", "sha": "e0254ad38cfca2170b2af68c96c183df77c76252", "save_path": "github-repos/MATLAB/kiran-mohan-SLAM-Algorithms-Octave", "path": "github-repos/MATLAB/kiran-mohan-SLAM-Algorithms-Octave/SLAM-Algorithms-Octave-e0254ad38cfca2170b2af68c96c183df77c76252/7_Odom_Calib_LeastSquares/octave/ls_calibrate_odometry.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.70616036109037}} {"text": "function [ aj, bj, zemu ] = class_matrix ( kind, m, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CLASS_MATRIX computes the Jacobi matrix for a quadrature rule.\n%\n% Discussion:\n%\n% This routine computes the diagonal AJ and subdiagonal BJ\n% elements of the order M tridiagonal symmetric Jacobi matrix\n% associated with the polynomials orthogonal with respect to\n% the weight function specified by KIND.\n%\n% For weight functions 1-7, M elements are defined in BJ even\n% though only M-1 are needed. For weight function 8, BJ(M) is\n% set to zero.\n%\n% The zero-th moment of the weight function is returned in ZEMU.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, integer M, the order of the Jacobi matrix.\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Output, real AJ(M), BJ(M), the diagonal and subdiagonal\n% of the Jacobi matrix.\n%\n% Output, real ZEMU, the zero-th moment.\n%\n temp = eps;\n\n parchk ( kind, 2 * m - 1, alpha, beta );\n\n temp2 = 0.5;\n\n if ( 500.0 * temp < abs ( ( gamma ( temp2 ) )^2 - pi ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CLASS - Fatal error!\\n' );\n fprintf ( 1, ' Gamma function does not match machine parameters.\\n' );\n error ( 'CLASS - Fatal error!' );\n end\n\n bj = zeros(m,1);\n aj = zeros(m,1);\n\n if ( kind == 1 )\n\n ab = 0.0;\n\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod ( i, 2 );\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 2 )\n\n zemu = pi;\n\n aj(1:m) = 0.0;\n\n bj(1) = sqrt ( 0.5 );\n bj(2:m) = 0.5;\n\n elseif ( kind == 3 )\n\n ab = alpha * 2.0;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 )^2 ...\n / gamma ( ab + 2.0 );\n\n aj(1:m) = 0.0;\n bj(1) = 1.0 / ( 2.0 * alpha + 3.0 );\n for i = 2 : m\n bj(i) = i * ( i + ab ) / ( 4.0 * ( i + alpha )^2 - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 4 )\n\n ab = alpha + beta;\n abi = 2.0 + ab;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 ) ...\n * gamma ( beta + 1.0 ) / gamma ( abi );\n aj(1) = ( beta - alpha ) / abi;\n bj(1) = 4.0 * ( 1.0 + alpha ) * ( 1.0 + beta ) ...\n / ( ( abi + 1.0 ) * abi * abi );\n a2b2 = beta * beta - alpha * alpha;\n\n for i = 2 : m\n abi = 2.0 * i + ab;\n aj(i) = a2b2 / ( ( abi - 2.0 ) * abi );\n abi = abi^2;\n bj(i) = 4.0 * i * ( i + alpha ) * ( i + beta ) * ( i + ab ) ...\n / ( ( abi - 1.0 ) * abi );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 5 )\n\n zemu = gamma ( alpha + 1.0 );\n\n for i = 1 : m\n aj(i) = 2.0 * i - 1.0 + alpha;\n bj(i) = i * ( i + alpha );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 6 )\n\n zemu = gamma ( ( alpha + 1.0 ) / 2.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n bj(i) = ( i + alpha * mod ( i, 2 ) ) / 2.0;\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 7 )\n\n ab = alpha;\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod(i,2);\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 8 )\n\n ab = alpha + beta;\n zemu = gamma ( alpha + 1.0 ) * gamma ( - ( ab + 1.0 ) ) ...\n / gamma ( - beta );\n apone = alpha + 1.0;\n aba = ab * apone;\n aj(1) = - apone / ( ab + 2.0 );\n bj(1) = - aj(1) * ( beta + 1.0 ) / ( ab + 2.0 ) / ( ab + 3.0 );\n for i = 2 : m\n abti = ab + 2.0 * i;\n aj(i) = aba + 2.0 * ( ab + i ) * ( i - 1 );\n aj(i) = - aj(i) / abti / ( abti - 2.0 );\n end\n\n for i = 2 : m - 1\n abti = ab + 2.0 * i;\n bj(i) = i * ( alpha + i ) / ( abti - 1.0 ) * ( beta + i ) ...\n / ( abti^2 ) * ( ab + i ) / ( abti + 1.0 );\n end\n\n bj(m) = 0.0;\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 9 )\n\n zemu = pi / 2.0;\n\n aj(1:m) = 0.0;\n\n bj(1:m) = 0.5;\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/toms655/class_matrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7061603502674157}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n% \n% The command invfreqs\n \n\n%verification of the result of the command freqs\nnum=[ -2/j^2 7 0];\nden=[3 0 2];\nw=0:.1:10;\nH=freqs(num,den,w);\nfreqs(num,den,w)\n[num1,den1]=invfreqs(H,w,2,2)\n\n%Equivalent frequency responses\n[num2,den2]=invfreqs(H,w,3,3)\nfreqs(num2,den2,w)\n\nfigure\n[num3,den3]=invfreqs(H,w,10,7);\nfreqs(num3,den3,w)\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/8/c82_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7061076500130234}} {"text": "%% Author: epokh\n%% Website: www.epokh.org/drupy\n%% This software is under GPL\n\n%%Transformation of the end effector frame following the RPY angles in\n%%closed form\n%%input: rotation angles along y,z,x axis expressed in degrees\n\nfunction [RPYmat]=RPY(fia,fio,fin)\n\nRPYmat=[cosd(fia)*cosd(fio),cosd(fia)*sind(fin)*sind(fio)-sind(fia)*cosd(fin),cosd(fia)*sind(fio)*cosd(fin)+sind(fia)*sind(fin),0;\n sind(fia)*cosd(fio),sind(fia)*sind(fio)*sind(fin)+cosd(fia)*cosd(fin),sind(fia)*sind(fio)*cosd(fin)-cosd(fia)*sind(fin),0;\n -sind(fio),cosd(fio)*sind(fin),cosd(fio)*cosd(fin),0;\n 0,0,0,1];\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/14886-robotic-toolbox/RPY.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.7061071074328101}} {"text": "function y = nanvar(x,w,dim)\n%Replacement for Matlab NANVAR Variance function, ignoring NaNs.\n%\n%\n%\n%\n\nif nargin < 2 || isempty(w), w = 0; end\n\nsz = size(x);\nif nargin < 3 || isempty(dim)\n % The output size for [] is a special case when DIM is not given.\n if isequal(x,[]), y = NaN(class(x)); return; end\n\n % Figure out which dimension sum will work along.\n dim = find(sz ~= 1, 1);\n if isempty(dim), dim = 1; end\nelseif dim > length(sz)\n sz(end+1:dim) = 1;\nend\n\n% Need to tile the mean of X to center it.\ntile = ones(size(sz));\ntile(dim) = sz(dim);\n\nif isequal(w,0) || isequal(w,1)\n % Count up non-NaNs.\n n = sum(~isnan(x),dim);\n\n if w == 0\n % The unbiased estimator: divide by (n-1). Can't do this when\n % n == 0 or 1, so n==1 => we'll return zeros\n denom = max(n-1, 1);\n else\n % The biased estimator: divide by n.\n denom = n; % n==1 => we'll return zeros\n end\n denom(n==0) = NaN; % Make all NaNs return NaN, without a divideByZero warning\n\n x0 = x - repmat(nanmean(x, dim), tile);\n y = nansum(abs(x0).^2, dim) ./ denom; % abs guarantees a real result\n\n% Weighted variance\nelseif numel(w) ~= sz(dim)\n error('MATLAB:nanvar:InvalidSizeWgts','The length of W must be compatible with X.');\nelseif ~(isvector(w) && all(w(~isnan(w)) >= 0))\n error('MATLAB:nanvar:InvalidWgts','W must be a vector of nonnegative weights, or a scalar 0 or 1.');\nelse\n % Embed W in the right number of dims. Then replicate it out along the\n % non-working dims to match X's size.\n wresize = ones(size(sz)); wresize(dim) = sz(dim);\n wtile = sz; wtile(dim) = 1;\n w = repmat(reshape(w, wresize), wtile);\n\n % Count up non-NaNs.\n n = nansum(~isnan(x).*w,dim);\n\n x0 = x - repmat(nansum(w.*x, dim) ./ n, tile);\n y = nansum(w .* abs(x0).^2, dim) ./ n; % abs guarantees a real result\nend\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/utilities/nanfunctions/nanvar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7060877415930575}} {"text": "function [mlfcoeffs, R2] = mlffit2(XNodes, YDataPoints, mlfcoeffs0, Precision)\n% \n% Fitting data [XNodes, YDataPoints] by Mittag-Leffler function \n% y(t) = C*t^(beta-1)*E_{alpha, beta}(a*t^alpha)\n% \n% Output: mlfcoeffs(1) = alpha\n% mlfcoeffs(2) = beta\n% mlfcoeffs(3) = C\n% mlfcoeffs(4) = a\n% \n% R2 = sum of squares of vertical offsets \n% of the fitting curve from the data points\n% \n% (C) Igor Podlubny, 2011\n\n% The following is just one-time installation\n% of the necessary packages 8738 and 31069\n% from Matlab Central FIle Exchange (FEX)\n\n% Check if the function 'mlf' from the FEX package 8738\n% (for evaluation of the Mittag-Leffler function)\n% is on your MATLAB path, and if it is not there, \n% require the FEX packages 31069 (\"requireFEXpackage\")\n% and 8738 (\"Mittag-Leffler function\"):\nif ~(exist('mlf', 'file') == 2)\n P = requireFEXpackage(31069); % \"requireFEXpackage\" \n P = requireFEXpackage(8738); % \"Mittag-Leffler function\"\nend\n\n% Also, the function 'fminsearchbnd' (FEX package 8277) is nedeed:\nif ~(exist('fminsearchbnd', 'file') == 2)\n P = requireFEXpackage(8277); % fminsearchbnd is part of 8277\nend\n\n\n% Now, we have MLF.M installed and can do the fitting\n\nc = fminsearchbnd(@(Params) mlfparam(Params, XNodes, Precision, YDataPoints), mlfcoeffs0, ...\n [eps; eps; -Inf; -Inf]);\n\nR2 = sum(c(3)*XNodes.^(c(2)-1).*(mlf(c(1), c(2), c(4)*XNodes.^c(1), Precision) - YDataPoints).^2); \nmlfcoeffs = c; \nend\n\nfunction f = mlfparam(Params, XNodes, Precision, YDataPoints)\nR2 = sum((Params(3)* XNodes.^(Params(2)-1).*mlf(Params(1), Params(2), ...\n Params(4)*XNodes.^Params(1), Precision) - YDataPoints).^2);\nf = R2;\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/32170-fitting-data-using-the-mittag-leffler-function/mlffit2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.7060877370752944}} {"text": "function out = poly(f)\n%POLY Polynomial coefficients of a CHEBTECH.\n% C = POLY(F) returns the polynomial coefficients of F so that \n% F(x) = C(1)*x^N + C(2)*x^(N-1) + ... + C(N)*x + C(N+1)\n% \n% Note that unlike the MATLAB POLY command, CHEBTECH/POLY can operate on\n% array-valued CHEBTECH objects, and hence produce a matrix output. In such\n% instances, the rows of C correspond to the columns of F = [F1, F2, ...].\n% That is, \n% F1(x) = C(1,1)*x^N + C(1,2)*x^(N-1) + ... + C(1,N)*x + C(1,N+1)\n% F2(x) = C(2,1)*x^N + C(2,2)*x^(N-1) + ... + C(2,N)*x + C(2,N+1).\n% This strange behaviour is a result of MATLAB's decision to return a row\n% vector from the POLY command, even for column vector input.\n%\n% See also CHEBCOEFFS, TRIGCOEFFS, LEGCOEFFS.\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% [Mathematical reference]: Section 3.3 Mason & Handscomb, \"Chebyshev\n% Polynomials\". Chapman & Hall/CRC (2003).\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Deal with empty case:\nif ( isempty(f) )\n out = [];\n return\nend\n\n% Flip the Chebyshev coefficients to match Matlab ordering:\ncoeffs = flipud(f.coeffs);\n[n, m] = size(coeffs);\n\n% Coefficients on the unit interval:\nif ( n == 1 )\n % Constant case:\n out = coeffs;\n \nelseif ( n == 2 )\n % Linear case:\n out = coeffs.';\n \nelse\n % General case:\n \n % Initialise working vectors:\n tn = zeros(m, n);\n tnold1 = tn;\n tnold1(:,2) = 1;\n tnold2 = tn;\n tnold2(:,1) = 1;\n zer = zeros(m, 1);\n \n % Transpose coeffs (as output is in this form):\n coeffs = coeffs.';\n \n % Initialise output:\n out = zeros(m, n);\n \n % Initial step:\n out(:,[1,2]) = [ zer coeffs(:,end).*tnold2(:,1) ] + ...\n bsxfun(@times, coeffs(:,end-1), tnold1(:,[2,1]));\n\n % Recurrence:\n for k = 3:n\n tn(:,1:k) = [ zer 2*tnold1(:,1:k-1) ] - [ tnold2(:,1:k-2), zer, zer ];\n out(:,1:k) = bsxfun(@times, coeffs(:,end-k+1), tn(:,k:-1:1)) + ...\n [ zer, out(:,1:k-1) ]; \n tnold2 = tnold1;\n tnold1 = tn;\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/@chebtech/poly.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7956581024858785, "lm_q1q2_score": 0.7059115188077728}} {"text": "function y_line=runline(y,n,dn)\n% Running line fit (local linear regression)\n%\n% Usage: y_line=runline(y,n,dn);\n%\n% Inputs: \n% y: input 1-d time series (real)\n% n: length of running window in samples\n% dn: stepsize of window in samples\n% \n% Outputs:\n% y_line: local line fit to data\n\ny=y(:);\nnt=length(y);\ny_line=zeros(nt,1);\nnorm=y_line;\nnwin=ceil((nt-n)/dn);\nyfit=zeros(nwin,n);\nxwt=((1:n)-n/2)/(n/2);\nwt=(1-abs(xwt).^3).^3;\nfor j=1:nwin, \n\ttseg=y(dn*(j-1)+1:dn*(j-1)+n);\n\ty1=mean(tseg); \n\ty2=mean((1:n)'.*tseg)*2/(n+1);\n\ta=(y2-y1)*6/(n-1); b=y1-a*(n+1)/2;\n\tyfit(j,:)=(1:n)*a+b;\n\ty_line((j-1)*dn+(1:n))=y_line((j-1)*dn+(1:n))+(yfit(j,:).*wt)';\n\tnorm((j-1)*dn+(1:n))=norm((j-1)*dn+(1:n))+wt';\nend\nmask=find(norm>0); y_line(mask)=y_line(mask)./norm(mask);\nindx=(nwin-1)*dn+n-1;\nnpts=length(y)-indx+1;\ny_line(indx:end)=(n+1:n+npts)'*a+b;\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/externalPackages/chronux_2_12/fly_track/FAnalyze/functions/runline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.705911518360742}} {"text": "function value = r4_gamr ( x )\n\n%*****************************************************************************80\n%\n%% R4_GAMR evaluates the reciprocal gamma function of an R4 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 value of the reciprocal gamma\n% function at X.\n%\n if ( x <= 0.0 && r4_aint ( x ) == x )\n\n value = 0.0;\n\n elseif ( abs ( x ) <= 10.0 )\n\n value = 1.0 / r4_gamma ( x );\n\n else\n\n [ alngx, sgngx ] = r4_lgams ( x );\n value = sgngx * exp ( - alngx );\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/r4_gamr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.7059115080605114}} {"text": "function lagrange2D\n%% STARTVARIABLES\n[X,Y]=meshgrid(-1:1:5,-1:1:5);\nZ = sin(Y)*sin(X);\n\nstep = 0.2;\n%% INTERPOLATION\n% erst kurven in x richtung ausrechnen\nxCurves={};\nfor i=1:size(X,1)\n % x vector must be a column vector for the lagrange function\n x = X(i,:)';\n % z vector must be a column vector for the lagrange function\n z = Z(i,:)';\n p=[];\n for j = x(1):step:x(end)\n % interpolate for every parameter value j and add it to p\n p = [p,lagrange(x,z,j)];\n end\n % save curves in x direction\n xCurves{i} = p;\nend\n\ny = Y(:,1);\n% matrix for the graphical outpu\nA=[];\n% interpolate in y-direction\nfor i=1:length(xCurves{1})\n p=[];\n z=[];\n for l=1:length(y)\n z = [z;xCurves{l}(i)];\n end\n for j = y(1):step:y(end)\n % interpolate for every parameter value j and add it to p\n p = [p;lagrange(y,z,j)];\n end\n A = [A,p];\nend\n\n%% GRAPHICAL OUTPUT\n% plot surface\nsurf(x(1):(x(end)-x(1))/(size(A,1)-1):x(end),y(1):(y(end)-y(1))/(size(A,1)-1):y(end),A);\nhold on;\n% plot points\nfor i=1:size(X,1)\n for j=1:size(Y,1)\n p = plot3(X(i,j),Y(i,j),Z(i,j));\n set(p,'Marker','.');\n set(p,'MarkerSize',30);\n end\nend\n\nend\n%% nested functions\nfunction res = lagrange(x,z,t)\n% lagrange interpolation in 1d\n% input: x...vektor, welcher die x (bzw. y) Werte beinhaltet\n\nres = 0;\nfor i=1:length(x)\n % delete the component not needed\n temp = [x(1:i-1);x(i+1:end)];\n \n denominator = x(i)-temp;\n \n numerator = t-temp;\n res = res + z(i)*(prod(numerator))/(prod(denominator));\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/25962-lagrange-interpolation-in-2d/lagrange2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384593, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7058994695570827}} {"text": "% Demonstration for EKF using a random sine signal model. \n%\n% A Very simple demonstration for extended Kalman filter (EKF), which is\n% used to track a random single-component sinusoid signal,\n% which is modelled as x_k = a_k*sin(\\theta_k), dtheta/dt = omega_k.\n% The signal is also filtered with unscented Kalman filter (UKF) for\n% comparison.\n%\n% Copyright (C) 2007 Jouni Hartikainen\n%\n% This software is distributed under the GNU General Public \n% Licence (version 2 or later); please refer to the file \n% Licence.txt, included with the software, for details.\n\nclc;\ndisp('Filtering the signal with EKF...');\n\nsave_plots = 1;\n\n% Measurement model and it's derivative\nf_func = @ekf_sine_f;\nh_func = @ekf_sine_h;\ndh_dx_func = @ekf_sine_dh_dx;\nd2h_dx2_func = @ekf_sine_d2h_dx2;\n\n% Initial values for the signal.\nf = 0;\nw = 10;\na = 1;\n \n% Number of samples and stepsize.\nd = 5;\nn = 500;\ndt = d/n;\nx = 1:n;\n\n% Check the derivative of the measurement function.\nder_check(h_func, dh_dx_func, 1, [f w a]');\n\n% Dynamic state transition matrix in continous-time domain.\nF = [0 1 0;\n 0 0 0;\n 0 0 0];\n \n% Noise effect matrix in continous-time domain.\nL = [0 0;\n 1 0;\n 0 1];\n \n% Spectral power density of the white noise.\nq1 = 0.2;\nq2 = 0.1;\nQc = diag([q1 q2]);\n \n% Discretize the plant equation.\n[A,Q] = lti_disc(F,L,Qc,dt);\n \n% Generate the real signal.\nX = zeros(3, n);\nX(:,1) = [f w a]';\nfor i = 2:n\n X(:,i) = A*X(:,i-1) + gauss_rnd([0 0 0]', Q);\nend \n \n% Generate the observations with Gaussian noise.\nsd = 1;\nR = sd^2;\n\nY = zeros(1,n);\nY_real = feval(h_func,X); \nY = Y_real + gauss_rnd(0,R,n);\n \nplot(x,Y,'.',x,Y_real)\n \n% Initial guesses for the state mean and covariance.\nM = [f w a]';\nP = diag([3 3 3]); \n \n% Reserve space for estimates.\nMM = zeros(size(M,1),size(Y,2));\nPP = zeros(size(M,1),size(M,1),size(Y,2));\n\n% Estimate with EKF\nfor k=1:size(Y,2)\n [M,P] = ekf_predict1(M,P,A,Q);\n [M,P] = ekf_update1(M,P,Y(:,k),dh_dx_func,R*eye(1),h_func);\n MM(:,k) = M;\n PP(:,:,k) = P;\nend\n\n% Initial guesses for the state mean and covariance.\nM = [f w a]';\nP = diag([3 3 3]); \n \n% Reserve space for estimates.\nMM2 = zeros(size(M,1),size(Y,2));\nPP2 = zeros(size(M,1),size(M,1),size(Y,2));\n\n% Estimate with EKF\nfor k=1:size(Y,2)\n [M,P] = ekf_predict1(M,P,A,Q);\n [M,P] = ekf_update2(M,P,Y(:,k),dh_dx_func,d2h_dx2_func,R*eye(1),h_func);\n MM2(:,k) = M;\n PP2(:,:,k) = P;\nend\n\nclf; clc;\ndisp('The filtering results using the 1st order EKF is now displayed')\n\n% Project the estimates to measurement space \nY_m = feval(h_func, MM);\nY_m2 = feval(h_func, MM2);\nplot(x,Y,'.', x,Y_real,'--',x,Y_m);\nlegend('Measurements','Real signal', 'Filtered estimate');\nxlim([0 ceil(max(x))]);\ntitle('Estimating a random Sine signal with extended Kalman filter.');\n\nif save_plots\n print -dpsc demo2_f1.ps \nend\n\nclc;\ndisp('The filtering result using the 1st order EKF is now displayed.');\nfprintf('Smoothing the estimates using the RTS smoother...');\n\n[SM1,SP1] = erts_smooth1(MM,PP,A,Q);\n\n[SM2,SP2] = etf_smooth1(MM,PP,Y,A,Q,[],[],[],...\n dh_dx_func,R*eye(1),h_func); \n\n[SM1_2,SP1_2] = erts_smooth1(MM2,PP2,A,Q);\n\n[SM2_2,SP2_2] = etf_smooth1(MM2,PP2,Y,A,Q,[],[],[],...\n dh_dx_func,R*eye(1),h_func); \n\nfprintf('ready.\\n');\ndisp(' ');\ndisp('Push any button to display the smoothing results.');\npause\n\nY_s1 = feval(h_func, SM1);\nplot(x,Y,'.', x, Y_real,'--',x,Y_s1);\nlegend('Measurements','Real signal','Smoothed estimate');\nxlim([0 ceil(max(x))]);\ntitle(['Smoothing a random Sine signal with extended ',...\n 'Kalman (RTS) smoother.']);\n\nif save_plots\n print -dpsc demo2_f2.ps\nend\n\nclc;\ndisp('The smoothing results using the ERTS smoother is now displayed.');\ndisp(' ');\ndisp('Push any button to see the smoothing results of a ETF smoother.');\npause\n \nY_s2 = feval(h_func, SM2);\nplot(x,Y,'.', x, Y_real,'--',x,Y_s2);\nlegend('Measurements','Real signal','Smoothed estimate');\ntitle(['Smoothing a random Sine signal with extended ',...\n 'Kalman (Two Filter) smoother.']);\nxlim([0 ceil(max(x))]);\n\nif save_plots\n print -dpsc demo2_f3.ps\nend\n\nclc;\ndisp('The smoothing results using the ETF smoother is now displayed.');\n\n\nY_s1_2 = feval(h_func, SM1_2);\nY_s2_2 = feval(h_func, SM2_2);\n% Errors. \nEMM_Y = sum((Y_m-Y_real).^2)/n;\nEMM_Y2 = sum((Y_m2-Y_real).^2)/n;\nESM1_Y = sum((Y_s1-Y_real).^2)/n;\nESM2_Y = sum((Y_s2-Y_real).^2)/n;\nESM1_2_Y = sum((Y_s1_2-Y_real).^2)/n;\nESM2_2_Y = sum((Y_s2_2-Y_real).^2)/n;\n \ndisp(' ');\nfprintf('Filtering now with UKF...');\n\n% In the rest the signal is filtered with UKF for comparison.\n\n% Initial guesses for the state mean and covariance.\nM = [f w a]';\nP = diag([3 3 3]); \n \n% Reserve space for estimates.\nU_MM = zeros(size(M,1),size(Y,2));\nU_PP = zeros(size(M,1),size(M,1),size(Y,2));\n\n% Estimate with UKF\nfor k=1:size(Y,2)\n [M,P,X_s,w] = ukf_predict3(M,P,f_func,Q,R*eye(1),dt);\n [M,P] = ukf_update3(M,P,Y(:,k),h_func,R*eye(1),X_s,w,[]);\n U_MM(:,k) = M;\n U_PP(:,:,k) = P;\nend\n[U_SM, U_SP] = urts_smooth1(U_MM,U_PP,f_func,Q,dt);\n\nfprintf('ready.\\n')\ndisp(' ');\ndisp('Push any button to see the filtering results.');\npause\n\nY_m_u = feval(h_func, U_MM);\nplot(x,Y,'.', x, Y_real,'--',x,Y_m_u);\nlegend('Measurements','Real signal', 'Filtered estimate');\nxlim([0 ceil(max(x))]);\ntitle('Estimating a random Sine signal with unscented Kalman filter.');\n\nclc;\ndisp('The filtering results of a UKF are now displayed.')\ndisp(' ');\ndisp('Push any button to display the smoothing results.');\npause\n \nY_m_su = feval(h_func, U_SM);\nplot(x,Y,'.', x, Y_real,'--',x,Y_m_su);\nlegend('Measurements','Real signal', 'Filtered estimate');\nxlim([0 ceil(max(x))]);\ntitle('Estimating a random Sine signal with unscented Kalman smoother (RTS).');\n\nclc;\ndisp('The smoothing results of a ERTS smoother are now displayed');\n\nUKF_EMM_Y = sum((Y_m_u-Y_real).^2)/n;\nURTS_EMM_Y = sum((Y_m_su-Y_real).^2)/n;\n\ndisp(' ');\ndisp('Mean square errors of all estimates:');\nfprintf('EKF1-MSE = %.4f\\n',sqrt(EMM_Y));\nfprintf('ERTS-MSE = %.4f\\n',sqrt(ESM1_Y));\nfprintf('ETF-MSE = %.4f\\n',sqrt(ESM2_Y));\nfprintf('EKF2-MSE = %.4f\\n',sqrt(EMM_Y2));\nfprintf('ERTS2-MSE = %.4f\\n',sqrt(ESM1_2_Y));\nfprintf('ETF2-MSE = %.4f\\n',sqrt(ESM2_2_Y));\nfprintf('UKF-RMSE = %.4f\\n',sqrt(UKF_EMM_Y));\nfprintf('URTS-RMSE = %.4f\\n',sqrt(URTS_EMM_Y));\n\n", "meta": {"author": "EEA-sensors", "repo": "ekfukf", "sha": "d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8", "save_path": "github-repos/MATLAB/EEA-sensors-ekfukf", "path": "github-repos/MATLAB/EEA-sensors-ekfukf/ekfukf-d08550a5b14caac525e51ed4ef5ec0ef1ea3e8f8/demos/ekf_sine_demo/ekf_sine_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7058994551137151}} {"text": "function [res,fval,it] = muller (f,Z0,itmax,ztol,ftol,option)\n% MULLER find a zero of a real or complex function Y = F(Z)\n% \n% Syntax:\n%\n% RES = MULLER (F,Z0) find the zero of a complex or real function \n% 'F' (either an anonymous function or .m function) using three initial \n% guesses contained in the vector Z0. Muller takes the function F and\n% evaluetes it at each initial point using feval. F doesn't need to be\n% vectorized.\n% The initial guesses can be real or complex numbers close to the zero, \n% bracketing the zero is not necessary. Parameters ITMAX, ZTOL and\n% FTOL are set by default to 1000, 1e-5 and 1e-5, respectively.\n%\n% RES = MULLER (F,Z0,ITMAX) the maximum number of iterations is set\n% equal to ITMAX. ZTOL and FTOL are set by default with the values mentioned\n% above.\n%\n% RES = MULLER (F,Z0,ITMAX,ZTOL) ZTOL is used as a stopping\n% criterion. If the absolute difference between the values of Z found in\n% the two latest iterations is less than ZTOL, the program is stopped. FTOL\n% is set by default with the value mentioned above.\n%\n% RES = MULLER (F,Z0,ITMAX,ZTOL,FTOL) FTOL is used as a stopping\n% criterion. If the value of the function F at the Z found in the last\n% iteration is less than FTOL, the program is stopped.\n%\n% RES = MULLER (F,Z0,ITMAX,ZTOL,FTOL,'both') indicate that both\n% criteria ZTOL and FTOL must be satisfied simultaneously. By default, \n% MULLER stops if one of the two criteria is fulfilled.\n%\n% [RES,FVAL] = MULLER (F,Z0,...) return the value of the function \n% F at the Z found in the last iteration.\n%\n% [RES,FVAL,IT] = MULLER (F,Z0,...) return the number of iterations\n% used to find the zero.\n%\n% Example 1:\n% myf = @(x) (x-1)^3; \n% \n% muller(myf,[0 0.1 0.2],[],[],[],'both')\n% ans = \n% 1.0000 + 0.0000i\n%\n% Example 2:\n% \n% [res,fval,it] = muller2('cosh',[0 0.1 0.2],[],[],[],'both')\n% \n% res = \n% 0.0000 + 1.5708i\n%\n% fval = \n% 5.5845e-012 + 3.0132e-012i\n% \n% it =\n% 5\n%\n% Method taken from:\n% Numerical Recipes: The art of scientific computing\n% W.H. Press; B.P. Flannery; S.A. Teukolsky; W.T. Vetterling\n% 1986\n%\n% Thanks to John D'Errico for his helpfull review.\n%\n% Written by Daniel H. Cortes\n% MAE Department, West Virginia University\n% March, 2008.\n%\n\n\n%=================================================\n% Checking proper values of the input parameters\n%=================================================\n\n\nif nargin > 6\n error ('Too many arguments.')\nelseif nargin < 2\n error('Too few arguments.')\nend\n\nif nargin < 6\n opt = 1;\nelseif ischar(option) == 1\n if size(option,2) == 4\n if sum(option == 'both') == 4\n opt = 2;\n else\n error ('Option parameter must be *both*.')\n end\n else\n error ('Option parameter must be *both*.')\n end\nelse\n error ('Option parameter must be a character array (string).')\nend\n\n\nif nargin < 5\n ftol = 1e-5;\nelseif isnumeric(ftol) ~= 1\n error ('FTOL must be a numeric argument.')\nelseif isempty(ftol) == 1\n ftol = 1e-5;\nelseif size(ftol,1) ~= 1 || size(ftol,2) ~= 1\n error ('FTOL cannot be an array')\nend\n\n\nif nargin < 4\n ztol = 1e-5;\nelseif isnumeric(ztol) ~= 1\n error ('ZTOL must be a numeric argument.')\nelseif isempty(ztol) == 1\n ztol = 1e-5;\nelseif size(ztol,1) ~= 1 || size(ztol,2) ~= 1\n error ('ZTOL cannot be an array.')\nend\n\n\nif nargin < 3\n itmax = 1000;\nelseif isnumeric(itmax) ~= 1\n error ('ITMAX must be a numeric argument.')\nelseif isempty(itmax) == 1\n itmax = 1000;\nelseif size(itmax,1) ~= 1 || size(itmax,2) ~= 1\n error ('ITMAX cannot be an array.')\nend\n\n\nif isnumeric(Z0) ~= 1\n error ('Z0 must be a vector of three numeric arguments.')\nelseif isempty(Z0) == 1 || length(Z0) ~= 3 || min(size(Z0)) ~= 1\n error ('Z0 must be a vector of length 3 of either complex or real arguments.')\nend\n\nif Z0(1)==Z0(2) || Z0(1)==Z0(3) || Z0(2)==Z0(3)\n error('The initial guesses must be different')\nend\n\n%=============================\n% Begining of Muller's method\n%=============================\n\nz0 = Z0(1);\nz1 = Z0(2);\nz2 = Z0(3);\n\ny0 = feval ( f, z0);\ny1 = feval ( f, z1);\ny2 = feval ( f, z2);\n\nfor it = 1:itmax\n q = (z2 - z1)/(z1 - z0);\n A = q*y2 - q*(1+q)*y1 + q^2*y0;\n B = (2*q + 1)*y2 - (1 + q)^2*y1 + q^2*y0;\n C = (1 + q)*y2;\n\n if ( A ~= 0 )\n\n disc = B^2 - 4*A*C;\n\n den1 = ( B + sqrt ( disc ) );\n den2 = ( B - sqrt ( disc ) );\n\n if ( abs ( den1 ) < abs ( den2 ) )\n z3 = z2 - (z2 - z1)*(2*C/den2);\n else\n z3 = z2 - (z2 - z1)*(2*C/den1);\n end\n\n elseif ( B ~= 0 )\n z3 = z2 - (z2 - z1)*(2*C/B);\n else\n warning('Muller Method failed to find a root. Last iteration result used as an output. Result may not be accurate')\n res = z2;\n fval = y2;\n return\n end\n\n y3 = feval ( f, z3);\n \n if opt == 1\n if ( abs (z3 - z2) < ztol || abs ( y3 ) < ftol )\n res = z3;\n fval = y3;\n return\n end\n else\n if ( abs (z3 - z2) < ztol && abs ( y3 ) < ftol )\n res = z3;\n fval = y3;\n return\n end\n end\n \n z0 = z1;\n z1 = z2;\n z2 = z3;\n\n y0 = y1;\n y1 = y2;\n y2 = y3;\n\nend\n\nres = z2;\nfval = y2;\nwarning('Maximum number of iterations reached. Result may not be accurate')\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/19050-muller/muller.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.7058869298512225}} {"text": "function pdf = arcsin_pdf ( x, a )\n\n%*****************************************************************************80\n%\n%% ARCSIN_PDF evaluates the Arcsin PDF.\n%\n% Discussion:\n%\n% The LOGISTIC EQUATION has the form:\n%\n% X(N+1) = 4.0D+00 * LAMBDA * ( 1.0D+00 - X(N) ).\n%\n% where 0 < LAMBDA <= 1. This nonlinear difference equation maps\n% the unit interval into itself, and is a simple example of a system\n% exhibiting chaotic behavior. Ulam and von Neumann studied the\n% logistic equation with LAMBDA = 1, and showed that iterates of the\n% function generated a sequence of pseudorandom numbers with\n% the Arcsin probability density function.\n%\n% The derived sequence\n%\n% Y(N) = ( 2 / PI ) * Arcsin ( SQRT ( X(N) ) )\n%\n% is a pseudorandom sequence with the uniform probability density\n% function on [0,1]. For certain starting values, such as X(0) = 0, 0.75,\n% or 1.0D+00, the sequence degenerates into a constant sequence, and for\n% values very near these, the sequence takes a while before becoming\n% chaotic.\n%\n% PDF(X) = 1 / ( PI * Sqrt ( A**2 - X**2 ) )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Daniel Zwillinger and Stephen Kokoska,\n% CRC Standard Probability and Statistics Tables and Formulae,\n% Chapman and Hall/CRC, 2000, pages 114-115.\n%\n% Parameters:\n%\n% Input, real X, the argument of the PDF.\n% -A < X < A.\n%\n% Input, real A, the parameter of the CDF.\n% A must be positive.\n%\n% Output, real PDF, the value of the PDF.\n%\n if ( a <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ARCSIN_PDF - Fatal error!\\n' );\n fprintf ( 1, ' Parameter A must be positive.\\n' );\n error ( 'ARCSIN_PDF - Fatal error!' );\n end\n\n if ( x <= -a | a <= x )\n pdf = 0.0;\n else\n pdf = 1.0 / ( pi * sqrt ( a * a - x * 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/prob/arcsin_pdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7058869260223908}} {"text": "function [kli, set_kli]= KLIndex(ar_est,ma_est,varx_est,ar,ma,varx,n_obs)\n\n%KLIndex Kullback-Leibler index.\n% kli = KLIndex(a_est,b_est,varx_est,a,b,varx,nobs) is the exact Kullbach-Leibler\n% Index between two time series models for nobs observations.\n% The estimated proces a_est, b_est,var_est and the true process a,b,varx are assumed\n% to be normally distributed.\n%\n% Possible second output argument: set of KLI's of AR models of increasing autoregressive\n% model order:\n% [kli set_kli] = KLIndex(a_est,b_est,varx_est,a,b,varx,nobs)\n\n%S. de Waele, Februari 2003.\n\nrc = ar_ma2rc(ar,ma,n_obs);\nar_order = length(rc)-1;\nrc_est = ar_ma2rc(ar_est,ma_est,n_obs);\nar_est_order = length(rc_est)-1;\n\n%Kullback-Leiber index of the estimated process\n%with respect to the true process: kli_fef.\nvarp_est = varx_est*[1 cumprod(1-rc_est(2:end).^2)];\n\n%Prediction errors (vareta)\nset_ar_est = rc2arset(rc_est,0:ar_est_order);\ncov = varx*arma2cor(ar,ma,ar_est_order);\ncovs = [cov(end:-1:2) cov];\nfor L = 0:ar_est_order,\n par_est = set_ar_est{1+L};\n sh = ar_est_order+L+1;\n vareta(L+1) = convol(par_est,convol(covs,par_est(end:-1:1)),sh,sh);\nend\n\nL = 0:ar_est_order; \nset_kli_fef = cumsum(log(varp_est)) + cumsum(vareta./varp_est) ...\n + (n_obs-L-1).*(log(varp_est) + vareta./varp_est);\n\nset_kli = set_kli_fef;\nkli = set_kli(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/3680-automatic-spectral-analysis/AutomaticSpectra/KullbackLeibler/KLIndex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.7058570368551084}} {"text": "function varargout = goertzel(x,fs,ft,N,varargin)\n% GOERTZEL Goertzel Algorithm.\n%\n% [RE,IM] = GOERTZEL(X,FS,FT,N) calculates the goertzel algorithm\n% for X, considering a sampling frequency FS, the target\n% frequency FT and using a block of size N.\n%\n% [MAG,PHASE] = GOERTZEL(...,'mag') returns the magnitude and\n% phase information of the transform.\n%\n% [...] = GOERTZEL(...,'overlap',OL) will perform the calculation\n% on blocks that overlap. The amount of overlapping is defined by\n% OL, and can be set from 0 to 1.\n%\n\n[mag,OL] = parse_inputs(varargin{:});\n\nif size(x,1)~=1 & size(x,2)~=1\n error('X must be a vector.')\nend\n\nflag_rot = 0;\nif size(x,2) == 1\n flag_rot = 1;\n x = x';\nend\n\nn = length(x);\nk = 1*(0.5+N*ft/fs);\nw = 2*pi*k/N;\nc = cos(w);\ns = sin(w);\ncoef = 2*c;\nADV = max(round((1-OL)*N),1);\n\nre = zeros(1,floor(n/ADV));\nim = re;\n\nfor j = 1 : floor((n-N)/ADV)\n q1 = 0;\n q2 = 0;\n for i = 1 : N\n q0 = coef*q1 - q2 + x(i+(j-1)*ADV);\n q2 = q1;\n q1 = q0;\n end\n re(j) = q1 - q2*c;\n im(j) = q2*s;\nend\n\nif mag == 0\n varargout{1} = re;\n varargout{2} = im;\nelse\n ma = sqrt(re.^2 + im.^2);\n ph = angle(re+i*im);\n \n varargout{1} = ma;\n varargout{2} = ph;\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction [mag,OL] = parse_inputs(varargin)\n\nmag = 0;\nOL = 0;\nflag_par = 0;\n\nfor i = 1 : nargin\n if flag_par == 1\n flag_par = 0;\n continue\n elseif strcmp(varargin{i},'mag')\n mag = 1;\n elseif strcmp(varargin{i},'overlap')\n if nargin == i \n error('OL not defined.')\n end\n flag_par = 1;\n OL = varargin{i+1};\n else\n error('Unknown parameter.')\n end\nend\n\nif OL>1 | OL<0\n error('OL should be set inside the interval [0,1].')\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/3127-dtmf-detector/goertzel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.70578466910971}} {"text": "function [beta_median beta_std beta_lbound beta_ubound sigma_median]=olsestimates(betahat,sigmahat,X,k,q,cband)\n\n\n\n% function [beta_median beta_std beta_lbound beta_ubound sigma_median]=olsestimates(betahat,sigmahat,X,k,q,cband)\n% estimates the posterior mean, standard deviation and confidence interval for the VAR coefficients of an OLS VAR model\n% inputs: - vector 'betahat': OLS VAR coefficientsm in vectorised form (defined in 1.1.15) \n% - matrix 'sigmahat': OLS VAR variance-covariance matrix of residuals (defined in 1.1.10)\n% - matrix 'X': matrix of regressors for the VAR model (defined in 1.1.8)\n% - integer 'k': number of coefficients to estimate for each equation in the BVAR model (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% - scalar 'cband': confidence level for VAR coefficients\n% outputs: - vector 'beta_median': median value of the posterior distribution of beta\n% - vector 'beta_std': standard deviation of the posterior distribution of beta\n% - vector 'beta_lbound': lower bound of the credibility interval of beta\n% - vector 'beta_ubound': upper bound of the credibility interval of beta\n% - vector 'sigma_median': median value of the posterior distribution of sigma (vectorised)\n\n\n\n% compute the point estimate of beta\nbeta_median=betahat;\n% compute estimates for the variance of each coefficient\n% first obtain omeagahat, the (OLS) variance-covariance matrix for betahat, from (a.9.1)\nomegahat=kron(sigmahat,(X'*X)\\speye(k));\n% consider only the diagonal (variance terms), and take the square root of each element\nbeta_std=diag(omegahat).^0.5;\n% build the confidence intervals\nfor ii=1:q\nbeta_lbound(ii,:)=norminv((1-cband)/2,beta_median(ii,1),beta_std(ii,1));\nbeta_ubound(ii,:)=norminv(1-(1-cband)/2,beta_median(ii,1),beta_std(ii,1));\nend\n\n\nsigma_median=sigmahat;\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/olsestimates.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7057846670998658}} {"text": "function r1 = rOneCalculation(fracFreq)\n%method for caculating r1 used in identifying noise type for a giving tau\n%value. input argument is array of fractrional frequency values for a given\n%tau. \n%r1 = <(Zi - Zavg)*(Zi+1 - Zavg)> / <(Zi - Zavg)^2>\n%Z is fractional freq values. Numerator sum is from 1 to N-1 and demonator\n%is from 1 to N\n\navgFF = mean(fracFreq); %get average value \nN = length(fracFreq); %get number of frac freq value in array\nn=0; %store numerator of r1\nj=0; %store denomenator of r1\n\n%This loop builds the numerator for r1\nfor i = 1:(N-1)\n if i == 1\n n = (fracFreq(i) - avgFF)*(fracFreq(i+1) - avgFF);\n else\n n = n + (fracFreq(i) - avgFF)*(fracFreq(i+1) - avgFF);\n end\nend\n%this loop builds the denomentor for r1\nfor i = 1:N\n if i == 1\n j = (fracFreq(i) - avgFF)^2;\n else\n j = j + (fracFreq(i) - avgFF)^2;\n end\nend\n\n%calculate and return r1\nr1 = n/j; \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/31319-stability-analyzer-53230a/Stability Analyzer 2.0/rOneCalculation.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7057846530172079}} {"text": "function [labels rts] = graph_connected_components(C)\n% C - connection matrix\n% labels =[1 1 1 2 2 3 3 ...] lenght(labels)=L, label for each vertex\n% labels(i) is order number of connected component, i is vertex number\n% rts - roots, numbers of started vertex in each component\n\nL=size(C,1); % number of vertex\n\n% Breadth-first search:\nlabels=zeros(1,L); % all vertex unexplored at the begining\nrts=[];\nccc=0; % connected components counter\nwhile true\n ind=find(labels==0);\n if ~isempty(ind)\n fue=ind(1); % first unexplored vertex\n rts=[rts fue];\n list=[fue];\n ccc=ccc+1;\n labels(fue)=ccc;\n while true\n list_new=[];\n for lc=1:length(list)\n p=list(lc); % point\n cp=find(C(p,:)); % points connected to p\n cp1=cp(labels(cp)==0); % get only unexplored vertecies\n labels(cp1)=ccc;\n list_new=[list_new cp1];\n end\n list=list_new;\n if isempty(list)\n break;\n end\n end\n else\n break;\n end\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/33877-find-graph-conected-components/graph_connected_components.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7056284684472741}} {"text": "function [T, M, S, DISTR, df] = dtiTTestStat(g1, g2, Y, mask)\n\n% Computes voxel-wise T-test statistics for two groups from a data array.\n%\n% [T, M, S, DISTR, df] = dtiTTestStat(g1, g2, DT_ARRAY, [MASK])\n%\n% Input:\n% g1, g2 List of indices that correspond to each group out of 1:N\n% E.g: g1 = 1:7, g2 = 8:14, N = 14\n% DT_ARRAY Data array of size XxYxZxN (or nxN), where X, Y, Z are the volume\n% dimensions and N is the number of subjects.\n% (n is the number of voxels).\n% MASK Optional XxYxZ binary array. Values of M and S are computed\n% where mask = 1; in other voxels, M and S are set to 0.\n% Default is entire volume.\n%\n% Output:\n% T XxYxZx1 array of test statistics (0 where mask = 0)\n% M XxYxZx2 array of means for both groups (0 where mask = 0)\n% S XxYxZx1 array of pooled standard deviations (0 where mask = 0)\n% DISTR The string 't'\n% df The number of degrees of freedom = N-2\n%\n% Utilities: ndfun.m, dtiSplitTensor.m, dti33to6.m\n%\n% WARNING: If using Pentium 4, eliminate NaN's from array before running\n% (processor bug).\n%\n% Copyright by Armin Schwartzman, 2005\n\n% HISTORY:\n% 2004.06.23 ASH (armins@stanford.edu) wrote it.\n%\n\n% Check inputs\nif (ndims(Y)==2 | ndims(Y)==3),\n Ind = 1; % Data in indexed nxN format\n Y = shiftdim(Y, -2);\nelse\n Ind = 0; % Data in XxYxZxN format\nend\nif (ndims(Y)<4 | ndims(Y)>5),\n error('Wrong input format');\nend\nif (~exist('mask')),\n mask = ones([size(Y,1) size(Y,2) size(Y,3)]);\nend\n\n% Computations\nN1 = length(g1);\nN2 = length(g2);\nN = N1 + N2;\n\nM = cat(4, mean(Y(:,:,:,g1), 4), mean(Y(:,:,:,g2), 4));\nYstd1 = std(Y(:,:,:,g1), 1, 4); Ystd1(~mask) = 1;\nYstd2 = std(Y(:,:,:,g2), 1, 4); Ystd2(~mask) = 1;\nS = sqrt((N1*Ystd1.^2 + N2*Ystd2.^2)/(N-2) .* (1/N1 + 1/N2));\nT = (M(:,:,:,1) - M(:,:,:,2)) ./ S;\n\n% Adjust output\nif Ind,\n T = shiftdim(T, 2);\n M = shiftdim(M, 2);\n S = shiftdim(S, 2);\nend\n\nDISTR = 't';\ndf = [N-2 N-2]; % Second entry is dummy\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/mrDiffusion/statistics/dtiTTestStat.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.798186784940666, "lm_q1q2_score": 0.7056284671809607}} {"text": " function [mean_pos,ma_pos] = mean_posit_track(t,s,tau,train_len)\n%| function [mean_pos,ma_pos] = mean_posit_track(t,s,tau,train_len)\n%| INPUT\n%|\tt: time indices\n%|\ts: position sequence (should be same length as t)\n%|\ttau: delay parameter,\n%|\t\tset to be the equivalence index to about 0.5sec for breathing.\n%|\ttrain_Len: training length (starting up stage),\n%|\t\tapproximately one period's equivalence\n%|\n%| OUTPUT\n%|\tmean_pos: a N*2 matrix,\n%|\t\tfor practical purposes, take the first column mean_pos(:,1)\n%|\tma_pos: naive moving average.\n%|\n%| Dan Ruan, University of Michigan, 2007\n%|\n%| Based on the paper by Dan Ruan, J A Fessler, James M Balter\n%| Mean position tracking of respiratory motion\n%| Med. Phys. 35(2):782-92, Feb. 2008\n%| doi 10.1118/1.2825616\n\nif nargin < 1, help(mfilename), error(mfilename), end\nif streq(t, 'test'), self_test, return, end\n\ns_complete = s;\ns_d = s(1:end-tau);\ns = s(tau+1:end);\nfor tt = 1:length(t)-train_len-tau;\n s_temp = s(tt:tt+train_len);\n sd_temp = s_d(tt:tt+train_len);\n params = fitellipse(s_temp,sd_temp);\n mean_pos(tt,:) = [params(1),params(2)];\n ma_pos(tt) = mean(s(tt:tt+train_len));\nend\n\nplot(t,s_complete,'linewidth',2);\nhold on\nplot(t(1+tau+train_len:end),ma_pos,'g:','linewidth',2);\nplot(t(1+tau+train_len:end),mean_pos(:,1),'r--','linewidth',2);\nhold off\nset(gca,'DataAspectRatio',[5 5 1]);\nset(gca,'fontsize',14,'FontWeight','demi');\nh = axis;\naxis(h + [0 0 -1 1]);\nxlabel('time (second)');\nylabel('displacement');\nlegend('Observation','Estimation with MA','Estimate with Ellipse Center','Location','SouthWest');\n\n\n%\nfunction a = fitellipse(X,Y)\n% fit ellipse with sample locations in X,Y\n% normalize data\nmx = mean(X);\nmy = mean(Y);\nsx = (max(X)-min(X))/2;\nsy = (max(Y)-min(Y))/2; \n\nx = (X-mx)/sx;\ny = (Y-my)/sy;\n\n% Force to column vectors\nx = x(:);\ny = y(:);\n\n% Build design matrix\nD = [ x.*x x.*y y.*y x y ones(size(x)) ];\n\n% Build scatter matrix\nS = D'*D;\n\n% Build 6x6 constraint matrix\nC(6,6) = 0; C(1,3) = -2; C(2,2) = 1; C(3,1) = -2;\n\n \n % Break into blocks\n tmpA = S(1:3,1:3); \n tmpB = S(1:3,4:6); \n tmpC = S(4:6,4:6); \n tmpD = C(1:3,1:3);\n tmpE = inv(tmpC)*tmpB';\n [evec_x, eval_x] = eig(inv(tmpD) * (tmpA - tmpB*tmpE));\n \n % Find the positive (as det(tmpD) < 0) eigenvalue\n I = find(real(diag(eval_x)) < 1e-8 & ~isinf(diag(eval_x)));\n \n % Extract eigenvector corresponding to negative eigenvalue\n A = real(evec_x(:,I));\n \n % Recover the bottom half...\n evec_y = -tmpE * A;\n A = [A; evec_y];\n\n\n\n% unnormalize\npar = [\n A(1)*sy*sy, ...\n A(2)*sx*sy, ...\n A(3)*sx*sx, ...\n -2*A(1)*sy*sy*mx - A(2)*sx*sy*my + A(4)*sx*sy*sy, ...\n -A(2)*sx*sy*mx - 2*A(3)*sx*sx*my + A(5)*sx*sx*sy, ...\n A(1)*sy*sy*mx*mx + A(2)*sx*sy*mx*my + A(3)*sx*sx*my*my ...\n - A(4)*sx*sy*sy*mx - A(5)*sx*sx*sy*my ...\n + A(6)*sx*sx*sy*sy ...\n ]';\n\n% Convert to geometric radii, and centers\n\nthetarad = 0.5*atan2(par(2),par(1) - par(3));\ncost = cos(thetarad);\nsint = sin(thetarad);\nsin_squared = sint.*sint;\ncos_squared = cost.*cost;\ncos_sin = sint .* cost;\n\nAo = par(6);\nAu = par(4) .* cost + par(5) .* sint;\nAv = - par(4) .* sint + par(5) .* cost;\nAuu = par(1) .* cos_squared + par(3) .* sin_squared + par(2) .* cos_sin;\nAvv = par(1) .* sin_squared + par(3) .* cos_squared - par(2) .* cos_sin;\n\n% ROTATED = [Ao Au Av Auu Avv]\n\ntuCentre = - Au./(2.*Auu);\ntvCentre = - Av./(2.*Avv);\nwCentre = Ao - Auu.*tuCentre.*tuCentre - Avv.*tvCentre.*tvCentre;\n\nuCentre = tuCentre .* cost - tvCentre .* sint;\nvCentre = tuCentre .* sint + tvCentre .* cost;\n\nRu = -wCentre./Auu;\nRv = -wCentre./Avv;\n\nRu = sqrt(abs(Ru)).*sign(Ru);\nRv = sqrt(abs(Rv)).*sign(Rv);\n\na = [uCentre, vCentre, Ru, Rv, thetarad];\n\n\n% self_test\nfunction self_test\nt = linspace(0, 60, 601);\ndt = t(2) - t(1);\ns = (8 + cos(2*pi/6*t)).^2 - 8^2;\ntau = round(0.5 / dt);\ntrain_len = round(5.1 / dt);\n\n[mean_pos ma_pos] = mean_posit_track(t, s, tau, train_len);\n\nprompt\ntt = t(tau+train_len+1:end);\nclf, plot(t, s, '-', tt, mean_pos(:,1), '--', tt, ma_pos, ':', 'linewidth', 2)\nlegend('signal', 'proposed', 'moving avg')\nxlabel t\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/ruan/mean_posit_track.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7056210026102434}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n\n\n\n\n%problem 3 - Inverse Fourier Transform of sin(w)/w\n\nsyms t w\nX=sin(w)/w;\nx=ifourier(X,t)\nezplot(x, [-3 3])\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/6/c69c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7056209992163343}} {"text": "function v = sum2(f) \n%SUM2 Double integral of a SPHEREFUN over its domain.\n% I = SUM2(F) returns the double definite integral of a SPHEREFUN.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n% Split f into its plus/minus terms. The minus terms have integral zero \n% on the sphere since the rows in this case are anti-periodic with period\n% pi. Thus, we only need to integrate the plus terms.\n\n[cols, d, rows] = cdr(f);\n\n% If there are no plus terms then the integral is zero\nif ( isempty(f.idxPlus) )\n v = 0;\n return\nend\n\ncols = cols(:, f.idxPlus); % Just keep the plus terms\nrows = rows(:, f.idxPlus);\nd = diag(d(f.idxPlus, f.idxPlus)).';\n\n% Integrate the rows over their domain.\nintRows = sum(rows);\n\n% One could use the following code to do the integrals in latitude (theta),\n% but this can be slow due to the fact that the integrand (which are\n% trigfuns) may first be converted to chebfuns when sum (with an interval\n% other than the period of the integrand) is called. Mathematically, this\n% is, of course, unnecessary and I tried arguing that this should not be\n% the case. However, I was not successful in convincing everyone and so we\n% are stuck with a potentially slow method to do definite integrals rather\n% than a fast one. See ticket numbers #1004 and #1034 for more details.\n%\n% We are going to do the integral the fast way.\n\n% Slow code: Left here in case someone ever makes sum(f,[a,b]) fast for\n% trigfuns.\n%\n% % Create a trigfun of the measure for the sphere.\n% measure = chebfun(@(x) sin(x), f.domain(3:4), 'trig');\n% \n% % Multiply the columns by the measure\n% cols = cols.*(measure*ones(1, size(cols, 2)));\n% \n% % Integrate each column over the non-doubled up latitude coordinate.\n% intCols = sum(cols, [0 pi]);\n\n%\n% Fast code: We know the columns are even functions, which means they have\n% cosine series expansions:\n% col(:, j) = sum_{k=0}^{m} a_k cos(k*t)\n% So, in the case of the elevation angle being measured as co-latitude, we\n% want to compute the integral\n% int_{0}^{pi}col(:,j).*sin(t)dt = sum_{k=0}^{m} a_k int_{0}^{pi}cos(k*t).*sin(t)dt\n% This simplifies down to\n% int_{0}^{pi}col(:,j).*sin(t)dt = sum_{k=0}^{m} a_k (1+(-1)^k)/(1-k^2)\n\n[a, ignore] = trigcoeffs(cols);\n\nk = (0:size(a, 1)-1).';\nintFactor = 2./(1-k(1:2:end).^2);\nintCols = sum(bsxfun(@times, a(1:2:end, :), intFactor));\n\n% Put the integrals together to get the final result.\nv = sum(d.*intRows.*intCols);\n\n% TODO: Add support for different domains.\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/sum2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7056209965948909}} {"text": "function [w, infos] = subsamp_svrg(problem, options)\n% Sabsampled SVRG algorithm.\n%\n% Inputs:\n% problem function (cost/grad/hess)\n% options options\n% Output:\n% w solution of w\n% infos information\n%\n% References:\n% Subsampled SVRG:\n% R. Kolte, M. Erdogdu and A. Ozgur, \n% \"Accelerating SVRG via second-order information,\" \n% OPT2015, 2015.\n%\n% \n% Created by H.Kasai on Oct. 28, 2016\n% Modified by H.Kasai on Mar. 25, 2018\n\n\n % set dimensions and samples\n d = problem.dim();\n n = problem.samples();\n \n\n % extract options \n if ~isfield(options, 'stepsizefun')\n options.stepsizefun = @stepsize_alg;\n else\n end\n \n if ~isfield(options, 'tol_optgap')\n tol_optgap = 1.0e-12;\n else\n tol_optgap = options.tol_optgap;\n end \n\n if ~isfield(options, 'batch_size')\n batch_size = 10;\n else\n batch_size = options.batch_size;\n end\n \n if batch_size > n\n batch_size = n;\n end \n num_of_bachces = floor(n / batch_size); \n \n if ~isfield(options, 'max_epoch')\n max_epoch = 100;\n else\n max_epoch = options.max_epoch;\n end \n \n if ~isfield(options, 'r')\n r = inf;\n else\n r = options.r;\n end \n \n if r > d + 1\n r = d - 1;\n end\n \n if ~isfield(options, 'w_init')\n w = randn(d,1);\n else\n w = options.w_init;\n end \n \n if ~isfield(options, 'f_opt')\n options.f_opt = -Inf;\n end \n \n if ~isfield(options, 'permute_on')\n permute_on = 1;\n else\n permute_on = options.permute_on;\n end \n \n if ~isfield(options, 'verbose')\n verbose = false;\n else\n verbose = options.verbose;\n end\n \n if ~isfield(options, 'store_w')\n options.store_w = false;\n end \n \n \n % initialize\n total_iter = 0; \n epoch = 0;\n grad_calc_count = 0;\n w = options.w_init;\n num_of_bachces = floor(n / options.batch_size); \n\n % store first infos\n clear infos; \n [infos, f_val, optgap] = store_infos(problem, w, options, [], epoch, grad_calc_count, 0); \n \n %\n sample_size = round(10*r*log(d)); \n \n % set start time\n start_time = tic();\n \n % display infos\n if verbose > 0\n fprintf('Sub-sampled SVRG: Epoch = %03d, cost = %.16e, optgap = %.4e\\n', epoch, f_val, optgap);\n end \n\n % main loop\n while (optgap > tol_optgap) && (epoch < max_epoch)\n\n % permute samples\n if permute_on\n perm_idx = randperm(n);\n else\n perm_idx = 1:n;\n end\n\n % compute full gradient\n full_grad = problem.grad(w,1:n);\n % store w\n w0 = w;\n grad_calc_count = grad_calc_count + n; \n\n % calculated Hessian using subsamples every outer loop\n sub_indices = datasample((1:n), sample_size); \n H = problem.hess(w, sub_indices); \n [u, sigma,~] = svd(H);\n Q = u(:,1:r); \n gamma = sigma(r+1,r+1);\n sigma = sigma(1:r,1:r);\n Sing_inv_gamma = diag(1./diag(sigma)) - diag(ones(r,1)/gamma);\n \n \n for j = 1 : num_of_bachces\n \n % update step-size\n step = options.stepsizefun(total_iter, options); \n \n % calculate variance reduced gradient\n start_index = (j-1) * batch_size + 1;\n indice_j = perm_idx(start_index:start_index+batch_size-1);\n grad = problem.grad(w, indice_j);\n grad_0 = problem.grad(w0, indice_j);\n grad_est = full_grad + grad - grad_0; \n \n % update w\n v = -Q*(Sing_inv_gamma)*(Q' * grad_est) - (1/gamma)*grad_est;\n w = w + step * v;\n \n % proximal operator\n if ismethod(problem, 'prox')\n w = problem.prox(w, step);\n end \n \n total_iter = total_iter + 1;\n end\n \n % measure elapsed time\n elapsed_time = toc(start_time);\n \n % count gradient evaluations\n grad_calc_count = grad_calc_count + j * batch_size + sample_size; \n epoch = epoch + 1;\n \n % store infos\n [infos, f_val, optgap] = store_infos(problem, w, options, infos, epoch, grad_calc_count, elapsed_time); \n\n % display infos\n if verbose > 0\n fprintf('Sub-sampled SVRG: Epoch = %03d, cost = %.16e, optgap = %.4e\\n', epoch, f_val, optgap);\n end\n end\n \n if optgap < tol_optgap\n fprintf('Optimality gap tolerance reached: tol_optgap = %g\\n', tol_optgap);\n elseif epoch == max_epoch\n fprintf('Max epoch reached: max_epochr = %g\\n', max_epoch);\n end \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/sgd_solver/subsamp_svrg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.7056209793212977}} {"text": "function cvx_optval = sum_largest( x, k, dim )\n\n%SUM_LARGEST Sum of the largest k values of a vector.\n% For a real vector X and an integer k between 1 and length(X) inclusive,\n% y = SUM_LARGEST(X,k) is the sum of the k largest elements of X; e.g.,\n% temp = sort( x )\n% y = sum( temp( 1 : k ) )\n% If k=1, then SUM_LARGEST(X,k) is equivalent to MAX(X); if k=length(X),\n% then SUM_LARGEST(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_LARGEST(X,k)=0. If k > length(X), then\n% SUM_LARGEST(X,k)=SUM(X). Non-integer values of k interpolate linearly\n% between their integral neighbors.\n%\n% For matrices, SUM_LARGEST(X,k) is a row vector containing the\n% application of SUM_LARGEST to each column. For N-D arrays, the\n% SUM_LARGEST operation is applied to the first non-singleton dimension\n% of X.\n%\n% SUM_LARGEST(X,k,DIM) performs the operation along dimension DIM of X.\n%\n% Disciplined convex programming information:\n% SUM_LARGEST(X,...) is convex and nondecreasing in X. Thus, when\n% used in CVX expressions, X must be convex (or affine). k and DIM\n% must both be constant.\n\n%\n% Check arguments\n%\n\nnarginchk(2,3);\nif ~isreal( x ),\n error( 'First argument must be real.' );\nelseif ~isnumeric( k ) || ~isreal( k ) || length( k ) ~= 1,\n error( 'Second argument must be a real scalar.' );\nelseif nargin < 3 || isempty( dim ),\n dim = cvx_default_dimension( size( x ) );\nelseif ~cvx_check_dimension( dim, false ),\n error( 'Third argument, if supplied, must be a positive integer.' );\nend\n\n%\n% Determine output size\n%\n\nsx = size( x );\nnd = max( dim, length( sx ) );\nsx = [ sx, ones( 1, dim - nd ) ];\nsy = sx;\nsy( dim ) = 1;\n\n%\n% Compute results\n%\n\nif k <= 0,\n\n cvx_optval = zeros( sy );\n\nelseif k <= 1,\n\n cvx_optval = k * max( x, [], dim );\n\nelseif k >= sx( dim ),\n\n cvx_optval = sum( x, dim );\n\nelse\n\n ck = ceil( k );\n x = sort( x, dim );\n ndxs = cell( 1, nd );\n [ ndxs{:} ] = deal( ':' );\n ndxs{ dim } = size( x, dim ) - ( 0 : ck - 1 );\n x = x( ndxs{ : } );\n if k ~= ck,\n ndxs{ dim } = ck;\n x( ndxs{ : } ) = ( k - floor( k ) ) * x( ndxs{ : } );\n end\n cvx_optval = sum( x, dim );\n\nend\n\n% Copyright 2005-2016 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/functions/sum_largest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7056166969199305}} {"text": "function triangle_plots ( )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_PLOTS plots the surface and the R(Theta) function for a triangle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 May 2013\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGLE_PLOTS:\\n' );\n fprintf ( 1, ' For a 2D triangle defined by a 0/1 characteristic function,\\n' );\n fprintf ( 1, ' plot the surface, and R(Theta),\\n' );\n fprintf ( 1, ' using a centered point, and then an offcentered point.\\n' );\n%\n% 1): Plot the surface, using a centered base point.\n%\n n = 61;\n theta = linspace ( 0.0, 2.0 * pi, n );\n\n f = zeros(n,1);\n x0 = [ 2.0 / 3.0, 1.0 / 3.0 ];\n for i = 1 : n\n r(i) = bisect_characteristic ( x0, theta(i), @triangle_characteristic );\n end\n x = x0(1) + r(1:n) .* cos ( theta(1:n) );\n y = x0(2) + r(1:n) .* sin ( theta(1:n) );\n\n xc = x0(1) + 0.5 .* cos ( theta(1:n) );\n yc = x0(2) + 0.5 .* sin ( theta(1:n) );\n\n clf\n hold on\n plot ( x0(1), x0(2), 'b.', 'MarkerSize', 50 );\n plot ( xc, yc, 'b-', 'LineWidth', 2 );\n plot ( x, y, 'ro', 'LineWidth', 3 );\n axis equal\n grid on\n xlabel ( '<---X--->', 'FontSize', 24 );\n ylabel ( '<---Y--->', 'FontSize', 24 );\n title ( 'Triangle transition surface', 'FontSize', 24)\n hold off\n filename = 'triangle_centered_surface.png';\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Created plotfile \"%s\".\\n', filename );\n%\n% 2): Plot R as a function of Theta for a centered base point.\n%\n plot ( theta, r, 'LineWidth', 3 );\n xlabel ( '<---Theta--->', 'FontSize', 24 )\n ylabel ( '<---R(Theta)--->', 'FontSize', 24 )\n title ( 'R(Theta) from base point to surface', 'FontSize', 24 )\n grid on\n filename = 'triangle_centered_plot.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Created plotfile \"%s\".\\n', filename );\n%\n% 3): Plot the surface, using an offcentered base point.\n%\n n = 61;\n theta = linspace ( 0.0 , 2.0 * pi, n );\n\n f = zeros(n,1);\n x0 = [ 1.0, 1.50 ];\n for i = 1 : n\n r(i) = bisect_characteristic ( x0, theta(i), @triangle_characteristic );\n end\n\n x = x0(1) + r(1:n) .* cos ( theta(1:n) );\n y = x0(2) + r(1:n) .* sin ( theta(1:n) );\n%\n% Coordinates of nominal triangle around (x0,y0), to\n% suggest coordinate system.\n%\n xc = x0(1) + 0.5 .* cos ( theta(1:n) );\n yc = x0(2) + 0.5 .* sin ( theta(1:n) );\n\n clf\n hold on\n plot ( x0(1), x0(2), 'b.', 'MarkerSize', 50 );\n plot ( xc, yc, 'b-', 'LineWidth', 2 );\n plot ( x, y, 'ro', 'LineWidth', 3 );\n axis equal\n grid on\n xlabel ( '<---X--->', 'FontSize', 24 );\n ylabel ( '<---Y--->', 'FontSize', 24 );\n title ( 'Triangle transition surface', 'FontSize', 24 )\n hold off\n filename = 'triangle_offcentered_surface.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Created plotfile \"%s\".\\n', filename );\n%\n% 4): Plot R as a function of Theta for an offcentered base point.\n%\n plot ( theta, r, 'LineWidth', 3 );\n xlabel ( '<---Theta--->', 'FontSize', 24 )\n ylabel ( '<---R(Theta)--->', 'FontSize', 24 )\n title ( 'R(Theta) from base point to surface', 'FontSize', 24 )\n grid on\n filename = 'triangle_offcentered_plot.png';\n print ( '-dpng', filename );\n fprintf ( 1, ' Created plotfile \"%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/hypersphere_surface/triangle_plots.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7056166932285377}} {"text": "function x = dvand ( n, alpha, b )\n\n%*****************************************************************************80\n%\n%% DVAND solves a Vandermonde system A' * x = b.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 14 November 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Ake Bjorck, Victor Pereyra,\n% Solution of Vandermonde Systems of Equations,\n% Mathematics of Computation,\n% Volume 24, Number 112, October 1970, pages 893-903.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real ALPHA(N), the parameters that define the matrix.\n% The values should be distinct.\n%\n% Input, real B(N), the right hand side of the linear system.\n%\n% Output, real X(N), the solution of the linear system.\n%\n x(1:n) = b(1:n);\n\n for k = 1 : n - 1\n for j = n : -1 : k + 1\n x(j) = ( x(j) - x(j-1) ) / ( alpha(j) - alpha(j-k) );\n end\n end\n\n for k = n - 1 : -1 : 1\n for j = k : n - 1\n x(j) = x(j) - alpha(k) * x(j+1);\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/vandermonde/dvand.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.7056007388609257}} {"text": "function points = intersectLineSphere(line, sphere, varargin)\n %INTERSECTLINESPHERE Return intersection points between a line and a sphere\n %\n % PTS = intersectLineSphere(LINE, SPHERE);\n % Returns the two points which are the intersection of the given line and\n % sphere.\n % LINE : [x0 y0 z0 dx dy dz]\n % SPHERE : [xc yc zc R]\n % PTS : [x1 y1 z1 ; x2 y2 z2]\n % If there is no intersection between the line and the sphere, return a\n % 2-by-3 array containing only NaN.\n %\n % Example\n % % draw the intersection between a sphere and a collection of parallel\n % % lines\n % sphere = [50.12 50.23 50.34 40];\n % [x, y] = meshgrid(10:10:90, 10:10:90);\n % n = numel(x);\n % lines = [x(:) y(:) zeros(n,1) zeros(n,2) ones(n,1)];\n % figure; hold on; axis equal;\n % axis([0 100 0 100 0 100]); view(3);\n % drawSphere(sphere);\n % drawLine3d(lines);\n % pts = intersectLineSphere(lines, sphere);\n % drawPoint3d(pts, 'ro');\n %\n % See also\n % spheres, circles3d, intersectPlaneSphere\n %\n % ---------\n % author : David Legland\n % INRA - TPV URPOI - BIA IMASTE\n % created the 18/02/2005.\n %\n % HISTORY\n % 2011-06-21 bug for tangent lines, add tolerance\n % Process input arguments\n % check if user-defined tolerance is given\n tol = 1e-14;\n if ~isempty(varargin)\n tol = varargin{1};\n end\n % difference between centers\n dc = bsxfun(@minus, line(:, 1:3), sphere(:, 1:3));\n % equation coefficients\n a = sum(line(:, 4:6) .* line(:, 4:6), 2);\n b = 2 * sum(bsxfun(@times, dc, line(:, 4:6)), 2);\n c = sum(dc.*dc, 2) - sphere(:,4).*sphere(:,4);\n % solve equation\n delta = b.*b - 4*a.*c;\n % initialize empty results\n points = NaN * ones(2 * size(delta, 1), 3);\n % process couples with two intersection points\n % proces couples with two intersection points\n inds = find(delta > tol);\n if ~isempty(inds)\n % delta positive: find two roots of second order equation\n u1 = (-b(inds) -sqrt(delta(inds))) / 2 ./ a(inds);\n u2 = (-b(inds) +sqrt(delta(inds))) / 2 ./ a(inds);\n \n % convert into 3D coordinate\n points(inds, :) = line(inds, 1:3) + bsxfun(@times, u1, line(inds, 4:6));\n points(inds+length(delta),:) = line(inds, 1:3) + bsxfun(@times, u2, line(inds, 4:6));\n end\n % process couples with one intersection point\n % proces couples with two intersection points\n inds = find(abs(delta) < tol);\n if ~isempty(inds)\n % delta around zero: find unique root, and convert to 3D coord.\n u = -b(inds) / 2 ./ a(inds);\n \n % convert into 3D coordinate\n pts = line(inds, 1:3) + bsxfun(@times, u, line(inds, 4:6));\n points(inds, :) = pts;\n points(inds+length(delta),:) = pts;\n end\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/math/intersectLineSphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.7056007272478494}} {"text": "function [cap res] = pll_synth_3rd_order(ipump, vco_sensitivity, fout, fcomp, bandwidth, pm)\n\n% Synthesizes PLL loop components for a 3rd order system using the\n% topology shown below. \n%\n% Input - 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% - bandwidth is the open loop bandwidth in Hertz\n% - pm is the phase margin in degrees\n% Output - cap is the capacitors of the loop in Farads [C1, C2, C3, 0]\n% - res is the resistors of the loop in Ohms [ R2, R3, 0] \n%\n%\n% The method used here is derived from that 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 22 pp.178-185.\n%\n% No closed form solution exists for 3rd \n% order systems, therefore some simplification of the model has been made \n% to derive the results. Due to the simplifications the results will \n% also not always be 100% accurate. It is recommended that the \n% results are verified using the pll_simulation.m script, which does not\n% use a simplified model.\n% Loop Topology\n% \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% 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\n%% Design Parameters\n% The following values will give sensible results but not necessarily\n% optimal\nT31 = 0.6; % T3/T1 ratio of time constants\ngamma = 1.0; % optimization factor p172 and pp220-227 of Banerjee\n\n% Conversion of parameters to more convenient units\nKpd = ipump/2/pi; % phase detector gain\nKvco = vco_sensitivity*2*pi; % vco gain\nomega = 2*pi* bandwidth; % open loop bandwidth in radians/sec\n\n%% Synthesis\n%% Find T1 using numerical methods\nt1 = (sec(pm*pi/180)-tan(pm*pi/180))/(omega*(1+T31)); % approximate value for T1\n\n% T1 is the root of this equation\nnum1 = @(t) atan(gamma./(omega.*t*(1+T31)))-atan(omega.*t)-atan(omega.*t*T31)- pm*pi/180;\nT1 = fzero(num1,t1);% find root numerically \n\n%% Find T2 and T3\nT3 = T1*T31;\nT2 = gamma/omega^2/(T1+T3);\n\n%% Solving for Loop Components\nA0 = Kpd * Kvco * fcomp/fout / omega^2 * sqrt((1+omega^2*T2^2)/(1+omega^2*T1^2)/(1+omega^2*T3^2));\nA1 = A0*(T1+T3);\nA2 = A0*T1*T3;\n\nC1 = A2/T2^2*(1+sqrt(1+T2/A2*(T2*A0-A1)));\nC3 = (-T2^2*C1^2+T2*A1*C1-A2*A0)/(T2^2*C1-A2);\nC2 = A0-C1-C3;\nR2 = T2/C2;\nR3 = A2/C1/C3/T2;\n\ncap = [C1 C2 C3 0];\nres = [R2 R3 0];\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_synth_3rd_order.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.705595268591777}} {"text": "function [U,s,V] = csvd(A,tst)\n%CSVD Compact singular value decomposition.\n%\n% s = csvd(A)\n% [U,s,V] = csvd(A)\n% [U,s,V] = csvd(A,'full')\n%\n% Computes the compact form of the SVD of A:\n% A = U*diag(s)*V',\n% where\n% U is m-by-min(m,n)\n% s is min(m,n)-by-1\n% V is n-by-min(m,n).\n%\n% If a second argument is present, the full U and V are returned.\n\n% Per Christian Hansen, IMM, 06/22/93.\n\nif (nargin==1)\n if (nargout > 1)\n [m,n] = size(A);\n if (m >= n)\n [U,s,V] = svd(full(A),0); s = diag(s);\n else\n [V,s,U] = svd(full(A)',0); s = diag(s);\n end\n else\n U = svd(full(A));\n end\nelse\n if (nargout > 1)\n [U,s,V] = svd(full(A)); s = diag(s);\n else\n U = svd(full(A));\n end\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/ext/csvd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787563, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7055672698019388}} {"text": "function varargout = ellipsoid( a, b, c )\n%ELLIPSOID Generate an ellipsoid-like surface. (Not necessarily an ellipsoid!)\n% ELLIPSOID(A,B,C), where A, B, and C are CHEBFUN2 objects on the domain [0\n% pi]x[0 2*pi] plots the \"ELLIPSOID\" of semi axis lengths A(th,phi),\n% B(th,phi), and C(th,phi).\n%\n% [X Y Z]=ELLIPSOID(A,B,C) returns X, Y, and Z as CHEBFUN2 objects such that\n% SURF(X,Y,Z) plots an ELLIPSOID of semi axis lengths A(th,phi), B(th,phi),\n% and C(th,phi).\n% \n% F = ELLIPSOID(A,B,C) returns the CHEBFUN2V representing the ELLIPSOID\n% SURF(F) plots the ELLIPSOID.\n%\n% Omitting output arguments causes the ELLIPSOID command to be displayed with\n% a SURF command and no outputs are returned.\n%\n% For the ellipsoid: \n% a = chebfun2(@(th,phi) 1+0*th,[0 pi 0 2*pi]);\n% F = ellipsoid(a,2*a,3*a); surf(F)\n%\n% For a badly shaped ship: \n% a = chebfun2(@(th,phi) th,[0 pi 0 2*pi])\n% F = ellipsoid(a,2*a,cos(2*a)+.25); surf(F)\n%\n% See also SPHERE, CYLINDER.\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 < 3 )\n error('CHEBFUN:CHEBFUN2:ellipsoid:inputs', 'Incorrect input arguments.');\nend\n\n% ELLIPSOID with axis lengths a(th,phi), b(th,phi), c(th,phi). \ndom = [0 pi 0 2*pi]; \nth = chebfun2(@(th, phi) th, dom);\nphi = chebfun2(@(th, phi) phi, dom);\n\nx = a.*sin(th).*cos(phi);\ny = b.*sin(th).*sin(phi);\nz = c.*cos(th);\n\nif ( nargout == 0 )\n surf(x, y, z)\n axis equal\nelseif ( nargout == 1 )\n varargout = { [x ; y ; z] };\nelse\n varargout = { x, y, z };\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/@chebfun2/ellipsoid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.7055621922993464}} {"text": "function [ m, d ] = easter_ds ( y )\n\n%*****************************************************************************80\n%\n%% EASTER_DS computes the month and day of Easter for a Gregorian year.\n%\n% Example:\n%\n% Input:\n%\n% Y = 2000\n%\n% Output:\n%\n% M = 4\n% D = 23\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 June 2012\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Peter Duffett-Smith,\n% Practical Astronomy With Your Calculator,\n% Third Edition,\n% Cambridge University Press, 1996,\n% ISBN: 0-521-35699-7,\n% LC: QB62.5.D83.\n%\n% Parameters:\n%\n% Input, integer Y, the year, which must be 1583 or greater.\n% (The formula is only valid for years after the Gregorian calendar\n% was adopted.)\n%\n% Output, integer M, D, the month and day of Easter.\n%\n if ( y <= 0 )\n m = -1;\n d = -1;\n return\n end\n\n a = year_to_golden_number ( y );\n\n a = a - 1;\n\n b = floor ( y / 100 );\n c = mod ( y, 100 );\n\n dd = floor ( b / 4 );\n e = mod ( b, 4 );\n\n f = floor ( ( b + 8 ) / 25 );\n g = floor ( ( b - f + 1 ) / 3 );\n h = mod ( 19 * a + b - dd - g + 15, 30 );\n\n i = floor ( c / 4 );\n k = mod ( c, 4 );\n\n l = mod ( 32 + 2 * e + 2 * i - h - k, 7 );\n mm = floor ( ( a + 11 * h + 22 * l ) / 451 );\n\n m = floor ( ( h + l - 7 * mm + 114 ) / 31 );\n d = mod ( h + l - 7 * mm + 114, 31 ) + 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/calpak/easter_ds.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.7053587750782158}} {"text": "function KC = slcenkernel(K0, K, w)\n%SLCENKERNEL Compute the centralized kernel matrix\n%\n% $ Syntax $\n% - KC = slcenkernel(K0)\n% - KC = slcenkernel(K0, [], w)\n% - KC = slcenkernel(K0, K)\n% - KC = slcenkernel(K0, K, w)\n%\n% $ Arguments $\n% - K0: the gram matrix of the referenced samples\n% - K: the kernel matrix for target samples\n% - w: the weights for the referenced samples\n% - KC: the centralized kernel matrix.\n%\n% $ Description $\n% - KC = slcenkernel(K0) compute the centralized kernel matrix from\n% the original kernel gram matrix K0.\n% \n% - KC = slcenkernel(K, [], w) compute the centralized kernel gram\n% matrix from the original kernel gram matrix K0. The mean feature\n% is obtained with the weights for referenced samples, given by w.\n%\n% - KC = slcenkernel(K0, K) compute the centralized kernel matrix\n% for target samples, with the original gram matrix for referenced\n% samples K0 and the kernel matrix for target samples w.r.t the \n% referenced samples K given.\n%\n% - KC = slcenkernel(K0, K, w) compute the centralied kernel matrix\n% for target samples, with feature mean computed in a weighted \n% manner.\n%\n% $ Remarks $\n% -# For original kernel matrix K, it is defined as \n% K(i, j) = , given that phi(i) and phi(j) are\n% the feature map of the samples x(i) and x(j) respectively.\n% Then the centralized kernel matrix is defined as\n% KC(i, j) = , where\n% mean_phi is the mean of all referenced feature maps. If w\n% is specified mean_phi is given by weighted mean. \n% Kernel centralization plays an important role in many \n% kernelized algorithms such as Kernel PCA.\n%\n% -# Suppose the mean feature map is defined by \n% mean_phi = sum_i w_i phi(i).\n% Then the centralized kernel gram matrix can be written as\n% KC = K - 1 * (w^T * K) - (K * w) * 1^T + 1 * (w^T * K * w) * 1^T.\n% It can be easily shown that the mean of columns (rows) of KC is\n% a zero vector. Thus, centralize the centralized kernel matrix\n% would keep the input unchanged. \n%\n% -# Instead of applying the formula given above, the function \n% implements a more efficient computational routine by reducing\n% the redundant computations.\n%\n% $ History $\n% - Created by Dahua Lin on May 2nd, 2006\n% - Modified by Dahua Lin on Sep 10, 2006\n% - use sladdrowcols to replace sladd to increase efficiency\n%\n\n%% parse and verify input arguments\n\n% for K0\nn0 = size(K0, 1);\nif ndims(K0) ~= 2 || size(K0, 2) ~= n0;\n error('sltoolbox:invaliddims', ...\n 'K0 should be a 2D square matrix');\nend\n\n% for K\nif nargin < 2 || isempty(K)\n K = K0;\nelse\n if ndims(K) ~= 2\n error('sltoolbox:invaliddims', ...\n 'K should be a 2D matrix');\n end\n if size(K, 1) ~= n0\n error('sltoolbox:sizmismatch', ...\n 'Size inconsistency between K0 and K');\n end\nend\n \n% for w \nif nargin < 3 || isempty(w)\n isweighted = false;\nelse\n if ~isequal(size(w), [1, n0])\n error('sltoolbox:sizmismatch', ...\n 'Size inconsistency between K0 and w');\n end \n isweighted = true;\nend\n\n\n%% compute\n\n% Steps:\n% 1. compute v1: mean row vector of K (1 x n)\n% 2. compute v2: mean column vector of K0 (n x 1)\n% 3. compute s3: mean value of of all elements of K0 (1 x 1)\n% 4. KC = K - expand(v1) - expand(v2) + s3\n\nif ~isweighted % non-weighted case\n\n v1 = sum(K, 1) * (1 / n0);\n v2 = sum(K0, 2) * (1 / n0);\n s3 = sum(v2) * (1 / n0);\n \nelse % weighted case\n \n w = w / sum(w); % normalize the weights\n \n v1 = w * K;\n v2 = K0 * w';\n s3 = w * v2;\n \nend\n\nKC = sladdrowcols(K, -v1, -v2+s3);\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/kernel/slcenkernel.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.7053587703030173}} {"text": "function data = create_synthetic_dataset(data)\n% create_synthetic_dataset creates test data for running nldr algorithms.\n%\n% inputs:\n% data a struct describing the test data\n% .dataset the number of the example, see code for more infos\n% .n the number of data points (default=400)\n% .state the initial state for the random numbers (default=0)\n% .noise the variance of Gaussian noise to add (default=0)\n% other options for some of the data sets (see code)\n% alternatively, data = 1 chooses the dataset directly,\n% the number of points defaults to 1000\n%\n% outputs:\n% data a struct containing .x the generated data, each column is\n% a data point, and other stuff:\n% .z the \"correct\" embedding\n% .e some random noise of same dimensionality\n% .x_noisefree the noisefree version of .x, i.e.\n% .x = .xnoise_free + sqrt(.noise) * .e\n%\n% Adapted from create.m, originally written by\n% (c) Stefan Harmeling, 2006\n% using the examples of the original LLE and ISOMAP code.\n\nif ~isfield(data, 'dataset'), \n number = data;\n clear data\n data.dataset = number;\nend\nif ~isfield(data, 'n'), data.n = 400; end\nif ~isfield(data, 'noise'), data.noise = 0.0; end\nif ~isfield(data, 'state'), data.state = 0; end\n\n% set the randomness\nrand('state', data.state);\nrandn('state', data.state);\n\ndata.typ = 'data';\nswitch data.dataset\n case 0 % \"swiss roll with hole\" \n data.name = 'swiss roll with hole';\n n = data.n;\n a = 1; % swiss roll goes from a*pi to b*pi\n b = 4; \n y = rand(2,n);\n % punch a rectangular hole at the center\n l1 = 0.05; l2 = 0.15;\n y = y - 0.5;\n ok = find((abs(y(1,:))>l1) | (abs(y(2,:))>l2));\n i = length(ok);\n y(:, 1:i) = y(:, ok);\n while (il1) || (abs(p(2))>l2)\n i = i + 1;\n y(:,i) = p;\n end\n end\n y = y + 0.5;\n tt = (b-a)*y(1,:) + a;\n tt = pi*tt;\n height = 21*y(2,:);\n data.col = tt;\n data.x = [tt.*cos(tt); height; tt.*sin(tt)];\n data.z = [tt; height]; % the ground truth\n data.az = -4;\n data.el = 13;\n \n case -1 % \"swiss roll\" dataset extracted from LLE's swissroll.m\n data.name = 'uniform swiss roll';\n n = data.n;\n a = 1; % swiss roll goes from a*pi to b*pi\n b = 4; \n y = rand(2,n);\n data.z = y; % the ground truth\n switch 1\n case 1\n % uniform distribution along the manifold (in data space)\n tt = sqrt((b*b-a*a)*y(1,:)+a*a);\n case 2\n% error('do not use this case')\n % nonuniform distribution along the manifold (in data space)\n tt = (b-a)*y(1,:) + a; \n end\n tt = pi*tt;\n % now tt should go from a*pi to b*pi\n height = 21*y(2,:);\n data.col = tt;\n data.x = [tt.*cos(tt); height; tt.*sin(tt)];\n data.az = -4;\n data.el = 13;\n\n case 1 % \"swiss roll (uniform in embedding space)\" \n % dataset extracted from LLE's swissroll.m\n data.name = 'classic swiss roll';\n n = data.n;\n a = 1; % swiss roll goes from a*pi to b*pi\n b = 4; \n y = rand(2,n);\n tt = (b-a)*y(1,:) + a;\n tt = pi*tt;\n height = 21*y(2,:);\n data.col = tt;\n data.x = [tt.*cos(tt); height; tt.*sin(tt)];\n data.z = [tt; height]; % the ground truth\n data.az = -4;\n data.el = 13;\n \n case 11 % \"undersampled swiss roll\"\n % dataset extracted from LLE's swissroll.m\n data.name = 'undersampled swiss roll';\n data.n = 100;\n n = data.n;\n a = 1; % swiss roll goes from a*pi to b*pi\n b = 4; \n y = rand(2,n);\n tt = (b-a)*y(1,:) + a;\n tt = pi*tt;\n height = 21*y(2,:);\n data.col = tt;\n data.x = [tt.*cos(tt); height; tt.*sin(tt)];\n data.z = [tt; height]; % the ground truth\n data.az = -4;\n data.el = 13;\n \n case 12 % \"swiss roll\"\n % dataset extracted from LLE's swissroll.m\n data.name = 'classic swiss roll';\n data.n = 400;\n n = data.n;\n a = 1; % swiss roll goes from a*pi to b*pi\n b = 4; \n y = rand(2,n);\n tt = (b-a)*y(1,:) + a;\n tt = pi*tt;\n height = 21*y(2,:);\n data.col = tt;\n data.x = [tt.*cos(tt); height; tt.*sin(tt)];\n data.z = [tt; height]; % the ground truth\n data.az = -4;\n data.el = 13;\n \n case 2 % \"scurve\" dataset extracted from LLE's scurve.m\n data.name = 'scurve';\n n = data.n;\n % I added 'ceil' and 'floor' to account for the case that n is odd\n angle = pi*(1.5*rand(1,ceil(n/2))-1); height = 5*rand(1,n);\n data.x = [[cos(angle), -cos(angle(1:floor(n/2)))]; height;[ sin(angle), 2-sin(angle)]];\n data.col = [angle, 1.5*pi + angle];\n data.z = [angle, 1.5*pi+angle; height]; % the ground truth\n \n case 3 % \"square\" dataset, a uniformly sampled 2D square randomly\n % rotated into higher dimensions\n data.name = 'square';\n n = data.n;\n d = 2; % intrinsic dimension\n % optional parameter for dataset==3\n % data.D dimension of the data\n if ~isfield(data, 'D'), data.D = 3; end\n % generate random rotation matrix\n D = data.D;\n A = randn(D, D);\n options.disp = 0;\n [R, dummy] = eigs(A*A', d, 'LM', options);\n tt = rand(d, n);\n data.col = tt(1,:);\n data.x = R*tt;\n data.z = tt; % the ground truth\n data.az = 7;\n data.el = 40;\n \n case 4 % spiral: two dimensional \"swiss roll\"\n data.name = 'spiral';\n n = data.n;\n tt = (3*pi/2)*(1+2*rand(1, n));\n data.col = tt;\n data.x = [tt.*cos(tt); tt.*sin(tt)];\n data.z = tt; % the ground truth\n \n case -4 % spiral: two dimensional \"swiss roll\"\n data.name = 'noisy spiral';\n n = data.n;\n tt = (3*pi/2)*(1+2*rand(1, n));\n data.col = tt;\n data.x = [tt.*cos(tt); tt.*sin(tt)];\n data.x = data.x + randn(size(data.x));\n data.z = tt; % the ground truth\n \n case 5 % hole: a dataset with a hole\n data.name = 'hole';\n n = data.n;\n data.x = rand(2,n) - 0.5;\n % punch a rectangular hole at the center\n l1 = 0.2; l2 = 0.2;\n ok = find((abs(data.x(1,:))>l1) | (abs(data.x(2,:))>l2));\n i = length(ok);\n data.x(:, 1:i) = data.x(:, ok);\n while (il1) || (abs(p(2))>l2)\n i = i + 1;\n data.x(:,i) = p;\n end\n end\n data.col = data.x(2,:);\n data.z = data.x;\n \n case 6 % P : taken from Saul's slides\n % note that for k=20, isomap and lle work fine which is very different\n % from the plots that Saul showed in his slides.\n data.name = 'P';\n load x\n x(2,:) = 500-x(2,:);\n data.x = x;\n data.z = x;\n data.col = data.z(2,:);\n data.n = size(x, 2);\n \n case 7 % fishbowl: uniform in data space\n gamma = 0.8;\n data.name = 'fishbowl (uniform in data space)';\n n = data.n;\n data.x = rand(3,n)-0.5;\n %project all data onto the surface of the unit sphere\n data.x = data.x ./ repmat(sqrt(sum(data.x.*data.x, 1)), [3 1]);\n ok = find(data.x(3,:) < gamma);\n i = length(ok);\n data.x(:, 1:i) = data.x(:, ok);\n while (i < n)\n p = rand(3,1)-0.5;\n p = p / sqrt(p'*p);\n if (p(3) < gamma)\n i = i+1;\n data.x(:, i) = p;\n end\n end\n % the projection on the plane works as follows:\n % start a beam from (0,0,1) through each surface point on the sphere\n % and look where it hits the xy plane.\n data.z = data.x(1:2,:) ./ repmat(1-data.x(3,:), [2 1]);\n data.col = data.x(3,:);\n data.az = -18;\n data.el = 16;\n case 8 % fishbowl: uniform in embedding space\n data.name = 'fishbowl (uniform in embedding space)';\n n = data.n;\n data.z = rand(2, n) - 0.5;\n % keep the disc\n ok = find(sum(data.z .* data.z) <= 0.25);\n i = length(ok);\n data.z(:, 1:i) = data.z(:, ok);\n while (i < n)\n p = rand(2,1) - 0.5;\n if (p'*p <= 0.25)\n i = i + 1;\n data.z(:, i) = p;\n end\n end\n gamma = 0.8; % same role/parameter as in case 7\n data.z = 2*sqrt((1+gamma)/(1-gamma))*data.z;\n % project the disc onto the sphere\n alpha = 2 ./ (1 + sum(data.z .* data.z, 1));\n data.x = [repmat(alpha, [2 1]).*data.z; zeros(1, n)];\n data.x(3,:) = 1-alpha;\n data.col = data.x(3,:);\n data.az = -18;\n data.el = 16;\n \n case 9 % a gaussian blob\n data.name = 'gaussian blob';\n n = data.n;\n data.x = randn(3,n);\n data.z = data.x(2:3,:);\n data.col = data.x(3,:);\n \nend\n\n\ndata.D = size(data.x, 1); % dimensionality of the data\n% finally generate noise\ndata.e = randn(size(data.x));\ndata.x_noisefree = data.x; % the noise free data\ndata.x = data.x_noisefree + sqrt(data.noise)*data.e;\n\n% precalculate the distanzmatrix\ndata.distances = distanz(data.x);\n\n\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/demo/create_synthetic_dataset.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.705253672282729}} {"text": "function g = gauss(N)\n\n% gauss(N)\n% \n% returns N normally distributed random numbers\n% reference : Num. Recipes, Chapter 7.2 Normal Deviates\n\nrsq = [];\n\nM = ceil(N/2);\nwhile length(rsq) < M\t% make shure we really have at least M values\n\tv = 2*rand(ceil(M*1.33),2)-1;\t\t% produce more random numbers\n\trsq = v(:,1).*v(:,1)+v(:,2).*v(:,2);\n\tind = find((rsq >=1) | (rsq == 0));\n\trsq(ind) = [];\t\t\t\t\t\t% because we want to remove some\nend\n\nv(ind,:) = [];\nv = v(1:M,:);\nrsq = rsq(1:M);\nfac = sqrt(-2 * log(rsq) ./ rsq);\ng = [v(:,1) .* fac ; v(:,2) .* fac];\ng = g(1:N);\n", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/OpenTSTOOL/tstoolbox/@core/private/gauss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122163480666, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.7052536691709641}} {"text": "function JTotal=calcSpherInvJacob(z,systemType)\n%%SPHERINVJACOB Calculate the Jacobian for a 3D Cartesian position with\n% respect to monostatic spherical range, azimuth, and elevation\n% components. This produces derivatives of (x,y,z) with respect to\n% (range,Az,El). The function calcSpherJacob produces derivatives\n% of (range,Az,El) with respect to (x,y,z) in the more general\n% bistatic case.\n%\n%INPUTS: z The 3XN position vectors in the global spherical coordinate\n% system, each with [range;Az;El] components.\n% systemType An optional parameter specifying the axis from which the\n% angles are measured in radians. Possible values are\n% 0 (The default if omitted) Azimuth is measured \n% counterclockwise from the x-axis in the x-y plane. Elevation\n% is measured up from the x-y plane (towards the z-axis). This\n% is consistent with common spherical coordinate systems for\n% specifying longitude (azimuth) and geocentric latitude\n% (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% 3 This is the same as 0 except azimuth is measured clockwise\n% from the y-axis in the x-y plane instead of counterclockwise\n% from the x-axis. This coordinate system often arises when\n% given \"bearings\" in a local East-North-Up coordinate system,\n% where the bearing directions are measured East of North.\n%\n%OUTPUTS: JTotal A 3X3XN Jacobian matrices where the rows in each matrix\n% are [x;y;z] in that order and the columns take the derivative\n% of the row component with respect to [r,azimuth,elevation] in\n% that order.\n%\n%This function evaluates analytic expressions for the Jacobian matrix that\n%were derived by differentiating standard equations for the spherical\n%coordinate systems.\n%\n%EXAMPLE:\n%Here, we verify that the inverse of calcSpherJacob is equal to\n%calcSpherInvJacob within reasonable finite precision limits.\n% z=[1e3;0.3;0.25];\n% systemType=2;\n% J=calcSpherInvJacob(z,systemType)\n% zC=spher2Cart(z,systemType);\n% J1Inv=calcSpherJacob(zC,systemType);\n% J1=inv(J1Inv)\n%The difference between J and J1 values is small (and the values themselves\n%are reasonable in magnitude), so we see that the results of this function\n%are consistent with inverting the Jacobian from calcSpherJacob.\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<2||isempty(systemType))\n systemType=0; \nend\n\nN=size(z,2);\n\nJTotal=zeros(3,3,N);\n\nfor curPoint=1:N\n r=z(1,curPoint);\n Az=z(2,curPoint);\n El=z(3,curPoint);\n \n sinAz=sin(Az);\n cosAz=cos(Az);\n sinEl=sin(El);\n cosEl=cos(El);\n \n J=zeros(3,3);\n switch(systemType)\n case 0\n %dx/dr\n J(1,1)=cosAz*cosEl;\n %dy/dr\n J(2,1)=cosEl*sinAz;\n %dz/dr\n J(3,1)=sinEl;\n %dx/dAz\n J(1,2)=-r*cosEl*sinAz;\n %dy/dAz\n J(2,2)=r*cosAz*cosEl;\n %dz/dAz\n J(3,2)=0;\n %dx/dEl\n J(1,3)=-r*cosAz*sinEl;\n %dy/dEl\n J(2,3)=-r*sinAz*sinEl;\n %dz/dEl\n J(3,3)=r*cosEl;\n case 1\n %dx/dr\n J(1,1)=cosEl*sinAz;\n %dy/dr\n J(2,1)=sinEl;\n %dz/dr\n J(3,1)=cosAz*cosEl;\n %dx/dAz\n J(1,2)=r*cosAz*cosEl;\n %dy/dAz\n J(2,2)=0;\n %dz/dAz\n J(3,2)=-r*cosEl*sinAz;\n %dx/dEl\n J(1,3)=-r*sinAz*sinEl;\n %dy/dEl\n J(2,3)=r*cosEl;\n %dz/dEl\n J(3,3)=-r*cosAz*sinEl;\n case 2\n %dx/dr\n J(1,1)=cosAz*sinEl;\n %dy/dr\n J(2,1)=sinAz*sinEl;\n %dz/dr\n J(3,1)=cosEl;\n %dx/dAz\n J(1,2)=-r*sinAz*sinEl;\n %dy/dAz\n J(2,2)=r*cosAz*sinEl;\n %dz/dAz\n J(3,2)=0;\n %dx/dEl\n J(1,3)=r*cosAz*cosEl;\n %dy/dEl\n J(2,3)=r*cosEl*sinAz;\n %dz/dEl\n J(3,3)=-r*sinEl;\n case 3\n %dx/dr\n J(1,1)=sinAz*cosEl;\n %dy/dr\n J(2,1)=cosAz*cosEl;\n %dz/dr\n J(3,1)=sinEl;\n %dx/dAz\n J(1,2)=r*cosEl*cosAz;\n %dy/dAz\n J(2,2)=-r*sinAz*cosEl;\n %dz/dAz\n J(3,2)=0;\n %dx/dEl\n J(1,3)=-r*sinAz*sinEl;\n %dy/dEl\n J(2,3)=-r*cosAz*sinEl;\n %dz/dEl\n J(3,3)=r*cosEl;\n otherwise\n error('Invalid system type specified.')\n end\n JTotal(:,:,curPoint)=J;\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/Jacobians/calcSpherInvJacob.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.7052536601885924}} {"text": "function [ 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\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\n", "meta": {"author": "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_t3_element.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7052476180371221}} {"text": "function y = quad_form( x, Q, v, w )\n\n%QUAD_FORM quadratic form.\n% QUAD_FORM(x,Q) is real(x'*Q*x) = x'*((Q+Q')/2)*x.\n% QUAD_FORM(x,Q,v,w) is real(x'*(Q*x+v)+w).\n%\n% x must be a row or column vector, and Q must either be a scalar or\n% a square matrix with the same number of rows as x. If supplied, v must\n% be a scalar or a vector of the same size as x, and w must be a scalar.\n% \n% NOTE: The use of QUAD_FORM can often be replaced by a call to NORM. For\n% example, if Q is positive definite, then the constraint\n% quad_form(x,Q) <= 1\n% is equivalent to\n% norm(sqrtm(Q)*x) <= 1\n% Generally speaking, the NORM version will be more reliable and more\n% accurate, so we encourage you to make similar conversions whenever\n% possible. We *strongly* discourage the QP-era practice of converting\n% NORM expressions into quadratic forms. \n%\n% Disciplined convex programming information:\n% QUAD_FORM(x,Q,v,w) is neither convex nor concave in x and (Q,v)\n% jointly, so at least one of the two must be constant.\n%\n% If (Q,v) is constant, then QUAD_FORM is convex if Q is positive\n% semidefinite, and concave if Q is negative semidefinite. An error \n% is generated if Q is indefinite (unless x is also constant). \n% QUAD_FORM is nonmonotonic in x, so x must be affine.\n% \n% If x is constant, then QUAD_FORM is affine in Q, v, and w. The\n% signs of x will govern whether the elements of Q, v, and w may\n% be convex, concave, or affine.\n\nnarginchk(2,4);\nsx = size( x );\nif length( sx ) ~= 2 || all( sx ~= 1 ),\n error( 'The first argument must be a vector.' );\nelse\n sx = prod( sx );\nend\nif ndims( Q ) > 2 || size( Q, 1 ) ~= size( Q, 2 ), %#ok\n error( 'The second argument must be a scalar or a square matrix.' );\nelseif all( size( Q, 1 ) ~= [ 1, sx ] ),\n error( 'The size of Q is incompatible with the size of x.' );\nend\nif nargin < 3,\n v = 0;\nelseif ndims( v ) > 2 || all( size( v ) ~= 1 ), %#ok\n error( 'The third argument must be a vector.' );\nelseif all( numel( v ) ~= [ 1, sx ] ),\n error( 'The size of v is incompatible with the size of x.' );\nend\nif nargin < 4,\n w = 0;\nelseif numel( w ) > 1,\n error( 'The fourth argument must be a real scalar.' );\nend\nif sx == 0,\n y = real( w );\nelse\n x = x( : );\n v = v( : );\n y = real( x' * ( Q * x + v ) + w );\nend\n\n% Copyright 2005-2016 CVX Research, Inc. \n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/functions/quad_form.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7052475989779458}} {"text": "%\n% rf(x, y, z, errtol)\n%\n% Inputs:\n%\n% x Input vector size 1xN.\n% y Input vector size 1xN.\n% z Input vector size 1xN.\n% errtol Error tolerance.\n%\n% Matlab function to compute Carlson's symmetric elliptic integral Rf.\n% Implementation of Carlson's Duplication Algorithm 1 in \"Computing\n% Elliptic Integrals by Duplication,\" by B. C. Carlson, Numer. Math.\n% 33, 1-16 (1979).\n%\n% Returns NaN's for any argument values outside input range.\n%\n% Algorithm is also from Carlson's ACM TOMS Algorithm 577.\n%\n% This code is a complete rewrite of the algorithm in vectorized form.\n% It was not produced by running a FORTRAN to Matlab converter.\n%\n% The following text is copied from ACM TOMS Algorithm 577 FORTRAN code:\n%\n% X AND Y ARE THE VARIABLES IN THE INTEGRAL RC(X,Y).\n%\n% ERRTOL IS SET TO THE DESIRED ERROR TOLERANCE.\n% RELATIVE ERROR DUE TO TRUNCATION IS LESS THAN\n% 16 * ERRTOL ** 6 / (1 - 2 * ERRTOL).\n%\n% SAMPLE CHOICES: ERRTOL RELATIVE TRUNCATION\n% ERROR LESS THAN\n% 1.D-3 3.D-19\n% 3.D-3 2.D-16\n% 1.D-2 3.D-13\n% 3.D-2 2.D-10\n% 1.D-1 3.D-7\n%\n% Note by TRH:\n%\n% Absolute truncation error when the integrals are order 1 quantities\n% is closer to errtol, so be careful if you want high absolute precision.\n%\n% Thomas R. Hoffend Jr., Ph.D.\n% 3M Company\n% 3M Center Bldg. 236-GC-26\n% St. Paul, MN 55144\n% trhoffendjr@mmm.com\n%\n\nfunction f = rf(x, y, z, errtol)\n\n% Argument limits as set by Carlson:\nLoLim = 5.0 * realmin;\nUpLim = 5.0 * realmax;\n\n% Check input arguments for acceptability:\nmask = (min([x; y; z]) >= 0) & ...\n (min([(x + y); (x + z); (y + z)]) >= LoLim) & ...\n (max([x; y; z]) < UpLim);\n\n% Define internally acceptable variable ranges for iterations:\nXi = x(mask);\nYi = y(mask);\nZi = z(mask);\n\n% Carlson's duplication algorithm for Rf:\nXn = Xi;\nYn = Yi;\nZn = Zi;\nMu = (Xn + Yn + Zn) / 3.0d+0;\nXndev = 2.0 - (Mu + Xn) ./ Mu;\nYndev = 2.0 - (Mu + Yn) ./ Mu;\nZndev = 2.0 - (Mu + Zn) ./ Mu;\nepslon = max( abs([Xndev Yndev Zndev]) );\nwhile (epslon >= errtol)\n Xnroot = sqrt(Xn);\n Ynroot = sqrt(Yn);\n Znroot = sqrt(Zn);\n lambda = Xnroot .* (Ynroot + Znroot) + Ynroot .* Znroot;\n Xn = 0.25 * (Xn + lambda);\n Yn = 0.25 * (Yn + lambda);\n Zn = 0.25 * (Zn + lambda);\n Mu = (Xn + Yn + Zn) / 3.0d+0;\n Xndev = 2.0 - (Mu + Xn) ./ Mu;\n Yndev = 2.0 - (Mu + Yn) ./ Mu;\n Zndev = 2.0 - (Mu + Zn) ./ Mu;\n epslon = max( abs([Xndev Yndev Zndev]) );\nend\nC1 = 1.0 / 24.0;\nC2 = 3.0 / 44.0;\nC3 = 1.0 / 14.0;\nE2 = Xndev .* Yndev - Zndev .* Zndev;\nE3 = Xndev .* Yndev .* Zndev;\nS = 1.0 + (C1 * E2 - 0.1D0 - C2 * E3) .* E2 + C3 * E3;\nf(mask) = S ./ sqrt(Mu);\n\n% Return NaN's where input argument was out of range:\nf(~mask) = NaN;\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/3705-ellipticintegrals-zip/Elliptic_Integrals/rf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970685907242, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7052471682901545}} {"text": "% The OxyGEN proyect by Profoty.xyz\n% Together against the Covid-19\n% V4.0 rev.17/03/2020\n% \n% Website/blog: oxygen.protofy.xyz\n% Contact: oxygen@protofy.xyz\n\n\n%GEOMETRICAL PARAMETERS\n\nclear;\n\n%Length from the bearing to the hinge\nl0 = 27.5;\n\n%Length of the vertical wall that supports the hinge\nh0 = 6.5;\n\n%Lenght of the vertical support of the bearing\nhb = 4.0;\n\n%Bearing radius\nbr = 1.1;\n\n%Array of different max and min positions of the bearing\nh1a = [9, 10, 11];\nh2a = [20, 20, 20];\n\n%Number of cycles per cam turn (1 to 3).\nnc = 1;\n\n%Minimum radius of the camshaft\nrmin = 5.5;\n\n\n%BREATHING CYCLE PARAMETERS\n\n%Duration of the inhale cycle / duration of the whole cycle\nlambda1 = 0.500;\nlambda2 = 0.100;\n\n%Soft transition between inhale and exhale cycles\ndpsi21 = 0.11;\ndpsi12 = 0.15;\n\n%Adjust parameters of the inhale curve\nga1 = 3.8;\ngb1 = .9;\nff1 = 50;\n\n%Adjust parametes of the exhale curve\nga2 = 3.5;\ngb2 = .70;\nff2 = 55;\n\n\n%GENERATION OF THE CURVES AND THE CAMSHAFT\n\n%Generation of the geometry\n\nl = sqrt(l0^2+hb^2);\n\n\nfor i = 1:numel(h1a);\n \n ymin(i) = h1a(i);\n ymax(i) = h2a(i);\n \n alphamin(i) = acos((h0 - h1a(i)) / l);\n alphamax(i) = acos((h0 - h2a(i)) / l);\n \n xmin(i) = l*sin(alphamin(i)); \n xmax(i) = l*sin(alphamax(i));\n \n d(i) = sqrt((xmin(i)-xmax(i))^2 + (ymin(i)-ymax(i))^2);\n \n alphatan(i) = (alphamin(i) + alphamax(i)) / 2;\n \n xtan(i) = l*sin(alphatan(i)); \n ytan(i) = h0 - l*cos(alphatan(i));\n \n xsup(i) = xtan(i) + (d(i)/2)*cos(alphatan(i));\n xinf(i) = xtan(i) - (d(i)/2)*cos(alphatan(i));\n \n ysup(i) = ytan(i) + (d(i)/2)*sin(alphatan(i));\n yinf(i) = ytan(i) - (d(i)/2)*sin(alphatan(i));\n \n xcam(i) = xtan(i) + (d(i)/2 + rmin + br)*cos(alphatan(i));\n ycam(i) = ytan(i) + (d(i)/2 + rmin + br)*sin(alphatan(i));\n \nend;\n\n\n%Time increment\ndt = 0.01;\n\n%time coordinate during the whole cycle\ntheta = 0:dt:2*pi;\n\n%Generation of the soft transition between inhale and exhale curves\npsi1 = [];\npsi2 = [];\n\nfor i = 1:numel(theta);\n \n if theta(i) < (lambda2-dpsi21/2)*2*pi;\n psi1(i) = 0;\n \n elseif theta(i) < (lambda2+dpsi21/2)*2*pi;\n psi1(i) = 0.5 + 0.5*cos((theta(i)-(lambda2+dpsi21/2)*2*pi)/(2*dpsi21));\n \n else theta(i) < (lambda1-dpsi12/2)*2*pi;\n psi1(i) = 1;\n \n end;\n \n psi2(i) = 1 - psi1(i);\n \nend; \n\n\n%Generation of the complete breathing cycle rho(theta)\n\nrho = [];\nrho1 = [];\nrho2 = [];\nrho2next = [];\n\nrhomin = 1000;\nrhomax = 0;\n\nfor i = 1:numel(theta);\n \n %Inhale curve\n rho1(i) = ff1*gampdf(theta(i), ga1, gb1);\n rho1next(i) = ff1*gampdf(theta(i)+2*pi, ga1, gb1);\n \n %Exhale curve\n rho2(i) = ff2*gampdf(theta(i), ga2, gb2);\n rho2next(i) = ff2*gampdf(theta(i)+2*pi, ga2, gb2);\n \n \n rho(i) = psi1(i)*rho1(i) + psi2(i)*rho1next(i);\n \n \n %Capturing min and max in order to generate the normalized curve\n if rho(i) > rhomax\n rhomax = rho(i);\n end;\n \n if rho(i) < rhomin\n rhomin = rho(i);\n end;\n\nend;\n\n\n%Generation of a normalised curve and camshaft\n\nrhonorm = [];\nrhocam = [];\n\nfor i = 1:numel(theta);\n \n rhonorm(i) = (rho(i)-rhomin)/(rhomax-rhomin);\n \n for n = 1:numel(d)\n \n rhocam(n,i) = rmin + rhonorm(i)*d(n);\n \n end;\n \nend;\n\n\n%Generation of the first derivate of the camshaft geometry to analize and\n%validate the design\n\ndrho = [];\ndrhonorm = [];\ndrhocam = [];\n\na = rmin;\nb = 1/dt;\n\nfor i = 1 : numel(rho)-1;\n \n drho(i) = b*(rho(i+1)-rho(i));\n drhonorm(i) = b*(rhonorm(i+1)-rhonorm(i));\n drhocam(i) = b*(rhocam(i+1)-rhocam(i)) + a;\n \nend;\n\ndrho(numel(rho)) = b*(rho(1)-rho(numel(rho)));\ndrhonorm(numel(rhonorm)) = b*(rhonorm(1)-rhonorm(numel(rhonorm)));\ndrhocam(numel(rhocam)) = b*(rhocam(1)-rhocam(numel(rhocam))) + a;\n\n\n%X and Y coordinates during two cycles (for 2-cycle camshaft plot)\n\ntheta2 = [theta/2, (2*pi+theta)/2];\n\nrhocam2 = [rhocam, rhocam];\ndrhocam2 = [drho, drho];\n\n\n%X and Y coordinates during three cycles (for 3-cycle camshaft plot)\n\ntheta3 = [theta/3, (2*pi+theta)/3, (4*pi+theta)/3];\n\nrhocam3 = [rhocam, rhocam, rhocam];\ndrhocam3 = [drho, drho, drho];\n\n\n\n%GENERATION OF THE PLOTS\n\n%Trying to print it out in real size (FAIL)\n%set(gcf,'PaperUnits','centimeters'); \n%set(gcf,'PaperSize',[42 29.7]);\n\n\nfpos = figure('Name', 'Dimensions', 'Units', 'centimeters', 'NumberTitle', 'off');\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 28, 20]);\nfpos = gcf;\nhold on\n\nxlim([-5 35]);\nylim([0 30]);\n\nfor i = 1:numel(xmin)\n \n plot([0, xmin(i)], [h0, ymin(i)], '-x') \n plot([0, xmax(i)], [h0, ymax(i)], '-x')\n \n plot([0, xtan(i)], [h0, ytan(i)], '--xb')\n \n plot([xsup(i), xinf(i)], [ysup(i), yinf(i)], '--xr')\n scatter(xcam(i), ycam(i))\n\nend;\n\nhold off\n\n\n\n\n%Plot of the breathing cycle interpolation by curves\n\nfcycle = figure('Name', 'Breath Cycle curves', 'Units', 'centimeters', 'NumberTitle', 'off');\n\nhold on\nplot(theta, psi1, '-k')\nplot(theta, psi2, '-k')\nplot(theta, rho1, '-g')\nplot(theta, rho1next, '-g')\nplot(theta, rho2, '-g')\nplot(theta, rho2next, '-g')\n%plot(theta, drho, '-r')\nplot(theta, rho, '-b')\nhold off\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of the normalized breathing cycle and first derivate\n\n\nfnorm = figure('Name', 'Normalized Breath Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n\nhold on\n%plot(theta, drhonorm, '-r')\nplot(theta, rhonorm, '-b')\nhold off\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of a 1-cycle camshaft\n\nfor n = 1:numel(d)\n\n fcam1 = figure('Name', '1-Cycle Camshaft', 'Units', 'centimeters', 'NumberTitle', 'off');\n %hold on\n \n %polarplot(theta, drhocam, '-r')\n polar(theta, rhocam(n,:), '-b')\n\n \n %rlim([0 25]);\n hold off\n\n set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n fcam3 = gcf;\n \nend\n\n\n% %Plot of a 2-cycle camshaft\n% \n% fcam2 = figure('Name', '2-Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n% \n% %hold on;\n% %polar(theta, drhocam2, '-r')\n% polar(theta2, rhocam2, '-b')\n% %hold off;\n% \n% set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n% set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n% fcam3 = gcf;\n% \n% \n% %Plot of a 3-cycle camshaft\n% \n% fcam3 = figure('Name', '3-Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n% \n% %hold on;\n% %polar(theta,drhocam3)\n% polar(theta3, rhocam3)\n% %hold off;\n% \n% set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n% set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n% fcam3 = gcf;\n\n% The OxyGEN proyect by Profoty.xyz\n% Together against the Covid-19\n% V4.0 rev.17/03/2020\n% \n% Website/blog: oxygen.protofy.xyz\n% Contact: oxygen@protofy.xyz", "meta": {"author": "ProtofyTeam", "repo": "OxyGEN", "sha": "8a2870695e01928c07af2cc73ed86e5e53d8f726", "save_path": "github-repos/MATLAB/ProtofyTeam-OxyGEN", "path": "github-repos/MATLAB/ProtofyTeam-OxyGEN/OxyGEN-8a2870695e01928c07af2cc73ed86e5e53d8f726/Matlab Files/V7/Respirador_V6_1_2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7052152951297179}} {"text": "function [M11,M12,M21,M22,f1,f2] = autoGen_acrobotDynamics(q1,q2,dq1,dq2,u,m1,m2,g,l1,l2)\n%AUTOGEN_ACROBOTDYNAMICS\n% [M11,M12,M21,M22,F1,F2] = AUTOGEN_ACROBOTDYNAMICS(Q1,Q2,DQ1,DQ2,U,M1,M2,G,L1,L2)\n\n% This function was generated by the Symbolic Math Toolbox version 6.2.\n% 11-Jul-2015 20:41:44\n\nt2 = cos(q1);\nt3 = l1.^2;\nt4 = sin(q1);\nt5 = cos(q2);\nt6 = l1.*t2;\nt7 = l2.*t5;\nt8 = t6+t7;\nt9 = sin(q2);\nt10 = l1.*t4;\nt11 = l2.*t9;\nt12 = t10+t11;\nM11 = -m1.*t2.^2.*t3-m1.*t3.*t4.^2-l1.*m2.*t2.*t8-l1.*m2.*t4.*t12;\nif nargout > 1\n M12 = -l2.*m2.*t5.*t8-l2.*m2.*t9.*t12;\nend\nif nargout > 2\n M21 = -l1.*l2.*m2.*t2.*t5-l1.*l2.*m2.*t4.*t9;\nend\nif nargout > 3\n t13 = l2.^2;\n M22 = -m2.*t5.^2.*t13-m2.*t9.^2.*t13;\nend\nif nargout > 4\n t14 = dq1.^2;\n t15 = dq2.^2;\n t16 = l1.*t2.*t14;\n t17 = l2.*t5.*t15;\n t18 = t16+t17;\n t19 = l1.*t4.*t14;\n t20 = l2.*t9.*t15;\n t21 = t19+t20;\n t22 = m2.*t12.*t18;\n t23 = g.*m2.*t12;\n t24 = g.*l1.*m1.*t4;\n f1 = t22+t23+t24-m2.*t8.*t21;\nend\nif nargout > 5\n t25 = l2.*m2.*t9.*t18;\n t26 = g.*l2.*m2.*t9;\n f2 = t25+t26-u-l2.*m2.*t5.*t21;\nend\n", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/acrobot/autoGen_acrobotDynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7052152861869809}} {"text": "function [r_eb_e,v_eb_e,C_b_e] = NED_to_ECEF(L_b,lambda_b,h_b,v_eb_n,C_b_n)\n%NED_to_ECEF - Converts curvilinear to Cartesian position, velocity\n%resolving axes from NED to ECEF and attitude from NED- to ECEF-referenced\n%\n% Software for use with \"Principles of GNSS, Inertial, and Multisensor\n% Integrated Navigation Systems,\" Second Edition.\n%\n% This function created 2/4/2012 by Paul Groves\n%\n% Inputs:\n% L_b latitude (rad)\n% lambda_b longitude (rad)\n% h_b height (m)\n% v_eb_n velocity of body frame w.r.t. ECEF frame, resolved along\n% north, east, and down (m/s)\n% C_b_n body-to-NED coordinate transformation matrix\n%\n% Outputs:\n% r_eb_e Cartesian position of body frame w.r.t. ECEF frame, resolved\n% along ECEF-frame axes (m)\n% v_eb_e velocity of body frame w.r.t. ECEF frame, resolved along\n% ECEF-frame axes (m/s)\n% C_b_e body-to-ECEF-frame coordinate transformation matrix\n\n% Copyright 2012, Paul Groves\n% License: BSD; see license.txt for details\n\n% Parameters\n\nR_0 = 6378137; %WGS84 Equatorial radius in meters\necc2= 0.0818191908425^2; %WGS84 eccentricity\n\n\n% Begins\n\n% Calculate transverse radius of curvature using (2.105)\nR_E = R_0 / sqrt(1 - ecc2*sin(L_b)^2);\n\n% Convert position using (2.112)\ncos_lat = cos(L_b);\nsin_lat = sin(L_b);\ncos_long = cos(lambda_b);\nsin_long = sin(lambda_b);\nr_eb_e = [(R_E + h_b) * cos_lat * cos_long;...\n (R_E + h_b) * cos_lat * sin_long;...\n ((1 - ecc2) * R_E + h_b) * sin_lat];\n \n% Calculate ECEF to NED coordinate transformation matrix using (2.150)\nC_e_n = [-sin_lat * cos_long, -sin_lat * sin_long, cos_lat;...\n -sin_long, cos_long, 0;...\n -cos_lat * cos_long, -cos_lat * sin_long, -sin_lat];\n \n% Transform velocity using (2.73)\nv_eb_e = C_e_n' * v_eb_n;\n\n% Transform attitude using (2.15)\nC_b_e = C_e_n' * C_b_n;\n\n% Ends", "meta": {"author": "benzenemo", "repo": "TightlyCoupledINSGNSS", "sha": "136225ef063709abfce681dd1e3e29234a187626", "save_path": "github-repos/MATLAB/benzenemo-TightlyCoupledINSGNSS", "path": "github-repos/MATLAB/benzenemo-TightlyCoupledINSGNSS/TightlyCoupledINSGNSS-136225ef063709abfce681dd1e3e29234a187626/CalculateTCRes/NED_to_ECEF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7052152716728602}} {"text": "\nfunction pkdo = umSYMBPKDO2d(i,j)\n\n r = sym('r');\n s = sym('s');\n \n a = 2*(1+r)/(1-s) - 1;\n b = s; \n \n pkdo = umSYMBJACOBI1d(a,i,0,0);\n pkdo = pkdo.*umSYMBJACOBI1d(b,j,2*i+1,0).*((0.5*(1-b)).^i);\n\n % normalize (sets L2 norm of each basis function to be 1)\n pkdo = pkdo*sqrt((i+0.5)*(i+j+1));\n \n % simplify\n pkdo = simple(pkdo); \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/Symbolic/umSYMBPKDO2d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172644875642, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.7052049645827712}} {"text": " function x = dtft2_adj(X, omega, N1, N2, n_shift, useloop)\n%function x = dtft2_adj(X, omega, N1, N2, n_shift, useloop)\n%|\n%| Compute adjoint of 2D DTFT for spectrum X at frequency locations omega\n%| in\n%|\tX\t[M,L]\t\t2D DTFT values\n%|\tomega\t[M,2]\t\tfrequency locations (radians)\n%|\tn_shift [2,1]\t\tuse [0:N-1]-n_shift (default [0 0])\n%|\tuseloop\t\t\t1 to reduce memory use (slower)\n%| out\n%|\tx\t[N1,N2,L]\tsignal values\n%|\n%| Requires enough memory to store M * (N1*N2) size matrices (for testing)\n%|\n%| Copyright 2001-9-17, Jeff Fessler, University of Michigan\n\nif nargin == 1 && streq(X, 'test'), dtft2_adj_test, return, end\nif nargin < 2, ir_usage(), end\n\nif ~isvar('n_shift') || isempty(n_shift), n_shift = [0 0]; end\nif ~isvar('useloop') || isempty(useloop), useloop = 0; end\n\n[nn1, nn2] = ndgrid([0:(N1-1)]-n_shift(1), [0:(N2-1)]-n_shift(2));\n\nif useloop % loop way: slower but less memory\n\n\tM = length(omega);\n\tx = zeros(N1,N2,ncol(X)); % [N1 N2 M]\n\tt1 = 1i * nn1;\n\tt2 = 1i * nn2;\n\tfor ii=1:M\n\t\tx = x + exp(omega(ii,1)*t1 + omega(ii,2)*t2) * X(ii,:);\n\tend\n\nelse % non-loop way\n\tx = exp(1i*(nn1(:)*omega(:,1)' + nn2(:)*omega(:,2)')) * X; % [N1*N2 L]\n\tx = reshape(x, [N1 N2 numel(x)/N1/N2]); % [N1 N2 L]\nend\n\n\nfunction dtft2_adj_test()\nN1 = 4; N2 = 6;\nn_shift = [2 1];\n% test with uniform frequency locations:\no1 = 2*pi*[0:(N1-1)]'/N1;\no2 = 2*pi*[0:(N2-1)]'/N2;\n[o1, o2] = ndgrid(o1, o2);\nX = o1 + o2; % test spectrum\nom = [o1(:) o2(:)];\nxd = dtft2_adj(X(:), om, N1, N2, n_shift);\nxl = dtft2_adj(X(:), om, N1, N2, n_shift, 1);\nprintm('loop max %% difference = %g', max_percent_diff(xl,xd))\nXp = X .* reshape(exp(-1i * om * n_shift(:)), size(X));\nxf = ifft2(Xp) * N1 * N2;\nprintm('ifft max %% difference = %g', max_percent_diff(xf,xd))\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/nufft/dtft2_adj.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7051531297265148}} {"text": "function zeta_values_test ( )\n\n%*****************************************************************************80\n%\n%% ZETA_VALUES_TEST demonstrates the use of ZETA_VALUES.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 February 2009\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'ZETA_VALUES_TEST:\\n' );\n fprintf ( 1, ' ZETA_VALUES returns values of \\n' );\n fprintf ( 1, ' the Riemann Zeta function.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N Zeta(N)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, n, zeta ] = zeta_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fprintf ( 1, '%6d %24.16f\\n', n, zeta );\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/zeta_values_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.8418256512199032, "lm_q1q2_score": 0.705129984757185}} {"text": "function [L, W, A, BE] = calc_tps(refx, refy, holx, holy, calc_BE) %coord in column vector style\n%calculate 2D tps warp\nn = length(refx);\nP = [ ones(n,1) refx refy]; \nV = [holx'; holy'];\nK = zeros(n,n);\nBE = 0 ;\nfor i=1:n,\n for j=1:n,\n r_2= (refx(i) - refx(j))^2 + (refy(i) -refy(j))^2 ;\n if r_2 > 0, K(i,j) = r_2 * log(r_2); end;\n end;\nend;\nfor i=1:n, K(i,i)=0; end;\nL = [K P;P' zeros(3,3)];\nW=zeros(2,n);\nA=zeros(2,3);\nY=[V zeros(2,3)]';\ntemp = ( inv(L)*Y )';\nW = temp(1:2,1:n);\nA = temp(1:2,n+1:n+3);\nif calc_BE == 0, return; end;\n\ntemp = zeros(n,n); % server as Ln-1\ntemp1 = inv(L);\nLn_inv = temp1(1:n,1:n);\n[bas_u, s, bas_v] = svd(Ln_inv);%col of bas_v basis vectors\nB = zeros(2,n-3); %storage of coefs of decomp of V\nfor i=1:n-3,\n B(1,i) = V(1,:)*bas_v(:,i);\n B(2,i) = V(2,:)*bas_v(:,i);\nend;\nBE = 0;\nfor i=1:n-3,\n BE = BE + s(i,i)*( B(1,i)^2 + B(2,i)^2 );\nend;\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/contrib/warp-tps/calc_tps.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947086083139, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.7050974056349137}} {"text": "function gauss = get_gauss_kernel_by_sigma(sigma, d)\n% generate gaussian kernel with given pixel resolution, \n% parameter d controls nonsingular dimensions. \n wd = round(8 * max(sigma));\n N = round((wd-1)/2);\n x = -N:N;\n size(x)\n \n ndims = numel(sigma);\n \n y = cell(ndims, 1);\n for i = 1 : ndims\n y{i} = 1/(sqrt(2*pi)*sigma(i)) * exp( - (x).^2/(2*sigma(i)^2) );\n if d(i) == 0\n y{i} = y{i}*0;\n y{i}((numel(y{i}) - 1)/2 + 1) = 1;\n end\n end\n \n if ndims == 2\n% K = y{2}' * y{1};\n K = y{1}' * y{2};\n elseif ndims == 3\n t = y{1}' * y{2};\n K = zeros((2*N+1)*[1,1,1]);\n for i = 1 : 2*N+1\n K(:,:,i) = t * y{3}(i);\n end\n end\n size(K)\n N\n \n gauss = K / sum(K(:));\nend", "meta": {"author": "visva89", "repo": "pTVreg", "sha": "c359620e3c8435392db02354274d6c74d682d437", "save_path": "github-repos/MATLAB/visva89-pTVreg", "path": "github-repos/MATLAB/visva89-pTVreg/pTVreg-c359620e3c8435392db02354274d6c74d682d437/mutils/My/image_utils/get_gauss_kernel_by_sigma.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806522, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.7050960177846554}} {"text": "function lattice_rule_test10 ( )\n\n%*****************************************************************************80\n%\n%% LATTICE_RULE_TEST10 tests LATTICE_NP1;\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 78-80, pages 32-40, 145-147.\n%\n dim_num = 2;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'LATTICE_RULE_TEST10\\n' );\n fprintf ( 1, ' LATTICE_NP1 applies a lattice rule to a\\n' );\n fprintf ( 1, ' nonperiodic function using a nonlinear transformation,\\n' );\n fprintf ( 1, ' to integrate a function over the unit square.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The spatial dimension DIM_NUM = %d\\n', dim_num );\n\n a(1:dim_num) = 0.0;\n b(1:dim_num) = 1.0;\n\n exact = e_01_2d ( dim_num, a, b );\n\n z(1:dim_num) = [ 1, 2 ];\n i4vec_print ( dim_num, z, ' The lattice generator vector:' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' M EXACT ESTIMATE ERROR\\n' );\n fprintf ( 1, '\\n' );\n\n for k = 3 : 18\n\n m = fibonacci ( k );\n\n quad = lattice_np1 ( dim_num, m, z, @f_01_2d );\n\n error = abs ( exact - quad );\n\n fprintf ( 1, ' %8d %10.6f %10.6f %10.6e\\n', 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_test10.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7050604748902228}} {"text": "function slopeplot(f,xs,X,Xplot,n)\n%SLOPEPLOT Plot of one-dimensional function with slope expansion\n%\n% slopeplot(f,xs,X,Xplot,n)\n%\n%Simple functions, which can be written in one string, can be entered\n% directly. The unknown must be 'x'. E.g.,\n%\n% slopeplot('sqrt(abs(x))',2,infsup(-1,1)); or\n% slopeplot('sin(x)',0,infsup(-1,1)); or\n% slopeplot('x.*x',1,infsup(-2,3));\n%\n%For a one-dimensional function f to be called by u=f(x) consisting of\n% operators overloaded by slope operators such that for a column vector\n% v, f(v) computes the vector f(v(i)), i=1:length(v).\n% Then the function f is expanded within X with respect to xs and\n% plotted together with the slopes in the interval Xplot).\n%\n%Parameter Xplot is optional; default is hull(xs,X) * midrad(1,0.2);\n%Parameter n is optional (number of grid points for function plot); default is 100\n%\n\n% written 12/06/98 S.M. Rump\n% modified 04/04/04 S.M. Rump set round to nearest for safety\n% modified 04/06/05 S.M. Rump rounding unchanged\n% modified 11/20/05 S.M. Rump fast check for 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 prod(size(xs))~=1\n error('slopeplot only for one-dimensional functions')\n end\n\n if nargin==3 | isempty(Xplot)\n Xplot = hull(xs,X);\n Xplot = Xplot + midrad(0,0.2*diam(Xplot));\n end\n\n if nargin<=4\n n = 100;\n end\n\n % slope evaluation\n x = slopeinit(xs,X);\n eval([ 'u = ' f ';' ])\n\n % plot function\n v = linspace(Xplot.inf,Xplot.sup,n);\n x = v;\n eval([ 'y = ' f ';' ])\n plot(x,y,'k')\n hold on\n\n % plot expansion range X\n A = axis;\n dy = A(4)-A(3);\n axis([ A(1:2) A(3)-.1*dy A(4)+.1*dy ])\n H = (A(4)-A(3))/200; % height of box for X\n infX = inf(X);\n supX = sup(X);\n XX = [ infX supX supX infX ];\n patch(XX,A(3)+[-H -H H H],'b')\n\n % plot expansion point xs\n if isa(xs,'intval')\n infxs = inf(xs);\n supxs = sup(xs);\n else\n infxs = xs;\n supxs = xs;\n end\n xxs = [ infxs supxs supxs infxs ];\n patch(xxs,A(3)+2*[-H -H H H],'r')\n plot([infX infxs supxs],A(3)*ones(1,3),'b')\n\n % lines infX,supX,xs to function\n x = infX; eval(['y = ' f ';']); plot([infX infX],[A(3) y],'b:')\n x = supX; eval(['y = ' f ';']); plot([supX supX],[A(3) y],'b:')\n x = infxs; eval(['y = ' f ';']); plot([infxs infxs],[A(3) y],'r:')\n x = supxs; eval(['y = ' f ';']); plot([supxs supxs],[A(3) y],'r:')\n x = infxs; eval(['y = ' f ';']); plot(infxs,y,'r.')\n x = supxs; eval(['y = ' f ';']); plot(supxs,y,'r.')\n\n % slopes\n plot( v , inf(u.c) + inf(u.s)*(v-infxs) , 'b-' );\n plot( v , inf(u.c) + sup(u.s)*(v-infxs) , 'b-' );\n plot( v , sup(u.c) + inf(u.s)*(v-supxs) , 'b-' );\n plot( v , sup(u.c) + sup(u.s)*(v-supxs) , 'b-' );\n\n % add text X and xs\n if infxs+.5*(supxs-infxs) 3); % boolean for derivative computation\n\n%setup default parameter for joint density estimator\ntol = 1e-6; % tolerance for logarithm in entropy\nminT = 0; % (assumed) smallest value in Tc\nmaxT = 256; % (assumed) largest value in Tc\nnT = 32; % number of \"bins\" for Tc\nminR = 0; % (assumed) smallest value in Rc\nmaxR = 256; % (assumed) largest value in Rc\nnR = 30; % number of \"bins\" for Rc\n\n% overwrite default parameter\nfor k=1:2:length(varargin), % overwrite defaults\n eval([varargin{k},'=varargin{',int2str(k+1),'};']);\nend;\n\nwidthT = (maxT-minT)/nT;\nwidthR = (maxR-minR)/nR;\n\n% to ensure nothing is missed at the boundary, two artifical bins are added\nminT = minT-2*widthT; maxT = maxT+2*widthT; nT = nT+4;\nminR = minR-2*widthR; maxR = maxR+2*widthR; nR = nR+4;\n\n% compute the Parzen-window estimator for the density and its derivative\n% rho is (nT*nR) x 1\n% drho is (nT*nR) x length(Tc), large but sparse \n[rho,drho] = rhoSpline(Tc,Rc,minT,maxT,nT,minR,maxR,nR);\n\n% reformat rho for efficient computation of marginal densities\n% rhoT and rhoR and undo formating\n% note, summation can be described via matrix muliplication:\n% rhoT = ST*rho, rhoR = SR*rho, where\n% ST = kron( eye(nT,nT), ones(1,nR) ) and\n% SR = kron( ones(1,nT), eye(nR,nR) );\n% this is used for the computation of the derivative \n\nrho = reshape(rho,nT,nR);\nrhoT = sum(rho,2);\nrhoR = sum(rho,1)';\nrho = rho(:);\n\n% compute MI\nDc = rhoT'*log(rhoT+tol) + rhoR'*log(rhoR+tol) - rho'*log(rho+tol);\n\nif ~doDerivative, return; end;\n\n% build the matrices ST, SR\nST = sparse(kron(ones(1,nR),speye(nT,nT)));\nSR = sparse(kron(speye(nR,nR),ones(1,nT)));\n\ndpsi = (log(rhoT+tol)+rhoT./(rhoT+tol))'*ST ...\n + (log(rhoR+tol)+rhoR./(rhoR+tol))'*SR ...\n - (log(rho +tol)+rho ./(rho +tol))';\n\n% apply chain rule for MI = psi(rho(Tc))\ndD = dpsi * drho;\nd2psi = log2(length(Tc))*sqrt(nT*nR);\n%==============================================================================\n\n", "meta": {"author": "C4IR", "repo": "FAIR.m", "sha": "975edebd37b833ae76696792870de5c05efcb9cb", "save_path": "github-repos/MATLAB/C4IR-FAIR.m", "path": "github-repos/MATLAB/C4IR-FAIR.m/FAIR.m-975edebd37b833ae76696792870de5c05efcb9cb/kernel/distances/MIspline.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624791, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.7050036720711659}} {"text": "function walshMatrix=walsh(N)\nhadamardMatrix = hadamard(N);\nHadIdx = 0:N-1; % Hadamard index\nM = log2(N)+1; % Number of bits to represent the index\n\nbinHadIdx = fliplr(dec2bin(HadIdx,M))-'0'; % Bit reversing of the binary index\nbinSeqIdx = zeros(N,M-1); % Pre-allocate memory\nfor k = M:-1:2\n % Binary sequency index\n binSeqIdx(:,k) = xor(binHadIdx(:,k),binHadIdx(:,k-1));\nend\nSeqIdx = binSeqIdx*pow2((M-1:-1:0)'); % Binary to integer sequency index\nwalshMatrix = hadamardMatrix(SeqIdx+1,:); % 1-based indexing", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41333-simulation-of-dct-walsh-hadamard-haar-and-slant-transform-using-variable-block-sizes/walsh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.7050036631963635}} {"text": "function value = normal_01_cdf_inv ( p )\n\n%*****************************************************************************80\n%\n%% NORMAL_01_CDF_INV inverts the standard normal CDF.\n%\n% Discussion:\n%\n% The result is accurate to about 1 part in 10**16.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 December 2004\n%\n% Author:\n%\n% Original FORTRAN77 version by Michael Wichura.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Michael Wichura,\n% The Percentage Points of the Normal Distribution,\n% Algorithm AS 241,\n% Applied Statistics,\n% Volume 37, Number 3, pages 477-484, 1988.\n%\n% Parameters:\n%\n% Input, real P, the value of the cumulative probability \n% densitity function. 0 < P < 1. If P is not in this range, an \"infinite\"\n% result is returned.\n%\n% Output, real VALUE, the normal deviate value with the \n% property that the probability of a standard normal deviate being \n% less than or equal to the value is P.\n%\n a = [ 3.3871328727963666080, 1.3314166789178437745e+2, ...\n 1.9715909503065514427e+3, 1.3731693765509461125e+4, ...\n 4.5921953931549871457e+4, 6.7265770927008700853e+4, ...\n 3.3430575583588128105e+4, 2.5090809287301226727e+3 ];\n b = [ 1.0, 4.2313330701600911252e+1, ...\n 6.8718700749205790830e+2, 5.3941960214247511077e+3, ...\n 2.1213794301586595867e+4, 3.9307895800092710610e+4, ...\n 2.8729085735721942674e+4, 5.2264952788528545610e+3 ];\n c = [ 1.42343711074968357734, 4.63033784615654529590, ...\n 5.76949722146069140550, 3.64784832476320460504, ...\n 1.27045825245236838258, 2.41780725177450611770e-1, ...\n 2.27238449892691845833e-2, 7.74545014278341407640e-4 ];\n const1 = 0.180625;\n const2 = 1.6;\n d = [ 1.0, 2.05319162663775882187, ...\n 1.67638483018380384940, 6.89767334985100004550e-1, ...\n 1.48103976427480074590e-1, 1.51986665636164571966e-2, ...\n 5.47593808499534494600e-4, 1.05075007164441684324e-9 ];\n e = [ 6.65790464350110377720, 5.46378491116411436990, ...\n 1.78482653991729133580, 2.96560571828504891230e-1, ...\n 2.65321895265761230930e-2, 1.24266094738807843860e-3, ...\n 2.71155556874348757815e-5, 2.01033439929228813265e-7 ];\n f = [ 1.0, 5.99832206555887937690e-1, ...\n 1.36929880922735805310e-1, 1.48753612908506148525e-2, ...\n 7.86869131145613259100e-4, 1.84631831751005468180e-5, ...\n 1.42151175831644588870e-7, 2.04426310338993978564e-15 ];\n split1 = 0.425;\n split2 = 5.0;\n\n if ( p <= 0.0 )\n value = -r8_huge ( );\n return\n end\n\n if ( 1.0 <= p )\n value = r8_huge ( );\n return\n end\n\n q = p - 0.5;\n\n if ( abs ( q ) <= split1 )\n\n r = const1 - q * q;\n value = q * r8poly_value ( 8, a, r ) / r8poly_value ( 8, b, r );\n\n else\n\n if ( q < 0.0 )\n r = p;\n else\n r = 1.0 - p;\n end\n\n if ( r <= 0.0 )\n\n value = r8_huge ( );\n\n else\n\n r = sqrt ( -log ( r ) );\n\n if ( r <= split2 )\n\n r = r - const2;\n value = r8poly_value ( 8, c, r ) / r8poly_value ( 8, d, r );\n\n else\n\n r = r - split2;\n value = r8poly_value ( 8, e, r ) / r8poly_value ( 8, f, r );\n\n end\n\n end\n\n if ( q < 0.0 )\n value = -value;\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/prob/normal_01_cdf_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7050036608506589}} {"text": "function determ = ring_adj_determinant ( n )\n\n%*****************************************************************************80\n%\n%% RING_ADJ_DETERMINANT returns the determinant of the RING_ADJ matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the order of A.\n%\n% Output, real DETERM, the determinant.\n%\n if ( n == 1 )\n determ = 1.0;\n elseif ( n == 2 )\n determ = -1.0;\n elseif ( mod ( n, 4 ) == 0 )\n determ = 0.0;\n elseif ( mod ( n, 4 ) == 1 )\n determ = 2.0;\n elseif ( mod ( n, 4 ) == 2 )\n determ = -4.0;\n elseif ( mod ( n, 4 ) == 3 )\n determ = 2.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/ring_adj_determinant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.8080672227971212, "lm_q1q2_score": 0.7049153310975432}} {"text": "% book : Signals and Systems Laboratory with MATLAB \n% authors : Alex Palamides & Anastasia Veloni\n%\n%\n%\n% Transformations of the time variable - discrete time signals \n\n\n%upsampling-downsampling \n x=[1,2,3,4,5,6]\n a=2;\n xds=downsample(x,a)\n xds=x(1:a:end)\n \n a=1/2; \n xups=upsample(x,1/a)\n xups=zeros(1,1/a*length(x))\n xups(1:1/a:end)=x \n\n %all transformations\n n=-20:20; \n p=( (n>=-10)&(n<=10));\n x=(0.9.^n).*p;\n stem(n,x);\n legend('x[n]') ;\n \n figure\n stem(n+10,x)\n legend('x[n-10]') \n \n figure\n stem(n-10,x) \n legend('x[n+10]') \n \n figure\n a=2;\n xd=downsample(x,a)\n nd=-10:10;\n stem(nd,xd);\n legend('x[2n]') \n \n figure\n a=1/3\n xup=upsample(x,1/a)\n nup=-61:61\n stem(nup,xup)\n legend('x[(1/3) n]')\n \n figure\n stem(-n,x)\n legend('x[-n]') \n \n \n \n figure\n n=-2:4;\n n1=-fliplr(n)\n x=0.9.^n\n x1=fliplr(x)\n subplot(121);\n stem(n,x);\n title('x[n]=0.9^n');\n subplot(122);\n stem(n1,x1);\n title('x[-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/28762-signals-and-systems-laboratory-with-matlab-m-files/M-FILES/2/c260.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8080672181749422, "lm_q1q2_score": 0.7049153163384346}} {"text": "function [ w, x ] = line_unit_o02 ( )\n\n%*****************************************************************************80\n%\n%% LINE_UNIT_O02 returns a 2 point quadrature rule for the unit line.\n%\n% Discussion:\n%\n% The integration region is:\n%\n% - 1.0 <= X <= 1.0\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 April 2009\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Carlos Felippa,\n% A compendium of FEM integration formulas for symbolic work,\n% Engineering Computation,\n% Volume 21, Number 8, 2004, pages 867-890.\n%\n% Parameters:\n%\n% Output, real W(2), the weights.\n%\n% Output, real X(2), the abscissas.\n%\n w(1:2,1) = [ ...\n 1.0000000000000000000, ...\n 1.0000000000000000000 ];\n\n x(1:2,1) = [ ...\n -0.57735026918962576451, ...\n 0.57735026918962576451 ];\n\n return\nend\n", "meta": {"author": "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_felippa_rule/line_unit_o02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7049153136376246}} {"text": "function sphere_triangle_quad_test05 ( )\n\n%*****************************************************************************80\n%\n%% SPHERE_TRIANGLE_TEST05 tests SPHERE01_TRIANGLE_QUAD_ICOS1V.\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_TEST05\\n' );\n fprintf ( 1, ' SPHERE01_TRIANGLE_QUAD_ICOS1V 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 vertex 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_icos1v ( 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_icos1v ( 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_test05.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7048798904591964}} {"text": "function [am,em]=lpcrr2am(rr);\n%LPCRR2AM Convert autocorrelation coefs to ar coef matrix [AM,EM]=(RR)\n%AM is a 3-dimensional matrix of size (p+1,p+1,nf) where p is the lpc order\n%and nf the number of frames.\n%The matrix AM(:,:,*) is upper triangular with 1's on the main diagonal\n%and contains the lpc coefficients for all orders from p down to 0.\n%\n%For lpc order p+1-r, AM(r,r:p+1,*), AM(p+1:-1:r,p+1,*) and EM(*,r) contain\n%the lpc coefficients, reflection coefficients and the residual energy respectively.\n%\n%If A=am(:,:,*), R=toeplitz(rr(*,:)) and E=diag(em(*,:)), then\n% A*R*A'=E; inv(R)=A'*(1/E)*A; A*R is lower triangular with the same diagonal as E\n%\n% This routine is equivalent to: c=chol(inv(toeplitz(rr))); d=diag(c).^-1; em=d.^2; am=diag(d)*c\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: lpcrr2am.m,v 1.4 2007/05/04 07:01:39 dmb Exp $\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(rr);\np=p1-1;\np2=p1+1;\nam=zeros(nf,p1,p1);\nem=zeros(nf,p1);\nam(:,p1,p1)=1;\nem(:,p1)=rr(:,1);\nar=ones(nf,p1);\nar(:,2) = -rr(:,2)./rr(:,1);\ne = rr(:,1).*(ar(:,2).^2-1);\nfor n = 2:p\n q=p2-n;\n em(:,q)=-e;\n am(:,q:p1,q)=ar(:,1:n);\n k = (rr(:,n+1)+sum(rr(:,n:-1:2).*ar(:,2:n),2)) ./ e;\n ar(:,2:n) = ar(:,2:n)+k(:,ones(1,n-1)).*ar(:,n:-1:2);\n ar(:,n+1) = k;\n e = e.*(1-k.^2);\nend\nem(:,1)=-e;\nam(:,:,1)=ar;\nam=permute(am,[3 2 1]);\n\n", "meta": {"author": "decouples", "repo": "Matlab_deep_learning", "sha": "1b823b82686080e32b03e1f1a4648896bd6e3c44", "save_path": "github-repos/MATLAB/decouples-Matlab_deep_learning", "path": "github-repos/MATLAB/decouples-Matlab_deep_learning/Matlab_deep_learning-1b823b82686080e32b03e1f1a4648896bd6e3c44/第 19 章 基于语音识别的信号灯图像模拟控制技术/voicebox/lpcrr2am.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7048798886135442}} {"text": "function [z, J, H] = fun(x)\n\n[x1,x2,x3] = split(x);\n\nz = [...\n x1*x2+sin(x3);\n x2/x1-cos(x3)];\n\nif nargout > 1\n J = [...\n x2 x1 cos(x3)\n -x2/x1^2 1/x1 sin(x3)];\n\n if nargout > 2\n H(:,:,1) = [...\n 0 1 0\n 2*x2/x1^3 -1/x1^2 0];\n\n H(:,:,2) = [...\n 1 0 0\n -1/x1^2 0 0];\n\n H(:,:,3) = [...\n 0 0 -sin(x3)\n 0 0 cos(x3)];\n end\nend\nreturn\n\n%% jac\nsyms x1 x2 x3 real\nx = [x1;x2;x3];\n\nz = fun(x);\n\nJ = jacobian(z,x)\nH1 = diff(J,'x1')\nH2 = diff(J,'x2')\nH3 = diff(J,'x3')\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/fun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053282, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.7048325850089999}} {"text": "% T in K\n% es in Pa\nfunction [T, T_approx] = calculate_saturation_vapor_pressure_liquid_inv (...\nes, method, tol_T)\n if (nargin < 2) || isempty(method), method = ''; end % [] ~= ''\n if (nargin < 3) || isempty(tol_T), tol_T = eps; end\n\n switch method\n case {'Bolton1980', 'approx'}\n % this also serves as a good starting point for more elaborate methods.\n es2 = es ./ 1e3;\n temp = log(es2 ./ 0.6112) ./ 17.67;\n t = 243.5 .* temp ./ (1 - temp);\n T = t + 273.15;\n if (nargout > 1), T_approx = T; end\n otherwise\n T_approx = calculate_saturation_vapor_pressure_liquid_inv (es,'approx');\n f = @(T_) calculate_saturation_vapor_pressure_liquid (T_, method);\n temp = warning('off', ...\n 'calculate_saturation_vapor_pressure_liquid:outRange');\n T = inv_func2 (f, es, T_approx, tol_T);\n warning(temp);\n % we disable the warning because fzero may rightesously probe \n % outside the valid range, in the search for the root.\n end\nend\n\n%!test\n%! method = 'Bolton1980';\n%! T = (123:10:332)';\n%! es = calculate_saturation_vapor_pressure_liquid (T, method);\n%! [T2, T3] = calculate_saturation_vapor_pressure_liquid_inv (es, method);\n%! %[T, T2, T3, T2-T, T3-T] % DEBUG\n%! %max(abs(T2-T)) % DEBUG\n%! tol = eps;\n%! myassert(T2, T, -tol)\n\n%!test\n%! method = 'Murphy&Koop2005';\n%! T = (123:10:332)';\n%! es = calculate_saturation_vapor_pressure_liquid (T, method);\n%! [T2, T3] = calculate_saturation_vapor_pressure_liquid_inv (es, method);\n%! %[T, T2, T3, T2-T, T3-T] % DEBUG\n%! %max(abs(T2-T)) % DEBUG\n%! tol = nthroot(eps, 3);\n%! myassert(T2, T, -tol)\n\n%!test\n%! % empty method should work.\n%! method = [];\n%! T = (123:10:332)';\n%! es = calculate_saturation_vapor_pressure_liquid (T, method);\n%! [T2, T3] = calculate_saturation_vapor_pressure_liquid_inv (es, method);\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/30553-converthumidity/convert_humidity/calculate_saturation_vapor_pressure_liquid_inv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.8198933315126792, "lm_q1q2_score": 0.7048325822819678}} {"text": "function [ x, seed ] = f_alpha ( n, q_d, alpha, seed )\n\n%*****************************************************************************80\n%\n%% F_ALPHA generates a 1/F^ALPHA noise sequence.\n%\n% Discussion:\n%\n% Thanks to Miro Stoyanov for pointing out that the second half of\n% the data returned by the inverse Fourier transform should be\n% discarded, 24 August 2010.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 August 2010\n%\n% Author:\n%\n% Original C version by Todd Walter.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Jeremy Kasdin,\n% Discrete Simulation of Colored Noise and Stochastic Processes\n% and 1/f^a Power Law Noise Generation,\n% Proceedings of the IEEE,\n% Volume 83, Number 5, 1995, pages 802-827.\n%\n% Parameters:\n%\n% Input, integer N, the number of samples to generate.\n%\n% Input, real Q_D, the variance of the noise.\n%\n% Input, real ALPHA, the exponent for the noise.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X(N), a sequence sampled with the given power law.\n%\n% Output, integer SEED, a seed for the random number generator.\n%\n\n% Set the deviation of the noise.\n%\n q_d = sqrt ( q_d );\n%\n% Generate the coefficients Hk.\n%\n hfa = zeros ( 2 * n, 1 );\n hfa(1) = 1.0; \n for i = 2 : n\n hfa(i) = hfa(i-1) * ( 0.5 * alpha + ( i - 2 ) ) / ( i - 1 );\n end\n hfa(n+1:2*n) = 0.0;\n%\n% Fill Wk with white noise.\n%\n wfa = zeros ( 2 * n, 1 );\n for i = 1 : n\n [ wfa(i), seed ] = r8_normal_01 ( seed );\n end\n wfa(1:n) = wfa(1:n) * q_d;\n wfa(n+1:2*n) = 0.0;\n%\n% Perform the discrete Fourier transforms of Hk and Wk.\n%\n [ h_azero, h_a, h_b ] = r8vec_sftf ( 2 * n, hfa );\n\n [ w_azero, w_a, w_b ] = r8vec_sftf ( 2 * n, wfa );\n%\n% Multiply the two complex vectors.\n%\n w_azero = w_azero * h_azero;\n\n for i = 1 : n\n wr = w_a(i);\n wi = w_b(i);\n w_a(i) = wr * h_a(i) - wi * h_b(i);\n w_b(i) = wi * h_a(i) + wr * h_b(i);\n end\n%\n% This scaling is introduced only to match the behavior\n% of the Numerical Recipes code...\n%\n w_azero = w_azero * 2 * n;\n\n w_a(1:n-1) = w_a(1:n-1) * n;\n w_b(1:n-1) = w_b(1:n-1) * n;\n\n w_a(n) = w_a(n) * 2 * n;\n w_b(n) = w_b(n) * 2 * n;\n%\n% Take the inverse Fourier transform of the result.\n%\n x = r8vec_sftb ( 2 * n, w_azero, w_a, w_b );\n%\n% Discard the second half of the inverse Fourier transform.\n%\n x = 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/colored_noise/f_alpha.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7048108776362221}} {"text": "function [mn] = calcSpectralMoment(angFreq,S_f,order)\n% Parameters\n% ------------\n% angFreq : [1 n] float vector\n% Vector of wave angular frequencies\n% \n% S_f : [1 n] float vector\n% Vector of wave spectra\n% \n% order : float\n% Order of the spectral moment\n%\n% Returns\n% ------------\n% mn : float vector\n% Spectral moment of the nth order\n%\n\n% Check the dimensions of angFreq and S_f \n[raf,caf] = size(angFreq);\n[rsf,csf] = size(S_f);\nif raf ~= rsf && caf ~= csf\n if raf == csf && caf == rsf\n S_f = S_f.';\n else\n disp('The vectors for wave angular frequency and spectral moment must be the same size')\n mn = NaN;\n return\n end\nend\n\n% Check the dimensions of order\n[ro,co] = size(order);\nif ro ~= 1 || co ~=1\n disp('The order of the spectal moment calculation must be a scale value')\n mn = NaN;\n return\nend\n\n% Spectral moment calculation\nmn = trapz(angFreq,angFreq.^(order).*S_f);\nend\n", "meta": {"author": "WEC-Sim", "repo": "WEC-Sim", "sha": "973dd8c437077b20b361a5c0dba733da98ca9285", "save_path": "github-repos/MATLAB/WEC-Sim-WEC-Sim", "path": "github-repos/MATLAB/WEC-Sim-WEC-Sim/WEC-Sim-973dd8c437077b20b361a5c0dba733da98ca9285/source/functions/BEMIO/calcSpectralMoment.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7048108660300699}} {"text": "function [L, Nc] = discretize(S, N)\n%DISCRETIZE Discretize a SPINOP2.\n% [L, NC] = DISCRETIZE(S, N) uses a Fourier spectral method in coefficient \n% space to discretize the SPINOP2 S with N grid points in each direction. L is \n% the linear part, a N^2xN^2 diagonal matrix stored as a NxN matrix, and NC is \n% the differentiation term of the nonlinear part (and hence is linear).\n%\n% Remark: DISCRETIZE will fail to discretize SPINOP2 objects which are not of \n% the right form. See HELP/SPINOP2.\n%\n% See also SPINOP2.\n\n% Copyright 2017 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n%% Set-up:\n \n% Get the domain DOM, the linear part LFUN, the nonlinear part NFUN, and the \n% number of variables NVARS from S:\ndom = S.domain;\nfuncL = S.lin;\nnVars = nargin(funcL);\n\n% Get the variables of the workspace:\nfunc = functions(funcL);\nwrk = func.workspace{1};\nnames = fieldnames(wrk);\nif ( isempty(names) == 0 )\n lengthNames = size(names, 1);\n for k = 1:lengthNames\n eval(sprintf('%s = wrk.(names{k});', names{k}));\n end\nend\n \n% Create a CHEBOPPREF object with TRIGSPEC discretization:\npref = cheboppref();\npref.discretization = @trigspec;\n\n%% Discretize the linear part:\n\n% Second-order Fourier differentiation matrix with TRIGSPEC (sparse diagonal \n% matrix):\nD2 = trigspec.diffmat(N,2)*(2*pi/(dom(2) - dom(1)))^2;\nif ( mod(N,2) == 0 )\n D2 = fftshift(D2);\nelse\n D2 = ifftshift(D2);\nend\n\n% Look for 'laplacian'/'lap', 'biharmonic'/'biharm', 'triharmonic'/'triharm',\n% 'quadharmonic'/'quadharm' or 'quintharmomic'/'quintharm':\nstrL = func2str(funcL);\nisLap = isempty(strfind(strL,'laplacian')) && isempty(strfind(strL,'lap'));\nisLap = ~isLap;\nisBih = isempty(strfind(strL,'biharmonic')) && isempty(strfind(strL,'biharm'));\nisBih = ~isBih;\nisTrih = isempty(strfind(strL,'triharmonic')) ...\n && isempty(strfind(strL,'triharm'));\nisTrih = ~isTrih;\nisQuadh = isempty(strfind(strL,'quadharmonic')) ...\n && isempty(strfind(strL,'quadharm'));\nisQuadh = ~isQuadh;\nisQuinth = isempty(strfind(strL,'quintharmonic')) ...\n && isempty(strfind(strL,'quintharm'));\nisQuinth = ~isQuinth;\n\n% NxN identity matrix for the Kronecker products:\nI = eye(N);\n\n% Construct the Laplacian operator -- needed for all the operators:\nif ( isLap || isBih || isTrih || isQuadh || isQuinth )\n \n % Compute the N^2xN^2 Laplacian with KRON:\n lapmat = kron(I, D2) + kron(D2, I);\n \n % Create a NxN matrix with the diagonal of the N^2xN^2 Laplacian:\n lapmat = reshape(full(diag(lapmat)), N, N);\n \nelse\n lapmat = 0;\nend\n\n% The linear part has a B*biharmonic(u) term:\nif ( isBih == 1 )\n \n % Pointwise multiplication since we only store the diagonal elements:\n bihmat = lapmat.^2;\n \nelse\n bihmat = 0;\nend\n\n% The linear part has a C*triharmonic(u) term:\nif ( isTrih == 1 )\n \n % Pointwise multiplication since we only store the diagonal elements:\n trihmat = lapmat.^3;\n \nelse\n trihmat = 0;\nend\n\n% The linear part has a D*quadharmonic(u) term:\nif ( isQuadh == 1 )\n \n % Pointwise multiplication since we only store the diagonal elements:\n quadhmat = lapmat.^4;\n \nelse\n quadhmat = 0;\nend\n\n% The linear part has a E*quintharmonic(u) term:\nif ( isQuinth == 1 )\n \n % Pointwise multiplication since we only store the diagonal elements:\n quinthmat = lapmat.^5;\n \nelse\n quinthmat = 0;\nend\n\n% Convert to a string and initialize L:\nstrL = func2str(funcL);\nL = [];\n\n% Get the constants A in front of the Laplacians:\nstr = strrep(strL, 'laplacian', '');\nstr = strrep(str, 'lap', '');\nstr = strrep(str, 'biharmonic', '0*');\nstr = strrep(str, 'biharm', '0*');\nstr = strrep(str, 'triharmonic', '0*');\nstr = strrep(str, 'triharm', '0*');\nstr = strrep(str, 'quadharmonic', '0*');\nstr = strrep(str, 'quadharm', '0*');\nstr = strrep(str, 'quintharmonic', '0*');\nstr = strrep(str, 'quintharm', '0*');\nfunc = eval(str);\ninputs = cell(1, nVars);\nfor k = 1:nVars\n inputs{k} = 1; \nend\nA = feval(func, inputs{:}); \n\n% Get the constants B in front of the biharmonic operators:\nstr = strrep(strL, 'laplacian', '0*');\nstr = strrep(str, 'lap', '0*');\nstr = strrep(str, 'biharmonic', '');\nstr = strrep(str, 'biharm', '');\nstr = strrep(str, 'triharmonic', '0*');\nstr = strrep(str, 'triharm', '0*');\nstr = strrep(str, 'quadharmonic', '0*');\nstr = strrep(str, 'quadharm', '0*');\nstr = strrep(str, 'quintharmonic', '0*');\nstr = strrep(str, 'quintharm', '0*');\nfunc = eval(str);\nB = feval(func, inputs{:}); \n\n% Get the constants C in front of the triharmonic operators:\nstr = strrep(strL, 'laplacian', '0*');\nstr = strrep(str, 'lap', '0*');\nstr = strrep(str, 'biharmonic', '0*');\nstr = strrep(str, 'biharm', '0*');\nstr = strrep(str, 'triharmonic', '');\nstr = strrep(str, 'triharm', '');\nstr = strrep(str, 'quadharmonic', '0*');\nstr = strrep(str, 'quadharm', '0*');\nstr = strrep(str, 'quintharmonic', '0*');\nstr = strrep(str, 'quintharm', '0*');\nfunc = eval(str);\nC = feval(func, inputs{:}); \n\n% Get the constants D in front of the quadharmonic operators:\nstr = strrep(strL, 'laplacian', '0*');\nstr = strrep(str, 'lap', '0*');\nstr = strrep(str, 'biharmonic', '0*');\nstr = strrep(str, 'biharm', '0*');\nstr = strrep(str, 'triharmonic', '0*');\nstr = strrep(str, 'triharm', '0*');\nstr = strrep(str, 'quadharmonic', '');\nstr = strrep(str, 'quadharm', '');\nstr = strrep(str, 'quintharmonic', '0*');\nstr = strrep(str, 'quintharm', '0*');\nfunc = eval(str);\nD = feval(func, inputs{:}); \n\n% Get the constants E in front of the quintharmonic operators:\nstr = strrep(strL, 'laplacian', '0*');\nstr = strrep(str, 'lap', '0*');\nstr = strrep(str, 'biharmonic', '0*');\nstr = strrep(str, 'biharm', '0*');\nstr = strrep(str, 'triharmonic', '0*');\nstr = strrep(str, 'triharm', '0*');\nstr = strrep(str, 'quadharmonic', '');\nstr = strrep(str, 'quadharm', '');\nstr = strrep(str, 'quintharmonic', '');\nstr = strrep(str, 'quintharm', '');\nfunc = eval(str);\nE = feval(func, inputs{:}); \n\n% Compute L:\nfor k = 1:nVars\n L = [L; A(k)*lapmat + B(k)*bihmat + C(k)*trihmat + D(k)*quadhmat + ...\n E(k)*quinthmat]; \nend\n\n%% Disretize the differentiation term of the nonlinear part:\n\n% We only support no differentiation, i.e., NC = 1.\n% [TODO]: Support diff order > 1.\nNc = 1;\n\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@spinop2/discretize.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7047988631590285}} {"text": "% SOSDEMO7 --- Chebyshev polynomials\n% Section 3.7 of SOSTOOLS User's Manual\n\nclear; echo on;\n \nndeg = 8; % Degree of Chebyshev polynomial\n\nsyms x gam;\n\n% =============================================\n% First, initialize the sum of squares program\nprog = sosprogram([x],[gam]);\n\n\n% Create the polynomial P\nZ = monomials(x,[0:ndeg-1]);\n[prog,P1] = sospolyvar(prog,Z);\nP = P1 + gam * x^ndeg; % The leading coeff of P is gam\n\n% Imposing the inequalities\nprog = sosineq(prog, 1 - P, [-1, 1]);\nprog = sosineq(prog, 1 + P, [-1, 1]);\n\n% And setting objective\nprog = sossetobj(prog, -gam);\n\n% Then solve the program\nprog = sossolve(prog);\n\n% =============================================\n% Finally, get solution\nSOLV = sosgetsol(prog, P)\nGAM = sosgetsol(prog, gam)\n\necho off\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/SOSTOOLS.300/SOSTOOLS.300/demos/sosdemo7.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.7047988603166043}} {"text": "function sar = sar(high, low)\n %constants\n uptrend = 1;\n downtrend = 2;\n sar(1)=NaN;\n \n %variables\n alpha=0.02;\n EP=high(1);%between the high and low\n \n %'previous trade' is either long or short on day 1. sar(1)=NaN\n \n %decide whether to start with long or short\n if(high(1)>high(2))\n position=uptrend;\n else\n position=downtrend;\n end\n \n if(position==uptrend)\n sar(1)=high(1);\n else\n sar(1)=low(1);\n end\n \n for n=1:length(high)-1\n if(position==uptrend)\n EP=min(EP,low(n));\n else\n EP=max(EP,high(n));\n end\n alpha=min(alpha+0.02,0.2);\n sar(n+1)=sar(n)+alpha*(EP-sar(n));\n \n %\"Parabolic SAR is never moved within the range of the current\n %or previous day (highest High to lowest Low over the 2 days).\"\n if(n>2)\n if(sar(n+1)min(low(n-1),low(n)))\n if(position==downtrend)\n sar(n+1)=min(low(n-1),low(n));\n else\n sar(n+1)=max(high(n-1),high(n));\n end\n end\n end\n if(sar(n+1)low(n+1))\n sar(n+1)=EP;\n if(position==uptrend)\n position=downtrend;\n EP=low(n);\n else\n position=uptrend;\n EP=high(n);\n end\n alpha=0.02;\n %sar(n+1)=sar(n)+alpha*(EP-sar(n));\n end\n end\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/30382-parabolic-sar/sar.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.7047988536894377}} {"text": "% Script used to generate a visualisation of how well EKF, UKF and PF\n% approximate a distribution\n% =========================================================================\n\n% Assume a target positioned at x = 1, travelling with speed v = 0.1\nstate = [2000; 0.1; 0; 0];\n\n% Instantiate an Observation model\n% obs = LinGaussObsModelX_2D('NumStateDims',4,'ObsErrVariance',0.2,'Mapping',[1 2]);\nobs = RangeBearing2CartesianX('NumStateDims',4,'MeasurementErrVariance',[(pi/90)^2,(1)^2],...\n 'Mapping',[1 3]);\n\n% View the transition matrix and process covariance matrices\nR = obs.covar();\n\n% Predict the target's position and velocity after the interval has passed\nmeasurement = obs.feval(state);\n\n%% EKF\n[ekf_mean, H_jac] = ExtendedKalmanFilterX.computeJac_(@(x)obs.finv(x),measurement);\nekf_covar = H_jac*R*H_jac';\n\n%% UKF\nalpha = 0.5;\nkappa = 0;\nbeta = 2;\n% Calculate unscented transformation parameters\n[c, Wmean, Wcov, OOM] = matlabshared.tracking.internal.calcUTParameters(alpha,beta,kappa,2);\n% Form the sigma points\nX = formSigmaPoints(measurement, R, c);\n% Perform Unscented Transform to get predicted measurement mean,\n% covariance and cross-covariance\n[ukf_mean,ukf_covar,Pxy] = unscentedTransform(@(x)obs.finv(x),X,Wmean,Wcov,OOM);\n\n%% PF\n% Generate 50 random noise samples from the dynamic model\nnoise = obs.random(50000000);\n\n% Add noise to the measurements\nYk1 = noise + measurement;\nXk1 = obs.finv(Yk1);\n\nXk = [Xk1];%,Xk2];\nYk = [Yk1];%,Yk2];\n\nfigure;\n[bandwidth,density,X,Y]=kde2d(Xk([1,3],:)');\nxLim = [1985,2005];\nyLim = [-200,200];\n\n% EKF\nsubplot(1,3,1);\n%contour(X,Y,density,1);\nh = surf(X,Y,density);\nz = get(h,'ZData');\n% set(h,'ZData',z-10^6)\nhold on;\nshading interp\nx1 = xLim(1):0.1:xLim(2); x2 = yLim(1):0.1:yLim(2);\n[X1,X2] = meshgrid(x1,x2);\nF = mvnpdf([X1(:) X2(:)],ekf_mean([1,3])',ekf_covar([1,3],[1,3]));\nF = reshape(F,length(x2),length(x1));\ncontour(x1,x2,F,4,'r','LineWidth',2);\n% plot_gaussian_ellipsoid(ekf_mean([1,3]),ekf_covar([1,3],[1,3]),'r',1);\n% plot_gaussian_ellipsoid(ekf_mean([1,3]),ekf_covar([1,3],[1,3]),'r',2);\n% shading interp\n%colormap(jet(3000))\ntitle('Taylor-Series Expansion (EKF)')\nxlabel('X (m)');\nylabel('Y (m)');\nxlim(xLim);\nylim(yLim);\nview(0,-90);\n\n% UKF\nsubplot(1,3,2);\nh = surf(X,Y,density);\nz = get(h,'ZData');\n%set(h,'ZData',z-10^6)\nhold on;\nshading interp\nx1 = xLim(1):0.1:xLim(2); x2 = yLim(1):0.1:yLim(2);\n[X1,X2] = meshgrid(x1,x2);\nF = mvnpdf([X1(:) X2(:)],ukf_mean([1,3])',ukf_covar([1,3],[1,3]));\nF = reshape(F,length(x2),length(x1));\ncontour(x1,x2,F,4,'r','LineWidth',2);\n%plot_gaussian_ellipsoid(ukf_mean([1,3]),ukf_covar([1,3],[1,3]),'r',1);\n%plot_gaussian_ellipsoid(ukf_mean([1,3]),ukf_covar([1,3],[1,3]),'r',2);\n%colormap(jet(3000))\ntitle('Unscented Transform (UKF)')\nxlabel('X (m)');\nylabel('Y (m)');\nxlim(xLim);\nylim(yLim);\nview(0,-90);\n\n\n% PF\nsubplot(1,3,3);\n%contour(X,Y,density,1);\nh = surf(X,Y,density);\nz = get(h,'ZData');\n%set(h,'ZData',z-10^6)\nhold on; \nshading interp\n%plot(Xk(1,1:1000),Xk(3,1:1000),'r.');\n%[bandwidth,density,X,Y]=kde2d(Xk([1,3],1:10000)');\ncontour(X,Y,density,4,'r','LineWidth',2)\n%colormap(jet(3000))\ntitle('Sampling (PF)')\n%set(h,'ZData',z-10)\nxlabel('X (m)');\nylabel('Y (m)');\n%set(gca,'Xdir','reverse')\nset(gca,'Ydir','reverse')\nxlim(xLim);\nylim(yLim);\nview(0,-90);\n\n% model = PositionalObsModelX(config);%PositionalObsModelX(config);%Polar2CartGaussianModelX(config);\n% \n% xkm1 = [0.5; 0.3; sqrt(2); sqrt(2)];\n% pkm1 = [0 0.5; 0 0.3; sqrt(2) sqrt(2); sqrt(2) sqrt(2)];\n% Pkm1 = [0 1 0 1; 0 1 0 1; 0 1 0 1; 1 1 0 1];\n% yk = model.obs(1,xkm1);\n% Yk = model.sample(1, yk, 500000);\n% pk = model.obs_cov();\n% Pk = model.eval(1,Yk,xkm1);\n% [bandwidth,density,X,Y]=kde2d(Yk');\n% figure;\n% %contour3(X,Y,density,50);\n% surf(X,Y,density);\n% hold on;", "meta": {"author": "sglvladi", "repo": "TrackingX", "sha": "f737445c070f0d7d470f52f8a2b5540d5bb682da", "save_path": "github-repos/MATLAB/sglvladi-TrackingX", "path": "github-repos/MATLAB/sglvladi-TrackingX/TrackingX-f737445c070f0d7d470f52f8a2b5540d5bb682da/Workspace/STT/3rd-Year-Annual-Report/approximation_viz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7047988518048016}} {"text": "function s = logsumexp(x, dim)\n% Returns log(sum(exp(x),dim)) while avoiding numerical underflow.\n% Default is dim = 1 (columns).\n% Written by Mo Chen (mochen@ie.cuhk.edu.hk). March 2009.\n\n% Downloaded from:\n% http://www.mathworks.com/matlabcentral/fileexchange/28899-logsumexp/content/logsumexp.m\n% \n% Copyright (c) 2010, Michael Chen\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\nif nargin == 1, \n % Determine which dimension sum will use\n dim = find(size(x)~=1,1);\n if isempty(dim), dim = 1; end\nend\n\n% subtract the largest in each column\ny = max(x,[],dim);\nx = bsxfun(@minus,x,y);\ns = y + log(sum(exp(x),dim));\ni = find(~isfinite(y));\nif ~isempty(i)\n s(i) = y(i);\nend\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/ndlutil/logsumexp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.7047988508470133}} {"text": "function bti_test06 ( )\n\n%*****************************************************************************80\n%\n%% BTI_TEST06 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_TEST06\\n' );\n fprintf ( 1, ' Test BURGERS_TIME_INVISCID\\n' );\n\n method = 6;\n nx = 81;\n nt = 200;\n t_max = 2.0;\n bc = 4;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Method: 6, Godonov.\\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 ( 6 )\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, Godonov' )\n\n filename = 'bti_test06.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_test06.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8670357718273068, "lm_q1q2_score": 0.7047850423144932}} {"text": "function cnoise_test02 ( m, n, var, r, alpha )\n\n%*****************************************************************************80\n%\n%% CNOISE_TEST02 tests F_ALPHA_TGAUSSIAN.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 01 April 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of realizations to create.\n%\n% Input, integer N, the size of the noise vector.\n%\n% Input, real VAR, the variance of the Gaussian distribution.\n%\n% Input, real R, defines the truncated range of the distribution.\n%\n% Input, real ALPHA, the value of ALPHA.\n%\n scale = exp ( 0.5 * ( 1.0 - alpha ) * log ( n ) );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CNOISE_TEST02:\\n' );\n fprintf ( 1, ' Test F_ALPHA_TGAUSSIAN.\\n' );\n fprintf ( 1, ' Noise is generated from a truncated Gaussian distribution\\n' );\n fprintf ( 1, ' with a specified variance and range.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of realizations M = %d\\n', m );\n fprintf ( 1, ' Dimension of noise vector N = %d\\n', n );\n fprintf ( 1, ' Noise exponent ALPHA = %f\\n', alpha );\n fprintf ( 1, ' Variance of Gaussian distribution VAR = %f\\n', var );\n fprintf ( 1, ' Truncated range = [ %f, %f ]\\n', -r, r );\n fprintf ( 1, ' Scale factor SCALE = %f\\n', scale );\n\n res = zeros ( m, 1 );\n\n tic\n for i = 1 : m\n x = f_alpha_tgaussian ( n, var, r, alpha );\n x = scale * x;\n res(i) = mean ( x );\n end\n result_time = toc;\n\n result_mean = mean ( res );\n result_std = std ( res );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Mean value of noise = %f\\n', result_mean );\n fprintf ( 1, ' STD of noise = %f\\n', result_std );\n fprintf ( 1, ' Computation time = %f seconds\\n', result_time );\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/cnoise/cnoise_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7047824972504155}} {"text": "function A = randsym(n,cnd)\n%RANDSYM Random symmetric matrix\n%\n% res = randsym(n,cnd)\n%\n% cnd, if specified, is the approximate condition number of the generated matrix\n%\n\n% written 11/05/12 S.M. Rump\n% modified 12/06/12 S.M. Rump lower case\n%\n\n if nargin==1\n A = randn(n);\n else\n s = exp( [ 0 rand(1,n-2) 1 ] * log(cnd) ) / cnd;\n A = randorth(n);\n A = A' * diag(s.*sign(randn(1,n))) * A;\n end\n\n % make sure A is symmetric\n A = tril(A)+tril(A,-1)';\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/utility/randsym.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7047663595370095}} {"text": "function [K] = spm_sptop(sigma,q,c)\n% Sparse Toeplitz convolution matrix given convolution kernel\n% FORMAT [K] = spm_sptop(sigma,q,c)\n%\n% sigma - of Gaussian kernel K (or kernel itself)\n% q - order of matrix\n% c - kernel index at t = 0 {default c = length(sigma)/2) \n% K - q x q sparse convolution matrix\n%_______________________________________________________________________\n%\n% Returns a q x q sparse convolution matrix. If sigma is a scalar then\n% a symmetrical Gaussian convolution matrix is returned with kernel width\n% = sigma. If sigma is a vector than sigma constitutes the kernel. To\n% obtain an assymmetrical convolution matrix (i.e. implement a phase shift\n% set c = 1.\n%\n% Boundary handling: The row-wise sum of K is set to unity (kernel truncation)\n%\n%_______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n% Karl Friston\n% $Id: spm_sptop.m 1143 2008-02-07 19:33:33Z spm $\n\n\n% if sigma = 0, return identity matrix; if q = 1, return 1.\n%-----------------------------------------------------------------------\nif ~any(sigma); K = speye(q); return; end\nif q == 1; K = 1; return; end\n\n% otherwise get kernel function\n%-----------------------------------------------------------------------\nif length(sigma) == 1\n E = ceil(3*sigma);\n x = [-E:E];\n k = exp(-x.^2/(2*sigma^2));\nelse\n if nargin < 3\n c = length(sigma)/2;\n end\n E = length(sigma);\n x = [1:E] - fix(c);\n k = sigma;\nend\n\n% and create convolution matrix\n%-----------------------------------------------------------------------\nK = k(:)*ones(1,q);\nj = ones(length(k),1)*[1:q];\ni = x(:)*ones(1,q) + j;\n\n% setting the row-wise sum to unity\n%-----------------------------------------------------------------------\nQ = find((i >= 1) & (i <= q));\nK = sparse(i(Q),j(Q),K(Q));\nQ = sum(K');\nK = inv(diag(Q + (~Q)))*K;\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/spm_sptop.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.7047663533358993}} {"text": "function mbasis = basis_matrix_overhauser_nul ( alpha )\n\n%*****************************************************************************80\n%\n%% BASIS_MATRIX_OVERHAUSER_NUL sets up the nonuniform left Overhauser spline basis matrix.\n%\n% Discussion:\n%\n% This basis matrix assumes that the data points P1, P2, and\n% P3 are not uniformly spaced in T, and that P1 corresponds to T = 0,\n% and P2 to T = 1. (???)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 13 February 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real ALPHA.\n% ALPHA = || P2 - P1 || / ( || P3 - P2 || + || P2 - P1 || )\n%\n% Output, real MBASIS(3,3), the basis matrix.\n%\n mbasis(1,1) = 1.0 / alpha;\n mbasis(1,2) = - 1.0 / ( alpha * ( 1.0 - alpha ) );\n mbasis(1,3) = 1.0 / ( 1.0 - alpha );\n\n mbasis(2,1) = - ( 1.0 + alpha ) / alpha;\n mbasis(2,2) = 1.0 / ( alpha * ( 1.0 - alpha ) );\n mbasis(2,3) = - alpha / ( 1.0 - alpha );\n\n mbasis(3,1) = 1.0;\n mbasis(3,2) = 0.0;\n mbasis(3,3) = 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/basis_matrix_overhauser_nul.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7047254200382281}} {"text": "function [ Y, gR, gPhi, gTheta ] = AFMT3( X, sigma, mAFMT, nAFMT, pAFMT, extrapVal, interpMethod, algorithm )\n%Computes discrete approximation to analytic fourier-mellin transformation.\n%Parameters:\n% x ...matrix with input data\n% sigma ...strictly positive number, ensuring\n% existence of transformation\n% mAFMT ...size of mellin-transformation (check)\n%\n% nAFMT ...size of fourier-transformation (check)\n\n%algorithm selects: F-AFMT ...fast AFMT\n% D-AFMT ...discrete AFMT\n%\n% (c) Lukas Mauch, Thomas Kuestner \n% ---------------------------------------------------------------------\n\nswitch algorithm\n %% forward-transformation (3d):\n case 'F-AFMT' \n [yLogPol, gR, gPhi, gTheta] = convToLogPol(X, mAFMT, nAFMT, pAFMT, interpMethod);\n scaleFactor = exp(2*pi*(gR./max(max(max(gR)))) * sigma); %maximal radius normalized to 2*pi \n Y = fftnshift(scaleFactor .* yLogPol, 1:3);\n \n case 'D-AFMT'\n \n %% backward-transformation:\n case 'iF-AFMT' \n [sizeY, sizeX, sizeZ] = size(X);\n \n %Compute center positions oM and oN:\n oY = fix(mAFMT/2)+1;\n oX = fix(nAFMT/2)+1;\n oZ = fix(pAFMT/2)+1;\n \n %Cartesian sample points:\n [gridCartX, gridCartY, gridCartZ] = meshgrid( -oX+1:nAFMT-oX, -oY+1:mAFMT-oY, -oZ+1:pAFMT-oZ );\n \n %Log-polar plane sample points:\n R = sqrt(max(abs(oY-1), abs(mAFMT-oY))^2 + max(abs(oX-1), abs(nAFMT-oX))^2 + ...\n max(abs(oZ-1), abs(pAFMT-oZ))^2); \n [gridR, gridPhi, gridTheta] = meshgrid( log(R)/sizeX:log(R)/sizeX:log(R), ...\n linspace(0,2*pi, sizeY), ...\n linspace(-pi/2, pi/2, sizeZ));\n \n scaleFactor = exp(-2*pi*sigma*(gridR./max(max(max(gridR)))));\n yLogPol = scaleFactor .* ifftnshift(X, 1:3);\n \n Y = convToCart(yLogPol, gridR, gridPhi, gridTheta, gridCartX, gridCartY, gridCartZ, interpMethod);\n \n case 'iD-AFMT' \n \n otherwise \n error('Unknown type of algorithm!')\n \nend\n\n\n %% helper functions:\n function [xLogPol, gridR, gridPhi, gridTheta] = convToLogPol( xCart, sizeR, sizePhi, sizeTheta, interpMethod )\n [m, n, p] = size(xCart);\n \n %Compute center positions oM and oN:\n oM = fix(m/2)+1;\n oN = fix(n/2)+1;\n oP = fix(p/2)+1;\n \n %Cartesian sample points:\n [gridX, gridY, gridZ] = meshgrid( -oN+1:n-oN, fliplr(-oM+1:m-oM), -oP+1:p-oP );\n \n %Log-polar plane sample points:\n maxR = sqrt(max(abs(oN-1), abs(n-oN))^2 + max(abs(oM-1), abs(m-oM))^2 + max(abs(oP-1), abs(p-oP))^2);\n [gridR, gridPhi, gridTheta] = meshgrid( log(maxR)/sizeR:log(maxR)/sizeR:log(maxR), ...\n linspace(0,2*pi,sizePhi), ...\n linspace(-pi/2, pi/2, sizeTheta));\n \n %Perform conversion to log-polar coordinates, using linear interpolation:\n convGridX = exp(gridR) .* cos(gridPhi) .* cos(gridTheta);\n convGridY = exp(gridR) .* sin(gridPhi) .* cos(gridTheta);\n convGridZ = exp(gridR) .* sin(gridTheta);\n xLogPol = interp3(gridX, gridY, gridZ, xCart, ...\n convGridX, convGridY, convGridZ, interpMethod, extrapVal);\n end\n\n function xCart = convToCart( xLogPol, gridR, gridPhi, gridTheta, gridX, gridY, gridZ, interpMethod ) \n %Perform conversion to cartesian coordinates:\n% convGridX = reshape(exp(gridR) .* cos(gridPhi) .* cos(gridTheta),[], 1);\n% convGridY = reshape(exp(gridR) .* sin(gridPhi) .* cos(gridTheta),[], 1);\n% convGridZ = reshape(exp(gridR) .* sin(gridTheta),[], 1);\n% F = TriScatteredInterp(convGridX, convGridY, convGridZ, reshape(xLogPol, [], 1), interpMethod);\n% xCart = F(gridX, gridY, gridZ);\n \n %interpolation in r-phi plane (worse but fast):\n convGridR = sqrt(abs(gridX).^2 + abs(gridY).^2 + abs(gridZ).^2);\n convGridPhi = atan(gridY./gridX);\n convGridTheta = asin(gridZ./convGridR);\n %unwrap:\n qA = logical(logical((gridX >= 0)) .* logical((gridY<=0)));\n qB = logical(logical((gridX < 0)) .* logical((gridY<=0)));\n qC = logical(logical((gridX < 0)) .* logical((gridY>0)));\n qD = logical(logical((gridX >= 0)) .* logical((gridY>0)));\n convGridPhi(qA) = abs(convGridPhi(qA));\n convGridPhi(qB) = pi-convGridPhi(qB);\n convGridPhi(qC) = pi+abs(convGridPhi(qC));\n convGridPhi(qD) = 2*pi-convGridPhi(qD);\n convGridPhi(isnan(convGridPhi)) = 0;\n convGridTheta(isnan(convGridTheta)) = 0;\n \n xCart = interp3(exp(gridR), gridPhi, gridTheta, xLogPol, ...\n convGridR, convGridPhi, convGridTheta, interpMethod, extrapVal);\n \n \n end\n\nend\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/FourierMellin/AFMT3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.7047254035195974}} {"text": "function [L, U, P, Q] = gecp(A)\n%GECP calculate Gauss elimination with complete pivoting\n%\n% (G)aussian (E)limination (C)omplete (P)ivoting\n% Input : A nxn matrix\n% Output\n% L = Lower triangular matrix with ones as diagonals \n% U = Upper triangular matrix\n% P and Q permutations matrices so that P*A*Q = L*U \n% \n% See also LU\n%\n% written by : Cheilakos Nick \n[n, n] = size(A);\np = 1:n; \nq = 1:n;\nfor k = 1:n-1\n [maxc, rowindices] = max( abs(A(k:n, k:n)) );\n [maxm, colindex] = max(maxc);\n row = rowindices(colindex)+k-1; col = colindex+k-1;\n A( [k, row], : ) = A( [row, k], : );\n A( :, [k, col] ) = A( :, [col, k] );\n p( [k, row] ) = p( [row, k] ); q( [k, col] ) = q( [col, k] );\n if A(k,k) == 0\n break\n end\n A(k+1:n,k) = A(k+1:n,k)/A(k,k);\n i = k+1:n;\n A(i,i) = A(i,i) - A(i,k) * A(k,i);\nend\nL = tril(A,-1) + eye(n);\nU = triu(A);\n P = eye(n);\n P = P(p,:);\n Q = eye(n);\n Q = Q(:,q);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/13451-gauss-elimination-with-complete-pivoting/gecp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.7047162172693172}} {"text": "function line = fitLine3d(points)\n%FITLINE3D Fit a 3D line to a set of points.\n%\n% LINE = fitLine3d(PTS)\n%\n% Example\n% pts = randn(300, 3);\n% pts = transformPoint3d(pts, createScaling3d([6 4 2]));\n% pts = transformPoint3d(pts, createRotationOx(pi/6));\n% pts = transformPoint3d(pts, createRotationOy(pi/4));\n% pts = transformPoint3d(pts, createRotationOz(pi/3));\n% pts = transformPoint3d(pts, createTranslation3d([5 4 3]));\n% elli = equivalentEllipsoid(pts);\n% figure; drawPoint3d(pts); axis equal;\n% hold on; drawEllipsoid(elli, ...\n% 'drawEllipses', true, 'EllipseColor', 'b', 'EllipseWidth', 3);\n% line = fitLine3d(pts);\n% drawLine3d(line, 'color', 'm', 'LineWidth', 4);\n%\n% See also \n% lines3d, equivalentEllipsoid, fitPlane\n%\n\n% ------\n% Author: David Legland\n% E-mail: david.legland@grignon.inra.fr\n% Created: 2012-11-11, using Matlab 7.9.0.529 (R2009b)\n% Copyright 2012-2022 INRA - Cepia Software Platform\n\n% number of points\nn = size(points, 1);\n\n% compute centroid\ncenter = mean(points);\n\n% compute the covariance matrix\ncovPts = cov(points)/n;\n\n% perform a principal component analysis with 2 variables, \n% to extract inertia axes\n[U, S] = svd(covPts);\n\n% sort axes from greater to lower\n[dummy, ind] = sort(diag(S), 'descend'); %#ok\n\n% format U to ensure first axis points to positive x direction\nU = U(ind, :);\nif U(1,1) < 0\n U = -U;\n % keep matrix determinant positive\n U(:,3) = -U(:,3);\nend\n\nline = [center U(:,1)'];\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/matGeom/geom3d/fitLine3d.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.7046598397702015}} {"text": "function [gx, gy, gz] = gaussPtetra(X1, X2, X3, X4, ng)\n\n%% USAGE: generate Gaussian nodes on tetra mesh\n%\n% INPUTS:\n% p --- nt-by-3 vector\n% t --- nt-by-4 vector\n% ng --- number of Gaussian nodes in an triangle\n% possible values = 1, 4, 5, 11, 15.\n%\n% OUTPUTS:\n% gx --- nt-by-ng vector: stores x coordinates of Gaussian nodes\n% gy --- nt-by-ng vector: stores y coordinates of Gaussian nodes\n% gz --- nt-by-ng vector: stores z coordinates of Gaussian nodes\n%\n% Last Modified: 07/02/2020 by Xu Zhang\n%%\n\nG = zeros(size(X1,1),3*ng); i = 1;\n\nif ng == 1 % accurate up to polynomial degree p = 1\n \n w1 = 1/4; % point at centroid\n G(:,[i,i+ng,i+2*ng]) = w1*(X1+X2+X3+X4);\n \nelseif ng == 4 % accurate up to polynomial degree p = 2\n \n w1 = 0.585410196624969; w2 = 0.138196601125011; % median line \n G(:,[i,i+ng,i+2*ng]) = w1*X1 + w2*(X2+X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X2 + w2*(X1+X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X3 + w2*(X1+X2+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X4 + w2*(X1+X2+X3); \n \nelseif ng == 5 % accurate up to polynomial degree p = 3\n \n w1 = 1/4; % point at centroid\n G(:,[i,i+ng,i+2*ng]) = w1*(X1+X2+X3+X4); i = i+1;\n \n w1 = 1/2; w2 = 1/6;% median line\n G(:,[i,i+ng,i+2*ng]) = w1*X1 + w2*(X2+X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X2 + w2*(X1+X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X3 + w2*(X1+X2+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X4 + w2*(X1+X2+X3);\n \nelseif ng == 11 % accurate up to polynomial degree p = 4\n \n w1 = 1/4; % point at centroid\n G(:,[i,i+ng,i+2*ng]) = w1*(X1+X2+X3+X4); i = i+1;\n \n w1 = 0.785714285714286; w2 = 0.071428571428571; % median line\n G(:,[i,i+ng,i+2*ng]) = w1*X1 + w2*(X2+X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X2 + w2*(X1+X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X3 + w2*(X1+X2+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X4 + w2*(X1+X2+X3); i = i+1;\n \n w1 = 0.399403576166799; w2 = 0.100596423833201; % line opposite sides\n G(:,[i,i+ng,i+2*ng]) = w1*(X1+X2) + w2*(X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*(X1+X3) + w2*(X2+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*(X1+X4) + w2*(X2+X3); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*(X2+X3) + w2*(X1+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*(X2+X4) + w2*(X1+X3); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*(X3+X4) + w2*(X1+X2); \n \nelseif ng == 15 % accurate up to polynomial degree p = 5\n \n w1 = 1/4; % point at centroid\n G(:,[i,i+ng,i+2*ng]) = w1*(X1+X2+X3+X4); i = i+1;\n \n w1 = 0; w2 = 1/3; % median line\n G(:,[i,i+ng,i+2*ng]) = w1*X1 + w2*(X2+X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X2 + w2*(X1+X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X3 + w2*(X1+X2+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X4 + w2*(X1+X2+X3); i = i+1; \n \n w1 = 0.727272727272727; w2 = 0.090909090909091; % median line\n G(:,[i,i+ng,i+2*ng]) = w1*X1 + w2*(X2+X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X2 + w2*(X1+X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X3 + w2*(X1+X2+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*X4 + w2*(X1+X2+X3); i = i+1; \n \n w1 = 0.066550153573664; w2 = 0.433449846426336; % line opposite sides\n G(:,[i,i+ng,i+2*ng]) = w1*(X1+X2) + w2*(X3+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*(X1+X3) + w2*(X2+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*(X1+X4) + w2*(X2+X3); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*(X2+X3) + w2*(X1+X4); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*(X2+X4) + w2*(X1+X3); i = i+1;\n G(:,[i,i+ng,i+2*ng]) = w1*(X3+X4) + w2*(X1+X2); \n \nend\ngx = G(:,1:ng); gy = G(:,ng+1:2*ng); gz = G(:,2*ng+1:3*ng); ", "meta": {"author": "lyc102", "repo": "ifem", "sha": "29f31c812001ca8d93dad08e67208ca60e8716d4", "save_path": "github-repos/MATLAB/lyc102-ifem", "path": "github-repos/MATLAB/lyc102-ifem/ifem-29f31c812001ca8d93dad08e67208ca60e8716d4/research/IVEM/gaussPtetra.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303732328411, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.7045935486249797}} {"text": "function [pospeakind,negpeakind]=peakdetect(signal)\n\n%\tPEAKDETECT peak detection\n%\n%\t[pospeakind,negpeakind]=peakdetect(signal)\n%\n%\tThe positive and negative polarity (concave down and up) peak index vectors are\n%\tgenerated from the signal vector and graphically displayed. Positive and negative\n%\tpolarity peaks occur at points of positive to negative and negative to positive\n%\tslope adjacency, respectively. The typically rare contingencies of peaks\n%\toccurring at the lagging edges of constant intervals are supported. Complex\n%\tsignals are modified to the modulus of the elements. If unspecified, the signal\n%\tvector is entered after the prompt from the keyboard.\n\n%\tImplemented using MATLAB 6.0.0\n%\n%\tExamples:\n%\n%\tť [p,n]=peakdetect([-1 -1 0 1 0 1 0 -1 -1])\n%\n%\tp =\n%\n%\t 4 6\n%\n%\tn =\n%\n%\t 1 5 8\n%\n%\tť [p,n]=peakdetect(cos(2*pi*(0:999999)/500000))\n%\n%\tp =\n%\n%\t 1 500001 1000000\n%\n%\tn =\n%\n%\t 250001 750001\n%\n%\tCopyright (c) 2001\n%\tTom McMurray\n%\tmcmurray@teamcmi.com\n\n%\tif signal is not input, enter signal or return for empty outputs\n\nif ~nargin\n signal=input('enter signal vector or return for empty outputs\\n');\n if isempty(signal)\n pospeakind=[];\n negpeakind=[];\n return\n end\nend\nsizsig=size(signal);\n\n%\twhile signal is unsupported, enter supported signal or return for empty outputs\n\nwhile isempty(signal)|~isnumeric(signal)|~all(all(isfinite(signal)))...\n |length(sizsig)>2|min(sizsig)~=1\n signal=input(['signal is empty, nonnumeric, nonfinite, or nonvector:\\nenter '...\n 'finite vector or return for empty outputs\\n']);\n if isempty(signal)\n pospeakind=[];\n negpeakind=[];\n return\n end\n sizsig=size(signal);\nend\n\n%\tif signal is complex, modify to modulus of the elements\n\nif ~isreal(signal)\n signal=abs(signal);\nend\n\n%\tif signal is constant, return empty outputs\n\nif ~any(signal-signal(1))\n pospeakind=[];\n negpeakind=[];\n disp('constant signal graph suppressed')\n return\nend\nsizsig1=sizsig(1);\nlensig=sizsig1;\n\n%\tif signal is a row vector, modify to a column vector\n\nif lensig==1\n signal=signal(:);\n lensig=sizsig(2);\nend\nlensig1=lensig-1;\nlensig2=lensig1-1;\n\n%\tif signal length is 2, return max/min as positive/negative polarity peaks\n\nif ~lensig2\n [sig,pospeakind]=max(signal);\n [sig,negpeakind]=min(signal);\n disp('2 element signal graph suppressed')\n return\nend\n\n%\tgenerate difference signal\n\ndifsig=diff(signal);\n\n%\tgenerate vectors corresponding to positive slope indices\n\ndsgt0=difsig>0;\ndsgt00=dsgt0(1:lensig2);\ndsgt01=dsgt0(2:lensig1);\n\n%\tgenerate vectors corresponding to negative slope indices\n\ndslt0=difsig<0;\ndslt00=dslt0(1:lensig2);\ndslt01=dslt0(2:lensig1);\n\n%\tgenerate vectors corresponding to constant intervals\n\ndseq0=difsig==0;\ndseq01=dseq0(2:lensig1);\nclear difsig\n\n%\tpositive to negative slope adjacencies define positive polarity peaks\n\npospeakind=find(dsgt00&dslt01)+1;\n\n%\tnegative to positive slope adjacencies define negative polarity peaks\n\nnegpeakind=find(dsgt01&dslt00)+1;\n\n%\tpositive slope to constant interval adjacencies initiate positive polarity peaks\n\npeakind=find(dsgt00&dseq01)+1;\nlenpeakind=length(peakind);\n\n%\tdetermine positive polarity peak terminations\n\nfor k=1:lenpeakind\n peakindk=peakind(k);\n l=peakindk+1;\n \n%\tif end constant interval occurs, positive polarity peak exists\n \n if l==lensig\n pospeakind=[pospeakind;peakindk];\n \n%\telse l' );\n ylabel ( '<--- Y --->' );\n zlabel ( '<---Z(X,Y)--->' );\n l = light ( 'Position', [ 0, 0, 25 ] );\n set ( gca, 'CameraPosition', [ -10, -10, 20 ] );\n lighting phong\n shading interp\n hold off\n filename = sprintf ( 'p%02d_data.png', prob );\n print ( '-dpng', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Created plot file \"%s\".\\n', filename );\n end\n%\n% #3: Plot the Shepard interpolant.\n%\n figure ( 2 );\n clf\n nix = 21;\n niy = 21;\n xmin = 0.0;\n xmax = 1.0;\n ymin = 0.0;\n ymax = 1.0;\n xi = linspace ( xmin, xmax, nix );\n yi = linspace ( ymin, ymax, niy );\n [XI,YI] = meshgrid ( xi, yi );\n NI = nix * niy;\n XI = reshape ( XI, NI, 1 );\n YI = reshape ( YI, NI, 1 );\n ZI = shepard_interp_2d ( nd, xd, yd, zd, p, NI, XI, YI );\n XI = reshape ( XI, nix, niy );\n YI = reshape ( YI, nix, niy );\n ZI = reshape ( ZI, nix, niy );\n surf ( XI, YI, ZI );\n xlabel ( '<--- X --->' );\n ylabel ( '<--- Y --->' );\n zlabel ( '<---Z(X,Y)--->' );\n title ( sprintf ( 'Shepard interpolant for problem %d with P = %g', prob, p ) )\n grid on\n hold off\n filename = sprintf ( 'p%02d_power%g.png', prob, p );\n print ( '-dpng', filename );\n fprintf ( 1, ' Created plot file \"%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/shepard_interp_2d/shepard_interp_2d_test01.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938799869521, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.7045740799726822}} {"text": "function mesh = mshSphere(N,rad)\n%+========================================================================+\n%| |\n%| OPENMSH - LIBRARY FOR MESH MANAGEMENT |\n%| openMsh is part of the GYPSILAB toolbox for Matlab |\n%| |\n%| COPYRIGHT : Matthieu Aussal (c) 2017-2018. |\n%| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, |\n%| route de Saclay, 91128 Palaiseau, France. All rights reserved. |\n%| LICENCE : This program is free software, distributed in the hope that|\n%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, |\n%| redistribute and/or modify it under the terms of the GNU General Public|\n%| License, as published by the Free Software Foundation (version 3 or |\n%| later, http://www.gnu.org/licenses). For private use, dual licencing |\n%| is available, please contact us to activate a \"pay for remove\" option. |\n%| CONTACT : matthieu.aussal@polytechnique.edu |\n%| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      |\n%| |\n%| Please acknowledge the gypsilab toolbox in programs or publications in |\n%| which you use it. |\n%|________________________________________________________________________|\n%| '&` | |\n%| # | FILE : mshSphere.m |\n%| # | VERSION : 0.40 |\n%| _#_ | AUTHOR(S) : Matthieu Aussal |\n%| ( # ) | CREATION : 14.03.2017 |\n%| / 0 \\ | LAST MODIF : 14.03.2018 |\n%| ( === ) | SYNOPSIS : Build uniform mesh for a sphere |\n%| `---' | |\n%+========================================================================+\n\n% Fibonnacci rules\nor = (1+sqrt(5))/2;\ntheta = (mod((2*pi/or) .* (0:N-1),2*pi))';\nphi = asin( -1 + 2/(N-1) * (0:N-1))';\n\n% Carthesian coordinates\n[x,y,z] = sph2cart(theta,phi,rad);\nX = [0 0 0 ; x y z];\n\n% Delaunay triangulation\nDT = delaunayTriangulation(X);\n[elt,vtx] = freeBoundary(DT);\n\n% Mesh\nmesh = msh(vtx,elt);\nend\n", "meta": {"author": "SwanLab", "repo": "Swan", "sha": "f8355f3561bb1a1603f56b3676873147d22a511e", "save_path": "github-repos/MATLAB/SwanLab-Swan", "path": "github-repos/MATLAB/SwanLab-Swan/Swan-f8355f3561bb1a1603f56b3676873147d22a511e/gypsilabModified/openMsh/mshSphere.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7045630767504973}} {"text": "function result = AngleAxisRotatePoint(angle_axis, pt)\n\nangle_axis = angle_axis(1:3);\n\ntheta2 = dot(angle_axis,angle_axis);\n\nif (theta2 > 0.0)\n % Away from zero, use the rodriguez formula\n %\n % result = pt costheta + (w x pt) * sintheta + w (w . pt) (1 - costheta)\n %\n % We want to be careful to only evaluate the square root if the\n % norm of the angle_axis vector is greater than zero. Otherwise\n % we get a division by zero.\n \n theta = sqrt(theta2);\n w = angle_axis / theta;\n \n costheta = cos(theta);\n sintheta = sin(theta);\n \n % w_cross_pt = cross(w, pt);\n w_cross_pt = xprodmat(w) * pt;\n \n %w_dot_pt = dot(w, pt);\n w_dot_pt = w * pt;\n \n result = pt * costheta + w_cross_pt * sintheta + (w' * (1 - costheta)) * w_dot_pt;\n \n \nelse\n % Near zero, the first order Taylor approximation of the rotation\n % matrix R corresponding to a vector w and angle w is\n %\n % R = I + hat(w) * sin(theta)\n %\n % But sintheta ~ theta and theta * w = angle_axis, which gives us\n %\n % R = I + hat(w)\n %\n % and actually performing multiplication with the point pt, gives us\n % R * pt = pt + w x pt.\n %\n % Switching to the Taylor expansion at zero helps avoid all sorts\n % of numerical nastiness.\n \n %w_cross_pt = cross(angle_axis, pt);\n w_cross_pt = xprodmat(angle_axis) * pt; % vectorize version\n \n result = pt + w_cross_pt;\n \nend\n", "meta": {"author": "jianxiongxiao", "repo": "ProfXkit", "sha": "7376c50abf5ead846247774a36be026e6f24953c", "save_path": "github-repos/MATLAB/jianxiongxiao-ProfXkit", "path": "github-repos/MATLAB/jianxiongxiao-ProfXkit/ProfXkit-7376c50abf5ead846247774a36be026e6f24953c/SiftFu/SiftFu/AngleAxisRotatePoint.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904955, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7045630553277015}} {"text": "function [IF_phase_unwrap, GDD_phase, MGD_phase]=phase_feature_extraction(sp_complex, sp_delay)\n\n% This function is using for different kinds of phase feature extraction,\n% include instantaneous frequency deviation (IF), group delay deviation\n% (GDD), modified group delay (MGD), phase distortion (PD), phase\n% distortion standard deviation (PDD) and relative phase shift (RPS).\n%\n% input: \n% sp_complex: [n*d] n is frame number (time), d is the feature dimension (frequency)\n% STFT of target waveform x(n) which contain both magnitude and phase information\n% sp_delay: [n*d] n is frame number, d is the feature dimension \n% STFT of modified target waveform n*x(n)\n%\n% output:\n% [n*d] n is frame number (time), d is the feature dimension (frequency)\n% IF_phase: instantaneous frequency deviation\n% GDD_phase: group delay deviation\n% MGD_phase: modified group delay\n% PD_phase: phase distortion\n% PDD_phase: phase distortion standard deviation\n% RPS_phase: relative phase shift\n%\n\nis_plot = 1;\n\nphase = angle(sp_complex);\nphase_unwrap = unwrap(phase);\n\n\n% [~, IF_phase] = gradient(phase); % deviation along time aixs\n[~, IF_phase_unwrap] = gradient(phase_unwrap); % deviation along time aixs\n\nGDD_phase = group_delay_feature(sp_complex); % deviation along frequency aixs\n\nMGD_phase = modified_group_delay_raw(sp_complex, sp_delay);\n\nif is_plot\n figure\n subplot(5,1,1)\n imagesc(phase');colormap jet\n title('original phase')\n \n subplot(5,1,2)\n imagesc(phase_unwrap');colormap jet\n title('original unwraped phase')\n\n subplot(5,1,3)\n imagesc(IF_phase_unwrap');colormap jet\n title('instantaneous frequency deviation')\n\n subplot(5,1,4)\n gdd = GDD_phase.^ 0.4;\n imagesc(real(gdd'));colormap jet\n title('group delay deviation')\n\n subplot(5,1,5)\n imagesc(MGD_phase');colormap jet\n title('modified group delay')\nend\n\n\n% RPS_phase = relative_phase_shift(phase);\n% \n% PD_phase = phase_distortion(phase);\n\n% PDD_phase = phase_distortion_std_deviation(phase)", "meta": {"author": "singaxiong", "repo": "SignalGraph", "sha": "e86d973556ae8796a05ee2adbd665f47c8525a21", "save_path": "github-repos/MATLAB/singaxiong-SignalGraph", "path": "github-repos/MATLAB/singaxiong-SignalGraph/SignalGraph-e86d973556ae8796a05ee2adbd665f47c8525a21/signal/phase/phase_feature_extraction/phase_feature_extraction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605945, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7045618089353646}} {"text": "% [mu,S] = mean_cov(x)\n% x is n x d\nfunction [mu,S] = mean_cov(x)\n\n%[n,d] = size(x);\n\nz = size(x,1);\nmu = sum(x,1)/z;\n\ndiffs = bsxfun(@minus,x,mu);\nS = (diffs'*diffs)/z;\n", "meta": {"author": "kristinbranson", "repo": "JAABA", "sha": "5d778a23e3e7cf272df9a89a72b1b66d94f535d7", "save_path": "github-repos/MATLAB/kristinbranson-JAABA", "path": "github-repos/MATLAB/kristinbranson-JAABA/JAABA-5d778a23e3e7cf272df9a89a72b1b66d94f535d7/misc/mean_cov.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.70456180012789}} {"text": "function f = kappa_inf(tau, P)\n% This function computes approximation to kappa in the limit of n->inf\n%\nx0 = norminv( (tau+1)/2, 0, 1);\nVP = 2 * (1 + 2*P);\nVQ = 2 * (1 + P)^2;\nf = 2*normcdf(sqrt(VP/VQ) * x0, 0, 1) - 1;\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/long-term-power-constraint/awgn/kappa_inf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.7043247058037241}} {"text": "function [H] = rigidbody(f);\n\n% RIGIDBODY creates the homogenous spatial transformation matrix\n% for a 6 parameter rigid-body transformation \n%\n% Use as\n% [H] = rigidbody(f)\n%\n% The transformation vector f should contain the \n% x-shift\n% y-shift\n% z-shift\n% followed by the\n% pitch (rotation around x-axis)\n% roll (rotation around y-axis)\n% yaw (rotation around z-axis)\n\n% Copyright (C) 2000-2005, Robert Oostenveld\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\n% $Log: rigidbody.m,v $\n% Revision 1.1 2009/01/30 04:02:11 arno\n% *** empty log message ***\n%\n% Revision 1.4 2006/04/13 10:37:38 roboos\n% added a ; to the end of a line\n%\n% Revision 1.3 2005/08/15 08:15:32 roboos\n% reimplemented the rotate function, which contained an error (the error is in the AIR technical reference)\n% changed all functions to be dependent on the rotate, translate and scale function\n% all functions now behave consistenly, which also means that they are not compleetly backward compatible w.r.t. the order of the rotations\n%\n% Revision 1.2 2004/05/19 09:57:07 roberto\n% added GPL copyright statement, added CVS log item\n%\n\n% compute the homogenous transformation matrix for the translation\nT = translate(f([1 2 3]));\n\n% compute the homogenous transformation matrix for the rotation\nR = rotate(f([4 5 6]));\n\n% compute the homogenous transformation matrix for the combination\nH = T*R;\n\n", "meta": {"author": "PatternRecognition", "repo": "OpenBMI", "sha": "3c42e609d5b867a8e15c780df3f8b0a8b86edcb8", "save_path": "github-repos/MATLAB/PatternRecognition-OpenBMI", "path": "github-repos/MATLAB/PatternRecognition-OpenBMI/OpenBMI-3c42e609d5b867a8e15c780df3f8b0a8b86edcb8/PR_BCI_team/Team_EarEEG/ear-EEG connecting/external/eeglab_10_0_1_0x/plugins/dipfit2.2/private/rigidbody.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958426, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7042579206082097}} {"text": "% experimentImage2D.m\n%\n% Create a Fourier measurement operator and measurements for reconstructing\n% an image.\n%\n% Inputs:\n% numMasks: number of random octanary Fourier masks. \n% imagePath: The path of the image to be recovered\n%\n% Outputs:\n% A : A function handle: n1*n2 x 1 -> n1*n2*numMasks x 1. It returns \n% A*x.\n% At : The transpose of A\n% b0 : A n1*n2*numMasks x 1 real, non-negative vector consists of the \n% measurements abs(A*x).\n% Xt : The true signal - a vectorization of the image\n%\n%\n%\n% PhasePack by Rohan Chandra, Ziyuan Zhong, Justin Hontz, Val McCulloch,\n% Christoph Studer, & Tom Goldstein \n% Copyright (c) University of Maryland, 2017\n\n%% -----------------------------START----------------------------------\n\n\nfunction [A, At, b0, Xt, plotter] = experimentImage2D(numMasks, imagePath)\n %% Read Image \n % Below Xt is n1 x n2 x 3; i.e. we have three n1 x n2 images, one for each of the 3 color channels \n image = rgb2gray(imread([imagePath]));\n image = double(image);\n dims = size(image);\n L = numMasks;\n\n %% Make octanary masks and linear sampling operators \n % Each mask has iid entries following the octanary pattern.\n % Entries have the form b = b1*b2 , where b1 is sampled\n % from {-1, 1, -i, i} with equal probability 1/4, and b2 from\n % { sqrt(1/2), sqrt(3)} with probability 4/5 and 1/5 respectively.\n b1 = [-1;1;-1i;1i];\n b2 = [repmat(sqrt(0.5),4,1); sqrt(3)];\n % Masks has size [n1,n2,L]\n masks = b1(randi(4,[dims,L])) .* b2(randi(5,[dims,L])); % Storage for L masks, each of dim n1 x n2\n \n %% Make linear operators that act on a vectorized image\n A = @(x) fourierMeasurementOperator(x, masks, dims);\n At = @(y) transposeOperator(y, masks, dims);\n \n \n Xt = image(:);\n b0 = abs(A(Xt(:)));\n \n % Set up plotting\n subplot(1,2,1);\n imagesc(image);\n title('original');\n subplot(1,2,2);\n \n plotter = @(x) imagesc(reshape(abs(x),dims));\n\nend\n\nfunction y = fourierMeasurementOperator(x, masks, dims)\n x = reshape(x, dims); % image comes in as a vector. Reshape to rectangle\n [n1,n2] = size(x);\n L = size(masks,3); % get number of masks\n\n % Compute measurements\n copies = repmat(x,[1,1,L]);\n y = fft2(masks.*copies);\n y = y(:);\nend\n\n\nfunction x = transposeOperator(y, masks, dims)\n n1 = dims(1);\n n2 = dims(2);\n L = size(masks,3); % get number of masks\n y = reshape(y, [n1,n2,L]); % image comes in as a vector. Reshape to rectangle\n \n x = n1*n2*ifft2(y).*conj(masks);\n x = sum(x,3);\n x = x(:);\nend\n\n", "meta": {"author": "tomgoldstein", "repo": "phasepack-matlab", "sha": "aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9", "save_path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab", "path": "github-repos/MATLAB/tomgoldstein-phasepack-matlab/phasepack-matlab-aac4525b2c53ad2e7005f70ace46b4a1bde4c6d9/benchmarks/experimentImage2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7042257616097217}} {"text": " function [fw, hr, hl] = fwhm1(psfs, varargin)\n%|function [fw, hr, hl] = fwhm1(psfs, options)\n%|\n%| compute fwhm of point-spread function centered at pixel imid\n%| and half-right width and half-left width (fw = hr + hl)\n%|\n%| in\n%|\tpsfs\t[np nc]\tcolumn psf(s)\n%|\n%| option\n%|\timid\t[1]\twhich pixel is the middle (default: peak)\n%|\tdx\t[1]\tpixel size (default: 1)\n%|\tmin0\t0|1\tif 1, then negative psf value set to 0 (default: 1)\n%|\tchat\t0|1\tif 1, then plot\n%| out\n%|\tfw\t[nc]\tfwhm of each psf column\n%|\n%| 2012-09-13, added 'min0' option to avoid fwhm < 1\n\nif ~nargin, ir_usage, end\nif streq(psfs, 'test'), fwhm1_test, return, end\n\narg.chat = 0;\narg.dx = 1;\narg.imid = [];\narg.min0 = true;\narg = vararg_pair(arg, varargin);\n\npsfs = squeeze(psfs); % in case [1 1 np]\n[np nc] = size(psfs);\nif (np == 1) % single row\n\tpsfs = psfs';\n\t[np nc] = size(psfs);\nend\n\nwarned = false;\nfor ic = 1:nc\n\tpsf = psfs(:,ic);\n\tif isempty(arg.imid)\n\t\timid = imax(psf);\n\telse\n\t\timid = arg.imid;\n\tend\n\n\t% normalize\n\tpsf = psf / psf(imid);\n\tif ~warned && (1 ~= max(psf))\n\t\twarn 'peak not at center'\n\t\twarned = true;\n\tend\n\n\t% right\n\tir = sum(cumprod(double(psf((imid+1):np) >= 0.5)));\n\tif (imid + ir == np)\n\t\thr(ic,1) = ir;\n\telse\n\t\thigh = psf(imid + ir);\n\t\tilow = imid + ir + 1;\n\t\tlow = psf(ilow);\n\t\tif arg.min0 && low < 0\n\t\t\twarn('psf(%d) = %g < 0, so using 0', ilow, low)\n\t\t\tlow = 0;\n\t\tend\n\t\thr(ic,1) = ir + (high - 1/2) / (high-low);\n\tend\n\n\t% left\n\til = sum(cumprod(double(psf((imid-1):-1:1) >= 0.5)));\n\tif (il == imid-1)\n\t\thl(ic,1) = il;\n\telse\n\t\thigh = psf(imid - il);\n\t\tilow = imid - il - 1;\n\t\tlow = psf(ilow);\n\t\tif arg.min0 && low < 0\n\t\t\twarn('psf(%d) = %g < 0, so using 0', ilow, low)\n\t\t\tlow = 0;\n\t\tend\n\t\thl(ic,1) = il + (high - 1/2) / (high-low);\n\tend\nend\n\nhr = hr * arg.dx;\nhl = hl * arg.dx;\nfw = hr + hl;\n\nif arg.chat && im\n\tplot(([1:np]-imid)*arg.dx, psf, '-o', ...\n\t[-hl hr], [0.5 0.5], '-')\n\txlabel 'x', ylabel 'psf(x)'\n\ttitle(sprintf('fwhm=%g', fw))\nend\n\n\n% fwhm1_test\nfunction fwhm1_test\ndx = 3;\nnx = 100;\nxx = [-nx/2:nx/2-1]' * dx;\nfx = 30;\nsx = fx / sqrt(log(256));\npsf = exp(-((xx/sx).^2)/2);\nfw = fwhm1(psf, 'dx', dx, 'chat', 1);\n\npsf = zeros(7,1); psf(5) = 2; psf([4 6]) = -0.2;\nfw = fwhm1(psf, 'dx', dx, 'chat', 1);\n", "meta": {"author": "JeffFessler", "repo": "mirt", "sha": "b7f36cc46916821e8bc8502301b1554ebc7efe1d", "save_path": "github-repos/MATLAB/JeffFessler-mirt", "path": "github-repos/MATLAB/JeffFessler-mirt/mirt-b7f36cc46916821e8bc8502301b1554ebc7efe1d/utilities/fwhm1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.704184770954257}} {"text": "function x = r8sto_sl ( n, a, b )\n\n%*****************************************************************************80\n%\n%% R8STO_SL solves a R8STO system.\n%\n% Discussion:\n%\n% The R8STO storage format is used for a symmetric Toeplitz matrix.\n% It stores the N elements of the first row.\n%\n% For this routine, the matrix is also required to be positive definite.\n%\n% This implementation of the algorithm assumes that the diagonal element\n% is 1.\n%\n% The real symmetric Toeplitz matrix can be described by N numbers, which,\n% for convenience, we will label A(0:N-1).\n%\n% Note that there is a typographical error in the presentation\n% of this algorithm in the reference, and another in the presentation\n% of a sample problem. Both involve sign errors. A minor error\n% makes the algorithm incorrect for the case N = 1.\n%\n% Example:\n%\n% To solve\n%\n% 1.0 0.5 0.2 x1 4.0\n% 0.5 1.0 0.5 * x2 = -1.0\n% 0.2 0.5 1.0 x3 3.0\n%\n% we input:\n%\n% N = 3\n% A(0:N-1) = (/ 1.0, 0.5, 0.2 /)\n% B(1:3) = (/ 4.0, -1.0, 3.0 /)\n%\n% with output:\n%\n% X(1:3) = (/ 355, -376, 285 /) / 56\n% = (/ 6.339, -6.714, 5.089 /)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gene Golub and Charles Van Loan,\n% Section 4.7.3, \"The General Right Hand Side Problem\",\n% Matrix Computations,\n% Third Edition,\n% Johns Hopkins, 1996.\n%\n% Parameters:\n%\n% Input, integer N, the order of the system.\n%\n% Input, real A(N), the R8STO matrix.\n%\n% Input, real B(N), the right hand side of the linear system.\n%\n% Output, real X(N), the solution of the linear system.\n%\n k = 0;\n\n beta = 1.0E+00;\n x(k+1) = b(k+1) / beta;\n\n if ( k < n-1 )\n y(k+1) = -a(k+2) / beta;\n end\n\n for k = 1 : n-1\n\n beta = ( 1.0E+00 - y(k) * y(k) ) * beta;\n\n x(k+1) = ( b(k+1) - a(2:k+1) * x(k:-1:1)' ) / beta;\n\n x(1:k) = x(1:k) + x(k+1) * y(k:-1:1);\n\n if ( k < n - 1 )\n y(k+1) = ( -a(k+2) - a(2:k+1) * y(k:-1:1)' ) / beta;\n y(1:k) = y(1:k) + y(k+1) * y(k:-1:1);\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/linplus/r8sto_sl.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7041847571378431}} {"text": "function [ n_data, mu, sigma, a, x, fx ] = ...\n truncated_normal_a_pdf_values ( n_data )\n\n%*****************************************************************************80\n%\n%% TRUNCATED_NORMAL_A_PDF_VALUES: values of the lower Truncated Normal AB PDF.\n%\n% Discussion:\n%\n% The Normal distribution, with mean Mu and standard deviation Sigma,\n% is truncated to the interval [A,+oo).\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% 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 A, the lower 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 a_vec = [ ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.0, ...\n 50.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 a = 0.0;\n mu = 0.0;\n sigma = 0.0;\n x = 0.0;\n fx = 0.0;\n else\n a = a_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_a_pdf_values.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.7041847571378431}} {"text": "function ihs_test03 ( )\n\n%*****************************************************************************80\n%\n%% IHS_TEST03 tests the improved distributed hypercube sampling algorithm.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 February 2014\n%\n% Author:\n%\n% John Burkardt\n%\n dim_num = 2;\n duplication = 5;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'IHS_TEST03' );\n fprintf ( 1, ' IHS implements the IHS Algorithm\\n' );\n fprintf ( 1, ' (Improved Distributed Hypercube Sampling)\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Demonstrate the code for a fixed dimension\\n' );\n fprintf ( 1, ' and duplication value, and increasing number of points.\\n' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension = %d\\n', dim_num );\n fprintf ( 1, ' Duplication factor = %d\\n', duplication );\n\n for i = 1 : 5\n\n point_num = 10 * 2^(i-1);\n\n opt = point_num / point_num^( 1.0 / dim_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of points = %d\\n', point_num );\n fprintf ( 1, ' Desired minimum distance = %f\\n', opt );\n%\n% Get the points.\n%\n x = ihs ( dim_num, point_num, duplication );\n%\n% Compute the covariance.\n%\n [ average, sd, covc ] = covariance ( dim_num, point_num, x );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Average minimum distance %f\\n', average );\n fprintf ( 1, ' Standard deviation: %f\\n', sd );\n fprintf ( 1, ' Covariance: %f\\n', covc );\n\n fprintf ( 1, '\\n' );\n\n for j = 1 : point_num\n\n if ( j <= 10 | point_num - 10 <= j )\n fprintf ( 1, '%4d ', j );\n for i = 1 : dim_num\n fprintf ( 1, '%4d ', x(i,j) );\n end\n fprintf ( 1, '\\n');\n elseif ( j == 11 )\n fprintf ( 1, '.... ........\\n' );\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/ihs/ihs_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225574, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7040185655165351}} {"text": "function [x, fx, exitFlag] = bisection_s(f,lb,ub,target,options)%#codegen\n% BISECTION Fast and robust root-finding method that handles n-dim arrays.\n% bisection_s => \"s\" = single or serial, for turning into a mex file\n% [x,fVal,ExitFlag] = BISECTION(f,LB,UB,target,options) finds x +/- TolX\n% (LB < x < UB) such that f(x) = target +/- TolFun.\n% \n% x = BISECTION(f,LB,UB) finds the root(s) of function f on the interval\n% [LB, UB], i.e. finds x such that f(x) = 0 where LB <= x <= UB. f will\n% never be evaluated outside of the interval specified by LB and UB. f\n% should have only one root and f(UB) and f(LB) must bound it. Elements\n% of x are NaN for instances where a solution could not be found.\n% \n% x = BISECTION(f,LB,UB,target) finds x such that f(x) = target.\n% \n% x = BISECTION(f,LB,UB,target,TolX) will terminate the search when the\n% search interval is smaller than TolX (TolX must be positive).\n% \n% x = BISECTION(f,LB,UB,target,options) solves with the default\n% parameters replaced by values in the structure OPTIONS, an argument\n% created with the OPTIMSET function. Used options are TolX and TolFun.\n% Note that OPTIMSET will not allow arrays for tolerances, so set the\n% fields of the options structure manually for non-scalar TolX or TolFun.\n% \n% [x,fVal] = BISECTION(f,...) returns the value of f evaluated at x.\n%\n% [x,fVal,ExitFlag] = BISECTION(...) returns an ExitFlag that describes\n% the exit condition of BISECTION. Possible values of elements of\n% ExitFlag and the corresponding exit conditions are\n%\n% 1 Search interval smaller than TolX.\n% 2 Function value within TolFun of target.\n% 3 Search interval smaller than TolX AND function value within \n% TolFun of target.\n% -1 No solution found.\n% \n% Any or all of f(scalar), f(array), LB, UB, target, TolX, or TolFun may\n% be scalar or n-dim arrays. All non-scalar arrays must be the same size.\n% All outputs will be this size.\n% \n% Default values are target = 0, TolX = 1e-6, and TolFun = 0.\n% \n% There is no iteration limit. This is because BISECTION (with a TolX\n% that won't introduce numerical issues) is guaranteed to converge if f\n% is a continuous function on the interval [UB, LB] and f(x)-target\n% changes sign on the interval.\n% \n% The bisection method is very robust root-finding method. The absolute\n% error is halved at each step so the method converges linearly. However,\n% Brent's method (such as implemented in FZERO) can converge\n% superlinearly and is as robust. FZERO also has more features and input\n% checking, so use BISECTION in cases where either the optimization\n% toolbox is unavailable or if FZERO would have to be implemented in a\n% loop to solve multiple cases, in which case BISECTION will be much\n% faster because of vectorization.\n%\n% Define LB, UB, target, TolX, and TolFun for each specific application\n% using great care for the following reasons:\n% - There is no iteration limit, so given an unsolvable task, such as\n% TolX = TolFun = 0, BISECTION remains in an unending loop. \n% - Spacing between very large floating point numbers is likely to be\n% greater than TolX. \n% - There is no initial check to make sure that f(x) - target changes\n% sign between LB and UB.\n% - Very large or very small numbers can introduce numerical issues.\n%\n% Example 1: Find cube root of array 'target' without using NTHROOT and\n% compare speed to using FZERO.\n% options = optimset('TolX', 1e-9);\n% target = [(-100:.1:100)' (-1000:1:1000)'];\n% \n% tic;\n% xfz = zeros(size(target));\n% for ii = 1:numel(target)\n% xfz(ii) = fzero(@(x) x.^3-target(ii), [-20 20], options);\n% end\n% fzero_time = toc\n% \n% tic;\n% xbis = bisection(@(x) x.^3, -20, 20, target, options);\n% bisection_time = toc\n% \n% fprintf('FZERO took %0.0f times longer than BISECTION.\\n',...\n% fzero_time/bisection_time)\n% \n% Example 2: Find roots by varying the function coefficients.\n% [A, B] = meshgrid(linspace(1,2,6), linspace(4,12,10));\n% f = @(x) A.*x.^0.2 + B.*x.^0.87 - 15;\n% xstar = bisection(f,0,5);\n% \n% See also FZERO, FMINBND, OPTIMSET, FUNCTION_HANDLE.\n% \n% [x,fVal,ExitFlag] = BISECTION(f,LB,UB,target,options)\n\n% Copyright 2010-2013 Sky Sartorius\n% Author - Sky Sartorius\n% Contact - www.mathworks.com/matlabcentral/fileexchange/authors/101715\n\n% --- Process inputs. ---\n% Set default values\ntolX = 1e-6;\ntolFun = 0;\nif nargin == 5\n if isstruct(options)\n if isfield(options,'TolX') && ~isempty(options.TolX)\n tolX = options.TolX;\n end \n if isfield(options,'TolFun') && ~isempty(options.TolFun)\n tolFun = options.TolFun;\n end\n else\n tolX = options;\n end \nend\nif nargin<4 || isempty(target); target=0; end\n\n\nub_in = ub; lb_in = lb; \nf = @(x) f(x) - target;\n\n% --- Flip UB and LB if necessary. ---\nisFlipped = lb>ub;\nif any(isFlipped(:))\n ub(isFlipped) = lb_in(isFlipped);\n lb(isFlipped) = ub_in(isFlipped);\n ub_in = ub; lb_in = lb;\nend\n\n% --- Make sure everything is the same size for a non-scalar problem. ---\nif isscalar(lb) && isscalar(ub)\n % Test if f returns multiple outputs for scalar input.\n if ~isscalar(target)\n ub = ub + zeros(size(target));\n else\n jnk = f(ub); \n if ~isscalar(jnk)\n ub = ub + zeros(size(jnk));\n end\n end\nend\n\n% Check if lb and/or ub need to be made into arrays.\nif isscalar(lb) && ~isscalar(ub) \n lb = lb + zeros(size(ub));\nelseif ~isscalar(lb) && isscalar(ub) \n ub = ub + zeros(size(lb));\nend\n\nx = zeros(size(lb));\ntestconvergence\n% --- Iterate ---\niterations = 0;\nwhile any(stillNotDone(:))\n bigger = fx.*f(ub) > 0;\n ub(bigger)= x(bigger);\n lb(~bigger)= x(~bigger);\n \n testconvergence;\n iterations = iterations + 1;\n \n if(iterations > 10000)\n% error('Too many iterations in bisection!');\n break;\n end\nend\n\n function testconvergence\n x=(ub+lb)/2;\n fx=f(x);\n outsideTolFun = abs(fx) > tolFun;\n outsideTolX = (ub - lb) > tolX;\n stillNotDone = outsideTolX & outsideTolFun;\n end\n\n% --- Check that f(x+tolX) and f(x-tolX) have opposite sign. ---\nfu = f(min(x+tolX,ub_in)); \nfl = f(max(x-tolX,lb_in));\nunboundedRoot = (fu.*fl) > 0;\n\n% Throw out unbounded results if not meeting TolFun convergence criteria.\nx(unboundedRoot & outsideTolFun) = NaN; \n\n% --- Catch NaN elements of UB, LB, target, or other funky stuff. ---\nx(isnan(fx)) = NaN;\n\n% --- Characterize results. ---\nfx = fx + target;\nif nargout > 2 \n exitFlag = +~outsideTolX;\n exitFlag(~outsideTolFun) = 2;\n exitFlag(~outsideTolFun & ~outsideTolX) = 3;\n exitFlag(isnan(x)) = -1;\nend\n\nend\n\n% V2: July 2010\n% V3: December 2012\n% don't remember when\n% typo line 39; added fn handle to see also; made array in example 2\n% smaller; changed wording in example 1\n% 2013-08-23 \n% -changed scalar*ones(...) calls to scalar+zeros(...) calls based on\n% http://undocumentedmatlab.com/blog/allocation-performance-take-2/\n% -rearranged help block and formatted a tiny bit", "meta": {"author": "Arrowstar", "repo": "ksptot", "sha": "2b414440d3b167ba2294f56dafce0f465c07f982", "save_path": "github-repos/MATLAB/Arrowstar-ksptot", "path": "github-repos/MATLAB/Arrowstar-ksptot/ksptot-2b414440d3b167ba2294f56dafce0f465c07f982/helper_methods/math/bisection_s.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7040185593863092}} {"text": "%% OPT05_RUN\n%\n% Modified:\n%\n% 09 January 2008\n%\n %---------------------------------------------------------------------\n % Running testcase, from D+S, pp. 157-8; x_* = [.1,10].\n % This tests the scaling implementation.\n %---------------------------------------------------------------------\n fprintf('---------------------------------------------------------\\n')\n fprintf('Running testcase_5 as scalar optimization problem:\\n' );\n fprintf('Exact solution (0.1, 10)\\n')\n fprintf('---------------------------------------------------------\\n')\n fname = 'opt05_fgh';\n options = [];\n options.verbose = 0;\n options.method = 'newton';\n options.globalization = 'trust_region';\n options.step_tolerance = 1.e-14;\n options.gradient_tolerance = 1.e-14;\n options.max_fevals = 151;\n options.max_iterations = 151;\n\n alpha = 10;\n fprintf ( 'Program scale ALPHA = %f\\n', alpha );\n x0 = [-1.2/alpha, alpha]; \n fprintf('Unscaled:\\n')\n%\n% should require ~94 iterations\n%\n x = entrust(fname, x0, options, alpha);\n\n fprintf('Newton produced (%10.7e, %10.7e)\\n\\n',x(1),x(2))\n f = opt05_fgh ( x, 'f', alpha );\n fprintf('Value of F(X) = %f\\n', f );\n\n options.scale_x = [ 1/alpha; alpha ];\n fprintf('Scaled:\\n')\n\n % should require ~24 iterations\n x = entrust(fname, x0, options, alpha);\n\n fprintf('Newton produced (%10.7e, %10.7e)\\n\\n',x(1),x(2))\n f = opt05_fgh ( x, 'f', alpha );\n fprintf('Value of F(X) = %f\\n', f );\n\n %---------------------------------------------------------------------\n % Test Gauss-Newton strategies.\n %---------------------------------------------------------------------\n fprintf('---------------------------------------------------------\\n')\n fprintf('Running testcase_5 as least squares problem: \\n')\n fprintf('Exact solution (0.1, 10)\\n')\n fprintf('---------------------------------------------------------\\n')\n fname = 'opt05_rj';\n options = [];\n options.verbose = 0;\n options.method = 'gauss_newton';\n options.step_tolerance = 1.e-15;\n options.globalization = 'none';\n options.gradient_tolerance = 1.e-10;\n options.max_iterations = 40;\n\n alpha = 10;\n fprintf ( 'Program scale ALPHA = %f\\n', alpha );\n x0 = [-1.2/alpha, alpha]; \n fprintf('Unscaled:\\n')\n\n x = entrust(fname, x0, options, alpha);\n\n fprintf('Gauss-Newton produced (%10.7e, %10.7e)\\n\\n',x(1),x(2))\n [ res, jac ] = opt05_rj ( x, 'f', alpha );\n fprintf('Norm of RES(X) = %f\\n', norm ( res ) );\n\n options.scale_x = [ 1/alpha; alpha ];\n fprintf('Scaled:\\n')\n\n x = entrust(fname, x0, options, alpha);\n\n fprintf('Gauss-Newton produced (%10.7e, %10.7e)\\n\\n',x(1),x(2))\n [ res, jac ] = opt05_rj ( x, 'f', alpha );\n fprintf('Norm of RES(X) = %f\\n', norm ( res ) );\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/entrust/opt05_run.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7040185575447928}} {"text": "function spiral_test03 ( )\n\n%*****************************************************************************80\n%\n%% SPIRAL_TEST03 generates a field on a regular grid and plots it.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 17 January 2015\n%\n% Author:\n%\n% John Burkardt\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPIRAL_TEST03:\\n' );\n fprintf ( 1, ' Generate a spiral velocity field on a regular grid.\\n' );\n fprintf ( 1, ' Store in GNUPLOT data and command files.\\n' );\n\n x_lo = 0.0;\n x_hi = 1.0;\n x_num = 21;\n\n y_lo = 0.0;\n y_hi = 1.0;\n y_num = 21;\n\n [ x, y ] = grid_2d ( x_num, x_lo, x_hi, y_num, y_lo, y_hi );\n\n n = x_num * y_num;\n c = 1.0;\n\n [ u, v ] = uv_spiral ( n, x, y, c );\n\n header = 'spiral';\n s = 0.05;\n spiral_gnuplot ( header, n, x, y, u, v, s );\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/spiral_data/spiral_test03.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.704018548658413}} {"text": "% Figure 3.30a Feedback Control of Dynamic Systems, 5e\n% Franklin, Powell, Emami\n%\n\nclf;\nnum=1;\na=10;\n\nzeta =1;\nden2=[1/(zeta*a) 1];\nden1=[1 2*zeta 1];\nden=conv(den1,den2);\nt=0:.1:8;\ny1=step(num,den,t);\n\nzeta =.7;\nden2=[1/(zeta*a) 1];\nden1=[1 2*zeta 1];\nden=conv(den1,den2);\ny2=step(num,den,t);\n\nzeta =.5;\nden2=[1/(zeta*a) 1];\nden1=[1 2*zeta 1];\nden=conv(den1,den2);\ny3=step(num,den,t);\n\naxis([0 5 .1 .9])\nplot(t,y1,'-',t,y2,'--',t,y3,'-.'),grid\ntitle('Fig. 3.30a Step response with extra pole, \\alpha= 10')\nxlabel('\\omega_n t')\nylabel('y(t)')\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/9907-feedback-control-of-dynamic-systems-fifth-ed/fig3_30a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.7039257955547288}} {"text": "function value = r8_beta ( a, b )\n\n%*****************************************************************************80\n%\n%% R8_BETA evaluates the beta function of R8 arguments.\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 A, B, the arguments.\n%\n% Output, real VALUE, the beta function of A and B.\n%\n persistent alnsml\n persistent xmax\n\n if ( isempty ( xmax ) )\n [ xmin, xmax ] = r8_gaml ( );\n alnsml = log ( r8_mach ( 1 ) );\n end\n\n if ( a <= 0.0 || b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8_BETA - Fatal error!\\n' );\n fprintf ( 1, ' A and B must be greater than 0.\\n' );\n error ( 'R8_BETA - Fatal error!' )\n end\n\n if ( a + b < xmax )\n value = r8_gamma ( a ) * r8_gamma ( b ) / r8_gamma ( a + b );\n return\n end\n\n value = r8_lbeta ( a, b );\n\n value = exp ( value );\n\n return\nend\n", "meta": {"author": "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_beta.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.7039257731814497}} {"text": "%% MULTIGRID OF FOR THE STOKES EQNS IN 2D\n%\n% This example is to show the convergence of multigrid methods for various\n% finite element approximation of the Stokes equation on the unit square:\n%\n% -div(mu*grad u) + grad p = f in \\Omega,\n% - div u = 0 in \\Omega,\n% u = g_D on \\Gamma.\n%\n% with the pure Dirichlet boundary condition.\n%\n\n%% Setting\nclear all; close all;\n% [node,elem] = squaremesh([0,1,0,1],0.5);\n[node,elem] = circlemesh(0,0,1,0.25);\n% [node,elem] = uniformrefine(node,elem);\nshowmesh(node,elem);\npde = Stokesdata1; \n% pde = StokesZulehnerdata;\nbdFlag = setboundary(node,elem,'Dirichlet');\noption.L0 = 1;\noption.maxIt = 3;\noption.printlevel = 1;\noption.plotflag = 0;\noption.rateflag = 0;\n\n%% MG options\noption.solver = 'asmg';\noption.smoothingstep = 2;\noption.smootherbarSp = 'SGS';\n\n%% CR-P0 element\ndisplay('CR-P0')\noption.elemType = 'CRP0';\nfemStokes(node,elem,pde,bdFlag,option);\n\n%% P2-P0 element\ndisplay('P2-P0')\noption.elemType = 'P2P0';\nfemStokes(node,elem,pde,bdFlag,option);\n\n%% P2-P1 element\ndisplay('P2-P1')\noption.elemType = 'P2P1';\noption.solver = 'asmg';\nfemStokes(node,elem,pde,bdFlag,option);\n\n%% isoP2-P0 element\ndisplay('isoP2-P0')\noption.elemType = 'isoP2P0';\nfemStokes(node,elem,pde,bdFlag,option);\n\n%% isoP2-P1 element\ndisplay('isoP2-P1')\noption.elemType = 'isoP2P1';\nfemStokes(node,elem,pde,bdFlag,option);\n\n%% P1b-P1 element\ndisplay('P1b-P0')\noption.elemType = 'P1bP1';\nfemStokes(node,elem,pde,bdFlag,option);\n\n\n%% Conclusion\n% ", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/iFEM/example/asmgrateStokes.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7038723455787552}} {"text": "function [D,dir] = dimensions(points,varargin)\n\n% Calculates the box-dimensions and dimension estimates of the point set \n% \"points\". Returns also the corresponding direction vectors.\n\n\nif nargin == 2\n P = varargin{1};\n points = P(points,:);\nelseif nargin == 3\n P = varargin{1};\n Bal = varargin{2};\n I = vertcat(Bal{points});\n points = P(I,:);\nend\n\nif size(points,2) == 3\n X = cov(points);\n [U,S,~] = svd(X);\n \n dp1 = points*U(:,1);\n dp2 = points*U(:,2);\n dp3 = points*U(:,3);\n \n D = [max(dp1)-min(dp1) max(dp2)-min(dp2) max(dp3)-min(dp3) ...\n (S(1,1)-S(2,2))/S(1,1) (S(2,2)-S(3,3))/S(1,1) S(3,3)/S(1,1)];\n \n dir = [U(:,1)' U(:,2)' U(:,3)'];\nelse\n X = cov(points);\n [U,S,~] = svd(X);\n \n dp1 = points*U(:,1);\n dp2 = points*U(:,2);\n \n D = [max(dp1)-min(dp1) max(dp2)-min(dp2) ...\n (S(1,1)-S(2,2))/S(1,1) S(2,2)/S(1,1)];\n \n dir = [U(:,1)' U(:,2)'];\nend\n", "meta": {"author": "InverseTampere", "repo": "TreeQSM", "sha": "6630bbf516f8b53adb7d60a2cccbd21e6fe51226", "save_path": "github-repos/MATLAB/InverseTampere-TreeQSM", "path": "github-repos/MATLAB/InverseTampere-TreeQSM/TreeQSM-6630bbf516f8b53adb7d60a2cccbd21e6fe51226/src/tools/dimensions.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475810629194, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.703868424862722}} {"text": "function result = simplex_nd ( func, n, v )\n\n%*****************************************************************************80\n%\n%% SIMPLEX_ND approximates an integral inside a simplex in ND.\n%\n% Integration region:\n%\n% The simplex bounded by the origin and a convex combination of N points.\n%\n% Discussion:\n%\n% An N+1 point second degree formula is used.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 25 May 2004\n%\n% Author:\n%\n% 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(X) at the N-dimensional point\n% X, of the form\n% function value = func ( n, x )\n%\n% Input, integer N, the dimension of the space.\n%\n% Input, real V(N+1,N), each of the\n% N+1 rows of V contains the N coordinates of one of the\n% vertices of the simplex.\n%\n% Output, real RESULT, the approximate integral of the function.\n%\n c = 1.0E+00 / sqrt ( n + 2 );\n w = 1.0E+00 / ( n + 1 );\n\n for i = 1 : n\n x(i) = w * ( 1.0E+00 - c ) * sum ( v(1:n+1,i) );\n end\n\n quad = 0.0E+00;\n\n for i = 1 : n+1\n\n x(1:n) = x(1:n) + c * v(i,1:n);\n\n quad = quad + w * feval ( func, n, x );\n\n x(1:n) = x(1:n) - c * v(i,1:n);\n\n end\n\n volume = simplex_volume_nd ( n, v );\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/simplex_nd.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.7038663483639174}} {"text": "function [ vTransVectorMean, vTransVectorCov ] = UnscentedTransform( hTransformFunction, vVectorMean, mVectorCov )\n%UNTITLED4 Summary of this function goes here\n% Detailed explanation goes here\n\nvectorOrder = size(vVectorMean, 1);\nnumSigmaPoints = (2 * vectorOrder) + 1;\n\nmVectorCovSqrt = chol(mVectorCov);\nif(vectorOrder <= 3) %.\n\nfunction [errh1, errl2, errh1s, errh1_elem, errl2_elem, errh1s_elem] = sp_h1_error (sp, msh, u, uex, graduex)\n\n grad_valu = sp_eval_msh (u, sp, msh, 'gradient');\n grad_valu = reshape (grad_valu, sp.ncomp, msh.rdim, msh.nqn, msh.nel);\n\n for idir = 1:msh.rdim\n x{idir} = reshape (msh.geo_map(idir,:,:), msh.nqn*msh.nel, 1);\n end\n grad_valex = reshape (feval (graduex, x{:}), sp.ncomp, msh.rdim, msh.nqn, msh.nel);\n\n w = msh.quad_weights .* msh.jacdet;\n\n [errl2, errl2_elem] = sp_l2_error (sp, msh, u, uex);\n errh1s_elem = sum (reshape (sum (sum ((grad_valu - grad_valex).^2, 1), 2), [msh.nqn, msh.nel]) .* w);\n errh1s = sqrt (sum (errh1s_elem));\n\n errh1 = sqrt (errl2^2 + errh1s^2);\n\n errh1_elem = sqrt (errl2_elem.^2 + errh1s_elem);\n errh1s_elem = sqrt (errh1s_elem);\n \nend\n", "meta": {"author": "rafavzqz", "repo": "geopdes", "sha": "3bfa57b1a38bd4da3148536c9f67cce81afce701", "save_path": "github-repos/MATLAB/rafavzqz-geopdes", "path": "github-repos/MATLAB/rafavzqz-geopdes/geopdes-3bfa57b1a38bd4da3148536c9f67cce81afce701/geopdes/inst/space/sp_h1_error.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8152324871074607, "lm_q1q2_score": 0.7038648895466398}} {"text": "%% Gaussian Mixture Model (GMM)\n%\n% Demonstrates EM clustering, and also compares againt K-means clustering.\n%\n% Sources:\n%\n% * \n% * \n%\n\nfunction gaussian_mix_demo()\n %% Data\n % sample 2D points from a mixture distribution of K bivariate Gaussians\n K = 5;\n sz = 512;\n [pts, labels, mus, sigmas] = make_gaussian_mixture(K, sz);\n whos pts labels mus sigmas\n\n %%\n % draw points (color-coded) with the ground-truth mixtures\n clr = uint8(hsv(K) * 255);\n clr(:,4) = 0;\n img = zeros([sz sz 3], 'uint8');\n img0 = cv.circle(img, pts, 1, 'Colors',clr(labels,:), 'Thickness','Filled');\n for k=1:K\n img0 = draw_gaussian(img0, mus(k,:), sigmas{k}, [0 255 255]);\n end\n imshow(img0), title(sprintf('%d Samples, K=%d', numel(labels), K))\n\n %% EM\n % cluster using EM by fitting a Gaussian mixture model\n em = cv.EM();\n em.ClustersNumber = K;\n em.CovarianceMatrixType = 'Generic';\n tic\n [~,L] = em.trainEM(pts);\n toc\n\n %%\n % draw clustered points along with the estimated mixture model\n means = em.getMeans();\n covs = em.getCovs();\n img1 = cv.circle(img, pts, 1, 'Colors',clr(L+1,:), 'Thickness','Filled');\n for k=1:K\n img1 = draw_gaussian(img1, means(k,:), covs{k}, [0 255 255]);\n end\n figure, imshow(img1), title('Gaussian Mixtures')\n\n %% Kmeans\n % cluster using Kmeans\n crit = struct('type','Count+EPS', 'maxCount',30, 'epsilon',0.1);\n L = cv.kmeans(pts, K, 'Criteria',crit, 'Attempts',10);\n\n %%\n % draw points color-coded by assigned label\n img2 = cv.circle(img, pts, 1, 'Colors',clr(L+1,:), 'Thickness','Filled');\n figure, imshow(img2), title('Kmeans')\nend\n\n%% Helper functions\n\nfunction [pts, labels, mus, sigmas] = make_gaussian_mixture(K, sz)\n %MAKE_GAUSSIAN_MIXTURE Random points from Gaussian mixture distribution\n %\n % [pts, labels, mus, sigmas] = make_gaussian_mixture(K, sz)\n %\n % ## Input\n % * __K__ number of components\n % * __sz__ image size, determines 2D points domain\n %\n % ## Output\n % * __pts__ matrix of 2D points\n % * __labels__ vector of corresponding component indices\n % * __mus__ K-by-2 mean of each component\n % * __sigmas__ cell array of length K, covariance of each component\n %\n % See also: gmdistribution.random\n %\n\n mus = zeros(K,2);\n sigmas = cell(K,1);\n pts = cell(K,1);\n labels = cell(K,1);\n for k=1:K\n mus(k,:) = (rand(1,2)*0.8 + 0.1) * sz;\n a = (rand(2,2) - 0.5) * sz * 0.1;\n sigmas{k} = (a.' * a) + sz*0.05*eye(2);\n n = 100 + randi([0 900]);\n pts{k} = my_mvnrnd(mus(k,:), sigmas{k}, n);\n labels{k} = k * ones(size(pts{k},1),1);\n end\n pts = single(cat(1, pts{:}));\n labels = int32(cat(1, labels{:}));\nend\n\n%%\n\nfunction X = my_mvnrnd(mu, sigma, num)\n %MY_MVNRND Random points from Gaussian distribution\n %\n % X = my_mvnrnd(mu, sigma, num)\n %\n % ## Input\n % * __mu__ 1x2 mean vector\n % * __sigma__ 2x2 covariance matrix\n % * __num__ number of points to generate\n %\n % ## Output\n % * __X__ matrix of 2D points, num-by-2\n %\n % See also: mvnrnd, randn\n %\n\n if mexopencv.require('stats')\n X = mvnrnd(mu, sigma, num);\n else\n X = bsxfun(@plus, randn(num,numel(mu)) * cholcov(sigma), mu);\n end\nend\n\n%%\n\nfunction img = draw_gaussian(img, mu, sigma, clr)\n %DRAW_GAUSSIAN Draw a bivariate Gaussian\n %\n % img = draw_gaussian(img, mu, sigma, clr)\n %\n % ## Input\n % * __img__ input image on which to draw\n % * __mu__ 1x2 mean vector\n % * __sigma__ 2x2 covariance matrix\n % * __clr__ color\n %\n % ## Output\n % * __img__ output image\n %\n % Represent a 2D Gaussian with an ellipse where:\n %\n % * its mean is the center of the ellipse\n % * its covariance matrix eigenvector corresponding to largest eigenvalue\n % is the direction of the ellipse\n % * its (scaled) eigenvalues are the major/minor axis lengths of the\n % ellipse\n %\n\n [w,u,~] = cv.SVD.Compute(sigma);\n ang = atan2(u(2,1), u(1,1)) * (180/pi);\n s = sqrt(w)*3;\n img = cv.ellipse(img, mu, s, 'Angle',ang, 'Color',clr, 'LineType','AA');\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/gaussian_mix_demo.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7038338938033637}} {"text": "function [A,xy]= cut_grid_data\n\n% Generate a cut-grid graph for the ICM 2006 talk example\n%\n% The graph has 64 nodes and 95 edges\n% A is an n x m incidence matrix (n is number of nodes, m is number of edges)\n% xy is the location data\n%\n% Original code by Arpita Ghosh, modified for ICM06 talk by Almir Mutapcic\n\nn = 8; \nr1 = 2;\ny = ones(n,1) * (1:n);\nx = y';\nx = x(:);\ny = y(:);\ndx = x * ones(1,n^2);\ndy = y * ones(1,n^2);\nxy = [ x, y ];\n\n% Find the adjacency matrix, manually deleting edges to get down to size\nAdj1 = tril( ( dx - dx' ) .^ 2 + ( dy - dy' ) .^2 < r1, -1 );\nAdj1(49,41) = 0;\nAdj1(50,42) = 0; \nAdj1(16,8) = 0;\nAdj1(24,16) = 0;\nAdj1(15,7) = 0;\nAdj1(23,15) = 0;\nAdj1(10,1) = 0; \nAdj1(21,13) = 0;\nAdj1(13,5) = 0; \nAdj1(22,14) = 0;\nAdj1(14,6) = 0; \nAdj1(51,43) = 0; \nAdj1(52,44) = 0; \nAdj1(53,45) = 0; \nAdj1(54,46) = 0; \nAdj1(42,41) = 0;\nAdj1(34,33) = 0;\nAdj1(26,25) = 0;\n\n% Build the incidence matrix\n[i,j] = find(Adj1);\nm = length(i);\nA = sparse( [i;j], [1:m,1:m]', [ones(m,1);-ones(m,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/cvx-w64/cvx/examples/graph_laplacian/cut_grid_data.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.7038255691044031}} {"text": "function [rho,rhou,Ener] = Euler1D(rho, rhou, Ener, FinalTime)\n\n% function [rho, rhou, Ener] = Euler1D(rho, rhou, Ener, FinalTime)\n% Purpose : Integrate 1D Euler equations until FinalTime starting with\n% initial conditions [rho, rhou, Ener]\n\nGlobals1D;\n\n% Parameters\ngamma = 1.4; CFL = 1.0; time = 0;\n\n% Prepare for adaptive time stepping\nmindx = min(x(2,:)-x(1,:));\n\n% Limit initial solution\nrho =SlopeLimitN(rho); rhou=SlopeLimitN(rhou); Ener=SlopeLimitN(Ener);\n\n% outer time step loop \nwhile(timeFinalTime)\n dt = FinalTime-time;\n end\n\n % 3rd order SSP Runge-Kutta\n \n % SSP RK Stage 1.\n [rhsrho,rhsrhou,rhsEner] = EulerRHS1D(rho, rhou, Ener);\n rho1 = rho + dt*rhsrho;\n rhou1 = rhou + dt*rhsrhou;\n Ener1 = Ener + dt*rhsEner;\n\n % Limit fields\n rho1 = SlopeLimitN(rho1); rhou1 = SlopeLimitN(rhou1); Ener1 = SlopeLimitN(Ener1);\n\n % SSP RK Stage 2.\n [rhsrho,rhsrhou,rhsEner] = EulerRHS1D(rho1, rhou1, Ener1);\n rho2 = (3*rho + rho1 + dt*rhsrho )/4;\n rhou2 = (3*rhou + rhou1 + dt*rhsrhou)/4;\n Ener2 = (3*Ener + Ener1 + dt*rhsEner)/4;\n\n % Limit fields\n rho2 = SlopeLimitN(rho2); rhou2 = SlopeLimitN(rhou2); Ener2 = SlopeLimitN(Ener2);\n\n % SSP RK Stage 3.\n [rhsrho,rhsrhou,rhsEner] = EulerRHS1D(rho2, rhou2, Ener2);\n rho = (rho + 2*rho2 + 2*dt*rhsrho )/3;\n rhou = (rhou + 2*rhou2 + 2*dt*rhsrhou)/3;\n Ener = (Ener + 2*Ener2 + 2*dt*rhsEner)/3;\n\n % Limit solution\n rho =SlopeLimitN(rho); rhou=SlopeLimitN(rhou); Ener=SlopeLimitN(Ener);\n \n % Increment time and adapt timestep\n time = time+dt;\nend\nreturn\n", "meta": {"author": "wme7", "repo": "Aero-matlab", "sha": "9430008f2e3b84f28633775a44dff534e780fbac", "save_path": "github-repos/MATLAB/wme7-Aero-matlab", "path": "github-repos/MATLAB/wme7-Aero-matlab/Aero-matlab-9430008f2e3b84f28633775a44dff534e780fbac/JSHesthaven&TWarburton/CFD1D/Euler1D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7038003236023169}} {"text": "function [A,B,D,E,I]=bpf1(X)\n% Multiple Feedback Bandpass Filter\n% Note that complex frequency variable s is not used here.\n% These arrays are real, not complex.\n% \nR1=X(1);R2=X(2);R3=X(3);C1=X(4);C2=X(5);\n%\nN=2;M=1;U=1;Y=1;\n%\nA1=[0 1 1;\n 1/R3 1 0;\n 1 0 0];\n%\nB2=[-(1/R1+1/R2) 0 1/R1;\n 0 0 0;\n 1 -1 0];\n% \nP=diag([C1 C2]);\n%\n% The following statements never change from circuit to circuit.\n%\nV=A1\\B2;H=V(U+1:U+N,1:N+M);I=eye(N);\nAB=P\\H;A=AB(1:N,1:N);B=AB(1:N,N+1:N+M);\nD=V(Y:Y,1:N);E=V(Y:Y,N+1:N+M);\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2435-shortcut-state-space-circuit-analysis/Matlab_Files/bpf1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.7037767854836735}} {"text": "% the MWF beamformer\n% r1MWF: h = PhiN^-1 * PhiX * refVec / (mu + trace(PhiN^-1 * PhiX)\n% SDWMWF: h = (PhiX + mu * PhiN)^-1 * PhiX * refVec\n% input: PhiN, (Nch, Nch, Nbin) the noise covariance matrix\n% PhiX, (Nch, Nch, Nbin) the speech covariance matrix\n% mu, the speech distortion/noise reduction trade-off parameter\n% refMic, the reference microphone, default = 1\n% output: h, (Nch, Nbin) the beamformer coefficients\n% % Ziteng Wang @ 201812\n\nfunction h = MWF(PhiX, PhiN, mu, refMic, choice)\nif nargin < 3\n mu = 1; % typical value {0, 1}\nelseif nargin < 4\n refMic = 1;\nelseif nargin < 5\n choice = 'r1MWF'; % collected from 'r1MWF' 'SDWMWF'\nend\n\n[Nch, ~, Nbin] = size(PhiX);\nrefVec = zeros(Nch, 1); \nrefVec(refMic) = 1;\nlambda = zeros(Nbin, 1);\nh = zeros(Nch, Nbin);\n\nfor bin = 1:Nbin\n if rcond(PhiN(:,:,bin)) < eps\n disp(['bin ' num2str(bin) ': Noise covariance ill-conditioned.']);\n PhiN(:,:,bin) = PhiN(:,:,bin) + 1e-10 * eye(Nch);\n end\n if strcmp(choice, 'r1MWF')\n tmp = PhiN(:,:,bin) \\ PhiX(:,:,bin);\n lambda(bin) = trace(tmp);\n h(:,bin) = tmp * refVec / (mu + lambda(bin));\n %%% Gain factor to normalize the steering vector. The results are \n %%% better. Needs further checking\n %gain_factor = norm(PhiX(:,refMic,bin) / PhiX(refMic,refMic,bin));\n %h(:,bin) = gain_factor * h(:,bin);\n elseif strcmp(choice, 'SDWMWF') % SDW-MWF is more sensitive to estimation errors.\n tmp = (PhiX(:,:,bin) + mu * PhiN(:,:,bin)) \\ PhiX(:,:,bin);\n h(:,bin) = tmp * refVec;\n end \nend\n\n\n", "meta": {"author": "ZitengWang", "repo": "MASP", "sha": "c3dae1444b60213a1ae31b0a81906a03e729c7c6", "save_path": "github-repos/MATLAB/ZitengWang-MASP", "path": "github-repos/MATLAB/ZitengWang-MASP/MASP-c3dae1444b60213a1ae31b0a81906a03e729c7c6/Beamformer/MWF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299529686199, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.7037767776424709}} {"text": "function [ deltaHD , deltaSEN , deltaPRO ] = CV2XMode4_common( lambda , Pt , distance, Psen , step_dB , noise , coding);\n\n% CV2XMode4_common is a script that calculates the probability of packet \n% loss due to half-duplex transmissions, the probability of packet loss \n% due to a received signal power below the sensing power threshold and the\n% probability of packet loss due to propagation effects for different \n% Tx-Rx distances based on the models described in the following paper:\n% \n% Manuel Gonzalez-Martín, Miguel Sepulcre, Rafael Molina-Masegosa, Javier Gozalvez, \n% \"Analytical Models of the Performance of C-V2X Mode 4 Vehicular Communications\", \n% IEEE Transactions on Vehicular Technology, Vol. 68, Issue 2, Feb. 2019. DOI: 10.1109/TVT.2018.2888704\n% Final version available at: https://ieeexplore.ieee.org/document/8581518\n% Post-print version available at: https://arxiv.org/abs/1807.06508\n%\n% CV2XMode4_common is called from the main script, CV2XMode4.\n%\n% Input parameters:\n% lambda: packet transmission frequency in Hz. .\n% Pt: transmission power in dBm. \n% distance: distance between tramsmitter and receiver in meters. It can be a vector with multiple distances.\n% Psen: sensing threshold in dBm.\n% step_dB: discrete steps to compute the PDF of the SNR and SINR in dB.\n% noise: noise corresponding to the DATA field of each message. Assumes a noise figure of 9dB and 10MHz channel (background noise of -95dBm). The total number of RBs in 10MHz is 50.\n% coding: ID of the coding used to identify the BLER curve \n% \n% Output metrics:\n% deltaHD: probability of packet loss due to half-duplex transmissions for different Tx-Rx distances\n% deltaSEN: probability of packet loss due to a received signal power below the sensing power threshold for different Tx-Rx distances\n% deltaPRO: probability of packet loss due to propagation effects for different Tx-Rx distances\n%\n% The equations that are identified with a number between brackets in this script are the ones\n% that also appear in the paper so that they can be easily identified. \n\n \n D = length(distance);\n\n deltaHD(1:D) = lambda/1000; % Equation (7)\n\n [PL_E_R, std_dev_E_R] = get_PL_SH(distance); % Obtains pathloss and shadowing for different Tx-Rx distances.\n deltaSEN = 0.5 * ( 1 - erf( (Pt - PL_E_R - Psen)./(std_dev_E_R*sqrt(2)) ) ); % Equation (10)\n\n [SNR, PDF_SNR] = get_SINRdistribution( Pt - PL_E_R , -180 , std_dev_E_R , 3 , noise , Psen , step_dB); % Obtains the PDF of the SNR experienced by Rx (without interference).\n deltaPRO = get_BLER( SNR , PDF_SNR , coding , step_dB); % Equation (13)\n\nend\n\n\n\n", "meta": {"author": "msepulcre", "repo": "C-V2X", "sha": "71d4c25f279249a06f7d4de81f7aa61b06a244e0", "save_path": "github-repos/MATLAB/msepulcre-C-V2X", "path": "github-repos/MATLAB/msepulcre-C-V2X/C-V2X-71d4c25f279249a06f7d4de81f7aa61b06a244e0/CV2XMode4_common.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574068, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.7037085666671763}} {"text": "function value = local_sum(input, window_size)\n% LOCAL_SUM Fast computation of 2D local sum using integral images.\n% \n% Algorithm is described in Viola and Jones, \"Robust real-time face\n% detection\", International Journal of Computer Vision, 2004. Computation\n% time is independent of window size. Precision may be an issue for very\n% large images, but a few thousand by a few thousand images seems to work\n% with no issues.\n%\n% Suprisingly, for small window sizes, MATLAB's conv2 actually seems to be\n% a faster way to do this, but this implementation gets much faster as\n% window sizes get larger. MATLAB Central's fastrunmean demonstrates\n% another way of computing fast means/sums. Fastrunmean is not quite as\n% fast as this integral image implementation, but doesn't have the same\n% potential precision issues for very large images.\n%\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////\n\npadsize = floor(window_size/2);\npadded = padarray(input, padsize+1, 0, 'pre'); % Zeropad to handle local sums at edges\npadded = padarray(padded, padsize, 0, 'post'); % Zeropad to handle local sums at edges\npadded = cumsum(cumsum(double(padded),1),2); % Create integral image\nvalue = padded(1:size(input,1),1:size(input,2))-... % Compute sum over local window\n padded(1:size(input,1),(window_size(2)+1):end)-...\n padded((window_size(1)+1):end,1:size(input,2))+...\n padded((window_size(1)+1):end,(window_size(2)+1):end);\n\nend\n\n% //////////////////////////////////////////\n% /// CLASSIFICATION: UNCLASSIFIED ///\n% //////////////////////////////////////////", "meta": {"author": "ngageoint", "repo": "MATLAB_SAR", "sha": "6291feff8e200d387e271f49ec09b1acd5514c4e", "save_path": "github-repos/MATLAB/ngageoint-MATLAB_SAR", "path": "github-repos/MATLAB/ngageoint-MATLAB_SAR/MATLAB_SAR-6291feff8e200d387e271f49ec09b1acd5514c4e/Utilities/misc/local_sum.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.7037085614556383}} {"text": "function [ C ] = gsp_gwft(G,g,f, param )\n%GSP_GWFT Generalized windowed Fourier transform\n% Usage: C = gsp_gwft(G,g,f, param );\n% C = gsp_gwft(G,g,f);\n%\n% Input parameters:\n% G : Graph\n% g : Window (graph signal or kernel)\n% f : Graph signal (column vector)\n% param : Structure of optional parameter\n% Output parameters:\n% C : Coefficient.\n%\n% This function compute the graph windowed Fourier transform of a signal\n% *f* with the window *g*. The function returns a matrix of size N^2*N. \n%\n% *param* a Matlab structure containing the following fields:\n% \n% * *param.verbose* : 0 no log, 1 print main steps, 2 print all steps.\n% By default, it is 1.\n% * *param.lowmemory* : use less memory. By default, it is 1.\n%\n% Reference: shuman2013windowed\n\n% Author : Nathanael Perraudin\n% Testing: test_gwft\n\n\n% Optional input arguments\nif nargin<4, param=struct; end\nif ~isfield(param, 'verbose'), param.verbose=1 ; end\nif ~isfield(param, 'lowmemory'), param.lowmemory=1 ; end\n\nif ~isfield(G,'U')\n error(['GSP_GWFT: You need first to compute the Fourier basis. ',...\n 'You can do it with the function gsp_compute_fourier_basis']);\nend\n\nif sum(G.U(:,1)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[x, y, z] = transformPoint3d(x, y, z, trans);\n\n% create image: simple threshold over 3 dimensions\nimg = abs(x) <= side(1)/2 & abs(y) <= side(2)/2 & abs(z) <= side(3)/2;\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/discreteCube.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7036472428028422}} {"text": "function [mi entropy fd_bins] = mutualinformationx(x,y,fd_bins,permtest)\n% MUTUALINFORMATIONX Compute mutual information between two vectors\n% \n% Inputs:\n% x,y : data matrices of equal size\n%\n% Optional inputs:\n% bins : number of bins to use for distribution discretization\n% permtest : perform permutation test and return mi in standard-Z values\n%\n% Outputs:\n% mi : mutual information in bits\n% entropy : entropy of x, y, and joint\n% nbins : number of bins used for discretization\n% (based on Freedman-Diaconis rule)\n%\n% Mike X Cohen (mikexcohen@gmail.com)\n\nif nargin<2, error('Specify two inputs.'); end\nif length(x)~=length(y), error('X and Y must have equal length'); end\n\n%% determine the optimal number of bins for each variable\n\n% vectorize in the case of matrices\nx=x(:); y=y(:);\n\nif nargin<3 || isempty(fd_bins)\n n = length(x);\n maxmin_range = max(x)-min(x);\n fd_bins1 = ceil(maxmin_range/(2.0*iqr(x)*n^(-1/3))); % Freedman-Diaconis\n \n n = length(y);\n maxmin_range = max(y)-min(y);\n fd_bins2 = ceil(maxmin_range/(2.0*iqr(y)*n^(-1/3)));\n \n % and use the average...\n fd_bins = ceil((fd_bins1+fd_bins2)/2);\nend\n\n%% bin data\n\nedges = linspace(min(x),max(x),fd_bins+1);\n[nPerBin1,bins1] = histc(x,edges);\n\nedges = linspace(min(y),max(y),fd_bins+1);\n[nPerBin2,bins2] = histc(y,edges);\n\n%% compute entropies\n\n% recompute entropy with optimal bins for comparison\nhdat1 = hist(x,fd_bins);\nhdat1 = hdat1./sum(hdat1);\nhdat2 = hist(y,fd_bins);\nhdat2 = hdat2./sum(hdat2);\n\n% convert histograms to probability values\nfor i=1:2\n eval([ 'entropy(' num2str(i) ') = -sum(hdat' num2str(i) '.*log2(hdat' num2str(i) '+eps));' ]);\nend\n\n%% compute joint probabilities\n\njointprobs = zeros(fd_bins);\nfor i1=1:fd_bins\n for i2=1:fd_bins\n jointprobs(i1,i2) = sum(bins1==i1 & bins2==i2);\n end\nend\njointprobs=jointprobs./sum(jointprobs(:));\n\nentropy(3) = -sum(jointprobs(:).*log2(jointprobs(:)+eps));\n\n%% mutual information\n\nmi = sum(entropy(1:2)) - entropy(3);\n\n%% optional permutation testing\n\nif nargin==4\n \n npermutes = 500;\n n = length(bins2);\n \n perm_mi = zeros(1,npermutes);\n \n for permi=1:npermutes\n \n jointprobs = zeros(fd_bins);\n \n % shuffle bins\n binbreak = randsample(round(n*.8),1,1)+round(n*.1);\n switch mod(permi,4)\n case 0, bins2 = [ bins2(binbreak:end); bins2(1:binbreak-1) ];\n case 1, bins2 = [ bins2(end:-1:binbreak); bins2(1:binbreak-1) ];\n case 2, bins2 = [ bins2(binbreak:end); bins2(binbreak-1:-1:1) ];\n case 3, bins2 = [ bins2(end:-1:binbreak); bins2(binbreak-1:-1:1) ];\n end\n \n for i1=1:fd_bins\n for i2=1:fd_bins\n jointprobs(i1,i2) = sum(bins1==i1 & bins2==i2);\n end\n end\n jointprobs=jointprobs./sum(jointprobs(:));\n \n perm_jentropy = -sum(jointprobs(:).*log2(jointprobs(:)+eps));\n \n % mutual information\n perm_mi(permi) = sum(entropy(1:2)) - perm_jentropy;\n end\n \n mi = (mi-mean(perm_mi))/std(perm_mi);\nend\n\n%%\n% simplified replacement for randsample\nfunction y = randsample(x,n,junk)\ny=randperm(x);\ny=y(1:n);\n", "meta": {"author": "mikexcohen", "repo": "AnalyzingNeuralTimeSeries", "sha": "e97c2e97f73c77dad1a258338e7ab94c78f515dd", "save_path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries", "path": "github-repos/MATLAB/mikexcohen-AnalyzingNeuralTimeSeries/AnalyzingNeuralTimeSeries-e97c2e97f73c77dad1a258338e7ab94c78f515dd/mutualinformationx.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.7036472360988513}} {"text": "function res = reconWUpyr(pyr, pind, daub_order);\n\n% RES = reconWUpyr(PYR, INDICES, DAUB_ORDER)\n \n% Reconstruct image from its separable undecimated orthonormal QMF/wavelet pyramid\n% representation, as created by buildWUpyr.\n%\n% PYR is a vector containing the N pyramid subbands, ordered from fine\n% to coarse. INDICES is an Nx2 matrix containing the sizes of\n% each subband. \n% \n% DAUB_ORDER: specifies the order of the daubechies wavelet filter used\n \n% JPM, Univ. de Granada, 03/2003, based on Rice Wavelet Toolbox \n% functions \"mrdwt\" and \"mirdwt\", and on Matlab Pyrtools from Eero Simoncelli.\n\n\nNor = 3;\nNsc = (size(pind,1)-2)/Nor-1;\nh = daubcqf(daub_order);\n\nyh = [];\n\nnband = 1;\nlast = prod(pind(1,:)); % empty \"high pass residual band\" for compatibility with full steerpyr 2\nfor nsc = 1:Nsc+1, % The number of scales corresponds to the number of pyramid levels (also for compatibility)\n for nor = 1:Nor,\n nband = nband +1;\n first = last + 1;\n last = first + prod(pind(nband,:)) - 1;\n band = pyrBand(pyr,pind,nband);\n sh = (daub_order/2 - 1)*2^nsc; % approximate phase compensation\n if nsc > 2,\n band = expand(band, 2^(nsc-2));\n end \n if nor == 1, % horizontal\n band = shift(band, [-sh -2^(nsc-1)]);\n elseif nor == 2, % vertical\n band = shift(band, [-2^(nsc-1) -sh]);\n else\n band = shift(band, [-sh -sh]); % diagonal\n end \n yh = [yh band]; \n end \nend \n\nnband = nband + 1;\nband = pyrBand(pyr,pind,nband);\nlpr = expand(band,2^Nsc);\n\nres= mirdwt(lpr,yh,h,Nsc+1);", "meta": {"author": "ricedsp", "repo": "D-AMP_Toolbox", "sha": "6e597d98c84755697b65554d59485d50a549c01a", "save_path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox", "path": "github-repos/MATLAB/ricedsp-D-AMP_Toolbox/D-AMP_Toolbox-6e597d98c84755697b65554d59485d50a549c01a/Packages/BLS-GSM/Added_PyrTools/reconWUpyr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.7036322505003014}} {"text": "function [Y, spectrum] = sllemap(G, d, sch)\n%SLLEMAP Solves Laplacian Eigenmap Embedding\n%\n% $ Syntax $\n% - Y = sllemap(G, d)\n% - Y = sllemap(G, d, sch)\n% - [Y, spectrum] = sllemap(...)\n%\n% $ Arguments $\n% - G: The affinity graph (in any acceptable form): n x n\n% - d: The embedding dimension\n% - sch: The scheme to use\n% - Y: The solved embedded coordinates (d x n)\n%\n% $ Description $\n% - Y = sllemap(G, d) uses the default scheme to solve the Laplacian\n% Eigenmap embedding in a d-dimensional space.\n%\n% - Y = sllemap(G, d, sch) uses the specified scheme to solve the \n% Laplacian Eigenmap embedding in a d-dimensional space.\n%\n% Three schemes are implemented to resolve the problem, they are\n% under three different formulations:\n% (1) 'minLI':\n% objective: minimize sum_ij w_ij ||y_i - y_j||^2\n% s.t. forall i, ||y_i||^2 = 1\n% in matrix form, it is expressed as:\n% minimize y^T * L * y, s.t. y^T * y = 1\n% (2) 'minLD': \n% objective: minimize sum_ij w_ij ||y_i - y_j||^2\n% s.t. forall i, d_ii ||y_i||^2 = 1\n% in matrix form, it is expressed as:\n% minimize y^T * L * y, s.t. y^T * D * y = 1\n% This is the original formulation in many papers in the fields\n% of spectral learning, clustering and manifold learning.\n% (3) 'maxWD': (default)\n% objective: maximize sum_ij w_ij \n% s.t. forall i, d_ii ||y_i||^2 = 1\n% in matrix form, it is expressed as:\n% maximize y^T * W * y, s.t. y^T * D * y = 1\n% In theory, this objective is equivalent to 'minLD'. However,\n% due to that its implementation is based on finding the \n% eigenvectors corresponding to the largest eigenvalues instead\n% of the smallest ones, thus it is much more efficient and\n% numerically stable. Hence, it is selected as the default\n% scheme.\n%\n% - [Y, spectrum] = sllemap(...) additionally outputs the spectrum \n% of the embedding. The definition of the spectrum varies for different\n% schemes:\n% 'minLI': the spectrum is the eigenvalues of L, in ascending order\n% 'minLD': the spectrum is the eigenvalues of D^(-1/2) * L * D^(-1/2),\n% in ascending order\n% 'maxWD': the spectrum is the eigenvalues of D^(-1/2) * W * D^(-1/2),\n% in descending order.\n%\n% $ Remarks $\n% - If the input graph does not have edge values or it is logical, \n% it just assume 1 between neighboring samples and 0 for other pairs.\n%\n% - The embedding dimension d should be strictly less than the number\n% of samples n.\n%\n% $ History $\n% - Created by Dahua Lin, on Sep 12nd, 2006\n%\n\n%% parse and verify input arguments\n\nif nargin < 2\n raise_lackinput('sllemap', 2);\nend\n\ngi = slgraphinfo(G, {'square'});\nn = gi.n;\nif strcmp(gi, 'adjmat')\n if isnumeric(G)\n W = G;\n else\n W = double(G);\n end\nelse\n W = sladjmat(G);\nend\n\nif d >= n\n error('sltoolbox:invalidarg', ...\n 'The embeded dimension d should be strictly less than n');\nend\n\nif nargin < 3 || isempty(sch)\n sch = 'maxWD';\nend\n\n%% main delegation\n\n% L = Di + Dj - Wij - Wji\n% we let\n% W = Wij + Wji\n% D = Di + Dj = diag(diag(W))\n% L = D - W\nW = W + W';\n\nswitch sch\n case 'maxWD'\n [Y, spectrum] = solve_maxWD(W, d);\n case 'minLD'\n [Y, spectrum] = solve_minLD(W, d);\n case 'minLI'\n [Y, spectrum] = solve_minLI(W, d);\n otherwise\n error('sltoolbox:invalidarg', ...\n 'Invalid scheme for solving eigenmap: %s', sch);\nend\n\n%% Core functions\n\nfunction [Y, spectrum] = solve_maxWD(W, d)\n\nvD = calcDv(W);\nW = calcNormalizeMat(W, vD);\n\n[spectrum, Y] = slsymeig(W, d+1, 'descend');\nspectrum = spectrum(2:d+1);\nY = Y(:, 2:d+1)';\nY = denormY(Y, vD);\n\nfunction [Y, spectrum] = solve_minLD(W, d)\n\nvD = calcDv(W);\nL = calcL(vD, W);\nL = calcNormalizeMat(L, vD);\n\n[spectrum, Y] = slsymeig(L, d+1, 'ascend');\nspectrum = spectrum(2:d+1);\nY = Y(:, 2:d+1)';\nY = denormY(Y, vD);\n\n\nfunction [Y, spectrum] = solve_minLI(W, d)\n\nvD = calcDv(W);\nL = calcL(vD, W);\n\n[spectrum, Y] = slsymeig(L, d+1, 'ascend');\nspectrum = spectrum(2:d+1);\nY = Y(:, 2:d+1)';\n\n\n%% Computation routines\n\nfunction vD = calcDv(W)\n\nvD = sum(W, 1)';\n\nfunction L = calcL(vD, W)\n\nn = length(vD);\nif issparse(W)\n D = sparse((1:n)', (1:n)', vD, n, n, n);\n L = D - W;\nelse\n L = -W;\n dinds = (1:n)'*(n+1) - n;\n L(dinds) = L(dinds) + vD;\nend\n\nfunction Mn = calcNormalizeMat(M, vD)\n\nvD(vD < eps) = eps;\ncv = 1 ./ sqrt(vD);\n\nif issparse(M)\n n = size(M,1);\n Mn = M;\n for i = 1 : n\n Mn(:,i) = Mn(:,i) * cv(i);\n end\n for i = 1 : n\n Mn(i,:) = Mn(i,:) * cv(i);\n end\nelse \n rv = cv';\n Mn = slmulrowcols(M, rv, cv);\nend\n\nfunction Y = denormY(Y, vD)\n\nvD = vD';\nvD(vD < eps) = eps;\nY = slmulvec(Y, 1 ./ sqrt(vD), 2);\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/manifold/sllemap.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.7036322397932038}} {"text": "% Chapter 4 - Electromagnetic Waves and Optical Resonators.\n% Program_4a - Iteration of the Ikeda Map.\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% Chaotic attractor for the Ikeda map (Figure 4.11(b)).\nclear\necho off\nA=10;\nB=0.15;\nN=10000;\nE=zeros(1,N);x=zeros(1,N);y=zeros(1,N);\nE(1)=A;x(1)=A;y(1)=0;\nfor n=1:N\n E(n+1)=A+B*E(n)*exp(1i*abs(E(n))^2);\n x(n+1)=real(E(n+1));\n y(n+1)=imag(E(n+1));\nend\naxis([8 12 -2 2])\naxis equal\nplot(x(50:N),y(50:N),'.','MarkerSize',1);\nfsize=15;\nset(gca,'XTick',8:1:12,'FontSize',fsize)\nset(gca,'YTick',-2:1:2,'FontSize',fsize)\nxlabel('Real E','FontSize',fsize)\nylabel('Imag E','FontSize',fsize)\n \n% End of Program_4a.\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/2374-dynamical-systems-with-applications-using-matlab/MATLAB files 20013a/Program_4a.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.703632234950845}} {"text": "function dn = dnmult(dn0,dn1)\n\n% DMULT dual number multiplication\n%\n% DN = DNMULT(DN0,DN1) returns the dual number DN which is the dual number\n% multiplication of the dual numbers DN0 and DN1\n% - DN0 (resp. DN1) is a dual number (DN0 = a0 + eps*b0, eps^2 = 0).\n% It is a 2-vector or a 2*N array (column i represents dual number\n% i) where N is the number of dual numbers. DN0 and DN1 must have\n% the same size.\n% - DN is a dual number. It is a 2*N array (each column is the dual\n% multiplication of the corresponding columns in DN0 and DN1)\n\ns0 = size(dn0);\ns1 = size(dn1);\nif s0 == [1 2]\n dn0 = dn0.';\n s0 = size(dn0);\nend\nif s1 == [1 2]\n dn1 = dn1.';\n s1 = size(dn1);\nend\n\n% wrong format\nif s0(1) ~= 2 || s1(1) ~= 2\n error('DualQuaternion:Dmult:wrongsize',...\n '%d rows in the DN0 array and %d rows in the DN1 array. It should be 2 for both.',...\n s0(1),s1(1));\nend\n\n% sizes do not match\nn1 = s0(2);\nn2 = s1(2);\nif n1 ~= n2\n error('DualQuaternion:Dmult:wrongsize',...\n '%d dual numbers in DN0 array and %d dual numbers in DN1 array.They should be equal.',...\n n1,n2);\nend\n\ndn = sym(zeros(2,n1));\ndn(1,:) = dn0(1,:).*dn1(1,:);\ndn(2,:) = dn0(1,:).*dn1(2,:)+dn0(2,:).*dn1(1,:);", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/43393-dual-quaternion-symbolic-toolbox/Dual quaternion symbolic toolbox/private/dnmult.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7034917330106227}} {"text": "% Author:\n% - Mehrtash Harandi (mehrtash.harandi at gmail dot com)\n%\n% This file is provided without any warranty of\n% fitness for any purpose. You can redistribute\n% this file and/or modify it under the terms of\n% the GNU General Public License (GPL) as published\n% by the Free Software Foundation, either version 3\n% of the License or (at your option) any later version.\n\nfunction outStein = Compute_Stein_Metric(Set1,Set2)\n\n\nsimFlag = false;\nif (nargin < 2)\n Set2 = Set1;\n simFlag = true;\nend\n\nl1 = size(Set1,3);\nl2 = size(Set2,3);\noutStein = zeros(l2,l1);\n\nif (simFlag)\n for tmpC1 = 1:l1\n X = Set1(:,:,tmpC1);\n for tmpC2 = tmpC1+1:l2\n Y = Set2(:,:,tmpC2);\n outStein(tmpC2,tmpC1) = log(det(0.5*(X+Y))) - 0.5*(log(det(X*Y)));\n if (outStein(tmpC2,tmpC1) < 1e-10)\n outStein(tmpC2,tmpC1) = 0.0;\n end\n outStein(tmpC1,tmpC2) = outStein(tmpC2,tmpC1);\n end\n end\n \nelse\n for tmpC1 = 1:l1\n X = Set1(:,:,tmpC1);\n for tmpC2 = 1:l2\n Y = Set2(:,:,tmpC2);\n outStein(tmpC2,tmpC1) = log(det(0.5*(X+Y))) - 0.5*(log(det(X*Y)));\n if (outStein(tmpC2,tmpC1) < 1e-10)\n outStein(tmpC2,tmpC1) = 0.0;\n end\n end\n end\nend\n\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/SPD_DR_ECCV2014/Compute_Stein_Metric.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7034917237854226}} {"text": "function angout = npi2pi(angin,units,approach)\n\n %NPI2PI Truncates angles into the -180 deg to 180 deg range\n %\n %\n % ang = NPI2PI(angin) transforms input angles into the\n % -180 to 180 degree range.\n %\n % ang = NPI2PI(angin,'units') uses the units defined by the\n % input string 'units'. If omitted, default units of 'degrees'\n % are assumed.\n %\n % ang = NPI2PI(angin,'units','method') uses the method\n % defined by the corresponding input string. Valid methods are:\n % 'exact' for the exact transformation; 'inward' where all angles\n % are shifted epsilon towards the origin before the -180 to 180 degree\n % transformation; 'outward' where all angles are shifted epsilon\n % away from the origin before the -180 to 180 degree transformation.\n % If omitted, default method of 'exact' is assumed.\n %\n % See also ZERO22PI, ANGLEDIM\n\n % Copyright 1996-2000 Systems Planning and Analysis, Inc. and The MathWorks, 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 %report_this_filefun(mfilename('fullpath'));\n\n if nargin == 0\n error('Incorrect number of arguments')\n elseif nargin == 1\n units = []; approach = [];\n elseif nargin == 2\n approach = [];\n end\n\n % Empty argument tests\n\n if isempty(approach); approach = 'exact'; end\n if isempty(units); units = 'degrees'; end\n\n % Convert inputs to radians\n\n angin = angledim(angin,units,'radians');\n\n % Exact approach -- Eliminates the use of ATAN2 function.\n\n % Approximate approach -- Some inconsistencies with ATAN2 function\n % across platforms when an exact multiple of -pi is used. Some platforms\n % atan2(-1,0) = -pi, and for some platforms atan2(-1,0) = pi;\n\n switch lower(approach)\n case 'exact'\n\n % Exact approach is not straightforward because of this mapping behavior:\n % -3pi maps to -pi; -2pi maps to -pi; -pi maps to -pi;\n % pi maps to pi; 2pi maps to pi; 3pi maps to pi\n % Note that the mapping point changes when the sign on pi changes.\n\n angout = pi*((abs(angin)/pi) - ...\n 2*ceil(((abs(angin)/pi)-1)/2)) .* sign(angin);\n\n case 'inward'\n\n % Move data epsilon towards (inward) the origin. Eliminates any\n % points which start identically on a multiple of pi. Then\n % use the atan2 function.\n\n epsilon = epsm('radians');\n angin = angin*(1 - epsilon);\n angout = atan2(sin(angin),cos(angin));\n\n case 'outward'\n\n % Move data epsilon towards (away from) the origin. Eliminates any\n % points which start identically on a multiple of pi. Then\n % use the atan2 function.\n\n epsilon = epsm('radians');\n angin = angin * (1 + epsilon);\n angout = atan2(sin(angin),cos(angin));\n\n otherwise\n error('Unrecognized approach string')\n end\n\n angout = angledim(angout,'radians',units); % Convert to the original units\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/npi2pi.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7034917181165206}} {"text": "function quadrule_test105 ( )\n\n%*****************************************************************************80\n%\n%% TEST105 tests JACOBI_EK_COMPUTE and JACOBI_SS_COMPUTE.\n%\n% Discussion:\n%\n% Compare with tabular values on page 178 of Stroud and Secrest.\n%\n% In particular,\n%\n% X W\n%\n% 1 -0.9833999115 0.4615276287E-03\n% 2 -0.9447138932 0.2732249104E-02\n% 3 -0.8849310847 0.8045830455E-02\n% .. ............. ................\n% 19 0.9656375637 0.7613987785E-01\n% 20 0.9934477866 0.3348337670E-01\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license. \n%\n% Modified:\n%\n% 30 April 2011\n%\n% Author:\n%\n% John Burkardt\n%\n order = 20;\n\n a = -1.0;\n b = 1.0;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST105\\n' );\n fprintf ( 1, ' JACOBI_EK_COMPUTE sets up Gauss-Jacobi quadrature;\\n' );\n fprintf ( 1, ' JACOBI_SS_COMPUTE sets up Gauss-Jacobi quadrature;\\n' );\n fprintf ( 1, ' Here, we simply compute a single rule and\\n' );\n fprintf ( 1, ' print it, to check for accuracy.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The integration interval is [%f, %f]\\n', a, b );\n\n alpha = 1.5;\n beta = 0.5;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N = %d\\n', order );\n fprintf ( 1, ' ALPHA = %f\\n', alpha );\n fprintf ( 1, ' BETA = %f\\n', beta );\n\n [ x, w ] = jacobi_ek_compute ( order, alpha, beta );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' JACOBI_EK_COMPUTE:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I X(I) W(I)\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : order\n fprintf ( 1, ' %4d %14.8f %14.8f\\n', i, x(i), w(i) );\n end\n\n [ x, w ] = jacobi_ss_compute ( order, alpha, beta );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' JACOBI_SS_COMPUTE:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I X(I) W(I)\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : order\n fprintf ( 1, ' %4d %14.8f %14.8f\\n', i, x(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/quadrule/quadrule_test105.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.7034091768827558}} {"text": "function DEM_demo_contact_lens\n% This demo illustrates tracking under the contact lens problem:\n% The contact lens refers to the non-Gaussian uncertainty induced by\n% nonlinear measurements. Here it is illustrated in terms of tracking the\n% motion of a target in Cartesian coordinates, given the distance to target\n% (range) and direction as measurements. The problem is to accumulate\n% information over time about the target location under random fluctuations\n% on the velocity (technically this is a constant acceleration model).\n% Comparative evaluations are made with Extended Kalman filtering.\n%\n% See: X. Tian, Y. Bar-Shalom, Coordinate Conversion and Tracking for \n% Very Long Range Radars. IEEE Transactions on Aerospace and Electronic\n% Systems, AES-45(3):1073-1088, July 2009.\n%__________________________________________________________________________\n% Copyright (C) 2011 Wellcome Trust Centre for Neuroimaging\n \n% Karl Friston\n% $Id: DEM_demo_contact_lens.m 7679 2019-10-24 15:54:07Z spm $\n \n \n% non-linear generative model\n%==========================================================================\n \n% The problem: states = [x(1) x(2)]; causes = [v(1) v(2)]\n%--------------------------------------------------------------------------\nx = [1e4 1e4 -8 -2]'; % initial states: location = 10km, 10km\n % velocity = -8m/s, -2m/s\nV = [1e-2 4]; % observation precision (inverse variance) \n % standard deviation of range: 1/sqrt(V(1)) = 10m\n % standard deviation of angle: 1/sqrt(V(2)) = .5 mrad\ns = 1; % smoothness of fluctuations\nw = 8; % precision of fluctuations in motion\nW = [128 128 w w]; % standard deviation of velocity: 1/sqrt(w) = .3536 m/s^2\n \n% preliminaries\n%--------------------------------------------------------------------------\nN = 256; % length of sequence\nt = 1:N; % time (seconds)\nM(1).E.s = s; % smoothness of fluctuations\nM(1).E.n = 4; % order of generalised coordinates\nM(1).E.K = 128; % rate of generalized gradient descent\n \n% Level 1: Hidden states = [x(1) x(2) v(1) v(2)];\n%--------------------------------------------------------------------------\nf = '[x(3); x(4); 0; 0]';\ng = '[sqrt(x(1)^2 + x(2)^2); 1000*atan(x(2)/x(1))]';\nM(1).f = inline(f,'x','v','P');\nM(1).g = inline(g,'x','v','P');\nM(1).x = x;\nM(1).V = diag(V); % precision of observation noise\nM(1).W = diag(W); % precision of fluctuations on hidden states\n \n \n% create data\n%==========================================================================\nDEM = spm_DEM_generate(M,N);\n \n\n% Comparative inversions (variants of generalised filtering)\n%==========================================================================\n\n% reset initial position and bearing\n%--------------------------------------------------------------------------\nDEM.M(1).x = [1e3; 1e3; 0; 0];\n\n% DEM and EKF\n%--------------------------------------------------------------------------\nDEM = spm_DEM(DEM);\n[EKF S] = spm_ekf(DEM.M,DEM.Y);\n \nspm_figure('Getwin','DEM');\nspm_DEM_qU(DEM.qU,DEM.pU)\n \n \n% show prediction errors\n%==========================================================================\nspm_figure('GetWin','Figure 1');\n \nD(1,:) = sqrt(sum((DEM.pU.x{1}([1 2],:) - DEM.qU.x{1}([1 2],:)).^2));\nD(2,:) = sqrt(sum((DEM.pU.x{1}([1 2],:) - EKF([1 2],:)).^2));\nD(3,:) = sqrt(sum((DEM.pU.x{1}([3 4],:) - DEM.qU.x{1}([3 4],:)).^2));\nD(4,:) = sqrt(sum((DEM.pU.x{1}([3 4],:) - EKF([3 4],:)).^2));\n\nfor i = 1:N\n E = DEM.pU.x{1}(:,i) - DEM.qU.x{1}(:,i);\n NEES(1,i) = E'*spm_inv(DEM.qU.S{i})*E;\n E = DEM.pU.x{1}(:,i) - EKF(:,i);\n NEES(2,i) = E'*spm_inv(S{i})*E;\nend\n\n\n% plot errors\n%--------------------------------------------------------------------------\nsubplot(2,2,1)\nplot(t,log(D(1:2,:)))\ntitle('log(location error (m))','Fontsize',16)\nxlabel('time (secs)')\nylabel('log distance from target')\naxis square\nlegend('DEM','EKF')\n \nsubplot(2,2,2)\nplot(t,log(D(3:4,:)))\ntitle('log(speed error (m/s))','Fontsize',16)\nxlabel('time (secs)')\nylabel('log distance from target')\naxis square\nlegend('DEM','EKF')\n\n\n% plot trajectories\n%--------------------------------------------------------------------------\nsubplot(2,2,3)\nplot(DEM.pU.x{1}(1,:),DEM.pU.x{1}(2,:) ),hold on\nplot(DEM.qU.x{1}(1,:),DEM.qU.x{1}(2,:),'-.'),hold on\nplot(EKF(1,:),EKF(2,:),':'),hold off\ntitle('location (m)','Fontsize',16)\naxis([8 12 8 12]*1000)\nxlabel('x')\nylabel('y')\naxis square\nlegend('true','DEM','EKF')\n\n% plot NEES\n%--------------------------------------------------------------------------\nsubplot(2,2,4)\nplot(t,log(NEES))\ntitle('log(NEES)','Fontsize',16)\nxlabel('time (secs)')\naxis square\nlegend('DEM','EKF')\ndrawnow\n\n\nreturn\n\n% prediction errors as a function of K\n%==========================================================================\nK = -0:1/2:12;\nfor i = 1:length(K)\n \n % DEM and EKF (linear)\n %----------------------------------------------------------------------\n DEM.M(1).E.K = exp(K(i));\n DEM = spm_DEM(DEM);\n \n % mean square error\n %----------------------------------------------------------------------\n kse(i,1) = mean(mean((DEM.pU.x{1} - DEM.qU.x{1}).^2));\n \nend\n\n% show prediction errors\n%==========================================================================\nspm_DEM_qU(DEM.qU,DEM.pU)\n \n% plot trajectories\n%--------------------------------------------------------------------------\nsubplot(2,1,2)\nplot(K,log(kse))\ntitle('log(MSE)','Fontsize',16)\nxlabel('log(K)','Fontsize',12)\naxis square\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/DEM_demo_contact_lens.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.7034091742788504}} {"text": "% Factor analysis\n% Z -> X, Z in R^k, X in R^D, k << D (high dimensional observations explained by small source)\n% Z ~ N(0,I), X|Z ~ N(L z, Psi), where Psi is diagonal.\n%\n% We compare to Zoubin Ghahramani's code.\n\nstate = 0;\nrand('seed', state);\nrandn('seed', state);\nmax_iter = 3;\nk = 2;\nD = 4;\nN = 10;\nX = randn(N, D);\n\n% Initialize as in Zoubin's ffa (fast factor analysis)\nX=X-ones(N,1)*mean(X);\nXX=X'*X/N;\ndiagXX=diag(XX);\ncX=cov(X);\nscale=det(cX)^(1/D);\nrandn('seed', 0); % must reset seed here so initial params are identical to mfa\nL0=randn(D,k)*sqrt(scale/k);\nW0 = L0;\nPsi0=diag(cX);\n\n[L1, Psi1, LL1] = ffa(X,k,max_iter);\n\n\nns = [k D];\ndag = zeros(2,2);\ndag(1,2) = 1;\nbnet = mk_bnet(dag, ns, 'discrete', [], 'observed', 2);\nbnet.CPD{1} = gaussian_CPD(bnet, 1, 'mean', zeros(k,1), 'cov', eye(k), 'cov_type', 'diag', ...\n\t\t\t 'clamp_mean', 1, 'clamp_cov', 1);\nbnet.CPD{2} = gaussian_CPD(bnet, 2, 'mean', zeros(D,1), 'cov', diag(Psi0), 'weights', W0, ...\n\t\t\t 'cov_type', 'diag', 'cov_prior_weight', 0, 'clamp_mean', 1);\n\nengine = jtree_inf_engine(bnet);\nevidence = cell(2,N);\nevidence(2,:) = num2cell(X', 1);\n\n[bnet2, LL2] = learn_params_em(engine, evidence, max_iter);\n\ns = struct(bnet2.CPD{2});\nL2 = s.weights;\nPsi2 = s.cov;\n\n\n\n% Compare to Zoubin's code\nassert(approxeq(LL2, LL1));\nassert(approxeq(Psi2, diag(Psi1)));\nassert(approxeq(L2, L1));\n\n\n\n", "meta": {"author": "bayesnet", "repo": "bnt", "sha": "bebba5f437b4e1e29169f0f3669df59fb5392e62", "save_path": "github-repos/MATLAB/bayesnet-bnt", "path": "github-repos/MATLAB/bayesnet-bnt/bnt-bebba5f437b4e1e29169f0f3669df59fb5392e62/BNT/examples/static/fa1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7034091530070985}} {"text": "function [IdxParent, IdxChildren, Ms] = WaveTreeStructure2D(N, L);\n% WaveTreeStructure: parent/children relationships for coefficients \n% of 2-dimensional wavelet transfom\n% Invoked after W = @(x) midwt(x,wav);WT = @(x) mdwt(x,wav);\n% It finds the relations between the coefficient images obtained by Rice\n% wavelet toolbox\n%\n% USAGE: [IdxParent, IdxChildren]=WaveTreeStructure2D(C, S)\n%\n% INPUT: N: image with size of N x N, scaling/coefficients \n% after 2-d wavelet transform \"mdwt\"\n% L: denotes total decomposition levels\n% [See instruction of \"mdwt\" function for definition of C and L]\n%\n% OUTPUT: IdxParent: N^2 x 1, parent index. \n% IdxParent(i)=j means the parent of the ith coefficient is coefficient j \n%\n% IdxChildren: nChildren x (M-Ms(N)), children index. \n% IdxChildren(i,2:end)=[j(1),...,j(nChildren)] means the children of \n% the ith coefficient are coefficients j(1),...,j(nChildren). \n% Since coefficients at level L (finest level) do not have any children, \n% they are not stored. \n%\n% The order of coefficients in IdxParent and IdxChildren are the \n% same as the coefficient order in C(:)\n%\n% Ms: 1 x N, number of wavelet coefficients for each decomposition \n% level (scaling coeff. are excluded) \n\n%--------------------------------------------------------------------------\n% Junzhou Huang, CSE, University of Texas at Arlington, Feb, 2012\n%--------------------------------------------------------------------------\nfor i=1:L \n Ms(i,1)=3*(N/2^(L-i+1))^2;\nend\n%---------------------------------------------------------------------------%\n% INITIALIZATIONS\nIdxParent=zeros(N^2,1);\nIdxChildren=zeros(N^2/4,5); %Col 1: index i; col 2-5 the 4 children of index i\n\nIJ=zeros(N^2, 2);\n% col 1: R (row pointer)\n% col 2: C (column pointer)\n[Isub, Jsub]=ind2sub([N, N], [1:N^2]');\nIJ(:,1)=Isub;IJ(:,2)=Jsub;\n\n%%%% Parent %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nB=zeros(N, N); \nB(1:N/2^(L-1),1:N/2^(L-1)) = ones(N/2^(L-1), N/2^(L-1));\nindex0=find(B==1);\nIdxParent(index0)=0;\n\nindex=find(B==0);\n[Isub, Jsub]=ind2sub([N, N], index);\n\nindexPar=sub2ind([N, N], ceil(Isub/2), ceil(Jsub/2));\nIdxParent(index)=indexPar;\n\n%%%%%%%% child %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nB=zeros(N, N); \nB(1:N/2^(L-1),1:N/2^(L-1)) = ones(N/2^(L-1), N/2^(L-1));\nindex0=find(B==1);\n\nIdxChildren(1:length(index0), 1)=index0;\nIdxChildren(1:length(index0), 2:5)=0;\n\nB(N/2+1:N, :) = ones(N/2, N);\nB(:, N/2+1:N) = ones(N, N/2);\n\nindex=find(B==0);\n[Isub, Jsub]=ind2sub([N, N], index);\nindexChild4=sub2ind([N, N], Isub*2, Jsub*2);\nindexChild3=sub2ind([N, N], Isub*2, Jsub*2-1);\nindexChild2=sub2ind([N, N], Isub*2-1, Jsub*2);\nindexChild1=sub2ind([N, N], Isub*2-1, Jsub*2-1);\n\nIdxChildren(length(index0)+1:end,:)=[index, indexChild1, indexChild2, indexChild3, indexChild4];\nIdxChildren2=IdxChildren;\n[YY,II] = sort(IdxChildren(:,1));\n\nIdxChildren=zeros(size(IdxChildren));\nIdxChildren=IdxChildren2(II,:);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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_WaTMRI/WaveTreeStructure2D.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7033930171479564}} {"text": "function [A,B,C,D,E,F,G] = bay_rr(X,Y,gam,level,nb,eigvals,eigvec)\n% Bayesian inference of the cost on the three levels of linear ridge regression\n% \n% >> cost = bay_rr(X, Y, gam, level)\n% \n% This function implements the cost functions related to the\n% Bayesian framework of linear ridge Regression [29]. Optimizing\n% this criteria results in optimal model parameters W,b,\n% hyperparameters. The criterion can also be used for model\n% comparison. \n% \n% The obtained model parameters w and b are optimal on the first\n% level w.r.t J = 0.5*w'*w+gam*0.5*sum(Y-X*w-b).^2. \n% \n% Full syntax\n% \n% * OUTPUTS on the first level: Cost proportional to the posterior of the model parameters.\n% \n% >> [costL1, Ed, Ew] = bay_rr(X, Y, gam, 1)\n% \n% costL1: Cost proportional to the posterior\n% Ed(*) : Cost of the fitting error term\n% Ew(*) : Cost of the regularization parameter\n% \n% * OUTPUTS on the second level: Cost proportional to the posterior of gam.\n% \n% >> [costL2, DcostL2, Deff, mu, ksi, eigval, eigvec] = bay_rr(X, Y, gam, 2)\n% \n% costL2 : Cost proportional to the posterior on the second level\n% DcostL2(*): Derivative of the cost proportional to the posterior\n% Deff(*) : Effective number of parameters\n% mu(*) : Relative importance of the fitting error term\n% ksi(*) : Relative importance of the regularization parameter\n% eigval(*) : Eigenvalues of the covariance matrix\n% eigvec(*) : Eigenvectors of the covariance matrix\n% \n% * OUTPUTS on the third level: The following commands can be\n% used to compute the level 3 cost function for different\n% models (e.g. models with different selected sets of\n% inputs). The best model can then be chosen as the model with\n% best level 3 cost (CostL3). \n% \n% >> [costL3, gam_optimal] = bay_rr(X, Y, gam, 3)\n% \n% costL3 : Cost proportional to the posterior on the third inference level\n% gam_optimal(*) : Optimal regularization parameter obtained from optimizing the second level\n% \n% * INPUTS:\n% \n% >> cost = bay_rr(X, Y, gam, level)\n% \n% X N x d matrix with the inputs of the training data\n% Y N x 1 vector with the outputs of the training data\n% gam Regularization parameter\n% level 1, 2, 3\n% \n% See also:\n% ridgeregress,bay_lssvm\n\n% -dislaimer-\n\n \n if ~exist('fminunc'),\n error('This function needs the optimization function ''fminunc''.');\n end \n \n[N,d] = size(X);\n\nif (level==1 || level==2),\n [W,b] = ridgeregress(X,Y,gam);\n Ew = .5*W'*W; % Ew\n Ed = .5*sum((X*W+b-Y).^2); % Ed\n Ewgd = Ew+gam*Ed; % Ewgd\n A=Ewgd; C=Ed; B=Ew;\n \n if level==2,\n if nargin>=7,\n if numel(eigvals)>length(eigvals), v = diag(eigvals); else v=eigvals; end\n V = eigvec; \n else\n eval('[V,v] = eigs(X''*X+eye(d)*2,nb);','[V,v] = eig(X''*X+eye(d)*2);v=diag(v);');v=v-2;\n v = v*(N-1)/N;\n end\n Peff = find(v>1000*eps); Neff=length(Peff);\n v = v(Peff); V= V(:,Peff); \n vall = zeros(N-1,1);vall(1:Neff)=v;\n Deff = 1+sum(gam.*v./(1+gam.*v)); % Deff\n CostL2 = sum(log(vall+1./gam))+(N-1)*log(Ewgd); % CostL2\n DcostL2 = -sum(1./(gam+vall.*gam^2))+(N-1)*Ed/Ewgd; % DcostL2\n mu = 2*Ed/(N-Deff); ksi = mu*gam; % mu and ksi\n A=CostL2; B=DcostL2; C=Deff; D=mu; E=ksi;F=v;G=V;\n end \n \nelseif level==3,\n \n % check fminunc\n resp = which('fminunc');\n %disp(' ');\n if isempty(resp),\n error(' ''fminunc'' not available');\n end\n\n eval('nb;','nb=''blabla'';');\n opties=optimset('MaxFunEvals', 2000,'GradObj','on', 'DerivativeCheck', 'off', 'TolFun', .0001, 'TolX', .0001, 'Display','off' );\n [CostL2,DCostL2, Deff, mu,ksi,v, V] = bay_rr(X,Y,gam,2,nb);\n gam_opt = exp(fminunc(@costL2, log(gam), opties,X,Y,nb,v,V));\n [CostL2,DCostL2, Deff, mu,ksi,v, V] = bay_rr(X,Y,gam_opt,2,nb,v,V); \n CostL3 = .5*length(v)*log(mu)+(N-1)*log(ksi) - log(Deff-1)-log(N-Deff) - sum(log(mu+ksi*v));\n A = CostL3; B = gam_opt;\n\nelse\n error('level should be ''1'', ''2'' or ''3''.');\nend\n\n\n\n\nfunction [C,Dc] = costL2(log_gam,X,Y,nb,v,V)\n%\n[C,Dc] = bay_rr(X,Y,exp(log_gam),2,nb,v,V); \n", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v3.0/Algorithms/extract_resp_sig/feat_based_extraction/LSSVMlabv1_8_R2009b_R2011a/bay_rr.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.7033923441322897}} {"text": "function value = e_constant ( )\n\n%*****************************************************************************80\n%\n%% E_CONSTANT returns the value of E.\n%\n% Discussion:\n%\n% \"E\" was named in honor of Euler.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 September 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Output, real E_CONSTANT, the base of the natural\n% logarithm system.\n%\n value = 2.718281828459045;\n\n return\nend\n", "meta": {"author": "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/e_constant.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7033779454672274}} {"text": "function boundary = p02_boundary_nearest ( m, n, point )\n\n%*****************************************************************************80\n%\n%% P02_BOUNDARY_NEAREST returns a nearest boundary point in problem 02.\n%\n% Discussion:\n%\n% The given input point need not be inside the region.\n%\n% In some cases, more than one boundary point may be \"nearest\",\n% but only one will be returned.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 April 2009\n%\n% Author:\n%\n% John Burkardt\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 M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, real POINT(M,N), the coordinates \n% of the points.\n%\n% Output, real BOUNDARY(M,N), points on the boundary\n% that are nearest to each point.\n%\n center = [ 0.0, 0.0 ];\n r1 = 1.0;\n r2 = 0.4;\n\n for j = 1 : n\n\n if ( point(1:2,j) == center(1:2)' )\n\n boundary(1,j) = r2;\n boundary(2,j) = center(2);\n\n else\n\n r = sqrt ( ( point(1,j) - center(1) ).^2 ...\n + ( point(2,j) - center(2) ).^2 );\n\n if ( r1 - r < r - r2 )\n boundary(1,j) = center(1) + r1 * ( point(1,j) - center(1) ) / r;\n boundary(2,j) = center(2) + r1 * ( point(2,j) - center(2) ) / r;\n else\n boundary(1,j) = center(1) + r2 * ( point(1,j) - center(1) ) / r;\n boundary(2,j) = center(2) + r2 * ( point(2,j) - center(2) ) / r;\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/test_triangulation/p02_boundary_nearest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.837619961306541, "lm_q1q2_score": 0.7033779402284971}} {"text": "%% hex8_hex20\n% Below is a demonstration of the features of the |hex8_hex20| function\n\n%% Syntax\n% |[E_HEX20,V_HEX20,V_HEX20_cell,Fb_HEX20,Fb_HEX20_QUAD8]=hex8_hex20(E_HEX8,V_HEX8,V_HEX8_cell,Fb_HEX8);|\n\n%% Description\n% The |hex8_hex20| converts 4-node tetrahedral elements to 10-node\n% tetrahedral elements. \n\n%% Examples\n\n%%\nclear; close all; clc;\n\n% Plot settings\nfontSize=15;\nfaceAlpha=0.5;\nedgeColor='k';\nedgeWidth1=2;\nedgeWidth2=1;\nmarkerSize1=75;\nmarkerSize2=10;\n\n%% CONVERSION FROM HEX8 TO HEX20, EXAMPLE FOR A SINGLE HEXAHEDRON\n% Creating a single 4-node HEXAHEDRON\n[V8,~]=platonic_solid(2,1); %q indicates solid type, r is the radius\nHEX8=[1:8];\n[F8,~]=element2patch(HEX8,[],'hex8');\n\n%%\n% Converting to a single 10-node HEXAHEDRON\n[HEX20,V20,~]=hex8_hex20(HEX8,V8,{});\n[F20,~]=element2patch(HEX20,[],'hex20');\n\n%%\n% Plotting elements\ncFigure;\nsubplot(1,2,1); hold on;\ntitle('A linear HEXAHEDRON','FontSize',fontSize);\n\nhp=gpatch(F8,V8,'gw','k',faceAlpha);\nhp.Marker='.';\nhp.MarkerSize=markerSize1;\n\npatchNormPlot(F8,V8,0.75); %Plotting face normals\n\nfor q=1:1:size(HEX8,2)\n text(V8(HEX8(1,q),1),V8(HEX8(1,q),2),V8(HEX8(1,q),3),[' ',num2str(q)],'FontSize',fontSize*2,'color','b');\nend\n\naxisGeom(gca,fontSize);\naxis off;\ncamlight('headlight'); lighting flat;\n\nsubplot(1,2,2); hold on;\ntitle('A quadratic HEXAHEDRON','FontSize',fontSize);\n\nhp=gpatch(F20,V20,'rw','k',faceAlpha);\nhp.Marker='.';\nhp.MarkerSize=markerSize1;\npatchNormPlot(F20,V20,0.75); %Plotting face normals\n\nfor q=1:1:size(HEX20,2)\n text(V20(HEX20(1,q),1),V20(HEX20(1,q),2),V20(HEX20(1,q),3),[' ',num2str(q)],'FontSize',fontSize*2,'color','b');\nend\n\naxisGeom(gca,fontSize);\naxis off;\ncamlight('headlight'); lighting flat;\n\ndrawnow; \n\n%% CONVERSION FROM HEX8 TO HEX20, EXAMPLE FOR A HEXAHEDRON MESH WITH NODAL PARAMETERS\nn=3;\nfor q=1:1:n\n [HEX8,V8]=subHex(HEX8,V8,1);\nend\n\n[F8,~]=element2patch(HEX8,[],'hex8');\n\n%Create nodal result e.g. displacement and color\nV4d=V8;\nV4d(:,1)=V4d(:,1)+0.5.*sin(pi*V4d(:,3));\nV4d(:,2)=V4d(:,2)+0.5.*cos(pi*V4d(:,3));\nD4=V4d-V8;\n\nC4=V8(:,1); %Color towards X\n\n%%\n% Converting to a single 10-node HEXAHEDRON\nHEX8_cell={D4,C4};\n[HEX20,V20,HEX20_cell]=hex8_hex20(HEX8,V8,HEX8_cell);\n[F20,~]=element2patch(HEX20,[],'hex20');\nD10=HEX20_cell{1};\nC10=HEX20_cell{2};\nV10d=V20+D10;\n\n%%\n% Plotting elements\nhf=cFigure; % Open figure for plotting\nsubplot(2,2,1); hold on;\ntitle('A linear HEXAHEDRON mesh','FontSize',fontSize);\n\nhp=gpatch(F8,V8,'gw','k',faceAlpha);\nhp.Marker='.';\nhp.MarkerSize=markerSize2;\n\naxisGeom(gca,fontSize); axis off;\nview([-50,12])\ncamlight('headlight'); lighting flat;\n\nsubplot(2,2,3); hold on;\ntitle('Data on linear HEXAHEDRON mesh','FontSize',fontSize);\n\nhp=gpatch(F8,V4d,C4,'k',faceAlpha);\nhp.Marker='.';\nhp.MarkerSize=markerSize2;\n\naxisGeom(gca,fontSize); axis off;\nview([-50,12])\ncamlight('headlight'); lighting flat;\n\nsubplot(2,2,2); hold on;\ntitle('A quadratic HEXAHEDRON mesh','FontSize',fontSize);\n\nhp=gpatch(F20,V20,'rw','k',faceAlpha);\nhp.Marker='.';\nhp.MarkerSize=markerSize2;\n\naxisGeom(gca,fontSize); axis off;\nview([-50,12])\ncamlight('headlight'); lighting flat;\n\nsubplot(2,2,4); hold on;\ntitle('Mapped data on quadratic HEXAHEDRON mesh','FontSize',fontSize);\n\nhp=gpatch(F20,V10d,C10,'k',faceAlpha);\nhp.Marker='.';\nhp.MarkerSize=markerSize2;\n\naxisGeom(gca,fontSize); axis off;\nview([-50,12])\ncamlight('headlight'); lighting flat;\n\ndrawnow; \n\n%% CONVERSION FROM HEX8 TO HEX20, EXAMPLE FOR KEEPING TRACK OF BOUNDARY FACES\n\n[F8,~]=element2patch(HEX8,[],'hex8');\n[indBoundary]=tesBoundary(F8);\nFb4=F8(indBoundary,:);\n\n[HEX20,V20,HEX20_cell,Fb10]=hex8_hex20(HEX8,V8,{},Fb4);\n[F20,~]=element2patch(HEX20,[],'hex20');\n\n% [indBoundary]=tesBoundary(F20,V20);\n% Fb20=F20(indBoundary,:);\n\n%%\n% \n\nhf=cFigure; % Open figure for plotting\nsubplot(1,2,1); hold on;\ntitle('A linear HEXAHEDRON mesh','FontSize',fontSize);\n\ngpatch(F8,V8,'gw','k',faceAlpha);\n\ngpatch(Fb4,V8,'rw','k',faceAlpha);\naxisGeom(gca,fontSize); axis off;\ncamlight('headlight'); lighting flat;\n\nsubplot(1,2,2); hold on;\ntitle('A quadratic HEXAHEDRON mesh','FontSize',fontSize);\n\nhp=gpatch(Fb10,V20,'rw','k',faceAlpha);\nhp.Marker='.';\nhp.MarkerSize=markerSize2;\n\naxisGeom(gca,fontSize); axis off;\ncamlight('headlight'); lighting flat;\n\ndrawnow;\n\n%% \n%\n% <>\n% \n% _*GIBBON*_ \n% \n% \n% _Kevin Mattheus Moerman_, \n \n%% \n% _*GIBBON footer text*_ \n% \n% License: \n% \n% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for\n% image segmentation, image-based modeling, meshing, and finite element\n% analysis.\n% \n% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors\n% \n% This program is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with this program. If not, see .\n", "meta": {"author": "gibbonCode", "repo": "GIBBON", "sha": "8178520664a6148db939eaea87e75b3cba4f2b4f", "save_path": "github-repos/MATLAB/gibbonCode-GIBBON", "path": "github-repos/MATLAB/gibbonCode-GIBBON/GIBBON-8178520664a6148db939eaea87e75b3cba4f2b4f/docs/HELP_hex8_hex20.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7033779369354247}} {"text": "function T_new = ExplicitScheme(T_old,alpha,dx,dy,dt,x_intervals,y_intervals)\n\nT_new = T_old;\n\nfor x_index = 2:1:(x_intervals-1)\n for y_index = 2:1:(y_intervals-1)\n\n T_new(x_index,y_index) = T_old(x_index,y_index) + (alpha*dt)*((T_old(x_index+1,y_index) - 2*T_old(x_index,y_index)+ T_old(x_index-1,y_index))/dx^2 + (T_old(x_index,y_index+1) - 2*T_old(x_index,y_index)+ T_old(x_index,y_index-1))/dy^2); \n \n end\nend\n\nend", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/41696-2d-transient-heat-conduction/ExplicitScheme.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9621075777163567, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.7033570038919386}} {"text": "%% Sharp Color Keys\n%\n%% \n% In this section we discuss color keys that are particular useful when\n% analyzing data with very small deviation in orientation. Let us consider\n% the following calcite data set\n\n% plotting conventions\nplotx2east, plotb2east\nmtexdata sharp\n\nebsd = ebsd('calcite');\n\nipfKey = ipfColorKey(ebsd);\n\nclose all;\nplot(ebsd,ipfKey.orientation2color(ebsd.orientations))\n\n%%\n% and have a look into the 100 inverse pole figure.\n\n% compute the positions in the inverse pole figure\nh = ebsd.orientations .\\ vector3d.X;\nh = project2FundamentalRegion(h);\n\n% compute the azimuth angle in degree\ncolor = h.rho ./ degree;\n\nplotIPDF(ebsd.orientations,vector3d.X,'property',color,'MarkerSize',3,'grid')\nmtexColorbar\n\n%%\n% We see that all individual orientations are clustered around azimuth\n% angle 115 degrees with some outliers at 65 degree. In order to\n% increase the contrast for the main group, we restrict the color range from\n% 110 degree to 120 degree.\n\ncaxis([110 120]);\n\n% by the following lines we colorcode the outliers in purple.\ncmap = colormap;\ncmap(end,:) = [1 0 1]; % make last color purple\ncmap(1,:) = [1 0 1]; % make first color purple\ncolormap(cmap)\n\n%%\n% The same colorcoding we can now apply to the EBSD map.\n\n% plot the data with the customized color\nplot(ebsd,color)\n\n% set scaling of the angles to 110 - 120 degree\ncaxis([110 120]);\n\n% colorize outliers in purple.\ncmap = colormap;\ncmap(end,:) = [1 0 1];\ncmap(1,:) = [1 0 1];\ncolormap(cmap)\n\n%% Sharpening the default colorcoding\n% Next, we want to apply the same ideas as above to the default MTEX color\n% key, i.e. we want to stretch the colors such that they cover just the\n% orientations of interest.\n\nipfKey = ipfHSVKey(ebsd.CS.properGroup);\n\n% To this end, we first compute the inverse pole figure direction such that\n% the mean orientation is just at the gray spot of the inverse pole figure\nipfKey.inversePoleFigureDirection = mean(ebsd.orientations,'robust') * ipfKey.whiteCenter;\n\nclose all;\nplot(ebsd,ipfKey.orientation2color(ebsd.orientations))\n\n%% \n% We observe that the orientation map is almost completely gray, except for\n% the outliers which appears black. Next, we use the option |maxAngle| to\n% increase contrast in the grayish part\n\nipfKey.maxAngle = 7.5*degree;\nplot(ebsd,ipfKey.orientation2color(ebsd.orientations))\n\n%%\n% You may play around with the option |maxAngle| to obtain better\n% results. As for interpretation keep in mind that white color represents\n% the mean orientation and the color becomes more saturated and later dark\n% as the orientation to color diverges from the mean orientation.\n%\n% Let's have a look at the corresponding color map.\n\nplot(ipfKey,'resolution',0.25*degree)\n\n% plot orientations into the color key\nhold on\nplotIPDF(ebsd.orientations,'points',10,'MarkerSize',1,'MarkerFaceColor','w','MarkerEdgeColor','w')\nhold off\n%%\n% observe how in the inverse pole figure the orientations are scattered\n% closely around the white center. Together with the fact that the\n% transition from white to color is quite rapidly, this gives a high\n% contrast.\n\n\n%% The axis angle color key\n% \n\n[grains,ebsd.grainId] = calcGrains(ebsd,'angle',1.5*degree);\nebsd(grains(grains.grainSize<=3)) = [];\n[grains,ebsd.grainId] = calcGrains(ebsd,'angle',1.5*degree);\n\ngrains = smooth(grains,5);\n\n%%\n\nipfKey = axisAngleColorKey(ebsd('indexed'));\n\n% use for the reference orientation the grain mean orientation\nipfKey.oriRef = grains.meanOrientation(ebsd.grainId);\n\nplot(ebsd,ipfKey.orientation2color(ebsd.orientations))\n\nhold on\nplot(grains.boundary,'lineWidth',4)\nhold off\n\n%%\n\nF = halfQuadraticFilter;\n\nebsdS = smooth(ebsd,F,'fill',grains);\n\n% use for the reference orientation the grain mean orientation\nipfKey.oriRef = grains.meanOrientation(ebsdS('indexed').grainId);\n\nplot(ebsdS('indexed'),ipfKey.orientation2color(ebsdS('indexed').orientations))\n\nhold on\nplot(grains.boundary,'lineWidth',4)\nhold off\n\n%%\n\nF = infimalConvolutionFilter;\nF.lambda = 0.01;\nF.mu = 0.02;\n\nebsdS = smooth(ebsd,F);\n\n[grains,ebsdS.grainId] = calcGrains(ebsdS,'angle',1*degree);\n%ebsdS(grains(grains.grainSize<=3)) = [];\n%[grains,ebsdS.grainId] = calcGrains(ebsdS,'angle',1.5*degree);\n\ngrains = smooth(grains,5);\n\n\n% use for the reference orientation the grain mean orientation\nipfKey.oriRef = grains(ebsdS('indexed').grainId).meanOrientation;\n%ipfKey.oriRef = mean(ebsdS('indexed').orientations);\n\nplot(ebsdS('indexed'),ipfKey.orientation2color(ebsdS('indexed').orientations),'micronbar','off')\n\nhold on\nplot(grains.boundary,'lineWidth',4)\nhold off\n\n\n%% \n% Another example is when analyzing the orientation distribution within\n% grains\n\nmtexdata forsterite\nebsd = ebsd('indexed');\n\n% segment grains\n[grains,ebsd.grainId] = calcGrains(ebsd);\n\n% find largest grains\nlargeGrains = grains(grains.grainSize > 800)\n\nebsd = ebsd(largeGrains(1))\n\n%%\n% When plotting one specific grain with its orientations we see that they\n% all are very similar and, hence, get the same color\n\n% plot a grain \nclose all\nplot(largeGrains(1).boundary,'linewidth',2)\nhold on\nplot(ebsd,ebsd.orientations)\nhold off\n\n%%\n% when applying the option sharp MTEX colors the mean orientation as white\n% and scales the maximum saturation to fit the maximum misorientation\n% angle. This way deviations of the orientation within one grain can be\n% visualized. \n\n% plot a grain \nplot(largeGrains(1).boundary,'linewidth',2)\nhold on\nipfKey = ipfHSVKey(ebsd);\nipfKey.inversePoleFigureDirection = mean(ebsd.orientations) * ipfKey.whiteCenter;\nipfKey.maxAngle = 2*degree;\nplot(ebsd,ipfKey.orientation2color(ebsd.orientations))\nhold off\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/EBSDAnalysis/EBSDSharpPlot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8354835432479663, "lm_q1q2_score": 0.7033314745627528}} {"text": "function [p, s, df] = myStatTest(x1, x2, type)\n% [p, s, df] = myStatTest(X1, X2, 'test') \n% Statistical test of two samples- gives the confidence level for\n% different tests of the two samples X1 and X2.\n%\n% 'test' Null hypothesis Assumption on distributions Type\n% -----------------------------------------------------------------\n% 't' Means are equal The variances are equal t-test\n% 'u' Means are equal The variances are not equal t-test\n% 'p' Means are equal The data are paired t-test\n% 'f' Variances are equal F-test\n% 'r' Pearson Correlation Z-test\n% \n% TEST(X1, X2) performs a t-test (for equal variances) by default.\n%\n% [P S] = TEST(X1, X2, ['test']) returns the confidence level in P\n% and the value of the statistic (t or F) in S.\n%\n% Ref: Press et al. 1992. Numerical recipes in C. 14.2, Cambridge.\n%\nif (nargin == 2)\n type = 't' ;\nend\nnanInds1 = isnan(x1);\nnanInds2 = isnan(x2);\n \nif (type == 't')\n [p s df] = ttest(x1(~nanInds1), x2(~nanInds2)) ;\nelseif (type == 'u')\n [p s df] = uttest(x1(~nanInds1), x2(~nanInds2)) ;\nelseif (type == 'p')\n nanIndsBoth = nanInds1|nanInds2;\n [p s df] = pttest(x1(~nanIndsBoth), x2(~nanIndsBoth)) ;\nelseif (type == 'f')\n [p s] = ftest(x1(~nanInds1), x2(~nanInds2)) ;\nelseif (type == 'r')\n sz = max([size(x1);size(x2)]);\n for(k=1:sz(1))\n nanIndsBoth(k,:) = nanInds1(k,:)|nanInds2(k,:);\n end\n n = sum(~nanIndsBoth,1);\n df = n-2;\n if(sz(1)>1&&sz(2)>1)\n % vectorized version- assumes that x1 is Nx1 and x2 is NxM. Returns the\n % 1xM correlation coefficients.\n mn = mean(x1,1);\n sd = std(x1,0,1);\n Z1 = (x1-repmat(mn, [sz(1) 1])) ./ repmat(sd, [sz(1) 1]);\n mn = mean(x2,1);\n sd = std(x2,0,1);\n Z2 = (x2-repmat(mn, [sz(1) 1])) ./ repmat(sd, [sz(1) 1]);\n s = 0;\n for(k=1:sz(1))\n s = s + Z1(k,:).*Z2(k,:);\n end\n s = s./n;\n fZ = 0.5*(log((1+s)./(1-s)));\n p = erfc((abs(fZ).*sqrt(df))./sqrt(2));\n else\n % just use matlab's built-in\n [pearson,p] = corrcoef(x1(~nanIndsBoth), x2(~nanIndsBoth));\n s = pearson(1,2);\n p = p(1,2);\n % t = s/sqrt((1-s^2)/df);\n % p = betainc( df / (df + t*t), df/2, 0.5);\n % Fischer's z' method (slightly less conservative):\n %z = 0.5*(log((1+s)/(1-s)));\n %df = length(x1)-3;\n %p = erfc((abs(z)*sqrt(df))/sqrt(2));\n end\nelseif(type=='k')\n % Kendall's tau\n % This is essentially a vectorized, simplfied version of the\n % implementation in Matlab's 'corr' function.\n sz = max([size(x1);size(x2)]);\n for(k=1:sz(1))\n nanIndsBoth(k,:) = nanInds1(k,:)|nanInds2(k,:);\n end\n n = sum(~nanIndsBoth,1);\n n2const = n.*(n-1)./2;\n [x1Rank,x1Adj] = tiedrank(x1,1);\n [x2Rank,x2Adj] = tiedrank(x2,1);\n K = zeros(1,sz(2));\n for(k=1:sz(1)-1)\n sgn1 = sign(repmat(x1(k,:),sz(1)-k,1)-x1(k+1:sz(1),:));\n % Zero-out Nans to effectively ignore these data points (the\n % missing values are accounted for in the DF)\n sgn1(isnan(sgn1)) = 0;\n sgn2 = sign(repmat(x2(k,:),sz(1)-k,1)-x2(k+1:sz(1),:));\n sgn2(isnan(sgn2)) = 0;\n for(j=1:size(sgn1,1))\n K = K + sgn1(j,:).*sgn2(j,:);\n end\n end\n %for(k=1:sz(1)-1)\n % tmp = sum(sign(repmat(x1(k,:),sz(1)-k,1)-x1(k+1:sz(1),:)).*sign(repmat(x2(k,:),sz(1)-k,1)-x2(k+1:sz(1),:)),1);\n % tmp(nanIndsBoth(k,:)) = 0;\n % K = K + tmp;\n %end\n s = K ./ sqrt((n2const - x1Adj(1,:)).*(n2const - x2Adj(1,:)));\n ties = ((x1Adj(1,:)>0) | (x2Adj(1,:)>0));\n % Following p-value calc is probably only valid for n>=10\n df = n-2;\n nfact = factorial(n);\n stdK = n2const.*(2.*n+5)./9;\n if(any(ties))\n stdK = stdK - (x1Adj(3,:) + x2Adj(3,:))./18 + x1Adj(2,:).*x2Adj(2,:)./(18.*n2const.*(n-2)) + x1Adj(1,:).*x2Adj(1,:)./n2const;\n end\n stdK = sqrt(stdK);\n tail = 'b';\n switch tail\n case 'b' % 'both or 'ne'\n p = normcdf(-(abs(K)-1) ./ stdK);\n p = min(2*p, 1); % Don't count continuity correction at center twice\n case 'r' % 'right' or 'gt'\n p = normcdf(-(K-1) ./ stdK);\n case 'l' % 'left' or 'lt'\n p = normcdf((K+1) ./ stdK);\n end\nend\nreturn;\n\n\n\nfunction [p, t, df] = uttest(d1, d2)\n%UTTEST Student's t-test for unequal variances.\n% UTTEST(X1, X2) gives the probability that Student's t\n% calculated on data X1 and X2, sampled from distributions\n% with different variances, is higher than observed, i.e.\n% the \"significance\" level. This is used to test whether\n% two sample have significantly different means.\n% [P, T] = UTTEST(X1, X2) gives this probability P and the\n% value of Student's t in T. The smaller P is, the more\n% significant the difference between the means.\n% E.g. if P = 0.05 or 0.01, it is very likely that the\n% two sets are sampled from distributions with different\n% means.\n%\n% This works if the samples are drawn from distributions with\n% DIFFERENT VARIANCE. Otherwise, use TTEST.\n%\n%See also: TTEST, PTTEST.\n[l1 c1] = size(d1) ;\nn1 = l1 * c1 ;\nx1 = reshape(d1, l1 * c1, 1) ;\n[l2 c2] = size(d2) ;\nn2 = l2 * c2 ;\nx2 = reshape(d2, l2 * c2, 1) ;\n[a1 v1] = avevar(x1) ;\n[a2 v2] = avevar(x2) ;\ndf = (v1 / n1 + v2 / n2) * (v1 / n1 + v2 / n2) / ...\n ( (v1 / n1) * (v1 / n1) / (n1 - 1) + (v2 / n2) * (v2 / n2) / (n2 -1) ) ;\nt = (a1 - a2) / sqrt( v1 / n1 + v2 / n2 ) ;\np = betainc( df / (df + t*t), df/2, 0.5) ;\nreturn;\n\n\nfunction [p, t, df] = pttest(d1, d2)\n%PTTEST Student's paired t-test.\n% PTTEST(X1, X2) gives the probability that Student's t\n% calculated on paired data X1 and X2 is higher than\n% observed, i.e. the \"significance\" level. This is used\n% to test whether two paired samples have significantly\n% different means.\n% [P, T] = PTTEST(X1, X2) gives this probability P and the\n% value of Student's t in T. The smaller P is, the more\n% significant the difference between the means.\n% E.g. if P = 0.05 or 0.01, it is very likely that the\n% two sets are sampled from distributions with different\n% means.\n%\n% This works for PAIRED SAMPLES, i.e. when elements of X1\n% and X2 correspond one-on-one somehow.\n% E.g. residuals of two models on the same data.\n%\n%See also: TTEST, UTTEST.\n[l1 c1] = size(d1) ;\nn1 = l1 * c1 ;\nx1 = reshape(d1, l1 * c1, 1) ;\n[l2 c2] = size(d2) ;\nn2 = l2 * c2 ;\nif (n1 ~= n2)\n error('PTTEST: paired samples must have the same number of elements !')\nend\nx2 = reshape(d2, l2 * c2, 1) ;\n[a1 v1] = avevar(x1) ;\n[a2 v2] = avevar(x2) ;\ndf = n1 - 1 ;\ncab = (x1 - a1)' * (x2 - a2) / (n1 - 1) ;\nif (a1 ~= a2)\n % use abs to avoid numerical errors for very similar data\n % for which v1+v2-2cab may be close to 0.\n t = (a1 - a2) / sqrt(abs(v1 + v2 - 2 * cab) / n1) ;\n p = betainc( df / (df + t*t), df/2, 0.5) ;\nelse\n t = 0 ;\n p = 1 ;\nend\nreturn;\n\n\nfunction [p, t, df] = ttest(d1, d2)\n%TTEST Student's t-test for equal variances.\n% TTEST(X1, X2) gives the probability that Student's t\n% calculated on data X1 and X2, sampled from distributions\n% with the same variance, is higher than observed, i.e.\n% the \"significance\" level. This is used to test whether\n% two sample have significantly different means.\n% [P, T] = TTEST(X1, X2) gives this probability P and the\n% value of Student's t in T. The smaller P is, the more\n% significant the difference between the means.\n% E.g. if P = 0.05 or 0.01, it is very likely that the\n% two sets are sampled from distributions with different\n% means.\n%\n% This works if the samples are drawn from distributions with\n% the SAME VARIANCE. Otherwise, use UTTEST.\n%\n%See also: UTTEST, PTTEST.\n[l1 c1] = size(d1) ;\nn1 = l1 * c1 ;\nx1 = reshape(d1, l1 * c1, 1) ;\n[l2 c2] = size(d2) ;\nn2 = l2 * c2 ;\nx2 = reshape(d2, l2 * c2, 1) ;\n[a1 v1] = avevar(x1) ;\n[a2 v2] = avevar(x2) ;\ndf = n1 + n2 - 2 ;\npvar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df ;\nt = (a1 - a2) / sqrt( pvar * (1/n1 + 1/n2)) ;\np = betainc( df / (df + t*t), df/2, 0.5) ;\nreturn;\n\n\nfunction [xbar, varx] = avevar(v)\n%AVEVAR average and variance of sample.\n% AVEVAR(X) gives the average of the sample in X.\n% X is a vector of values.\n% [A, V] = AVEVAR(X) returns the average of X in A,\n% and the variance in V. The variance is corrected\n% using the two-pass formula.\n%\n% Ref: [1] Chan, Golub and LeVeque. 1983. American\n% Statistician, vol. 37, pp. 242--247.\n% [2] Press et al. 1992. Numerical recipes in C.\n% Cambridge university press.\n[n l] = size(v) ;\nx = reshape(v, n*l, 1) ;\nxbar = sum(x) / n / l ;\nd = x - xbar ;\nvarx = ( sum(d .* d) - sum(d) * sum(d) / n / l) / (n * l - 1) ;\nreturn;\n\n\nfunction [p, f, df] = ftest(d1, d2)\n%FTEST F-test for two samples.\n% FTEST(X1, X2) gives the probability that the F value\n% calculated as the rati of the variances of the two samples is\n% greater than observed, i.e. the significance level.\n% [P, F] = FTEST(X1, X2) gives the probability P and returns\n% the value of F.\n%\n% A small value of P would lead to reject the hypothesis that\n% both data sets are sampled from distributions with the same\n% variances.\n%\n%See also : TTEST, TEST.\n[l1 c1] = size(d1) ;\nn1 = l1 * c1 ;\nx1 = reshape(d1, l1 * c1, 1) ;\n[l2 c2] = size(d2) ;\nn2 = l2 * c2 ;\nx2 = reshape(d2, l2 * c2, 1) ;\n[a1 v1] = avevar(x1) ;\n[a2 v2] = avevar(x2) ;\nf = v1 / v2 ;\ndf1 = n1 - 1 ;\ndf2 = n2 - 1 ;\nif (v1 > v2)\n p = 2 * betainc( df2 / (df2 + df1 * f), df2 / 2, df1 / 2) ;\nelse\n f = 1 / f ;\n p = 2 * betainc( df1 / (df1 + df2 * f), df1 / 2, df2 / 2) ;\nend\nif (p > 1)\n p = 2 - p ;\nend \n\ndf = [df1,df2];\nreturn;\n", "meta": {"author": "vistalab", "repo": "vistasoft", "sha": "7f0102c696c091c858233340cc7e1ab02f064d4c", "save_path": "github-repos/MATLAB/vistalab-vistasoft", "path": "github-repos/MATLAB/vistalab-vistasoft/vistasoft-7f0102c696c091c858233340cc7e1ab02f064d4c/mrTest/diffusion/core/myStatTest.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7033123869439574}} {"text": "function int = MITGaussLaguerre( norder, alpha )\n\n%% LAGUERRE_COM computes the abscissa and weights for Gauss-Laguerre\n%quadrature.\n%\n% Discussion:\n%\n% In the simplest case, ALPHA is 0, and we are approximating the\n% integral from 0 to INFINITY of EXP(-X) * F(X). When this is so,\n% it is easy to modify the rule to approximate the integral from\n% A to INFINITY as well.\n%\n% If ALPHA is nonzero, then there is no simple way to extend the\n% rule to approximate the integral from A to INFINITY. The simplest\n% procedures would be to approximate the integral from 0 to A.\n%\n% The integration interval is [ A, +Infinity ) or [ 0, +Infinity ).\n%\n% The weight function w(x) = EXP ( - X ) or EXP ( - X ) * X**ALPHA.\n%\n% The integral to approximate:\n%\n% Integral ( A <= X < +INFINITY ) EXP ( - X ) * F(X) dX\n% or\n% Integral ( 0 <= X < +INFINITY ) EXP ( - X ) * X**ALPHA * F(X) dX\n%\n% The quadrature rule:\n%\n% EXP ( - A ) * Sum ( 1 <= I <= NORDER ) WEIGHT(I) * F ( A+XTAB(I) )\n% or\n% Sum ( 1 <= I <= NORDER ) WEIGHT(I) * F ( XTAB(I) )\n%\n% Modified:\n%\n% 12 October 2005\n%\n% Reference:\n%\n% Arthur Stroud and Don Secrest,\n% Gaussian Quadrature Formulas,\n% Prentice Hall, 1966.\n%\n% Parameters:\n%\n% Input, integer NORDER, the order of the quadrature rule to be\n% computed.\n% NORDER must be at least 1.\n%\n% Input, real ALPHA, the exponent of the X factor.\n% Set ALPHA = 0.0 for the simplest rule.\n% ALPHA must be nonnegative.\n%\n% Output, real XTAB(NORDER), the Gauss-Laguerre abscissas.\n%\n% Output, real WEIGHT(NORDER), the Gauss-Laguerre weights.\n%\n\n%\n% Set the recursion coefficients.\n%\n for i = 1 : norder\n b(i) = ( alpha + 2 * i - 1 );\n end\n\n for i = 1 : norder\n c(i) = ( i - 1 ) * ( alpha + i - 1 );\n end\n\n cc = gamma ( alpha + 1.0 ) * prod ( c(2:norder) );\n int.x = zeros(norder,1);\n int.w = int.x;\n int.n =norder;\n for i = 1 : norder\n%\n% Compute an estimate for the root.\n%\n if ( i == 1 )\n\n x = ( 1.0 + alpha ) * ( 3.0+ 0.92 * alpha ) ...\n / ( 1.0 + 2.4 * norder + 1.8 * alpha );\n\n elseif ( i == 2 )\n\n x = x + ( 15.0 + 6.25 * alpha ) ...\n / ( 1.0 + 0.9 * alpha + 2.5 * norder );\n\n else\n\n r1 = ( 1.0 + 2.55 * ( i - 2 ) ) / ( 1.9 * ( i - 2 ) );\n\n r2 = 1.26 * ( i - 2 ) * alpha / ( 1.0 + 3.5 * ( i - 2 ) );\n\n ratio = ( r1 + r2 ) / ( 1.0 + 0.3 * alpha );\n\n x = x + ratio * ( x - xtab(i-2) );\n\n end\n%\n% Use iteration to find the root.\n%\n [ x, dp2, p1 ] = laguerre_root ( x, norder, alpha, b, c );\n%\n% Set the abscissa and weight.\n%\n int.x(i) = x;\n int.w(i) = ( cc / dp2 ) / p1;\n\n end\n int.n = norder;\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [ x, dp2, p1 ] = laguerre_root ( x, norder, alpha, b, c )\n\n%% LAGUERRE_ROOT improves an approximate root of a Laguerre polynomial.\n%\n% Modified:\n%\n% 12 October 2005\n%\n% Reference:\n%\n% Arthur Stroud and Don Secrest,\n% Gaussian Quadrature Formulas,\n% Prentice Hall, 1966.\n%\n% Parameters:\n%\n% Input, real X, the approximate root, which\n% should be improved on output.\n%\n% Input, integer NORDER, the order of the polynomial to be computed.\n%\n% Input, real ALPHA, the exponent of the X factor.\n%\n% Input, real B(NORDER), C(NORDER), the recursion coefficients.\n%\n% Output, real X, the approximate root, which\n% should be improved on output.\n%\n% Output, real DP2, the value of L'(NORDER)(X).\n%\n% Output, real P1, the value of L(NORDER-1)(X).\n%\n maxstep = 10;\n\n eps = d_epsilon ( x );\n\n for i = 1 : maxstep\n\n [ p2, dp2, p1 ] = laguerre_recur ( x, norder, alpha, b, c );\n\n d = p2 / dp2;\n x = x - d;\n\n if ( abs ( d ) <= eps * ( abs ( x ) + 1.0 ) )\n return;\n end\n\n end\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [ p2, dp2, p1 ] = laguerre_recur ( x, norder, alpha, b, c )\n\n%% LAGUERRE_RECUR finds the value and derivative of a Laguerre\n%polynomial.\n%\n% Modified:\n%\n% 12 October 2005\n%\n% Reference:\n%\n% Arthur Stroud and Don Secrest,\n% Gaussian Quadrature Formulas,\n% Prentice Hall, 1966.\n%\n% Parameters:\n%\n% Input, real X, the point at which polynomials are evaluated.\n%\n% Input, integer NORDER, the order of the polynomial to be computed.\n%\n% Input, real ALPHA, the exponent of the X factor in the\n% integrand.\n%\n% Input, real B(NORDER), C(NORDER), the recursion\n% coefficients.\n%\n% Output, real P2, the value of L(NORDER)(X).\n%\n% Output, real DP2, the value of L'(NORDER)(X).\n%\n% Output, real P1, the value of L(NORDER-1)(X).\n%\n p1 = 1.0;\n dp1 = 0.0;\n\n p2 = x - alpha - 1.0;\n dp2 = 1.0;\n\n for i = 2 : norder\n\n p0 = p1;\n dp0 = dp1;\n\n p1 = p2;\n dp1 = dp2;\n\n p2 = ( x - b(i) ) * p1 - c(i) * p0;\n dp2 = ( x - b(i) ) * dp1 + p1 - c(i) * dp0;\n\n end\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/QuadratureMethods/MITGaussLaguerre.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.8128673110375457, "lm_q1q2_score": 0.7033123734493285}} {"text": "function geometry_test0205 ( )\n\n%*****************************************************************************80\n%\n%% TEST0205 tests DEGREES_TO_RADIANS, RADIANS_TO_DEGREES.\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, 'TEST0205\\n' );\n fprintf ( 1, ' DEGREES_TO_RADIANS converts an angle from degrees\\n' );\n fprintf ( 1, ' to radians;\\n' );\n fprintf ( 1, ' RADIANS_TO_DEGREES converts an angle from radians\\n' );\n fprintf ( 1, ' to degrees;\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Degrees Radians Degrees\\n' );\n fprintf ( 1, '\\n' );\n\n for i = -2 : 14\n angle_deg = 30 * i;\n angle_rad = degrees_to_radians ( angle_deg );\n angle_deg2 = radians_to_degrees ( angle_rad );\n fprintf ( 1, ' %10f %10f %10f\\n', angle_deg, angle_rad, angle_deg2 );\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_test0205.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.8652240721511739, "lm_q1q2_score": 0.7033123630132977}} {"text": "% J. C. Spall, March 1999\n% This code evaluates the basic root-finding (R-M) SA algorithm. Computes sample mean \n% and standard deviation of the mean from Navg realizations.\n%\nn=1000;\nrandn('seed',71111113)\na=0.081;\nA=5.1;\nalpha=.501;\ns=.1;\ntheta_0=[1,1]';\nNavg=2000;\nloss_eq2_5(theta_0)\nrslossavg=0;\nrslossavgsq=0;\nfor i=1:Navg\n theta=theta_0;\n for k=1:n\n theta=theta-(a/(k+A)^alpha)*gradloss(theta,s)';\n end\n rslossavg=(i-1)*rslossavg/i+loss_eq2_5(theta)/i;\n rslossavgsq=(i-1)*rslossavgsq/i+(loss_eq2_5(theta)^2)/i;\nend\nmean=rslossavg\nstdevmean=(((Navg/(Navg-1))*(rslossavgsq-mean^2))^.5)/(Navg^.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/3387-stochastic-search-and-optimization/basicRM_SA.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476385, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7032881401204363}} {"text": "function a = rutis1_inverse ( )\n\n%*****************************************************************************80\n%\n%% RUTIS1_INVERSE returns the inverse of the RUTIS1 matrix.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 October 2007\n%\n% Author:\n%\n% John Burkardt\n%\n% 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 -2.0, 4.0, 4.0, -5.0; ...\n 4.0, -2.0, -5.0, 4.0; ...\n 4.0, -5.0, -2.0, 4.0; ...\n -5.0, 4.0, 4.0, -2.0 ];\n\n a(1:4,1:4) = a(1:4,1:4) / 15.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_inverse.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.703288137455952}} {"text": "function b = r8col_normalize_li ( m, n, a )\n\n%*****************************************************************************80\n%\n%% R8COL_NORMALIZE_LI normalizes an R8COL with the column infinity norm.\n%\n% Discussion:\n%\n% Each column is scaled so that the entry of maximum norm has the value 1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 February 2012\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), the array to be examined.\n%\n% Output, real B(M,N), the normalize array.\n%\n b(1:m,1:n) = a(1:m,1:n);\n\n for j = 1 : n\n c = a(1,j);\n for i = 2 : m\n if ( abs ( c ) < abs ( a(i,j) ) ) \n c = a(i,j);\n end\n end\n if ( c ~= 0.0 )\n b(1:m,j) = b(1:m,j) / c;\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/svd_snowfall/r8col_normalize_li.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7032385483152693}} {"text": "function jacobi_rule ( order, alpha, beta, a, b, filename )\n\n%*****************************************************************************80\n%\n%% JACOBI_RULE generates a Gauss-Jacobi rule.\n%\n% Discussion:\n%\n% This program computes a standard Gauss-Jacobi quadrature rule\n% and writes it to a file.\n%\n% The user specifies:\n% * the ORDER (number of points) in the rule;\n% * ALPHA, the exponent of (1-x);\n% * BETA, the exponent of (1+x);\n% * A, the left endpoint;\n% * B, the right endpoint;\n% * FILENAME, the root name of the output files.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_RULE\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Compute a Gauss-Jacobi rule for approximating\\n' );\n fprintf ( 1, ' Integral ( A <= x <= B ) (B-x)^alpha (x-A)^beta f(x) dx\\n' );\n fprintf ( 1, ' of order ORDER.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The user specifies ORDER, ALPHA, BETA and FILENAME.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ORDER is the number of points\\n' );\n fprintf ( 1, ' ALPHA is the exponent of (B-x):\\n' );\n fprintf ( 1, ' BETA is the exponent of (x-A);\\n' );\n fprintf ( 1, ' A is the left endpoint;\\n' );\n fprintf ( 1, ' B is the right endpoint;\\n' );\n fprintf ( 1, ' FILENAME is used to generate 3 files:\\n' );\n fprintf ( 1, ' filename_w.txt - the weight file\\n' );\n fprintf ( 1, ' filename_x.txt - the abscissa file.\\n' );\n fprintf ( 1, ' filename_r.txt - the region file.\\n' );\n%\n% Get ORDER.\n%\n if ( nargin < 1 )\n order = input ( ' Enter the rule order ORDER: ' );\n elseif ( ischar ( order ) )\n order = str2num ( order );\n end\n%\n% Get ALPHA.\n%\n if ( nargin < 2 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ALPHA is the exponent of (B-x) in the integral:\\n' );\n fprintf ( 1, ' Note that -1.0 < ALPHA is required.\\n' );\n alpha = input ( ' Enter the value of ALPHA: ' );\n elseif ( ischar ( alpha ) )\n alpha = str2num ( alpha );\n end\n%\n% Get BETA.\n%\n if ( nargin < 3 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' BETA is the exponent of (x-A) in the integral:\\n' );\n fprintf ( 1, ' Note that -1.0 < BETA is required.\\n' );\n beta = input ( ' Enter the value of BETA: ' );\n elseif ( ischar ( beta ) )\n beta = str2num ( beta );\n end\n%\n% Get A.\n%\n if ( nargin < 4 )\n a = input ( ' Enter the left endpoint A: ' );\n elseif ( ischar ( a ) )\n a = str2num ( a );\n end\n%\n% Get B.\n%\n if ( nargin < 5 )\n b = input ( ' Enter the right endpoint B: ' );\n elseif ( ischar ( b ) )\n b = str2num ( b );\n end\n%\n% Get FILENAME.\n%\n if ( nargin < 6 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' FILENAME is the ''root name'' of the quadrature files).\\n' );\n filename = input ( ' Enter the value of FILENAME as a quoted string: ' );\n end\n%\n% Input summary.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ORDER = %d\\n', order );\n fprintf ( 1, ' ALPHA = %f\\n', alpha );\n fprintf ( 1, ' BETA = %f\\n', beta );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n fprintf ( 1, ' FILENAME = \"%s\".\\n', filename );\n%\n% Construct the rule.\n%\n kind = 4;\n [ x, w ] = cgqf ( order, kind, alpha, beta, a, b );\n%\n% Write the rule.\n%\n r = [ a, b ]';\n rule_write ( order, filename, x, w, r );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'JACOBI_RULE:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction [ t, wts ] = cdgqf ( nt, kind, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CDGQF computes a Gauss quadrature formula with default A, B and simple knots.\n%\n% Discussion:\n%\n% This routine computes all the knots and weights of a Gauss quadrature\n% formula with a classical weight function with default values for A and B,\n% and only simple knots.\n%\n% There are no moments checks and no printing is done.\n%\n% Use routine EIQFS to evaluate a quadrature computed by CGQFS.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n parchk ( kind, 2 * nt, alpha, beta );\n%\n% Get the Jacobi matrix and zero-th moment.\n%\n [ aj, bj, zemu ] = class_matrix ( kind, nt, alpha, beta );\n%\n% Compute the knots and weights.\n%\n [ t, wts ] = sgqf ( nt, aj, bj, zemu );\n\n return\nend\nfunction [ t, wts ] = cgqf ( nt, kind, alpha, beta, a, b )\n\n%*****************************************************************************80\n%\n%% CGQF computes knots and weights of a Gauss quadrature formula.\n%\n% Discussion:\n%\n% The user may specify the interval (A,B).\n%\n% Only simple knots are produced.\n%\n% The user may request that the routine print the knots and weights,\n% and perform a moment check.\n%\n% Use routine EIQFS to evaluate this quadrature formula.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 16 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, real A, B, the interval endpoints.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Compute the Gauss quadrature formula for default values of A and B.\n%\n [ t, wts ] = cdgqf ( nt, kind, alpha, beta );\n%\n% All knots have multiplicity = 1.\n%\n mlt = zeros(nt,1);\n mlt(1:nt) = 1;\n%\n% NDX(I) = I.\n%\n ndx = ( 1 : nt );\n%\n% Scale the quadrature rule.\n%\n [ t, wts ] = scqf ( nt, t, mlt, wts, nt, ndx, kind, alpha, beta, a, b );\n\n return\nend\nfunction [ aj, bj, zemu ] = class_matrix ( kind, m, alpha, beta )\n\n%*****************************************************************************80\n%\n%% CLASS_MATRIX computes the Jacobi matrix for a quadrature rule.\n%\n% Discussion:\n%\n% This routine computes the diagonal AJ and subdiagonal BJ\n% elements of the order M tridiagonal symmetric Jacobi matrix\n% associated with the polynomials orthogonal with respect to\n% the weight function specified by KIND.\n%\n% For weight functions 1-7, M elements are defined in BJ even\n% though only M-1 are needed. For weight function 8, BJ(M) is\n% set to zero.\n%\n% The zero-th moment of the weight function is returned in ZEMU.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, integer M, the order of the Jacobi matrix.\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Output, real AJ(M), BJ(M), the diagonal and subdiagonal\n% of the Jacobi matrix.\n%\n% Output, real ZEMU, the zero-th moment.\n%\n temp = eps;\n\n parchk ( kind, 2 * m - 1, alpha, beta );\n\n temp2 = 0.5;\n\n if ( 500.0 * temp < abs ( ( gamma ( temp2 ) )^2 - pi ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CLASS - Fatal error!\\n' );\n fprintf ( 1, ' Gamma function does not match machine parameters.\\n' );\n error ( 'CLASS - Fatal error!' );\n end\n\n bj = zeros(m,1);\n aj = zeros(m,1);\n\n if ( kind == 1 )\n\n ab = 0.0;\n\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod ( i, 2 );\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 2 )\n\n zemu = pi;\n\n aj(1:m) = 0.0;\n\n bj(1) = sqrt ( 0.5 );\n bj(2:m) = 0.5;\n\n elseif ( kind == 3 )\n\n ab = alpha * 2.0;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 )^2 ...\n / gamma ( ab + 2.0 );\n\n aj(1:m) = 0.0;\n bj(1) = 1.0 / ( 2.0 * alpha + 3.0 );\n for i = 2 : m\n bj(i) = i * ( i + ab ) / ( 4.0 * ( i + alpha )^2 - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 4 )\n\n ab = alpha + beta;\n abi = 2.0 + ab;\n zemu = 2.0^( ab + 1.0 ) * gamma ( alpha + 1.0 ) ...\n * gamma ( beta + 1.0 ) / gamma ( abi );\n aj(1) = ( beta - alpha ) / abi;\n bj(1) = 4.0 * ( 1.0 + alpha ) * ( 1.0 + beta ) ...\n / ( ( abi + 1.0 ) * abi * abi );\n a2b2 = beta * beta - alpha * alpha;\n\n for i = 2 : m\n abi = 2.0 * i + ab;\n aj(i) = a2b2 / ( ( abi - 2.0 ) * abi );\n abi = abi^2;\n bj(i) = 4.0 * i * ( i + alpha ) * ( i + beta ) * ( i + ab ) ...\n / ( ( abi - 1.0 ) * abi );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 5 )\n\n zemu = gamma ( alpha + 1.0 );\n\n for i = 1 : m\n aj(i) = 2.0 * i - 1.0 + alpha;\n bj(i) = i * ( i + alpha );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 6 )\n\n zemu = gamma ( ( alpha + 1.0 ) / 2.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n bj(i) = ( i + alpha * mod ( i, 2 ) ) / 2.0;\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 7 )\n\n ab = alpha;\n zemu = 2.0 / ( ab + 1.0 );\n\n aj(1:m) = 0.0;\n\n for i = 1 : m\n abi = i + ab * mod(i,2);\n abj = 2 * i + ab;\n bj(i) = abi * abi / ( abj * abj - 1.0 );\n end\n bj(1:m) = sqrt ( bj(1:m) );\n\n elseif ( kind == 8 )\n\n ab = alpha + beta;\n zemu = gamma ( alpha + 1.0 ) * gamma ( - ( ab + 1.0 ) ) ...\n / gamma ( - beta );\n apone = alpha + 1.0;\n aba = ab * apone;\n aj(1) = - apone / ( ab + 2.0 );\n bj(1) = - aj(1) * ( beta + 1.0 ) / ( ab + 2.0 ) / ( ab + 3.0 );\n for i = 2 : m\n abti = ab + 2.0 * i;\n aj(i) = aba + 2.0 * ( ab + i ) * ( i - 1 );\n aj(i) = - aj(i) / abti / ( abti - 2.0 );\n end\n\n for i = 2 : m - 1\n abti = ab + 2.0 * i;\n bj(i) = i * ( alpha + i ) / ( abti - 1.0 ) * ( beta + i ) ...\n / ( abti^2 ) * ( ab + i ) / ( abti + 1.0 );\n end\n\n bj(m) = 0.0;\n bj(1:m) = sqrt ( bj(1:m) );\n\n end\n\n return\nend\nfunction [ d, z ] = imtqlx ( n, d, e, z )\n\n%*****************************************************************************80\n%\n%% IMTQLX diagonalizes a symmetric tridiagonal matrix.\n%\n% Discussion:\n%\n% This routine is a slightly modified version of the EISPACK routine to\n% perform the implicit QL algorithm on a symmetric tridiagonal matrix.\n%\n% The authors thank the authors of EISPACK for permission to use this\n% routine.\n%\n% It has been modified to produce the product Q' * Z, where Z is an input\n% vector and Q is the orthogonal matrix diagonalizing the input matrix.\n% The changes consist (essentialy) of applying the orthogonal transformations\n% directly to Z as they are generated.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Roger Martin, James Wilkinson,\n% The Implicit QL Algorithm,\n% Numerische Mathematik,\n% Volume 12, Number 5, December 1968, pages 377-383.\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real D(N), the diagonal entries of the matrix.\n%\n% Input, real E(N), the subdiagonal entries of the\n% matrix, in entries E(1) through E(N-1). \n%\n% Input, real Z(N), a vector to be operated on.\n%\n% Output, real D(N), the diagonal entries of the diagonalized matrix.\n%\n% Output, real Z(N), the value of Q' * Z, where Q is the matrix that \n% diagonalizes the input symmetric tridiagonal matrix.\n%\n itn = 30;\n\n prec = eps;\n\n if ( n == 1 )\n return\n end\n\n e(n) = 0.0;\n\n for l = 1 : n\n\n j = 0;\n\n while ( 1 )\n\n for m = l : n\n\n if ( m == n )\n break\n end\n\n if ( abs ( e(m) ) <= prec * ( abs ( d(m) ) + abs ( d(m+1) ) ) )\n break\n end\n\n end\n\n p = d(l);\n\n if ( m == l )\n break\n end\n\n if ( j == itn )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'IMTQLX - Fatal error!\\n' );\n fprintf ( 1, ' Iteration limit exceeded.\\n' );\n error ( 'IMTQLX - Fatal error!' );\n end\n\n j = j + 1;\n g = ( d(l+1) - p ) / ( 2.0 * e(l) );\n r = sqrt ( g * g + 1.0 );\n g = d(m) - p + e(l) / ( g + r8_sign ( g ) * abs ( r ) );\n s = 1.0;\n c = 1.0;\n p = 0.0;\n mml = m - l;\n\n for ii = 1 : mml\n\n i = m - ii;\n f = s * e(i);\n b = c * e(i);\n\n if ( abs ( f ) >= abs ( g ) )\n c = g / f;\n r = sqrt ( c * c + 1.0 );\n e(i+1) = f * r;\n s = 1.0 / r;\n c = c * s;\n else\n s = f / g;\n r = sqrt ( s * s + 1.0 );\n e(i+1) = g * r;\n c = 1.0 / r;\n s = s * c;\n end\n\n g = d(i+1) - p;\n r = ( d(i) - g ) * s + 2.0 * c * b;\n p = s * r;\n d(i+1) = g + p;\n g = c * r - b;\n f = z(i+1);\n z(i+1) = s * z(i) + c * f;\n z(i) = c * z(i) - s * f;\n\n end\n\n d(l) = d(l) - p;\n e(l) = g;\n e(m) = 0.0;\n\n end\n\n end\n\n for ii = 2 : n\n\n i = ii - 1;\n k = i;\n p = d(i);\n\n for j = ii : n\n if ( d(j) < p )\n k = j;\n p = d(j);\n end\n end\n\n if ( k ~= i )\n d(k) = d(i);\n d(i) = p;\n p = z(i);\n z(i) = z(k);\n z(k) = p;\n end\n\n end\n\n return\nend\nfunction parchk ( kind, m, alpha, beta )\n\n%*****************************************************************************80\n%\n%% PARCHK checks parameters ALPHA and BETA for classical weight functions.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 04 January 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta\n%\n% Input, integer M, the order of the highest moment to\n% be calculated. This value is only needed when KIND = 8.\n%\n% Input, real ALPHA, BETA, the parameters, if required\n% by the value of KIND.\n%\n if ( kind <= 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND <= 0.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check ALPHA for Gegenbauer, Jacobi, Laguerre, Hermite, Exponential.\n%\n if ( 3 <= kind && alpha <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' 3 <= KIND and ALPHA <= -1.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check BETA for Jacobi.\n%\n if ( kind == 4 && beta <= -1.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND == 4 and BETA <= -1.0.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n%\n% Check ALPHA and BETA for rational.\n%\n if ( kind == 8 )\n tmp = alpha + beta + m + 1.0;\n if ( 0.0 <= tmp || tmp <= beta )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'PARCHK - Fatal error!\\n' );\n fprintf ( 1, ' KIND == 8 but condition on ALPHA and BETA fails.\\n' );\n error ( 'PARCHK - Fatal error!' );\n end\n end\n\n return\nend\nfunction value = r8_sign ( x )\n\n%*****************************************************************************80\n%\n%% R8_SIGN returns the sign of an R8.\n%\n% Discussion:\n%\n% The value is +1 if the number is positive or zero, and it is -1 otherwise.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, the number whose sign is desired.\n%\n% Output, real VALUE, the sign of X.\n%\n if ( 0 <= x )\n value = +1.0;\n else\n value = -1.0;\n end\n\n return\nend\nfunction r8mat_write ( output_filename, m, n, table )\n\n%*****************************************************************************80\n%\n%% R8MAT_WRITE writes an R8MAT file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 11 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, real TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 ) \n fprintf ( 1, '\\n' );\n fprintf ( 1, 'R8MAT_WRITE - Error!\\n' );\n fprintf ( 1, ' Could not open the output file.\\n' );\n error ( 'R8MAT_WRITE - Error!' );\n end\n%\n% Write the data.\n%\n% For smaller data files, and less precision, try:\n%\n% fprintf ( output_unit, ' %14.6f', table(i,j) );\n%\n for j = 1 : n\n for i = 1 : m\n fprintf ( output_unit, ' %24.16f', 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 rule_write ( order, filename, x, w, r )\n\n%*****************************************************************************80\n%\n%% RULE_WRITE writes a quadrature rule to a file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 February 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer ORDER, the order of the rule.\n%\n% Input, string FILENAME, specifies the output files.\n% write files 'filename_w.txt', 'filename_x.txt', 'filename_r.txt' defining \n% weights, abscissas, and region.\n%\n% Input, real X(ORDER), the abscissas.\n%\n% Input, real W(ORDER), the weights.\n%\n% Input, real R(2), the region.\n%\n filename_x = strcat ( filename, '_x.txt' );\n filename_w = strcat ( filename, '_w.txt' );\n filename_r = strcat ( filename, '_r.txt' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1,' Creating quadrature files.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' \"Root\" file name is \"%s\".\\n', filename );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Weight file will be \"%s\".\\n', filename_w );\n fprintf ( 1, ' Abscissa file will be \"%s\".\\n', filename_x );\n fprintf ( 1, ' Region file will be \"%s\".\\n', filename_r );\n\n r8mat_write ( filename_w, 1, order, w' );\n r8mat_write ( filename_x, 1, order, x' );\n r8mat_write ( filename_r, 1, 2, r' );\n\n return\nend\nfunction [ t, wts ] = scqf ( nt, t, mlt, wts, nwts, ndx, kind, alpha, ...\n beta, a, b )\n\n%*****************************************************************************80\n%\n%% SCQF scales a quadrature formula to a nonstandard interval.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real T(NT), the original knots.\n%\n% Input, integer MLT(NT), the multiplicity of the knots.\n%\n% Input, real WTS(NWTS), the weights.\n%\n% Input, integer NWTS, the number of weights.\n%\n% Input, integer NDX(NT), used to index the array WTS.\n% For more details see the comments in CAWIQ.\n%\n% Input, integer KIND, the rule.\n% 1, Legendre, (a,b) 1.0\n% 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5)\n% 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha\n% 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta\n% 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a))\n% 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2)\n% 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha\n% 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta\n% 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5)\n%\n% Input, real ALPHA, the value of Alpha, if needed.\n%\n% Input, real BETA, the value of Beta, if needed.\n%\n% Input, real A, B, the interval endpoints.\n%\n% Output, real T(NT), the scaled knots.\n%\n% Output, real WTS(NWTS), the scaled weights.\n%\n temp = eps;\n\n parchk ( kind, 1, alpha, beta )\n\n if ( kind == 1 )\n\n al = 0.0;\n be = 0.0;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 2 )\n\n al = -0.5;\n be = -0.5;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 3 )\n\n al = alpha;\n be = alpha;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 4 )\n\n al = alpha;\n be = beta;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 5 )\n\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = 1.0 / b;\n al = alpha;\n be = 0.0;\n\n elseif ( kind == 6 )\n\n if ( b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = 1.0 / sqrt ( b );\n al = alpha;\n be = 0.0;\n\n elseif ( kind == 7 )\n\n al = alpha;\n be = 0.0;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n elseif ( kind == 8 )\n\n if ( a + b <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' A + B <= 0.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = a;\n slp = a + b;\n al = alpha;\n be = beta;\n\n elseif ( kind == 9 )\n\n al = 0.5;\n be = 0.5;\n\n if ( abs ( b - a ) <= temp )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SCQF - Fatal error!\\n' );\n fprintf ( 1, ' |B - A| too small.\\n' );\n fprintf ( 1, ' A = %f\\n', a );\n fprintf ( 1, ' B = %f\\n', b );\n error ( 'SCQF - Fatal error!' );\n end\n\n shft = ( a + b ) / 2.0;\n slp = ( b - a ) / 2.0;\n\n end\n\n p = slp^( al + be + 1.0 );\n\n for k = 1 : nt\n\n t(k) = shft + slp * t(k);\n l = abs ( ndx(k) );\n\n if ( l ~= 0 )\n tmp = p;\n for i = l : l + mlt(k) - 1\n wts(i) = wts(i) * tmp;\n tmp = tmp * slp;\n end\n end\n\n end\n\n return\nend\nfunction [ t, wts ] = sgqf ( nt, aj, bj, zemu )\n\n%*****************************************************************************80\n%\n%% SGQF computes knots and weights of a Gauss Quadrature formula.\n%\n% Discussion:\n%\n% This routine computes all the knots and weights of a Gauss quadrature\n% formula with simple knots from the Jacobi matrix and the zero-th\n% moment of the weight function, using the Golub-Welsch technique.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2010\n%\n% Author:\n%\n% Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Sylvan Elhay, Jaroslav Kautsky,\n% Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of\n% Interpolatory Quadrature,\n% ACM Transactions on Mathematical Software,\n% Volume 13, Number 4, December 1987, pages 399-415.\n%\n% Parameters:\n%\n% Input, integer NT, the number of knots.\n%\n% Input, real AJ(NT), the diagonal of the Jacobi matrix.\n%\n% Input, real BJ(NT), the subdiagonal of the Jacobi\n% matrix, in entries 1 through NT-1. On output, BJ has been overwritten.\n%\n% Input, real ZEMU, the zero-th moment of the weight function.\n%\n% Output, real T(NT), the knots.\n%\n% Output, real WTS(NT), the weights.\n%\n\n%\n% Exit if the zero-th moment is not positive.\n%\n if ( zemu <= 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SGQF - Fatal error!\\n' );\n fprintf ( 1, ' ZEMU <= 0.\\n' );\n error ( 'SGQF - Fatal error!' );\n end\n%\n% Set up vectors for IMTQLX.\n%\n wts = zeros ( nt, 1 );\n wts(1) = sqrt ( zemu );\n wts(2:nt) = 0.0;\n%\n% Diagonalize the Jacobi matrix.\n%\n [ t, wts ] = imtqlx ( nt, aj, bj, wts );\n\n wts(1:nt) = wts(1:nt).^2;\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\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/jacobi_rule/jacobi_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7032385431862282}} {"text": "%achievability bound for AWGN channel under a long-term power constraint\n%\n\nfunction rate_ach_lt=awgn_ach_lt(snr_db, nn, error)\n\nsnr = 10^(snr_db);\n\nrate_ach_lt = zeros(1,length(nn)); %achievable rate (kappa beta)\n\n%Check whether a long-term power constraint will be beneficial \nC=log(1+snr);\nV = 1-1/(1+snr)^2;\nn_min = ( (1+snr)/snr*sqrt(2*pi*snr)*(1-error)*exp(qfuncinv(error)^2/2) + qfuncinv(error)/(1+snr)^2/sqrt(V))^2;\n\nn_index=find(nn <= n_min);\n\nif length(n_index)>0\n rate_ach_lt(n_index) = kappabeta_ach(2*nn(n_index),error,snr,1)./nn(n_index); %use the kappa beta bound for short-term power constraint \nend\n\n\nindex_large_n = find(nn>n_min);\n\nnumber_taus=20; %increase this number of gain tightness (at the cost of complexity)\nnumber_errors=20; %increase this number of gain tightness (at the cost of complexity)\n\nfor index_n= index_large_n\n n=nn(index_n);\n %tic\n disp(['ach_awgn_lt(): n=', num2str(n)]);\n\n temp_rate_arr=[];\n for error_n = (error/number_errors): (error /number_errors): (error * (number_errors-1)/number_errors)\n %ach SISO kappa beta bound\n P_n= snr*(1-error_n)./(1-error);\n tau_array = (error_n/number_taus) : (error_n/number_taus): (error_n*(number_taus-1)/number_taus);\n for tau = tau_array\n temp_rate = (log2(kappa_inf(tau, P_n)) - betaq_up_v2(1-error_n+tau, 2*n, P_n))/n;\n temp_rate_arr=[temp_rate_arr,temp_rate];\n end\n rate_ach_lt(index_n)=max(temp_rate_arr); \n end\nend", "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/long-term-power-constraint/awgn/awgn_ach_lt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.7031750127877943}} {"text": "function x = mono_upto_next_grlex ( m, n, x )\n\n%*****************************************************************************80\n%\n%% MONO_UPTO_NEXT_GRLEX: grlex next monomial with total degree up to N.\n%\n% Discussion:\n%\n% We consider all monomials in an M dimensional space, with total\n% degree up to N.\n%\n% For example:\n%\n% M = 3\n% N = 3\n%\n% # X(1) X(2) X(3) Degree\n% +------------------------\n% 1 | 0 0 0 0\n% |\n% 2 | 0 0 1 1\n% 3 | 0 1 0 1\n% 4 | 1 0 0 1\n% |\n% 5 | 0 0 2 2\n% 6 | 0 1 1 2\n% 7 | 0 2 0 2\n% 8 | 1 0 1 2\n% 9 | 1 1 0 2\n% 10 | 2 0 0 2\n% |\n% 11 | 0 0 3 3\n% 12 | 0 1 2 3\n% 13 | 0 2 1 3\n% 14 | 0 3 0 3\n% 15 | 1 0 2 3\n% 16 | 1 1 1 3\n% 17 | 1 2 0 3\n% 18 | 2 0 1 3\n% 19 | 2 1 0 3\n% 20 | 3 0 0 3\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 September 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the maximum degree.\n% 0 <= N.\n%\n% Input, integer X(M), the current monomial.\n% To start the sequence, set X = [ 0, 0, ..., 0, 0 ].\n%\n% Output, integer X(M), the next monomial.\n% The last value in the sequence is X = [ N, 0, ..., 0, 0 ].\n%\n if ( n < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONO_UPTO_NEXT_GRLEX - Fatal error!\\n' );\n fprintf ( 1, ' N < 0.\\n' );\n error ( 'MONO_UPTO_NEXT_GRLEX - Fatal error!' );\n end\n\n if ( sum ( x(1:m) ) < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONO_UPTO_NEXT_GRLEX - Fatal error!\\n' );\n fprintf ( 1, ' Input X sums to less than 0.\\n' );\n error ( 'MONO_UPTO_NEXT_GRLEX - Fatal error!' );\n end\n\n if ( n < sum ( x(1:m) ) )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'MONO_UPTO_NEXT_GRLEX - Fatal error!\\n' );\n fprintf ( 1, ' Input X sums to more than N.\\n' );\n error ( 'MONO_UPTO_NEXT_GRLEX - Fatal error!' );\n end\n\n if ( n == 0 )\n return\n end\n\n if ( x(1) == n )\n x(1) = 0;\n else\n x = mono_next_grlex ( m, 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/monomial/mono_upto_next_grlex.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7030991708151113}} {"text": "function [lambda_vec, error_train, error_val] = ...\n validationCurve(X, y, Xval, yval)\n%VALIDATIONCURVE Generate the train and validation errors needed to\n%plot a validation curve that we can use to select lambda\n% [lambda_vec, error_train, error_val] = ...\n% VALIDATIONCURVE(X, y, Xval, yval) returns the train\n% and validation errors (in error_train, error_val)\n% for different values of lambda. You are given the training set (X,\n% y) and validation set (Xval, yval).\n%\n\n% Selected values of lambda (you should not change this)\nlambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';\n\n% You need to return these variables correctly.\nerror_train = zeros(length(lambda_vec), 1);\nerror_val = zeros(length(lambda_vec), 1);\n\n% ====================== YOUR CODE HERE ======================\n% Instructions: Fill in this function to return training errors in \n% error_train and the validation errors in error_val. The \n% vector lambda_vec contains the different lambda parameters \n% to use for each calculation of the errors, i.e, \n% error_train(i), and error_val(i) should give \n% you the errors obtained after training with \n% lambda = lambda_vec(i)\n%\n% Note: You can loop over lambda_vec with the following:\n%\n% for i = 1:length(lambda_vec)\n% lambda = lambda_vec(i);\n% % Compute train / val errors when training linear \n% % regression with regularization parameter lambda\n% % You should store the result in error_train(i)\n% % and error_val(i)\n% ....\n% \n% end\n%\n%\nfor i=1:length(lambda_vec)\n\tlambda=lambda_vec(i);\n\t[theta]=trainLinearReg(X, y, lambda);\n\tlambda=0;\t% Set to zero when calculating error since already been trained\n\t% We are calc J as error not as cost. So, lambda should not be included when \n\t% calculating error for thetas that have been trained, else it will be biased \n\t% Refer to 2.1 of Exercise 5, error is computed without lambda\n\t[e_train]=linearRegCostFunction(X, y, theta, lambda);\n\t[e_val]=linearRegCostFunction(Xval, yval, theta, lambda);\t% J over all CV set for new set of theta\n\n% Accumulating error from i=1:m\n\tif (i==1)\n\t\terror_train=e_train;\n\t\terror_val=e_val;\n\telse\n\t\terror_train=[error_train; e_train];\n\t\terror_val=[error_val; e_val];\n\tend\nend\n\n% Above methods are also accepted when submitted, following method are also accepted\n\n%for i=1:length(lambda_vec)\n%lambda=lambda_vec(i);\n%[theta] = trainLinearReg(X, y, lambda);\n\n% For training set\n%m=length(y);\n%thetas=theta(2:end,1);\n%h=X*theta;\n%lambda=0;\n%error_train(i)=(1/(2.*m))*sum((h-y).^2)+(lambda/(2.*m)).*sum(thetas.^2);\n\n% For CV set\n%n=length(yval);\n%h2=Xval*theta;\n%lambda=0;\n%error_val(i)=(1/(2.*n))*sum((h2-yval).^2)+(lambda/(2.*n)).*sum(thetas.^2);\n%end\n\n% =========================================================================\n\nend\n", "meta": {"author": "yhyap", "repo": "machine-learning-coursera", "sha": "fb33f0ad54ff2104660c86b0d26456b15029a798", "save_path": "github-repos/MATLAB/yhyap-machine-learning-coursera", "path": "github-repos/MATLAB/yhyap-machine-learning-coursera/machine-learning-coursera-fb33f0ad54ff2104660c86b0d26456b15029a798/mlclass-ex5/validationCurve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.8807970873650401, "lm_q1q2_score": 0.7030405974632239}} {"text": "function value = cn_jac_monomial_integral ( n, alpha, beta, expon )\n\n%*****************************************************************************80\n%\n%% CN_JAC_MONOMIAL_INTEGRAL: integral of a monomial with Jacobi weight over CN.\n%\n% Discussion:\n%\n% value = integral ( CN )\n% product ( 1 <= i <= n ) x(I)^expon(i) (1-x(i))^alpha (1+x(i))^beta dx(i)\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 January 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the spatial dimension.\n%\n% Input, real ALPHA, the exponent of (1-X) in the weight factor.\n%\n% Input, real BETA, the exponent of (1+X) in the weight factor.\n%\n% Input, integer EXPON(N), the exponents.\n%\n% Output, real VALUE, the value of the integral.\n%\n value = 1.0;\n for i = 1 : n\n value2 = c1_jac_monomial_integral ( alpha, beta, expon(i) );\n value = value * value2;\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/cn_jac_monomial_integral.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.7030405893896935}} {"text": "classdef GaussianMultC\n%%GAUSSIANMULTC A collection of functions for the Gaussian multivariate\n% copulae. Implemented functions are: PDF.\n%\n%REFERENCES:\n%[1] H. Joe and D. Kurowicka, Dependence Modeling: Vine Copula Handbook.\n% World Scientific, 2011.\n%\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n methods(Static)\n function jprob = PDF(u,R)\n %PDF Generates a joint probability for column vector u or a row\n % vector of joint probabilities for matrix u with each column as\n % the input vector.\n %\n %INPUTS: u: A d-by-n matrix where each column represents a\n % d-dimensional random vector and n is the number of\n % random vectors. Entries must be in [0,1].\n % R: A d-by-d correlation matrix.\n %\n %October 2020 Codie T. Lewis, Naval Research Laboratory, Washington D.C.\n %\n if ~exist('u','var') || isempty(u)\n jprob = [];\n return\n end\n\n s2 = size(u,2);\n I = eye(size(R));\n jprob = zeros(1,s2);\n\n for col = 1:s2\n v = GaussianD.invCDF(u(:,col));\n jprob(col) = exp(-0.5*v'*(inv(R)-I)*v)/sqrt(det(R));\n end\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/Statistics/Multivariate_Copulae/GaussianMultC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.703040587856299}} {"text": "function [out] = percolation_3(S,Smax)\n%percolation_3 \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: Non-linear percolation (empirical)\n% Constraints: -\n% @(Inputs): S - current storage [mm]\n% Smax - maximum contributing storage [mm]\n\nout = Smax^(-4)./(4)*(4/9)^(4)*S^5;\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/percolation_3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.7030079638720653}} {"text": "function R = SeparateAngles(X,deep,is_real)\n% SeparateAngles: Frequency angular partitioning\n% Usage:\n% R = SeparateAngles(X,deep)\n% Inputs:\n% X m by m matrix (m = 2*2^(j+1)). \n% The input is the Fourier transform of an object obtained\n% after windowing with a bandpass Meyer window which\n% isolates frequencies in the range 2^(j-1) <= |k| <=\n% 2^j. We interpret the array as samples at the frequency\n% points (k1,k2), -2^(j+1) <= k1,k2 < 2^(j+1) \n%\n% deep 2^deep is the number of angular wedges in each of the\n% directional panels NESW (North, East, South, West).\n% Outputs:\n% R Array of smoothly localized Fourier samples\n% size = 4 * m * 2^j * 2*2^(j+1)/m, m = 2^deep \n%\n% (i) first index -- cardinal point 1 = W, 2 = E, 3 = N, 4 = S. \n% (ii) second index -- indexes orientations according to the\n% organization below; e.g. (1,3) would correspond to\n% the wedge marked with a star. \n%\n% j \n% ------------------------------------->\n% |\n% | 1 4\n% | \n% |\n% |\n% | 2 3\n% |\n% i |\n% | \n% | 3* 2\n% |\n% |\n% | \n% | 4 1 \n% \\/\n%\n%\n% West East\n%\n% North and South are obtained by transposition. \n%\n% (iii) third and fourth indices-- frequency points, regular\n% samples along parallel slanted lines (shape of a parallelogram)\n%\n% Description \n% Smoothly localizes the FT near angular wedges \n% Operates by interpolating the FT along vertical and horizontal \n% directions\n% See Also\n% Adj_SeparateAngles, AtA, AtA_Toeplitz\n%\n% By Emmanuel Candes, 2003-2004\n\n if nargin < 3\n is_real = 0;\n end\n \n n = size(X,1);\n n2 = n/2;\n boxlen = n/2^deep;\n boxcnt = 2^deep;\t\n \n R = zeros(4,boxcnt,n2/2,2*boxlen);\n \n [ix,w] = DetailMeyerWindow([n2/4 n2/2],3);\n lx = reverse(-ix);\n \n m = 0:(boxcnt - 1);\n ym = (m-boxcnt/2).*boxlen + boxlen/2;\n slope = -ym./n2; \n \n % recall that fft_mid0 operates along columns\n % Columns: West and East\n \n F = ifft_mid0(X).*sqrt(n); \n \n for r = 1:(n2/2), \n k = lx(r); t = n2 + k + 1;\n shift = ym + slope.*(k+n2);\n alpha = -k./n2;\n w = MakeSineWindow(boxlen,alpha);\n y = Evaluate_FT(F(:,t),shift,boxlen,0,w); \n R(1,:,r,:) = reshape(y,2*boxlen,boxcnt).';\n rsym = n2/2+1-r;\n if (is_real)\n R(2,:,rsym,:) = conj(fliplr(squeeze(R(1,:,r,:))));\n else\n t = n2 - k + 1;\n shift = -shift + 1;\n y = Evaluate_FT(F(:,t),shift,boxlen,0,w);\n R(2,:,rsym,:) = reshape(y,2*boxlen,boxcnt).';\n end\n end\n \n % Rows: North and South\n F = ifft_mid0(X.').*sqrt(n); \n for r = 1:(n2/2),\t \n k = lx(r); t = n2 + k + 1;\n shift = ym + slope.*(k+n2);\n alpha = -k./n2;\n w = MakeSineWindow(boxlen,alpha);\n y = Evaluate_FT(F(:,t),shift,boxlen,0,w);\n R(3,:,r,:) = reshape(y,2*boxlen,boxcnt).';\n \n rsym = n2/2+1-r;\n if (is_real)\n R(4,:,rsym,:) = conj(fliplr(squeeze(R(3,:,r,:))));\n else\n t = n2 - k + 1;\n shift = -shift + 1;\n y = Evaluate_FT(F(:,t),shift,boxlen,0,w);\n R(4,:,rsym,:) = reshape(y,2*boxlen,boxcnt).';\n end\n end\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/CurveLab-2.1.3/fdct_usfft_matlab/CurveCoeff/SeparateAngles.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7030079605529513}} {"text": "function [V,Beta,R] = qr_left (A)\n%QR_LEFT left-looking Householder QR factorization.\n% Example:\n% [V,Beta,R] = qr_left (A)\n% See also: cs_demo\n\n% Copyright 2006-2007, Timothy A. Davis.\n% http://www.cise.ufl.edu/research/sparse\n\n[m n] = size (A) ;\nV = zeros (m,n) ;\nBeta = zeros (1,n) ;\nR = zeros (m,n) ;\nfor k = 1:n\n x = A (:,k) ;\n for i = 1:k-1\n v = V (i:m,i) ;\n beta = Beta (i) ;\n x (i:m) = x (i:m) - v * (beta * (v' * x (i:m))) ;\n end\n [v,beta,s] = gallery ('house', x (k:m), 2) ;\n V (k:m,k) = v ;\n Beta (k) = beta ;\n R (1:(k-1),k) = x (1:(k-1)) ;\n R (k,k) = s ;\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/SuiteSparse/CXSparse/MATLAB/Test/qr_left.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418137109956, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.7029490787798944}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% MATLAB Code for %\n% %\n% Multi-Objective Particle Swarm Optimization (MOPSO) %\n% Version 1.0 - Feb. 2011 %\n% %\n% According to: %\n% Carlos A. Coello Coello et al., %\n% \"Handling Multiple Objectives with Particle Swarm Optimization,\" %\n% IEEE Transactions on Evolutionary Computation, Vol. 8, No. 3, %\n% pp. 256-279, June 2004. %\n% %\n% Developed Using MATLAB R2009b (Version 7.9) %\n% %\n% Programmed By: S. Mostapha Kalami Heris %\n% %\n% e-Mail: sm.kalami@gmail.com %\n% kalami@ee.kntu.ac.ir %\n% %\n% Homepage: http://www.kalami.ir %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nclc;\nclear;\nclose all;\n\n%% Problem Definition\n\nTestProblem=1; % Set to 1, 2, or 3\n\nswitch TestProblem\n case 1\n CostFunction=@(x) MyCost1(x);\n nVar=5;\n VarMin=-4;\n VarMax=4;\n \n case 2\n CostFunction=@(x) MyCost2(x);\n nVar=3;\n VarMin=-5;\n VarMax=5;\n \n case 3\n CostFunction=@(x) MyCost3(x);\n nVar=2;\n VarMin=0;\n VarMax=1;\nend\n\nVarSize=[1 nVar];\n\nVelMax=(VarMax-VarMin)/10;\n\n%% MOPSO Settings\n\nnPop=100; % Population Size\n\nnRep=100; % Repository Size\n\nMaxIt=100; % Maximum Number of Iterations\n\nphi1=2.05;\nphi2=2.05;\nphi=phi1+phi2;\nchi=2/(phi-2+sqrt(phi^2-4*phi));\n\nw=chi; % Inertia Weight\nwdamp=1; % Inertia Weight Damping Ratio\nc1=chi*phi1; % Personal Learning Coefficient\nc2=chi*phi2; % Global Learning Coefficient\n\nalpha=0.1; % Grid Inflation Parameter\n\nnGrid=10; % Number of Grids per each Dimension\n\nbeta=4; % Leader Selection Pressure Parameter\n\ngamma=2; % Extra (to be deleted) Repository Member Selection Pressure\n\n%% Initialization\n\nparticle=CreateEmptyParticle(nPop);\n\nfor i=1:nPop\n particle(i).Velocity=0;\n particle(i).Position=unifrnd(VarMin,VarMax,VarSize);\n\n particle(i).Cost=CostFunction(particle(i).Position);\n\n particle(i).Best.Position=particle(i).Position;\n particle(i).Best.Cost=particle(i).Cost;\nend\n\nparticle=DetermineDomination(particle);\n\nrep=GetNonDominatedParticles(particle);\n\nrep_costs=GetCosts(rep);\nG=CreateHypercubes(rep_costs,nGrid,alpha);\n\nfor i=1:numel(rep)\n [rep(i).GridIndex rep(i).GridSubIndex]=GetGridIndex(rep(i),G);\nend\n \n%% MOPSO Main Loop\n\nfor it=1:MaxIt\n for i=1:nPop\n rep_h=SelectLeader(rep,beta);\n\n particle(i).Velocity=w*particle(i).Velocity ...\n +c1*rand*(particle(i).Best.Position - particle(i).Position) ...\n +c2*rand*(rep_h.Position - particle(i).Position);\n\n particle(i).Velocity=min(max(particle(i).Velocity,-VelMax),+VelMax);\n\n particle(i).Position=particle(i).Position + particle(i).Velocity;\n\n flag=(particle(i).PositionVarMax);\n particle(i).Velocity(flag)=-particle(i).Velocity(flag);\n \n particle(i).Position=min(max(particle(i).Position,VarMin),VarMax);\n\n particle(i).Cost=CostFunction(particle(i).Position);\n\n if Dominates(particle(i),particle(i).Best)\n particle(i).Best.Position=particle(i).Position;\n particle(i).Best.Cost=particle(i).Cost;\n \n elseif ~Dominates(particle(i).Best,particle(i))\n if rand<0.5\n particle(i).Best.Position=particle(i).Position;\n particle(i).Best.Cost=particle(i).Cost;\n end\n end\n\n end\n \n particle=DetermineDomination(particle);\n nd_particle=GetNonDominatedParticles(particle);\n \n rep=[rep\n nd_particle];\n \n rep=DetermineDomination(rep);\n rep=GetNonDominatedParticles(rep);\n \n for i=1:numel(rep)\n [rep(i).GridIndex rep(i).GridSubIndex]=GetGridIndex(rep(i),G);\n end\n \n if numel(rep)>nRep\n EXTRA=numel(rep)-nRep;\n rep=DeleteFromRep(rep,EXTRA,gamma);\n \n rep_costs=GetCosts(rep);\n G=CreateHypercubes(rep_costs,nGrid,alpha);\n \n end\n \n disp(['Iteration ' num2str(it) ': Number of Repository Particles = ' num2str(numel(rep))]);\n \n w=w*wdamp;\nend\n\n%% Results\n\ncosts=GetCosts(particle);\nrep_costs=GetCosts(rep);\n\nfigure;\n\nplot(costs(1,:),costs(2,:),'b.');\nhold on;\nplot(rep_costs(1,:),rep_costs(2,:),'rx');\nlegend('Main Population','Repository');\n", "meta": {"author": "sfvsfv", "repo": "Mathematical-modeling", "sha": "cef1a3688246851f067777b3599b1b3831d3d948", "save_path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling", "path": "github-repos/MATLAB/sfvsfv-Mathematical-modeling/Mathematical-modeling-cef1a3688246851f067777b3599b1b3831d3d948/美赛A题常见代码/多目标粒子群优化算法代码/mopso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642018, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.7029231982574252}} {"text": "% [Sol] = homography2Motion(H)\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB 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% MVTB 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 MVTB. If not, see .\n\n% Homography estimation between views of a plane\n% decompose it into rotation and translation and plane normal\n% p - retinal (calibrated) coordinates of the first view\n% q - retinal (calibrated) coordinate in the second view\n% Sol = [rotation, translation*1/d, plane normal] four possible solutions\n% H - two view homography\n%\n% Algorith, 5.2 in Chapter 5, \"An introduction to 3-D Vision\"\n% by Y. Ma, S. Soatto, J. Kosecka, S. Sastry (MASKS)\n%\n% Code distributed free for non-commercial use\n% Copyright (c) MASKS, 2003\n%\n% Last modified 5/5/2003\n\nfunction [Sol] = homography2Motion(Hest);\n\n % decomposition of H into motion and structure in case of calibration case\n [u,s,v] = svd(Hest);\n H = Hest/s(2,2);\n [u,s,v] = svd(H'*H);\n \n if det(u) < 0 u = -u; end;\n \n s1 = s(1,1); s2 = s(2,2); s3 = s(3,3);\n v1 = u(:,1); v2 = u(:,2); v3 = u(:,3);\n u1 = (v1*sqrt(1-s3) + v3*sqrt(s1 -1))/sqrt(s1 - s3);\n u2 = (v1*sqrt(1-s3) - v3*sqrt(s1 -1))/sqrt(s1 - s3);\n \n \n U1 = [v2, u1, skew(v2)*u1];\n U2 = [v2, u2, skew(v2)*u2];\n W1 = [H*v2, H*u1, skew(H*v2)*H*u1];\n W2 = [H*v2, H*u2, skew(H*v2)*H*u2];\n \n N1 = skew(v2)*u1;\n N2 = skew(v2)*u2;\n \n R1 = W1*U1'\n R2 = W2*U2'\n\n Sol(:,:,1) = [W1*U1', (H - W1*U1')*N1, N1];\n Sol(:,:,2) = [W2*U2', (H - W2*U2')*N2, N2];\n Sol(:,:,3) = [W1*U1', -(H - W1*U1')*N1, -N1];\n Sol(:,:,4) = [W2*U2', -(H - W2*U2')*N2, -N2];\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/kosecka.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026550642019, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.7029231933615707}} {"text": "% INTERNAL FUNCTION: Kalman filter for non-regime-switching models\n% \n% ::\n% \n% f=missing_observations_kalman_filter(y,T,R,Z,H,Q,init,dy,ca,level)\n% \n% Args:\n% \n% y (p x n matrix): data\n% T (m x m x nT): state matrix, see below\n% R (m x r x nR): state matrix, see below\n% Z (p x m | logical): state matrix or selector, see below\n% H (p x p x nH): Covariances of measurement errors\n% Q (r x r x nQ): Covariances of shocks\n% init (struct):\n% dy (p x ndy):\n% ca (m x nca):\n% level (0 | 1 | 2 | {3}): controls the level output produced.\n% \n% - if level==0, only the likelihood is returned\n% - if level==1, filters/forecasts are returned in addition to level 0\n% - if level==2, updates are returned in addition to level 1\n% - if level==3, smoothed values are returned in addition to level 2\n% \n% nstep (integer | {1}): Number of forecast steps\n% \n% Returns:\n% :\n% \n% - **f** [struct]: output structure\n% \n% - **retcode** [0|305]: 305 if computation of the likelihood breaks\n% downs\n% - **incr** [vector]: likelihood in each period\n% - **log_lik** [scalar]: log likelihood\n% - **a** [m x n+1 x nstep]: filtered stated (available if level >0)\n% - **P** [m x m x n+1 x nstep]: Covariance matrix of filtered state\n% (available if level >0)\n% - **att** [m x n]: Updated state vector (available if level >1)\n% - **Ptt** [m x m x n]: Covariance matrix for updates (available if\n% level >1)\n% - **iF** [p x p x n]: Inverses of covariance matrix of forecast\n% errors\n% - **v** [p x n]: Forecast errors\n% - **K** [m x p x n]: Kalman gains\n% - **alpha** [m x n]: smoothed state vector\n% - **V** [m x m x n]: Covariance matrix of smoothed state vector\n% - **r** [m x n+1]: quantity useful for the efficient computation of\n% the state vector\n% - **eta** [r x n]: smoothed shocks\n% - **epsilon** [p x n]: smoothed measurement errors\n% \n% Note:\n% \n% The system is of the form\n% .. math::\n% \n% alpha(t+1) = T*alpha(t) + ca(t) + R(t)*eta(t), eta ~ N(0, Q)\n% y(t) = Z*alpha(t) + dy(t) + epsilon(t), epsilon ~ N(0,H)\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/filtering/+obsw/missing_observations_kalman_filter.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.7029231901981216}} {"text": "%########################################################################\n%\n%\t- PPGI Toolbox - \n% A MATLAB toolbox for Photoplethysmography Imaging (PPGI)\n%\n% Author : Christian S. Pilz\n% Company : The Nature of Space of Time\n% Date : 07.05.2019\n%\n% Contact : cpi@partofthestars.com\n% Web Page : www.partofthestars.com\n%\n% Version : beta0.1\n%\n%########################################################################\n%\n%\tseparate.m:\n%\n% Description:\n%\n% Implements the Kalman based separation of frequencies based upon the diffusion process algorithm.\n%\n% References:\n%\n%\tChristian S. Pilz, Jarek Krajewski, Vladimir Blazek.\n% On the Diffusion Process for Heart Rate Estimation from Face Videos under Realistic Conditions.\n% Pattern Recognition: 39th German Conference, GCPR 2017, Basel, Switzerland.\n% Proceedings (Lecture Notes in Computer Science), Springer, 2017\n%\n\nfunction [S,CS,QCS,SMM,SPP,FMM,FPP] = separate(Y,dt,FF,nharm,BF,BQ,BL,BH,R,qr)\n% - Separate periodic signal from other signals\n%\n% Syntax:\n% [S,CS,QCS,SMM,SPP,FMM,FPP] = separate(Y,dt,FF,nharm,BF,BQ,BL,BH,R,qr)\n%\n% In:\n% Y - Signal as 1xD vector\n% dt - Sampling period in seconds (e.g. 0.1)\n% FF - Fundamental frequencies as 1xD vector in BPM (from the IMM)\n% nharm - Number of harmonics to be estimated (e.g. 3)\n% BF - Feedback matrix for the bias model (e.g. [0 1; 0 0])\n% BQ - Process spectral density for the bias model (e.g. 0.01)\n% BL - Noise multiplier matrix for the bias model (e.g. [0;1])\n% BH - Measurement matrix for the bias model (e.g. [1 0])\n% R - Measurement variance (e.g. 0.1^2)\n% qr - Resonator's process noise spectral density (e.g. 0.1)\n%\n% Out:\n% S - Cleaned signal as 1xD vector\n% CS - Fundamental signal and its harmonics as (nharm)xD vector\n% QCS - Quadrature periodic signals as (nharm)xD vector\n% SMM - The smoother means NxD\n% SPP - The smoother covariances NxNxD\n% FMM - The filter means NxD\n% FPP - The filter covariances NxNxD\n%\n% Description:\n% Separate given signal into true signal and periodic\n% signal by using the known frequency of the periodic signal.\n% See TRACK for the model used.\n\n % Number of harmonics (including fundamental)\n N = nharm;\n \n % Prior means and covariances\n m0 = zeros(2*N+size(BF,1),1); % XXX: Could be function parameter\n P0 = 10*eye(size(m0,1)); % XXX: Could be function parameter\n\n % Mean to measurement at step 1\n m0(1) = Y(1);\n \n %\n % Form the constant matrices\n %\n F = zeros(size(m0,1));\n H = zeros(1,size(m0,1));\n L = zeros(size(m0,1),N+size(BQ,1));\n Qc = zeros(N+size(BQ,1));\n \n for j=1:N\n i1 = 1+2*(j-1);\n i2 = 2+2*(j-1);\n L(i2,j) = 1;\n Qc(j,j) = qr;\n H(1,i1) = 1;\n end\n \n %\n % Form the bias model\n %\n i1 = 1+2*N;\n i2 = 2+2*N;\n j1 = N+2-size(BQ,1);\n j2 = N+1;\n F(i1:i2,i1:i2) = BF;\n L(i1:i2,j1:j2) = BL;\n H(1,i1:i2) = BH; \n Qc(j1:j2,j1:j2) = BQ; \n \n \n%% Run filter\n \n m = m0;\n P = P0;\n\n FMM = zeros(size(m,1),length(Y));\n FPP = zeros(size(P,1),size(P,2),length(Y));\n \n for k=1:length(Y)\n \n %\n % Update the resonators\n %\n w = 2*pi*FF(k)/60;\n for j=1:N\n i1 = 1+2*(j-1);\n i2 = 2+2*(j-1);\n F(i1:i2,i1:i2) = [0 j*w; -j*w 0];\n end\n \n %\n % Discretize\n %\n [A,Q] = lti_disc(F,L,Qc,dt);\n\n %\n % Estimate with KF\n %\n [m,P] = kf_predict(m,P,A,Q);\n [m,P] = kf_update(m,P,Y(k),H,R);\n \n FMM(:,k) = m;\n FPP(:,:,k) = P;\n end\n \n \n%% Run smoother\n\n % Allocate and set initial\n SMM = zeros(size(FMM));\n SPP = zeros(size(FPP));\n SMM(:,end) = m;\n SPP(:,:,end) = P;\n \n for k=length(Y)-1:-1:1\n \n %\n % Update each resonator\n %\n w = 2*pi*FF(k+1)/60;\n for j=1:N\n i1 = 1+2*(j-1);\n i2 = 2+2*(j-1);\n F(i1:i2,i1:i2) = [0 j*w; -j*w 0];\n end\n \n %\n % Discretize\n %\n [A,Q] = lti_disc(F,L,Qc,dt);\n \n % Smoother\n m_pred = A * FMM(:,k);\n P_pred = A * FPP(:,:,k) * A' + Q;\n D = FPP(:,:,k) * A' / P_pred;\n m = FMM(:,k) + D * (m - m_pred);\n P = FPP(:,:,k) + D * (P - P_pred) * D';\n \n % Store results\n SMM(:,k) = m;\n SPP(:,:,k) = P;\n \n end\n \n %\n % Extract the signals\n %\n S = SMM(end-size(BF,1)+1,:);\n CS = SMM(1:2:(2*nharm),:);\n QCS = SMM(2:2:(2*nharm+1),:);\n \nfunction [A,Q] = lti_disc(F,L,Q,dt)\n% LTI_DISC - Discretize LTI ODE with Gaussian Noise\n%\n% Syntax:\n% [A,Q] = lti_disc(F,L,Qc,dt)\n%\n% In:\n% F - NxN Feedback matrix\n% L - NxL Noise effect matrix (optional, default identity)\n% Qc - LxL Diagonal Spectral Density (optional, default zeros)\n% dt - Time Step (optional, default 1)\n%\n% Out:\n% A - Transition matrix\n% Q - Discrete Process Covariance\n%\n% Description:\n% Discretize LTI ODE with Gaussian Noise. The original\n% ODE model is in form\n%\n% dx/dt = F x + L w, w ~ N(0,Qc)\n%\n% Result of discretization is the model\n%\n% x[k] = A x[k-1] + q, q ~ N(0,Q)\n%\n% Which can be used for integrating the model\n% exactly over time steps, which are multiples\n% of dt.\n%\n\n %\n % Check number of arguments\n %\n if nargin < 1\n error('Too few arguments');\n end\n if nargin < 2\n L = [];\n end\n if nargin < 3\n Q = [];\n end\n if nargin < 4\n dt = [];\n end\n\n if isempty(L)\n L = eye(size(F,1));\n end\n if isempty(Q)\n Q = zeros(size(F,1),size(F,1));\n end\n if isempty(dt)\n dt = 1;\n end\n\n %\n % Closed form integration of transition matrix\n %\n A = expm(F*dt);\n\n %\n % Closed form integration of covariance\n % by matrix fraction decomposition\n %\n n = size(F,1);\n Phi = [F L*Q*L'; zeros(n,n) -F'];\n AB = expm(Phi*dt)*[zeros(n,n);eye(n)];\n Q = AB(1:n,:)/AB((n+1):(2*n),:);\n\n function [x,P] = kf_predict(x,P,A,Q,B,u)\n% KF_PREDICT - Perform Kalman Filter prediction step\n%\n% Syntax:\n% [X,P] = KF_PREDICT(X,P,A,Q,B,U)\n%\n% In:\n% X - Nx1 mean state estimate of previous step\n% P - NxN state covariance of previous step\n% A - Transition matrix of discrete model (optional, default identity)\n% Q - Process noise of discrete model (optional, default zero)\n% B - Input effect matrix (optional, default identity)\n% U - Constant input (optional, default empty)\n%\n% Out:\n% X - Predicted state mean\n% P - Predicted state covariance\n% \n% Description:\n% Perform Kalman Filter prediction step. The model is\n%\n% x[k] = A*x[k-1] + B*u[k-1] + q, q ~ N(0,Q).\n% \n% The predicted state is distributed as follows:\n% \n% p(x[k] | x[k-1]) = N(x[k] | A*x[k-1] + B*u[k-1], Q[k-1])\n%\n% The predicted mean x-[k] and covariance P-[k] are calculated\n% with the following equations:\n%\n% m-[k] = A*x[k-1] + B*u[k-1]\n% P-[k] = A*P[k-1]*A' + Q.\n%\n% If there is no input u present then the first equation reduces to\n% m-[k] = A*x[k-1]\n%\n\n %\n % Check arguments\n %\n if nargin < 3\n A = [];\n end\n if nargin < 4\n Q = [];\n end\n if nargin < 5\n B = [];\n end\n if nargin < 6\n u = [];\n end\n \n %\n % Apply defaults\n %\n if isempty(A)\n A = eye(size(x,1));\n end\n if isempty(Q)\n Q = zeros(size(x,1));\n end\n if isempty(B) & ~isempty(u)\n B = eye(size(x,1),size(u,1));\n end\n\n %\n % Perform prediction\n %\n if isempty(u)\n x = A * x;\n P = A * P * A' + Q;\n else\n x = A * x + B * u;\n P = A * P * A' + Q;\n end\n\n function [X,P,K,IM,IS,LH] = kf_update(X,P,y,H,R)\n% KF_UPDATE - Kalman Filter update step\n%\n% Syntax:\n% [X,P,K,IM,IS,LH] = KF_UPDATE(X,P,Y,H,R)\n%\n% In:\n% X - Nx1 mean state estimate after prediction step\n% P - NxN state covariance after prediction step\n% Y - Dx1 measurement vector.\n% H - Measurement matrix.\n% R - Measurement noise covariance.\n%\n% Out:\n% X - Updated state mean\n% P - Updated state covariance\n% K - Computed Kalman gain\n% IM - Mean of predictive distribution of Y\n% IS - Covariance or predictive mean of Y\n% LH - Predictive probability (likelihood) of measurement.\n% \n% Description:\n% Kalman filter measurement update step. Kalman Filter\n% model is\n%\n% x[k] = A*x[k-1] + B*u[k-1] + q, q ~ N(0,Q)\n% y[k] = H*x[k] + r, r ~ N(0,R)\n%\n% Prediction step of Kalman filter computes predicted\n% mean m-[k] and covariance P-[k] of state:\n%\n% p(x[k] | y[1:k-1]) = N(x[k] | m-[k], P-[k])\n%\n% See for instance KF_PREDICT how m-[k] and P-[k] are\n% calculated. \n%\n% Update step computes the posterior mean m[k] and\n% covariance P[k] of state given new measurement:\n%\n% p(x[k] |�y[1:k]) = N(x[k] |�m[k], P[k])\n%\n% Innovation distribution is defined as\n%\n% p(y[k] |�y[1:k-1]) = N(y[k] | IM[k], IS[k])\n% \n% Updated mean x[k] and covarience P[k] are given by\n% the following equations (not the only possible ones):\n%\n% v[k] = y[k] - H[k]*m-[k]\n% S[k] = H[k]*P-[k]*H[k]' + R[k]\n% K[k] = P-[k]*H[k]'*[S[k]]^(-1) \n% m[k] = m-[k] + K[k]*v[k]\n% P[k] = P-[k] - K[k]*S[k]*K[k]'\n%\n% Example:\n% m = m0;\n% P = P0;\n% M = m0;\n% for i=1:size(Y,2)\n% [m,P] = kf_predict(m,P,A,Q);\n% [m,P] = kf_update(m,P,Y(:,i),H,R);\n% M = [M m];\n% end\n%\n\n %\n % Check which arguments are there\n %\n if nargin < 5\n error('Too few arguments');\n end\n\n %\n % update step\n %\n IM = H*X;\n IS = (R + H*P*H');\n K = P*H'/IS;\n X = X + K * (y-IM);\n P = P - K*IS*K';\n if nargout > 5\n LH = gauss_pdf(y,IM,IS);\n end\n\n function [P,E] = gauss_pdf(X,M,S)\n%GAUSS_PDF Multivariate Gaussian PDF\n%\n% Syntax:\n% [P,E] = GAUSS_PDF(X,M,S)\n%\n% In:\n% X - Dx1 value or N values as DxN matrix\n% M - Dx1 mean of distibution or N values as DxN matrix.\n% S - DxD covariance matrix\n%\n% Out:\n% P - Probability of X. \n% E - Negative logarithm of P\n% \n% Description:\n% Calculate values of PDF (Probability Density\n% Function) of multivariate Gaussian distribution\n%\n% N(X | M, S)\n%\n% Function returns probability of X in PDF. If multiple\n% X's or M's are given (as multiple columns), function\n% returns probabilities for each of them. X's and M's are\n% repeated to match each other, S must be the same for all.\n%\n\n if size(M,2) == 1\n DX = X-repmat(M,1,size(X,2)); \n E = 0.5*sum(DX.*(S\\DX),1);\n d = size(M,1);\n E = E + 0.5 * d * log(2*pi) + 0.5 * log(det(S));\n P = exp(-E);\n elseif size(X,2) == 1\n DX = repmat(X,1,size(M,2))-M; \n E = 0.5*sum(DX.*(S\\DX),1);\n d = size(M,1);\n E = E + 0.5 * d * log(2*pi) + 0.5 * log(det(S));\n P = exp(-E);\n else\n DX = X-M; \n E = 0.5*DX'*(S\\DX);\n d = size(M,1);\n E = E + 0.5 * d * log(2*pi) + 0.5 * log(det(S));\n P = exp(-E);\n end\n", "meta": {"author": "partofthestars", "repo": "PPGI-Toolbox", "sha": "b7a7945561ccd98bf66ca629ac6d1b4bf4f0ac34", "save_path": "github-repos/MATLAB/partofthestars-PPGI-Toolbox", "path": "github-repos/MATLAB/partofthestars-PPGI-Toolbox/PPGI-Toolbox-b7a7945561ccd98bf66ca629ac6d1b4bf4f0ac34/lib/algorithm/models/diffusion_process/separate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.7029231867333107}} {"text": "function [ yval, ypval, yppval, left_out ] = spline_cubic_val2 ( ...\n n, t, y, ypp, left, tval )\n\n%*****************************************************************************80\n%\n%% SPLINE_CUBIC_VAL2 evaluates a piecewise cubic spline at a point.\n%\n% Discussion:\n%\n% This routine is a modification of SPLINE_CUBIC_VAL; it allows the\n% user to speed up the code by suggesting the appropriate T interval\n% to search first.\n%\n% SPLINE_CUBIC_SET must have already been called to define the\n% values of YPP.\n%\n% In the LEFT interval, let RIGHT = LEFT+1. The form of the spline is\n%\n% SPL(T) =\n% A\n% + B * ( T - T(LEFT) )\n% + C * ( T - T(LEFT) )**2\n% + D * ( T - T(LEFT) )**3\n%\n% Here:\n% A = Y(LEFT)\n% B = ( Y(RIGHT) - Y(LEFT) ) / ( T(RIGHT) - T(LEFT) )\n% - ( YPP(RIGHT) + 2 * YPP(LEFT) ) * ( T(RIGHT) - T(LEFT) ) / 6\n% C = YPP(LEFT) / 2\n% D = ( YPP(RIGHT) - YPP(LEFT) ) / ( 6 * ( T(RIGHT) - T(LEFT) ) )\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% Reference:\n%\n% Carl de Boor,\n% A Practical Guide to Splines,\n% Springer Verlag, 1978.\n%\n% Parameters:\n%\n% Input, integer N, the number of knots.\n%\n% Input, real T(N), the knot values.\n%\n% Input, real Y(N), the data values at the knots.\n%\n% Input, real YPP(N), the second derivatives of the spline at\n% the knots.\n%\n% Input, integer LEFT, the suggested T interval to search.\n% LEFT should be between 1 and N-1. If LEFT is not in this range,\n% then its value will be ignored.\n%\n% Input, real TVAL, a point, typically between T(1) and T(N), at\n% which the spline is to be evalulated. If TVAL lies outside\n% this range, extrapolation is used.\n%\n% Output, real YVAL, YPVAL, YPPVAL, the value of the spline, and\n% its first two derivatives at TVAL.\n%\n% Output, integer LEFT_OUT, the actual interval in which TVAL lies.\n%\n left_out = left;\n%\n% Determine the interval [T(LEFT), T(RIGHT)] that contains TVAL.\n%\n% What you want from R8VEC_BRACKET3 is that TVAL is to be computed\n% by the data in interval {T(LEFT), T(RIGHT)].\n%\n left_out = r8vec_bracket3 ( n, t, tval, left_out );\n right = left_out + 1;\n%\n% In the interval LEFT_OUT, the polynomial is in terms of a normalized\n% coordinate ( DT / H ) between 0 and 1.\n%\n dt = tval - t(left_out);\n h = t(right) - t(left_out);\n\n yval = y(left_out) + dt * ( ( y(right) - y(left_out) ) / h ...\n - ( ypp(right) / 6.0 + ypp(left_out) / 3.0 ) * h ...\n + dt * ( 0.5 * ypp(left_out) ...\n + dt * ( ( ypp(right) - ypp(left_out) ) / ( 6.0 * h ) ) ) );\n\n ypval = ( y(right) - y(left_out) ) / h ...\n - ( ypp(right) / 6.0 + ypp(left_out) / 3.0 ) * h ...\n + dt * ( ypp(left_out) ...\n + dt * ( 0.5 * ( ypp(right) - ypp(left_out) ) / h ) );\n\n yppval = ypp(left_out) + dt * ( ypp(right) - ypp(left_out) ) / h;\n\n return\nend\n", "meta": {"author": "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_cubic_val2.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.7028391481680655}} {"text": "function b = r83_np_ml ( n, a_lu, x, job )\n\n%*****************************************************************************80\n%\n%% R83_NP_ML computes A * x or x * A, where A has been factored by R83_NP_FA.\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% 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% 30 January 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 at least 2.\n%\n% Input, real A_LU(3,N), the LU factors from R83_FA.\n%\n% Input, real X(N), the vector to be multiplied by A.\n%\n% Input, integer JOB, specifies the product to find.\n% 0, compute A * x.\n% nonzero, compute A' * x.\n%\n% Output, real B(N), the product A*x or A'*x.\n%\n b(1:n) = x(1:n);\n\n if ( job == 0 )\n%\n% Compute X := U * X\n%\n for i = 1 : n\n\n b(i) = a_lu(2,i) * b(i);\n\n if ( i < n )\n b(i) = b(i) + a_lu(1,i+1) * b(i+1);\n end\n\n end\n%\n% Compute X: = L * X.\n%\n for i = n : -1 : 2\n b(i) = b(i) + a_lu(3,i-1) * b(i-1);\n end\n\n else\n%\n% Compute X: = L' * X.\n%\n for i = 1 : n-1\n b(i) = b(i) + a_lu(3,i) * b(i+1);\n end\n%\n% Compute X: = U' * X.\n%\n for i = n : -1 : 2\n b(i) = a_lu(2,i) * b(i);\n b(i) = b(i) + a_lu(1,i) * b(i-1);\n end\n b(1) = a_lu(2,1) * b(1);\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/linplus/r83_np_ml.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7028391406731485}} {"text": "%input is defined in \"b\", ref is defined in \"n\" (e.g inp=[g*sin(45) g*cos(45) 0], ref=[0 0 1])\n%Cbn_est=(I-S(e))Cbn, e=E[inp_err]\n\nfunction [Cnb E]=align_wander(inp, ref)\n\n%Compute the dcm matrix\nCnb=align_vector(inp,ref);\n\nif (nargout==2) %Compute the error matrix \n E=zeros(3);\n ep=0.001;\n \n for i=1:3\n %ith perturbation\n inp_err=inp;\n inp_err(i)=inp_err(i)+ep;\n Cnb_err=align_vector(inp_err,ref);\n err=Cnb_err*Cnb'-eye(3);\n E(:,i)=[-err(2,3);err(1,3);-err(1,2)]/ep;\n end\n \nend\n\n\n\n\n\n\nfunction Cnb=align_vector(inp, ref)\n%normalize\ninp=inp/norm(inp);\nref=ref/norm(ref);\n\n%angles\ndotp=dot(ref,inp);\ncrosv=cross(ref,inp);\ncrosp=norm(crosv);\n\n\nif (crosp==0) %inp and ref is already aligned\n if (dotp>=0) %no rotation is necessary assert(dotp==1)\n Cnb=eye(3);\n else %assert(dotp==-1)\n %Find a vector that is ortogonal to ref\n if (ref(1)^2>ref(2)^2)\n vr_a=[-ref(3);0;ref(1)];\n else\n vr_a=[0;-ref(3);ref(2)];\n end\n vr_a=vr_a/norm(vr_a)*pi;\n \n %rotate around computed orthogonal vector\n Cnb=rot2dcm_v000(vr_a);\n end\nelse\n Cnb=eye(3)+skew(crosv)+((1-dotp)/crosp^2)*skew(crosv)*skew(crosv);\nend\n\nreturn;\n", "meta": {"author": "JzHuai0108", "repo": "ekfmonoslam", "sha": "443f6be744732453cdb90679abcaf5c962a6295e", "save_path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam", "path": "github-repos/MATLAB/JzHuai0108-ekfmonoslam/ekfmonoslam-443f6be744732453cdb90679abcaf5c962a6295e/instk/initialization/align_wander_v000.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.7027889767396712}} {"text": "%% INCREMENTAL TENSOR LEARNING\n%%% Incremental tensor analysis: Theory and applications (2008)\n%%% http://dl.acm.org/citation.cfm?id=1409621\nclose all; clear all; clc;\n\n%% LIBRARIES\naddpath('libs/poblano_toolbox_1.1');\naddpath('libs/tensor_toolbox_2.5');\naddpath('libs/nway331');\naddpath('libs/itl');\n\n%% TENSORS\nA = full(ttensor(tenrand([2,3,4]),{rand(10,2),rand(30,3), rand(40,4)}));\nB = full(ttensor(tenrand([2,3,4]),{rand(10,2),rand(30,3), rand(40,4)}));\nD = {A,A,A,A,A,B,B,B,B,B};\n\n%% Dynamic Tensor Decomposition (DTA) \n%%% Compute DTA with no forgetting factor\n[T,C] = DTA(D{1},[2,3,4]);\nfor i = 2:10\n [T,C] = DTA(D{i},[2,3,4],C);\n err = norm(full(T)-D{i})/norm(D{i});\n fprintf('tensor #%d has error %f\\n',i,err);\nend\n%%% Compute DTA with forgetting factor alpha = 0.1\n[T,C] = DTA(D{1},[2,3,4]);\nalpha = 0.1;\nfor i = 2:10\n [T,C] = DTA(D{i},[2,3,4],C, alpha);\n err = norm(full(T)-D{i})/norm(D{i});\n fprintf('tensor #%d has error %f\\n',i,err);\nend\n\n%% Streaming Tensor Decomposition (STA)\n%%% Compute STA with no forgetting factor\n[T,S] = STA(D{1},[2,3,4]);\nfor i = 2:10\n [T,S] = STA(D{i},[2,3,4],T,S);\n err = norm(full(T)-D{i})/norm(D{i});\n fprintf('tensor #%d has error %f\\n',i,err);\nend\n%%% Compute STA with forgetting factor alpha = 0.9\n[T,S] = STA(D{1},[2,3,4]);\nalpha = 0.9;\nfor i = 2:10\n [T,S] = STA(D{i},[2,3,4],T,S, alpha);\n err = norm(full(T)-D{i})/norm(D{i});\n fprintf('tensor #%d has error %f\\n',i,err);\nend\n\n%% Window-based Tensor Decomposition (WTA)\n[T,C] = WTA(D{1},[2,3,4]);\nfor i = 2:10\n [T,C] = WTA(D{i},[2,3,4],tensor(T));\n err = norm(full(T)-D{i})/norm(D{i});\n fprintf('tensor #%d has error %e\\n',i,err);\nend\n", "meta": {"author": "andrewssobral", "repo": "mtt", "sha": "0152a77df09f24af4c294f46845931e4e0e63b55", "save_path": "github-repos/MATLAB/andrewssobral-mtt", "path": "github-repos/MATLAB/andrewssobral-mtt/mtt-0152a77df09f24af4c294f46845931e4e0e63b55/tensor_demo_inclearn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092016, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.702750667816093}} {"text": "% test_surface_param.m\n\n% Author: Ramon Casero \n% Copyright © 2013-2014 University of Oxford\n% Version: 0.6.3\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%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Open surface for 4 cardiac valves\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nload('data/valve-annula-points-009.mat');\n\n% plot points\nhold off\nsubplot(2, 2, 1)\nplot3(x(:, 1), x(:, 2), x(:, 3), '*')\naxis equal\n\n% compute simple XY parametrization\nuv0 = surface_param(x, 'xy');\nd0 = dmatrix(uv0', uv0', 'euclidean');\n\n% plot parametrization\nsubplot(2, 2, 2)\nhold off\nplot(uv0(:, 1), uv0(:, 2), '.')\naxis equal\ntitle('XY')\n\n\n% compute PCA parametrization\nuv = surface_param(x, 'pca');\n\n% plot parametrization, aligned with the XY case\n[~, uv] = procrustes(uv0, uv, 'Scaling', false);\nsubplot(2, 2, 3)\nhold off\nplot(uv(:, 1), uv(:, 2), '.')\naxis equal\ntitle('PCA')\n\n\n% compute Isomap parametrization\nparam.type = 'isomap';\nparam.neigh = 'epsilon';\nparam.size = .0020;\nparam.d = dmatrix(x', x', 'euclidean');\nuv = surface_param(x, param);\n\n% plot parametrization\n[~, uv] = procrustes(uv0, uv, 'Scaling', false);\nsubplot(2, 2, 4)\nhold off\nplot(uv(:, 1), uv(:, 2), '.')\naxis equal\ntitle('Isomap')\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Open planar triangular mesh to compare isomap and MDS map\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% quadrangular mesh split into asymmetric triangles\n\n% create rectangle with triangular mesh\n[tri, x] = surface_tridomain('rect', 'step', 1/10, [0 0], [1 1/5*3]);\nx(:, end+1) = 0;\n\n% plot original mesh and parametrization\ncon = dmatrix_mesh(tri);\nhold off\ngplot(con, x(:, 1:2))\n\n%% Isomap on a triangular mesh\n% note that we need to compute the local distances on the mesh, and then\n% apply Dijkstra. If we don't provide the distance matrix, by default\n% surface_param() will compute distances between all pairs of vertices\nclear param\nparam.type = 'isomap';\nparam.d = dmatrix_mesh(tri, x);\nparam.d = dijkstra(param.d, 1:length(param.d));\nuv = surface_param(x, param);\n\n% rigid registration to overlap the solution with the original data\n[~, uv] = procrustes(x, uv, 'Scaling',false);\n\n% add parametrization to the plot\nhold on\ngplot(con, uv, 'r')\n\n\n%% Open classic MDSmap on the same triangular mesh\nclear param\nparam.type = 'cmdsmap';\nparam.options.constraint_map = 0.4 * ones(size(x, 1), 1); % trigger warning\nparam.options.end_points = [1 2 3]; % trigger warning\nparam.options.nb_iter_max = 4; % trigger warning\nparam.tri = tri;\nuv = surface_param(x, param);\n\n% rigid registration to overlap the solution with the original data\n[~, uv] = procrustes(x, uv, 'Scaling',false);\n\n% add parametrization to the plot\nhold on\ngplot(con, uv, 'g')\n\n%% check that MDSmap with Dijkstra is the same as Isomap\nclear param\nparam.type = 'cmdsmap';\nparam.options.constraint_map = 0.4 * ones(1, size(x, 1)); % trigger warning\nparam.options.end_points = [1 2 3]; % trigger warning\nparam.options.nb_iter_max = 4; % trigger warning\n[~, param.d] = dmatrix_mesh(tri, x, 'dijkstra');\nuv = surface_param(x, param);\n\n% rigid registration to overlap the solution with the original data\n[~, uv] = procrustes(x, uv, 'Scaling',false);\n\n% add parametrization to the plot\n% it is expected that this perfectly overlaps the Isomap result computed\n% above\nhold on\ngplot(con, uv, 'k')\n\n%% lmdscale (MDSmap with local neighbourhood)\nclear param\nparam.type = 'lmdscale';\nparam.tri = tri;\nparam.options.constraint_map = 0.4 * ones(size(x, 1), 1);\nparam.options2.MaxIter = 100;\nparam.options2.MaxInc = .01;\n[uv, out] = surface_param(x, param);\nout.stopCondition\n\n% rigid registration to overlap the solution with the original data\n[~, uv] = procrustes(x, uv, 'Scaling',false);\n\n% add parametrization to the plot\n% it is expected that this perfectly overlaps the Isomap result computed\n% above\nhold on\ngplot(con, uv, 'c')\n\n% plot error\nfigure\nplot(out.err.maxinc)\nhold on\nplot(out.err.medinc)\n\n% plot stress\nhold off\nplot(out.err.stress1)\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Closed surface from scattered point set\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n%% create a closed surface triangular mesh of a left ventricle\n\n% seed the random generator so that we always get the same points\nrng(0)\n\n% load low resolution segmentation of LV, with detail removed\nscimat = scimat_load('data/008-lv-resampled-0_31.mha');\n\n% keep perimeter only\nscimat.data = bwperim(scimat.data);\n\n% coordinates of perimeter points\nidx = find(scimat.data);\n[r, c, s] = ind2sub(size(scimat.data), idx);\nx = scimat_index2world([r c s], scimat);\n\n% subsample boundary points\nx = x(randi(size(x, 1), round(size(x, 1)/5), 1), :);\n\n% order a bit the vertices, so that nearby vertices are close\nx = sortrows(x);\n\n% plot point set\nsubplot(2, 2, 1)\nhold off\nplot3(x(:, 1), x(:, 2), x(:, 3), '.')\naxis equal\n\n% mesh the points using an alpha-shape\n[~, s] = alphavol(x, scimat.axis(1).spacing * 40);\ntri = s.bnd;\n\n% check that we don't have non-manifold vertices\nidx = tri_find_nonmanifold_vertex(tri, x, scimat);\nif (nnz(idx))\n error('Assertion fail: mesh has non-manifold vertices')\nend\n\n% remove points not connected to any triangle\n[tri, x] = tri_squeeze(tri, x);\n\n% plot mesh\nsubplot(2, 2, 2)\nhold off\ntrisurf(tri, x(:, 1), x(:, 2), x(:, 3));\naxis equal\n\n% PCA-normalization of mesh\nx = pca_normalize(x);\n\n% plot mesh\nsubplot(2, 2, 3)\nhold off\ntrisurf(tri, x(:, 1), x(:, 2), x(:, 3));\naxis equal\n\n% median radius of the points\nsphrad = median(sqrt(sum(x.^2, 2)))\n\n%% sphproj: simple projection on a sphere around the centroid\nclear param\nparam.type = 'sphproj';\n[latlon, out] = surface_param(x, param);\nout.medrad\n\n% rigid registration to overlap the solution with the original data\n[xx, yy, zz] = sph2cart(latlon(:, 2), latlon(:, 1), sphrad);\n[~, x1] = procrustes(x, [xx, yy, zz], 'Scaling',false);\n\n% plot result\nsubplot(1, 2, 1)\nhold off\ntrisurf(tri, x(:, 1), x(:, 2), x(:, 3));\naxis equal\nsubplot(1, 2, 2)\nhold off\ntrisurf(tri, x1(:, 1), x1(:, 2), x1(:, 3))\ntitle('sphproj')\naxis equal\n\n%% CALD\n\n% % using the SPHARM-MAT toolbox GUI\n% faces = tri;\n% vertices = x;\n% save('/tmp/bar_obj.mat', 'faces', 'vertices')\n% SPHARM_MAT\n% load('/tmp/bar_CALD_smo.mat')\n\nclear param\nparam.type = 'cald';\nparam.tri = tri;\nparam.options.MeshGridSize = 50;\nparam.options.MaxSPHARMDegree = 6;\nparam.options.Tolerance = 2;\nparam.options.Smoothing = 2;\nparam.options.Iteration = 100;\nparam.options.LocalIteration = 10;\nlatlon = surface_param(x, param);\n\n% check for self-intersections\nbad = cgal_check_self_intersect(param.tri, x);\nnnz(bad>0)\n\n% rigid registration to overlap the solution with the original data\n[xx, yy, zz] = sph2cart(latlon(:, 2), latlon(:, 1), sphrad);\n[~, x1] = procrustes(x, [xx, yy, zz], 'Scaling',false);\n\n% plot parametrization\nsubplot(1, 2, 2)\nhold off\ntrisurf(tri, x1(:, 1), x1(:, 2), x1(:, 3))\ntitle('CALD')\naxis equal\n\n%% smdscale\n\n% compute spherical MDSmap parametrization, no need the constrain the\n% distance matrix more\nclear param\nparam.type = 'smdscale';\nparam.tri = tri;\nparam.dmethod = 'fastmarching';\n% param.options.constraint_map = .2 * sphrad * ones(size(x, 1), 1);\nparam.sphrad = sqrt(sum(cgal_trifacet_area(tri, x))/4/pi);\nparam.init = 'random';\nparam.options2.MaxIter = 15;\nparam.options2.MaxAlpha = .01 / 180 * pi;\n[uv, out] = surface_param(x, param);\nout.stopCondition\nlat = uv(:, 1);\nlon = uv(:, 2);\n\n% plot parametrization\nsubplot(1, 2, 2)\nhold off\n[xx, yy, zz] = sph2cart(lon, lat, param.sphrad);\n[~, x1] = procrustes(x, [xx, yy, zz], 'Scaling', false);\ntrisurf(param.tri, x1(:, 1), x1(:, 2), x1(:, 3));\ntitle('smdscale')\naxis equal\n\n% check for self-intersections\nbad = cgal_check_self_intersect(param.tri, x1);\nnnz(bad>0)\n\n% plot error\nfigure\nsubplot(2, 2, 1)\nhold off\nplot(out.err.rawstress)\ntitle('Raw stress')\nsubplot(2, 2, 2)\nhold off\nplot(out.err.stress1)\ntitle('Stress1')\nsubplot(2, 1, 2)\nhold off\nplot(out.err.maxalpha)\nhold on\nplot(out.err.medalpha)\ntitle('Alpha')\n\n% TODO:\n% %% compare spherical Isomap and CALD\n% \n% % compute great circle distances for CALD\n% dsphCALD = zeros(size(out.dsph));\n% for I = 1:length(dsphCALD)\n% dsphCALD(:, I) = distance(latCALD(I), lonCALD(I), latCALD, lonCALD, ...\n% [out.sphrad 0], 'radians');\n% end\n% \n% % plot distances to optimize vs spherical distances for CALD\n% subplot(2, 1, 1)\n% hold off\n% plot(d(:), dsphCALD(:), '.')\n% hold on\n% plot([0 max(d(:))], [0 max(d(:))], 'r', 'LineWidth', 2)\n% title('CALD')\n% xlabel('Distance on the mesh')\n% ylabel('Distance on the spherical parametrization')\n% axis equal\n% \n% \n% % plot boxplots with the distance ratios\n% N = numel(d);\n% subplot(1, 1, 1)\n% hold off\n% boxplot([d(:)-dsphCALD(:) ; d(:)-out.dsph(:)], ...\n% [ones(N, 1); 2*ones(N, 1)], 'labels', {'CALD', 'Sph Isomap'}, ...\n% 'notch', 'on')\n% title('Target distance - distance on spherical parametrization')\n", "meta": {"author": "vigente", "repo": "gerardus", "sha": "4d7c5195b826967781f1bb967872410e66b7cd3d", "save_path": "github-repos/MATLAB/vigente-gerardus", "path": "github-repos/MATLAB/vigente-gerardus/gerardus-4d7c5195b826967781f1bb967872410e66b7cd3d/matlab/test/test_surface_param.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.7027142126745203}} {"text": "function x = Inv_GUSFT_CG(b,lambda,MaxIts,ErrTol,Pre,x0,mu)\n% Inv_UtU_CG: Invert GUSFT_Toeplitz. \n% Usage:\n% x = Inv_GUSFT_CG(b,lambda,MaxIts,ErrTol,Pre,x0,mu);\n% Inputs:\n% b vector of length n\n% lambda vector of Fourier multipliers; length 2*n-1\n% MaxIts Maximum number of CG iterations. Default 6.\n% ErrTol Error tolerance. Default 1.e-9.\n% Pre Boolean variable. Pre = 1 if we apply a preconditioner\n% x0 Initial guess\n% mu Variable for use with the preconditioner\n% Outputs:\n% x Vector of length n\n% Description \n% Performs the inverse UtU where U is the nouniform FT. This is\n% an approximate inverse which uses a conjugate gradient\n% solver. Each iteration uses GUSFT_Toeplitz (which can be\n% applied by merely using only 2 FFTs). \n% See Also\n% GUSFT_Toeplitz\n%\n% By Emmanuel candes, 2003-2004\n\nif (nargin < 2)\n error('Not enough input arguments.');\nend\n\nif (nargin < 3) | isempty(MaxIts)\n MaxIts = 6;\nend\n\nif (nargin < 4) | isempty(ErrTol)\n ErrTol = 1.e-9;\nend\n\nif (nargin < 5) | isempty(Pre)\n\tPre = 0;\nend\n\nif (nargin < 6) | isempty(x0)\n\tx0 = b;\nend\n\nif (nargin < 7) | isempty(mu)\n\tmu = ones(size(b));\nend\n\n% Initialization\nxk = x0;\n\nif MaxIts > 0,\n\t temp = GUSFT_Toeplitz(xk,lambda);\n\t\n\t rk=b-temp; \n\t if Pre == 0,\n\t dk = rk;\n\t else\n\t dk=ApplyCirculantPrecond(rk,mu); \n\t end\t \t \n\n\t% Conjugate gradient iteration\n\tfor j=1:MaxIts,\n\t\t perr=max(abs(rk));\n\t\t fprintf(['Iteration ',int2str(j-1),': Residual error=']);\n\t\t fprintf('%f\\n',perr);\n\t\n\t\t if perr>ErrTol,\t\t\t\n\t\t\t temp = GUSFT_Toeplitz(dk,lambda);\n\t\t\t a0 = sum(conj(rk).*dk);\n\t\t\t a1 = sum(conj(dk).*temp);\n\t\n\t\t\t % Update x and residual \n\t\t\t a=a0/a1;\n\t\t\t xk=xk+a*dk;\t\t\n\t\t\t rk=rk-a*temp;\n\t\t\t\n\t\t\t % Update search direction\n\t\t\t if Pre == 0,\n\t\t\t b = sum(abs(rk.^2))/a0;\n\t\t\t dk = rk+b*dk;\n\t\t\t else\n\t\t\t rkp = ApplyCirculantPrecond(rk,mu); \n\t\t\t b = sum(conj(rkp).*rk)/a0;\n\t\t\t dk = rkp+b*dk;\n\t\t\t end \n\t\t end\n\tend\nend\n\nx = xk;\n\n% References: Jonathan R. Shewchuk \"An introduction to the Conjugate\n% Gradient Method Without the Agonizing Pain\"\n%\n% Amir Averbuch and David L. Donoho \"BeamLab 200\"\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_TRAFO/CurveLab-2.1.3/fdct_usfft_matlab/USFFT/Inv_GUSFT_CG.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7027142067209479}} {"text": "function Z = inormal(varargin)\n% Applies a rank-based inverse normal transformation.\n% \n% Usage: Z = inormal(X)\n% inormal(X,c)\n% inormal(X,method)\n% inormal(X,...,quanti)\n%\n% Inputs:\n% X : Original data. Can be a vector or an array.\n% c : Constant to be used in the transformation.\n% Default c=3/8 (Blom).\n% method : Method to choose c. Accepted values are:\n% 'Blom' (c=3/8),\n% 'Tukey' (c=1/3),\n% 'Bliss', (c=1/2) and\n% 'Waerden' or 'SOLAR' (c=0).\n% quanti : All data guaranteed to be quantitative and\n% without NaN?\n% This can be a true/false. If true, the function\n% runs much faster if X is an array.\n% Default is false.\n%\n% Outputs:\n% Z : Transformed data.\n% \n% References:\n% * Van der Waerden BL. Order tests for the two-sample\n% problem and their power. Proc Koninklijke Nederlandse\n% Akademie van Wetenschappen. Ser A. 1952; 55:453-458\n% * Blom G. Statistical estimates and transformed\n% beta-variables. Wiley, New York, 1958.\n% * Tukey JW. The future of data analysis.\n% Ann Math Stat. 1962; 33:1-67.\n% * Bliss CI. Statistics in biology. McGraw-Hill,\n% New York, 1967.\n%\n% _____________________________________\n% Anderson M. Winkler\n% Yale University / Institute of Living\n% Aug/2011 (first version)\n% Jun/2014 (this version)\n% http://brainder.org\n\n\n% Accept inputs & defaults\nc0 = 3/8; % Default (Blom, 1958)\nquanti = false;\nif nargin == 1,\n c = c0;\nelseif nargin > 1 && ischar(varargin{2}),\n switch lower(varargin{2}),\n case 'blom'\n c = 3/8;\n case 'tukey'\n c = 1/3;\n case 'bliss'\n c = 1/2;\n case 'waerden'\n c = 0;\n case 'solar'\n c = 0; % SOLAR is the same as Van der Waerden\n otherwise\n error('Method %s unknown. Use either ''Blom'', ''Tukey'', ''Bliss'', ''Waerden'' or ''SOLAR''.',varargin{2});\n end\nelseif nargin > 1 && isscalar(varargin{2}),\n c = varargin{2}; % For a user-specified value for c\nend\nif nargin == 3,\n quanti = varargin{3};\n if isempty(varargin{2}),\n c = c0;\n end\nend\nX = varargin{1};\n\n% If the trait is quantitative, avoid the loop\nif quanti,\n % Get the rank for each value\n [~,iX] = sort(X);\n [~,ri] = sort(iX);\n \n % Do the actual transformation\n N = size(X,1);\n p = ((ri-c)/(N-2*c+1));\n Z = sqrt(2)*erfinv(2*p-1);\n \nelse\n Z = nan(size(X));\n for x = 1:size(X,2),\n \n % Remove NaNs\n XX = X(:,x);\n ynan = ~isnan(XX);\n XX = XX(ynan);\n \n % Get the rank for each value\n [~,iX] = sort(XX);\n [~,ri] = sort(iX);\n \n % Do the actual transformation\n N = size(XX,1);\n p = ((ri-c)/(N-2*c+1));\n Y = sqrt(2)*erfinv(2*p-1);\n \n % Check for repeated values\n [U,~,IC] = unique(XX);\n if numel(U) < N,\n sIC = sort(IC);\n dIC = diff(vertcat(sIC,1));\n U = unique(sIC(~dIC));\n for u = 1:numel(U),\n Y(IC == U(u)) = mean(Y(IC == U(u)));\n end\n end\n \n % Put the NaNs back\n Z(ynan,x) = Y;\n end\nend\n", "meta": {"author": "yetianmed", "repo": "subcortex", "sha": "76179cf552b773e79b06a54568eae1fdd13722f4", "save_path": "github-repos/MATLAB/yetianmed-subcortex", "path": "github-repos/MATLAB/yetianmed-subcortex/subcortex-76179cf552b773e79b06a54568eae1fdd13722f4/functions/inormal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.7027141983671314}} {"text": "function xa = binom ( x, xx, npl, m, nt )\n\n%*****************************************************************************80\n%\n%% BINOM: binomial expansion series for the (-1/M) power of a Chebyshev series.\n%\n% Discussion:\n%\n% This routine uses a certain number of terms of the binomial expansion \n% series to estimate the (-1/M) power of a given Chebyshev series. \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 X(NPL), the given Chebyshev series.\n%\n% Input, real XX(NPL), an initial estimate for\n% the Chebyshev series for the input function raised to the (-1/M) power.\n%\n% Input, integer NPL, the number of terms in the \n% Chebyshev series.\n%\n% Input, integer M, defines the exponent, (-1/M).\n% 0 < M.\n%\n% Input, integer NT, the number of terms of the binomial\n% series to be used.\n%\n% Output, real XA(NPL), the estimated Chebyshev series\n% for the input function raised to the (-1/M) power.\n%\n xa = zeros ( npl, 1 );\n\n dm = m;\n alfa = - 1.0 / dm;\n\n ww(1:npl) = x(1:npl);\n\n for k = 1 : m\n\n w2 = mltply ( ww, xx, npl );\n\n ww(1:npl) = w2(1:npl);\n\n end\n\n ww(1) = ww(1) - 2.0;\n\n xa(1) = 2.0;\n xa(2:npl) = 0.0;\n\n w3(1) = 2.0;\n w3(2:npl) = 0.0;\n\n for k = 2 : nt\n\n dkmm = k - 1;\n dkm2 = k - 2;\n coef = ( alfa - dkm2 ) / dkmm;\n\n w2 = mltply ( w3, ww, npl );\n\n w3(1:npl) = w2(1:npl) * coef;\n\n xa(1:npl) = xa(1:npl) + w3(1:npl);\n\n end\n\n w2 = mltply ( xa, xx, npl );\n\n xa(1:npl) = w2(1:npl);\n\n return\nend\n", "meta": {"author": "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/binom.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7027141979827699}} {"text": "function [count edges mid loc] = histcn(X, varargin)\n% function [count edges mid loc] = histcn(X, edge1, edge2, ..., edgeN)\n%\n% Purpose: compute n-dimensional histogram\n%\n% INPUT\n% - X: is (M x N) array, represents M data points in R^N\n% - edgek: are the bin vectors on dimension k, k=1...N.\n% If it is a scalar (Nk), the bins will be the linear subdivision of\n% the data on the range [min(X(:,k)), max(X(:,k))] into Nk\n% sub-intervals\n% If it's empty, a default of 32 subdivions will be used\n%\n% OUTPUT\n% - count: n-dimensional array count of X on the bins, i.e.,\n% count(i1,i2,...,iN) = cardinal of X such that\n% edge1(i1) <= X(:,i1) < edge1(i1)+1 and\n% ...\n% edgeN(iN) <= X(:,iN) < edgeN(iN)+1\n% - edges: (1 x N) cell, each provides the effective edges used in the\n% respective dimension\n% - mid: (1 x N) cell, provides the mid points of the cellpatch used in\n% the respective dimension\n% - loc: (M x N) array, index location of X in the bins. Points have out\n% of range coordinates will have zero at the corresponding dimension.\n%\n% DATA ACCUMULATE SYNTAX:\n% [ ... ] = histcn(..., 'AccumData', VAL);\n% where VAL is M x 1 array. Each VAL(k) corresponds to position X(k,:)\n% will be accumulated in the cell containing X. The accumulate result\n% is returned in COUNT.\n% NOTE: Calling without 'AccumData' is similar to having VAL = ones(M,1)\n%\n% [ ... ] = histcn(..., 'AccumData', VAL, 'FUN', FUN);\n% applies the function FUN to each subset of elements of VAL. FUN is\n% a function that accepts a column vector and returns\n% a numeric, logical, or char scalar, or a scalar cell. A has the same class\n% as the values returned by FUN. FUN is @SUM by default. Specify FUN as []\n% for the default behavior.\n%\n% Usage examples:\n% M = 1e5;\n% N = 3;\n% X = randn(M,N);\n% [N edges mid loc] = histcn(X);\n% imagesc(mid{1:2},N(:,:,ceil(end/2)))\n%\n% % Compute the mean on rectangular patch from scattered data\n% DataSize = 1e5;\n% Lat = rand(1,DataSize)*180;\n% Lon = rand(1,DataSize)*360;\n% Data = randn(1,DataSize);\n% lat_edge = 0:1:180;\n% lon_edge = 0:1:360;\n% meanData = histcn([Lat(:) Lon(:)], lat_edge, lon_edge, 'AccumData', Data, 'Fun', @mean);\n%\n% See also: HIST, ACCUMARRAY\n% \n% Bruno Luong: \n% Last update: 25/August/2011\n\nif ndims(X)>2\n error('histcn: X requires to be an (M x N) array of M points in R^N');\nend\nDEFAULT_NBINS = 32;\n\nAccumData = [];\nFun = {};\n\n% Looks for where optional parameters start\n% For now only 'AccumData' is valid\nsplit = find(cellfun('isclass', varargin, 'char'), 1, 'first');\nif ~isempty(split)\n for k = split:2:length(varargin)\n if strcmpi(varargin{k},'AccumData')\n AccumData = varargin{k+1}(:);\n elseif strcmpi(varargin{k},'Fun')\n Fun = varargin(k+1); % 1x1 cell\n end\n end\n varargin = varargin(1:split-1);\nend\n\n% Get the dimension\nnd = size(X,2);\nedges = varargin;\nif nd0, 2);\nif ~isempty(AccumData)\n count = accumarray(loc(hasdata,:), AccumData(hasdata), sz, Fun{:});\nelse\n count = accumarray(loc(hasdata,:), 1, sz);\nend\n\nreturn\n\nend % histcn\n", "meta": {"author": "buzsakilab", "repo": "buzcode", "sha": "2d700a38b3c2a860ad1333be90f14d7a37a72815", "save_path": "github-repos/MATLAB/buzsakilab-buzcode", "path": "github-repos/MATLAB/buzsakilab-buzcode/buzcode-2d700a38b3c2a860ad1333be90f14d7a37a72815/utilities/histcn.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.7027141959982456}} {"text": "function [Fn,Ln] = fibs3(n)\n% fibs: vpi tool to efficiently compute the n'th Fibonacci number and the n'th Lucas number\n% usage: [Fn,Ln] = fibs3(n)\n%\n% For efficiency, fibs3 uses a variety of tricks to\n% maximize speed. While computation of fibonacci numbers\n% is commonly done recursively, fibs3 does so using a\n% direct iterative scheme given the binary representation\n% of n. In addition, several Fibonacci and Lucas number\n% identities are employed to maximize throughput.\n%\n% The methods employed by fibs3 will be O(log2(n)) in time.\n\nif (nargin~=1) || (numel(n) ~= 1) || (n~=round(n)) || (abs(n) > 2^53)\n error('n must be scalar and an integer, <= 2^53 in absolute value')\nend\n\n% much faster if n is not a vpi but a double.\n% also, we don't need to worry about n being\n% larger than 2^53, as this would have a vast\n% number of digits.\nn = double(n);\n\n% ensure that n is positive, handle the negative\n% cases later.\nnsign = sign(n);\nn = abs(n);\n\n% get the binary representation of n. Thus\n% nbin is a character vector, of length\n% ceil(log2(n)).\nnbin = dec2bin(n);\n\n% get the 4 highest order bits from nbin\nk = min(numel(nbin),4);\n\n% zero is a special case to stop at.\nif n == 0\n Fn = vpi(0);\n Ln = vpi(2);\n return\nelse\n % start the sequence from the top\n % few bits of n.\n nhigh = bin2dec(nbin(1:k));\n Fseq = [1 1 2 3 5 8 13 21 34 55 89 144 233 377 610];\n Lseq = [1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364];\n \n Fn = vpi(Fseq(nhigh));\n Ln = vpi(Lseq(nhigh));\nend\n\n% We need to loop forwards. Essentially, we started\n% with the highest order bit(s) of the binary representation\n% for n. Look at each successively lower order bit.\n% If the next bit is 0, then we are essentially doubling\n% the index at this step. If the next bit is odd, then\n% we are moving to 2*n+1.\nfor k = 5:numel(nbin)\n bit = (nbin(k) == '1');\n if bit\n % the next bit was odd. Use\n % a 2*n+1 rule to step up.\n F2n = Fn.*Ln;\n % we want to do this...\n % L2n = (5 .*Fn.*Fn + Ln.*Ln)./2;\n % Instead use the identity that\n % 5F(n)^2 + L(n)^2 = 2*L(n)^2 + 4*(-1)^(n+1)\n % to make that expression more efficiently\n % computed. See that the form used below\n % has only a single multiplication between a\n % pair of large integers, whereas the prior\n % form for L2n would have had several multiples\n % as well as a divide.\n L2n = Ln.*Ln + 2*(-1)^(nhigh+1);\n \n Fn = (L2n + F2n)./2;\n Ln = (5 .*F2n + L2n)./2;\n else\n % the next bit was even. Use the 2*n\n % rule to step up.\n F2n = Fn.*Ln;\n Ln = Ln.*Ln + 2*(-1)^(nhigh+1);\n Fn = F2n;\n end\n \n % update the top bits of n\n nhigh = 2*nhigh + bit;\nend\n\n% if n was negative, then we may need to apply a\n% sign change to Fn and Ln.\nif nsign < 0\n if iseven(n)\n Fn = (-nsign).*Fn;\n Ln = nsign.*Ln;\n else\n Fn = nsign.*Fn;\n Ln = (-nsign).*Ln;\n end\nend\n\n% ==================================\n% End mainline, begin subfunctions.\n% ==================================\n\nfunction result = iseven(n)\n% tests if a scalar value is an even integer\nif isnumeric(n)\n result = (mod(n,2) == 0);\nelseif isa(n,'vpi')\n % must have been a vpi\n result = (mod(trailingdigit(n,1),2) == 0);\nelse\n error('n must be either numeric or vpi')\nend\n\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34766-the-fibonacci-sequence/FibonacciSequence/fibs3.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.7026905620688678}} {"text": "function [F,L,Qc,H,Pinf,dF,dQc,dPinf,params] = cf_exp_to_ss(magnSigma2, lengthScale)\n% CF_EXP_TO_SS - Exponential covariance functions to state space\n%\n% Syntax:\n% [F,L,Qc,H,Pinf,dF,dQc,dPinf,params] = cf_exp_to_ss(magnSigma2, lengthScale)\n%\n% In:\n% magnSigma2 - Magnitude scale parameter (default: 1)\n% lengthScale - Length scale parameter (default: 1)\n%\n% Out:\n% F - Feedback matrix\n% L - Noise effect matrix\n% Qc - Spectral density of white noise process w(t)\n% H - Observation model matrix\n% Pinf - Covariance of the stationary process\n% dF - Derivatives of F w.r.t. parameters\n% dQc - Derivatives of Qc w.r.t. parameters\n% dPinf - Derivatives of Pinf w.r.t. parameters\n% params - Input and output parameter information\n%\n% Description:\n% This function converts the exponential (Ornstein-Uhlenbeck) covariance \n% function to state space models. The covariance function \n% parametrization is as follows\n%\n% k(tau) = magnSigma2 exp(-|tau|/lengthScale),\n%\n% where magnSigma2 is the magnitude scale parameter, lengthScale the \n% distance scale parameter, and tau the time difference between states, \n% tau = t-t'.\n% This function takes the covariance function parameters as inputs and\n% outputs the corresponding state space model matrices. The state space\n% model is given as follows in terms of a stochastic differential\n% equation\n%\n% df(t)/dt = F f(t) + L w(t),\n%\n% where w(t) is a white noise process with spectral denisty Qc. The\n% observation model for discrete observation y_k of f(t_k) at step k, \n% is as follows \n%\n% y_k = H f(t_k) + r_k, r_k ~ N(0, R),\n%\n% where r_k is the Gaussian measurement noise with covariance R.\n% Pinf is the stationary covariance, where the value of Pinf(i,j), \n% is defined as follows\n% \n% Pinf(i,j) = E[(f_i(t)-E[f_i(t)])(f_j(t)-E[f_j(t)])],\n%\n% where f_i(t) is component i of state vector f(t).\n% Derivatives: All have same form. For example, dF has the following\n% form:\n%\n% dF(:,:,1) = dF/d(magnSigma2 = input parameter_1),\n% dF(:,:,i) = dF/d(input parameter_i).\n%\n% References:\n%\n% [1] Simo Sarkka, Arno Solin, Jouni Hartikainen (2013).\n% Spatiotemporal learning via infinite-dimensional Bayesian\n% filtering and smoothing. IEEE Signal Processing Magazine,\n% 30(4):51-61.\n%\n% [2] Jouni Hartikainen and Simo Sarkka (2010). Kalman filtering and \n% smoothing solutions to temporal Gaussian process regression \n% models. Proceedings of IEEE International Workshop on Machine \n% Learning for Signal Processing (MLSP).\n%\n% See also:\n% COV_EXP, SPEC_EXP\n%\n% Copyright:\n% 2012-2014 Arno Solin\n% 2013-2014 Jukka Koskenranta\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%% Apply defaults\n\n % Check if magnSigm2 is given\n if nargin < 1 || isempty(magnSigma2), magnSigma2 = 1; end\n\n % Check if lengthScale is given\n if nargin < 2 || isempty(lengthScale), lengthScale = 1; end\n \n \n%% Form state space model\n\n % Feedback matrix \n F = -1/lengthScale;\n\n % Noise effect matrix\n L = 1;\n\n % Spectral density\n Qc = 2*magnSigma2/lengthScale;\n\n % Observation model \n H = 1;\n\n \n%% Stationary covariance\n \n % Calculate Pinf only if requsted\n if nargout > 4,\n Pinf = magnSigma2;\n end\n\n \n%% Calculate derivatives\n\n % Calculate derivatives only if requested\n if nargout > 5\n\n % Derivative of F w.r.t. parameter magnSigma2\n dFmagnSigma2 = 0;\n \n % Derivative of F w.r.t parameter lengthScale\n dFlengthScale = 1/lengthScale^2;\n \n % Derivative of Qc w.r.t. parameter magnSigma2\n dQcmagnSigma2 = 2/lengthScale;\n \n % Derivative of Qc w.r.t. parameter lengthScale\n dQclengthScale = -2*magnSigma2/lengthScale^2;\n \n % Derivative of Pinf w.r.t. parameter magnSigma2\n dPinfmagnSigma2 = 1;\n \n % Derivative of Pinf w.r.t. parameter lengthScale\n dPinflengthScale = 0;\n \n % Stack all derivatives\n dF = zeros(1,1,2); \n dQc = zeros(1,1,2); \n dPinf = zeros(1,1,2);\n \n dF(:,:,1) = dFmagnSigma2;\n dF(:,:,2) = dFlengthScale;\n dQc(:,:,1) = dQcmagnSigma2;\n dQc(:,:,2) = dQclengthScale;\n dPinf(:,:,1) = dPinfmagnSigma2;\n dPinf(:,:,2) = dPinflengthScale;\n \n end\n \n \n%% Return parameter names\n\n % Only return if requested\n if nargout > 8\n \n % Stationarity\n p.stationary = true;\n \n % Input parameter information \n p.in{1}.name = 'magnSigma2'; p.in{1}.default = 1; p.in{1}.opt = true;\n p.in{2}.name = 'lengthScale'; p.in{2}.default = 1; p.in{2}.opt = true;\n \n % Return parameter setup\n params = p;\n \n end\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/cf_exp_to_ss.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.7026905578204214}} {"text": "% This example shows how to use the stretchmesh function to expand the\n% size of the computation window at the edges without increasing the\n% number of gridpoints. It uses the same example waveguide\n% structure considered in 'basic-semivector.m'\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\nfprintf (1,'generating index mesh...\\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% Stretch the 40 gridpoints on the south and east edges of the\n% computational window by factors of 4 and 3, respectively.\n\n[x,y,xc,yc,dx,dy] = stretchmesh(x,y,[0,40,40,0],[1,4,3,1]);\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", "meta": {"author": "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/nonuniform_mesh_semivector.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7026858437044459}} {"text": "%[2012]-\"Flower pollination algorithm for global optimization\"\n\n% (9/12/2020)\n\nfunction FPA = jFlowerPollinationAlgorithm(feat,label,opts)\n% Parameters\nlb = 0;\nub = 1; \nthres = 0.5; \nbeta = 1.5; % levy component\nP = 0.8; % switch probability\n\nif isfield(opts,'N'), N = opts.N; end\nif isfield(opts,'P'), P = opts.P; end \nif isfield(opts,'T'), max_Iter = opts.T; end\nif isfield(opts,'beta'), beta = opts.beta; 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); \nfor i = 1:N\n for d = 1:dim\n X(i,d) = lb + (ub - lb) * rand();\n end\nend \n% Compute fitness \nfit = zeros(1,N); \nfitG = inf;\nfor i = 1:N\n fit(i) =fun(feat,label,(X(i,:) > thres),opts); \n % Best flower\n if fit(i) < fitG\n fitG = fit(i); \n Xgb = X(i,:);\n end\nend \n% Pre\nXnew = zeros(N,dim);\n\ncurve = zeros(1,max_Iter);\ncurve(1) = fitG;\nt = 2; \n% Iterations\nwhile t <= max_Iter\n\tfor i = 1:N\n % Global pollination \n if rand() < P\n % Levy distribution (2)\n L = jLevyDistribution(beta,dim); \n for d = 1:dim\n % Global pollination (1)\n Xnew(i,d) = X(i,d) + L(d) * (X(i,d) - Xgb(d)); \n end\n % Local pollination\n else\n % Different flower j, k in same species\n R = randperm(N); \n J = R(1); \n K = R(2);\n % Epsilon [0 to 1]\n eps = rand();\n for d = 1:dim\n % Local pollination (3)\n Xnew(i,d) = X(i,d) + eps * (X(J,d) - X(K,d));\n end\n end\n % Check boundary\n XB = Xnew(i,:); XB(XB > ub) = ub; XB(XB < lb) = lb;\n Xnew(i,:) = XB; \n end\n % Fitness\n for i = 1:N\n % Compute fitness\n Fnew = fun(feat,label,(Xnew(i,:) > thres),opts);\n % Update if there is better solution\n if Fnew <= fit(i)\n X(i,:) = Xnew(i,:);\n fit(i) = Fnew;\n end\n % Best flower\n if fit(i) < fitG\n Xgb = X(i,:); \n fitG = fit(i);\n end\n end\n curve(t) = fitG; \n fprintf('\\nIteration %d Best (FPA)= %f',t,curve(t))\n t = t + 1;\nend\n% Select features\nPos = 1:dim; \nSf = Pos((Xgb > thres) == 1);\nsFeat = feat(:,Sf);\n% Store results\nFPA.sf = Sf; \nFPA.ff = sFeat;\nFPA.nf = length(Sf);\nFPA.c = curve;\nFPA.f = feat; \nFPA.l = label;\nend\n\n\n%// Levy Flight //\nfunction LF = jLevyDistribution(beta,dim)\n% Sigma \nnume = gamma(1 + beta) * sin(pi * beta / 2); \ndeno = gamma((1 + beta) / 2) * beta * 2 ^ ((beta - 1) / 2);\nsigma = (nume / deno) ^ (1 / beta); \n% Parameter u & v \nu = randn(1,dim) * sigma;\nv = randn(1,dim);\n% Step \nstep = u ./ abs(v) .^ (1 / beta);\nLF = 0.01 * step;\nend\n\n\n\n\n", "meta": {"author": "JingweiToo", "repo": "Wrapper-Feature-Selection-Toolbox", "sha": "91b050142f331d2a58f7127aba91356b397379b3", "save_path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox", "path": "github-repos/MATLAB/JingweiToo-Wrapper-Feature-Selection-Toolbox/Wrapper-Feature-Selection-Toolbox-91b050142f331d2a58f7127aba91356b397379b3/jFlowerPollinationAlgorithm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.7026858392978769}} {"text": "%% function Xhat = triangulate(x1,x2,P2,homogeneous)\n% triangulates the points Xhat, x1,x2 using P1(assumed to be [I|0]),P2\n% Assumes the points x1,x2 are normalized so their last dimension is 1\n% Xhat is the homogeneous coordinates of the reconstructed X\nfunction Xhat = triangulate(x1,x2,P2,homogeneous)\nXhat = ones(4,size(x1,2));\nP1 = [eye(3) zeros(3,1)];\nfor i = 1 : size(x1,2)\n if homogeneous\n A =[x1(1,i)*P1(3,:) - P1(1,:);\n x1(2,i)*P1(3,:) - P1(2,:);\n x2(1,i)*P2(3,:) - P2(1,:);\n x2(2,i)*P2(3,:) - P2(2,:)]; \n [u,s,v] = svd(A);\n Xhat(:,i) = v(:,end);\n else\n A =[x1(1,i)*P1(3,1:3) - P1(1,1:3);\n x1(2,i)*P1(3,1:3) - P1(2,1:3);\n x2(1,i)*P2(3,1:3) - P2(1,1:3);\n x2(2,i)*P2(3,1:3) - P2(2,1:3)];\n b = -[x1(1,i)*P1(3,4) - P1(1,4);\n x1(2,i)*P1(3,4) - P1(2,4);\n x2(1,i)*P2(3,4) - P2(1,4);\n x2(2,i)*P2(3,4) - P2(2,4)]; \n [u,s,v] = svd(A);\n bprime = u'*b;\n y = bprime(1:3) ./ (diag(s));\n Xhat(1:3,i) = v*y;\n end\nend\nXhat = Xhat./repmat(Xhat(4,:),4,1);\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/triangulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.7026048858404317}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% angular resolution\ndt=pi/40;\t\t\nt=0:dt:2*pi-dt;\n\n%% parameters of a side-cut fiber\nh=100;\nr1=20;\nr2=25;\na=-1;\t \nb=0;\nc=1;\nd=-h;\n\n%% key nodes of a side-cut fiber\n\nn1=[r1*sin(t(:)) r1*cos(t(:)) zeros(size(t(:)))];\nn2=[r2*sin(t(:)) r2*cos(t(:)) zeros(size(t(:)))];\n\nn3=[r1*sin(t(:)) r1*cos(t(:)) -d-(a*r1*sin(t(:))+b*r1*cos(t(:)))/c];\nn4=[r2*sin(t(:)) r2*cos(t(:)) -d-(a*r2*sin(t(:))+b*r2*cos(t(:)))/c];\n\nno=[n1;n2;n3;n4];\n\n%% PLCs of the side-cut fiber\n\nclear fc;\ncount=1; \nfor i=1:length(t)-1\n % the last number in each cell is the fc id\n fc{count}={[i+length(t) i+3*length(t) i+3*length(t)+1 i+length(t)+1],1}; count=count+1;\n fc{count}={[i i+2*length(t) i+2*length(t)+1 i+1],2}; count=count+1;\nend\ni=length(t);\nfc{count}={[i+length(t) i+3*length(t) 1+3*length(t) 1+length(t)],1}; count=count+1;\nfc{count}={[i i+2*length(t) 1+2*length(t) 1],2}; count=count+1;\n\nfc{count}={1:1+length(t)-1,3};count=count+1; % bottom inner circle\nfc{count}={[1+length(t):1+length(t)*2-1 nan fliplr(1:1+length(t)-1)],4};count=count+1; % button outter circle\nfc{count}={1+length(t)*2:1+length(t)*3-1,5};count=count+1; % top inner circle\nfc{count}={[1+length(t)*3:1+length(t)*4-1 nan fliplr(1+length(t)*2:1+length(t)*3-1)],6}; % top outter circle\n\n%% mesh generation of the cladding for the side-cut fiber\n%[node,elem,face]=s2m(no,face,1,50);\n[node,elem,face]=surf2mesh(no,fc,min(no),max(no),1,50,[0 0 1],[],0);\n\nplotmesh(no,fc,'y>-0.1');\nfigure\nplotmesh(node,elem,'x>0 | y>0');\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_directplc_ex1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7025924336423627}} {"text": "%vgg_F_from_7pts_2img Computes fundamental matrix from 7 points across 2 images.\n%\n% [P,X] = vgg_F_from_7pts_2img(x), where\n% x ... double(3,7,2) or cell{2} of double(3,7), 7 homogeneous points in 2 images\n% F ... double(3,3), fundamental matrix\n% There are 0 to 3 solutions for F. Solutions are pruned by requirement that\n% scalars s in all equations s*cross(e1,x1)==F*x2 are positive.\n% In case of multiple solutions, F has one dimension\n% more such that F(:,:,n) is the n-th solution.\n%\n% Also the form F = vgg_F_from_7pts_2img(x1,x2) is accepted.\n\nfunction F = vgg_F_from_7pts_2img(x1,x2)\n\nif nargin==1\n if iscell(x1)\n x2 = x1{2};\n x1 = x1{1};\n else\n x2 = x1(:,:,2);\n x1 = x1(:,:,1);\n end\nend\nif any(size(x1)~=[3 7]) | any(size(x2)~=[3 7])\n error('Wrong size of input points.');\nend\n\n% Linear step\nA = vgg_vec_swap(x1,x2)';\n[u,s,v] = svd(A,0);\nFF{1} = reshape(v(:,end-1),[3 3]);\nFF{2} = reshape(v(:,end ),[3 3]);\n\n% Solving cubic equation and getting 1 or 3 solutions for F\na = vgg_singF_from_FF(FF);\nF = [];\nfor i = 1:length(a)\n Fi = a(i)*FF{1} + (1-a(i))*FF{2};\n %for n = 1:7, disp(norm(x(:,n,1)'*Fi*x(:,n,2))), end % test code\n if signs_OK(Fi,x1,x2)\n F = cat(3, F, Fi);\n end\nend\n\nreturn\n\n%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% Checks sign consistence of F and x\nfunction OK = signs_OK(F,x1,x2)\n[u,s,v] = svd(F');\ne1 = v(:,3);\nl1 = vgg_contreps(e1)*x1;\ns = sum( (F*x2) .* l1 );\nOK = all(s>0) | all(s<0);\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_multiview/vgg_F_from_7pts_2img.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7025924336423627}} {"text": "function x = poisson_solution ( nrow, ncol, rhs_num )\n\n%*****************************************************************************80\n%\n%% POISSON_SOLUTION returns the solution of a Poisson linear system.\n%\n% Discussion:\n%\n% The Poisson matrix is associated with an NROW by NCOL rectangular\n% grid of points.\n%\n% Assume that the points are numbered from left to right, bottom to top.\n%\n% If the K-th point is in row I and column J, set X = I + J.\n%\n% This will be the solution to the linear system.\n%\n% Example:\n%\n% NROW = 3, NCOL = 3\n%\n% ^\n% | 7 8 9\n% J 4 5 6\n% | 1 2 3\n% |\n% +-----I---->\n%\n% Solution vector X = ( 2, 3, 4, 3, 4, 5, 4, 5, 6 )\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 05 March 2015\n%\n% Author:\n%\n% John Burkardt\n%\n% Reference:\n%\n% Gene Golub, Charles Van Loan,\n% Matrix Computations, second edition,\n% Johns Hopkins University Press, Baltimore, Maryland, 1989\n% (Section 4.5.4).\n%\n% Parameters:\n%\n% Input, integer NROW, NCOL, the number of rows and columns\n% in the grid.\n%\n% Input, integer RHS_NUM, the number of right hand sides.\n%\n% Output, real X(NROW*NCOL,RHS_NUM), the solution.\n%\n n = nrow * ncol;\n\n x = zeros ( n, rhs_num );\n\n k = 0;\n for j = 1 : nrow\n for i = 1 : ncol\n k = k + 1;\n x(k,1) = i + j;\n end\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/test_mat/poisson_solution.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.7025924226651176}} {"text": "function f = solharm(l, m, varargin)\n% SOLHARM Complex-valued, solid harmonic of degree L and order M.\n%\n% F = SOLHARM(L, M) returns the degree L, order M real-valued \n% solid harmonic on the ball. F is normalized so that its two-norm\n% over the sphere is 1. \n%\n% F = SOLHARM(L, M, 'complex') returns the degree L, order M complex-valued \n% solid harmonic on the ball. F is normalized so that its two-norm\n% over the sphere is 1. \n%\n% See also spherefun.sphharm.\n\n% Copyright 2019 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\nif nargin == 2\n % Complex solid harmonics\n F = complex_solharm(l,abs(m)); \n % Determine if the cos or sin term should be added:\n pos = abs(max(0, sign(m+1)));\n % Compute the real spherical harmonic:\n % Real part of pos = 1, imaginary part if pos = 0\n F(:,1,:) = (-1)^(1-pos)*F(:,2*abs(m)+1,:);\n F = (-1i)^(1-pos)*F/(1+(m~=0));\n f = ballfun(F,'coeffs');\n \nelseif nargin > 2 && strcmp(varargin{1},'complex')\n % Complex solid harmonics\n F = complex_solharm(l,m)/sqrt(1+(abs(m)>0)); \n f = ballfun(F,'coeffs');\n\nelse\n % Don't know what to do.\n error('CHEBFUN:BALLFUN:solharm:input', ...\n 'Unrecognized inputs.')\nend\nend\n\nfunction F = complex_solharm(l,m)\n% SOLHARM Complex-valued, solid harmonic of degree L and order M.\n%\n% F = SOLHARM(L, M) returns the degree L, order M complex-valued \n% solid harmonic on the ball. F is normalized so that its two-norm\n% over the sphere is 1.\n\nif ( l < abs(m) )\n error('CHEBFUN:BALLFUN:solHarm', 'Degree must be >= order for solid harmonic ');\nend\n\n% abs(m) <= l\n% Compute P^abs(m)_l \nS = [l+1,2*abs(m)+1,2*l+1];\nPlm = normalized_legendre(l,abs(m));\nif m < 0\n Plm = (-1)^m*Plm; \nend\n% Normalize the solid harmonic so that its two-norm over the ball is 1\n% This is the normalization constant so that the integral of r^l is 1\nPlm = Plm*sqrt(2*l+3);\n\n% Compute the chebyshev coefficients of r^l\nr = chebpts(l+1, [-1 1]);\nmonomial = r.^l;\nmonomial = chebtech2.vals2coeffs(monomial);\n\n% Return the Spherical Harmonic Y^m_l\nF = zeros(S);\nF(:,abs(m)+m+1,:) = reshape(monomial*Plm.',l+1,1,2*l+1);\nend\n\n\nfunction Pold = normalized_legendre(l_max,m_max)\n%NORMALIZED_LEGENDRE Generate the fully normalized associated Legendre\n% polynomials P^m_max_l_max\n%\n% Normalization for the spherical harmonics is \\tilde{P}^m_l =\n% P^m_l/(2*sqrt(pi)).\n\n% Copyright 2018 by The University of Oxford and The Chebfun Developers.\n% See http://www.chebfun.org/ for Chebfun information.\n\n%% Below is the implementation the Modified Forward Column (MFC) method \n% described in the Holmes and Featherstones paper (2002)\n% It computes P^m_n/u^m by a stable recurrence to avoid numerical errors\n% near the poles\n\n% Discretization number of the polynomial\np = 2*l_max+1;\n\n% Interpolation points\nth = pi*trigpts(p);\n\n% Precompute vector cos(th)\nCosTh = cos(th);\n\n%% Compute P_m_max^m_max / u^m_max\n\n% Initialize P^0_0 / u^0\nPold = ones(p, 1);\n\n% Compute P^m_m/u^m\nfor m = 1:m_max\n % Compute Pm^m with Pm-1^m-1\n Pold = sqrt((2*m+1)/(2*m-(m==1)))*Pold;\nend\n\n% Initialize the recurrence (Pm^m-1 does not exist)\nPoldold = zeros(p, 1);\n\n%% Compute P^m_l / u^m with the recurrence formula, m_max+1 <= l <= l_max\nfor l = m_max+1:l_max\n anm = sqrt((4*l^2-1)/((l-m_max)*(l+m_max)));\n bnm = sqrt((2*l+1)*(l+m_max-1)*(l-m_max-1)/((l-m_max)*(l+m_max)*(2*l-3)));\n % Compute the normalized associated legendre polynomial P^m_l/u^m\n Pl = anm*CosTh.*Pold - bnm*Poldold;\n\n % Update the polynomials for the recurrence\n Poldold = Pold;\n Pold = Pl;\nend\n\n% Normalize the polynomial and recover associated Legendre polynomials\n% Divide by sqrt(2) if m_max > 0\nPold = (-1)^m_max*sin(th).^m_max.*Pold/sqrt(4*pi);\n\n% FFT to recover the coefficients\nPold = trigtech.vals2coeffs(Pold);\nend", "meta": {"author": "chebfun", "repo": "chebfun", "sha": "8c49396a55e46ddd57a1d108c6a8f32e37536d54", "save_path": "github-repos/MATLAB/chebfun-chebfun", "path": "github-repos/MATLAB/chebfun-chebfun/chebfun-8c49396a55e46ddd57a1d108c6a8f32e37536d54/@ballfun/solharm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.7025924186473361}} {"text": "function [ states ] = BuildStateList\n%BuildStateList builds a state list from a state matrix\n\n% state discretization for the mountain car problem\nxdiv = (0.55-(-1.5)) / 50.0;\nxpdiv = (0.07-(-0.07)) / 50.0;\n\nx = -1.5:xdiv:0.5;\nxp= -0.07:xpdiv:0.07;\n\nN=size(x,2);\nM=size(xp,2);\n\nstates=[];\nindex=1;\nfor i=1:N \n for j=1:M\n states(index,1)=x(i);\n states(index,2)=xp(j);\n index=index+1;\n end\nend", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/reinforcement_learning/mountain_car_functions/BuildStateList.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.7025907722400677}} {"text": "function [Rob,Sen,Lmk,Obs,Frm,Fac] = solveGraphCholesky(Rob,Sen,Lmk,Obs,Frm,Fac,options)\n\n% SOLVEGRAPHCHOLESKY Solves the SLAM graph using Cholesky decomposition.\n% [Rob,Sen,Lmk,Obs,Frm,Fac] = solveGraphCholesky(Rob,Sen,Lmk,Obs,Frm,Fac)\n% solves the graph-SLAM problem using Cholesky decomposition of the\n% Hessian matrix. \n%\n% IMPORTANT NOTE: This method is illustrative and constitutes the\n% motivation for this toolbox. One can achieve better performances, both\n% in computing time and possibly in robustness and accuracy, by using\n% Matlab's built-in nonlinear optimization tools, such as LSQNONLIN.\n% \n% See courseSLAM.pdf in the documentation for details about the Cholesky\n% decomposition for solving the graph-SLAM problem.\n%\n% See also ERRORSTATEJACOBIANS, UPDATESTATES, COMPUTEERROR,\n% COMPUTERESIDUAL, COLAMD, '\\', MLDIVIDE, LSQNONLIN.\n\n% Copyright 2015- Joan Sola @ IRI-UPC-CSIC.\n\nglobal Map\n\n% Control of iterations and exit conditions\nn_iter = options.niterations; % exit criterion of number of iterations\ntarget_dres = options.target_dres; % exit criterion for error variation\ntarget_res = options.target_res; % exit criterion for current residual\nres_old = 1e10; % last iteration's error\n\n% Map states range\nMap.mr = find(Map.used);\n\nfor it = 1:n_iter\n \n% fprintf('----------------\\nIteration: %d; \\n',it)\n\n \n % Compute Jacobians for projection onto the manifold\n [Frm,Lmk] = errorStateJacobians(Frm,Lmk);\n \n % Build Hessian H and rhs vector b, in global Map\n Fac = buildProblem(Rob,Sen,Lmk,Obs,Frm,Fac);\n \n if it == 1 % do this only once:\n \n % Column permutation\n p = colamd(Map.H(Map.mr,Map.mr))';\n \n % Permutated map range\n pr = Map.mr(p);\n end\n \n % Decomposition\n [Map.R, ill] = chol(Map.H(pr,pr));\n \n if ill\n error('Ill-conditioned Hessian')\n end\n\n % Solve for dx and reorder:\n % - dx is Map.x(mr)\n % - reordered dx is Map.x(pr)\n y = -Map.R'\\Map.b(pr); % solve for y\n Map.x(pr) = Map.R\\y;\n \n % NOTE: Matlab is able to do all the reordering and Cholesky\n % factorization for you. If you just use the operator '\\', as in \n % 'dx = -H\\b', Matlab will reorder H, then factor it as R'R, then solve\n % the two subproblems, then reorder back the result into dx. Use the\n % following line to accomplish this, and comment out the code from line\n % 'if it == 1' until here:\n %\n % Map.x(Map.mr) = -Map.H(Map.mr,Map.mr)\\Map.b(Map.mr);\n \n % Update nominal states\n [Rob,Lmk,Frm] = updateStates(Rob,Lmk,Frm);\n \n % Check resulting errors\n [res, err_max] = computeResidual(Rob,Sen,Lmk,Obs,Frm,Fac);\n dres = res - res_old;\n res_old = res;\n \n % fprintf('Residual: %.2e; variation: %.2e \\n', res, dres)\n \n if ( ( -dres <= target_dres ) || (err_max <= target_res) ) %&& ( abs(derr) < target_derr) )\n break;\n end\n \nend\n\nend\n\n\nfunction Fac = buildProblem(Rob,Sen,Lmk,Obs,Frm,Fac)\n\n% BUILDPROBLEM Build least squares problem's matrix H and vector b \n% Fac = BUILDPROBLEM(Rob,Sen,Lmk,Obs,Frm,Fac) Builds the least squares\n% problem's matrix H and vector b for a solution using sparse Cholesky\n% factorization of H.\n\nglobal Map\n\n% Reset Hessian and rhs vector\nMap.H(Map.mr,Map.mr) = 0;\nMap.b(Map.mr) = 0;\n\n% Iterate all factors\nfor fac = find([Fac.used])\n \n % Extract some pointers\n rob = Fac(fac).rob;\n sen = Fac(fac).sen;\n lmk = Fac(fac).lmk;\n frames = Fac(fac).frames;\n \n % Compute factor error, info mat, and Jacobians\n [Fac(fac), e, W, ~, J1, J2, r1, r2] = computeError(...\n Rob(rob), ...\n Sen(sen), ...\n Lmk(lmk), ...\n Obs(sen,lmk), ...\n Frm(frames), ...\n Fac(fac));\n\n % Compute sparse Hessian blocks\n H_11 = J1' * W * J1;\n H_12 = J1' * W * J2;\n H_22 = J2' * W * J2;\n \n % Compute rhs vector blocks\n b1 = J1' * W * e;\n b2 = J2' * W * e;\n \n % Update H and b\n Map.H(r1,r1) = Map.H(r1,r1) + H_11;\n Map.H(r1,r2) = Map.H(r1,r2) + H_12;\n Map.H(r2,r1) = Map.H(r2,r1) + H_12';\n Map.H(r2,r2) = Map.H(r2,r2) + H_22;\n \n Map.b(r1,1) = Map.b(r1,1) + b1;\n Map.b(r2,1) = Map.b(r2,1) + b2;\n\nend\n\nend\n\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/InterfaceLevel/solveGraphCholesky.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.7025907629230215}} {"text": "function jed = ymdf_to_jed_islamic_b ( y, m, d, f )\n\n%*****************************************************************************80\n%\n%% YMDF_TO_JED_ISLAMIC_B converts an Islamic B 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 Julian Ephemeris Date.\n%\n\n%\n% Check the date.\n%\n [ y, m, d, ierror ] = ymd_check_islamic ( y, m, d );\n\n if ( ierror ~= 0 )\n jed = -1.0;\n return\n end\n%\n% Convert the calendar date to a computational date.\n%\n y_prime = y + 5519 - floor ( ( 12 - m ) / 12 );\n m_prime = mod ( m + 11, 12 );\n d_prime = d - 1;\n%\n% Convert the computational date to a JED.\n%\n j1 = floor ( ( 10631 * y_prime + 14 ) / 30 );\n\n j2 = floor ( ( 2951 * m_prime + 51 ) / 100 );\n\n jed = j1 + j2 + d_prime - 7664 - 0.5 + 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_islamic_b.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.7025886622834014}} {"text": "function [D, X] = ODL(Y, k, lambda, opts, method)\n% * Solving the following problem:\n% (D, X) = \\arg\\min_{D,X} 0.5||Y - DX||_F^2 + lambda||X||_1\n% * Syntax: `[D, X] = ODL(Y, k, lambda, opts, sc_method)`\n% - INPUT: \n% + `Y`: collection of samples.4/7/2016 7:35:39 PM\n% + `k`: number of atoms in the desired dictionary.\n% + `lambda`: norm 1 regularization parameter.\n% + `opts`: option.\n% + `sc_method`: sparse coding method used in the sparse coefficient update. Possible values:\n% * `'fista'`: using FISTA algorithm. See also [`fista`](#fista).\n% * `'spams'`: using SPAMS toolbox [[12]](#fn_spams). \n% - OUTPUT:\n% + `D, X`: as in the problem.\n% -----------------------------------------------\n% Author: Tiep Vu, thv102@psu.edu, 4/7/2016\n% (http://www.personal.psu.edu/thv102/)\n% -----------------------------------------------\n\tif nargin == 0\n\t\taddpath(fullfile('..', 'utils'));\n addpath(fullfile('..', 'build_spams'));\n d = 50; % data dimension\n N = 100; % number of samples \n k = 50; % dictionary size \n lambda = 0.1;\n Y = normc(rand(d, N)); \n %\n\t\topts.max_iter = 500;\n\t\topts.show_progress = 0;\n\t\topts.check_grad = false; \n\t\topts.tol = 1e-8; \n\t\topts.verbose = true;\n\t\t\n\tend \n\t%%\n\topts = initOpts(opts);\n\t%%\n\t%% ========= initial D ==============================\n\tD = PickDfromY(Y, [0, size(Y,2)], k);\n X = zeros(size(D,2), size(Y,2));\n if opts.verbose \n fprintf('cost: %f', ODL_cost(Y, D, X, lambda));\n end \n optsX = opts;\n\toptsX.max_iter = 200;\n\toptsX.tol = 1e-8;\n optsD = opts;\n\toptsD.max_iter = 200;\n\toptsD.tol = 1e-8;\n\titer = 0;\n\twhile iter < opts.max_iter\n\t\titer = iter + 1;\n\t\t%% ========= sparse coding step ==============================\n\t\tX = lasso_fista(Y, D, X, lambda, optsX);\n \tif opts.verbose \n\t\t\tcostX = ODL_cost(Y, D, X, lambda);\n\t\t\tfprintf('iter: %3d, costX = %5f\\n', iter, costX)\n\t\tend \n\t\t%% ========= dictionary update step ==============================\n\t\tF = X*X'; E = Y*X';\n\t\tD = ODL_updateD(D, E, F, optsD);\n\t\tif opts.verbose \n\t\t\tcostD = ODL_cost(Y, D, X, lambda);\n\t\t\tfprintf('iter: %3d, costD = %5f\\n', iter, costD)\n\t\tend \n\tend\n\t%%\n\tif nargin == 0\n\t\tpause;\n\tend\nend\n", "meta": {"author": "tiepvupsu", "repo": "DICTOL", "sha": "1a0361aa35c32d70525d06910d0e9b87997ff246", "save_path": "github-repos/MATLAB/tiepvupsu-DICTOL", "path": "github-repos/MATLAB/tiepvupsu-DICTOL/DICTOL-1a0361aa35c32d70525d06910d0e9b87997ff246/ODL/ODL.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.7025886545869445}} {"text": "function y = vl_gaussian(x)\n% VL_GAUSSIAN Standard Gaussian density function\n% Y=VL_GAUSSIAN(X) computes the standard (zero mean, unit variance)\n% Gaussian density.\n%\n% To obtain the Gaussian density of standard deviation S do\n%\n% Y = 1/S * VL_GAUSSIAN(X/S).\n%\n% See also: VL_DGAUSSIAN(), VL_DDGAUSSIAN(), VL_HELP().\n\n% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.\n% All rights reserved.\n%\n% This file is part of the VLFeat library and is made available under\n% the terms of the BSD license (see the COPYING file).\n\ny = 1/sqrt(2*pi)*exp(-0.5*x.^2) ;\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/special/vl_gaussian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.8006919997179626, "lm_q1q2_score": 0.7025886436749288}} {"text": "function C = estimateC(W,R,B,C,lam,tol)\n\n% INPUT:\n% W: 2-by-P matrix\n% R: 2-by-3 matrix\n% B: 3K-by-P matrx\n% C: 1-by-K vector\n\n% This function estimates c by minimizing\n% f(C) + lam*r(C), where\n% f(C) = 0.5 * norm(W-R*S,'fro')^2 where S = \\sum_i C_i*B_i\n% r(C) = \\|C\\|_1\n% It implements proximal gradient + nesterov\n\nP = size(W,2);\nK = size(B,1)/3;\n\nC = C'; % transpose to be a column vector\nC0 = C; % C0: the previous estimate\nt = 1; % auxiliary variable for nesterov\nt0 = 1; % auxiliary variable for nesterov\nfvalue = inf;\n\n% next we work on the linear system y = X*C\ny = W(:); % vectorized W\nX = zeros(2*P,K); % each column is a rotated Bk\nfor k = 1:K\n RBk = R*B(3*k-2:3*k,:);\n X(:,k) = RBk(:);\nend\n\nif lam == 0\n C = X\\y;\n C = C';\n return\nend\n\n% mu is set as the 2-norm of the Hessian of f(C)\nmu = norm(X'*X); \n\nfor iter = 1:1000\n \n % Z is an auxiliary variable in nesterov method\n Z = C + (t0-1)/t*(C-C0);\n \n % gradient descent \n Z = Z + X'*(y-X*Z)/mu;\n \n % nonegative thresholding\n% Z = Z - lam/mu;\n% Z = max(Z,0);\n \n % soft thresholding\n Z = sign(Z).*max(abs(Z)-lam/mu,0);\n \n % update C\n C0 = C;\n C = Z;\n \n % update t\n t0 = t;\n t = (1+sqrt(1+4*t^2))/2;\n \n % function value\n fvalue0 = fvalue;\n fvalue = 0.5 * norm(y-X*C,'fro')^2 + lam*sum(abs(C));\n if fvalue > fvalue0\n t0 = 1; % APG with restart\n t = 1;\n end\n \n % check convergence\n RelChg = norm(C-C0,'fro')/(norm(C0,'fro')+eps) ;\n% fprintf('Iter %d: FunVal = %f, RelChg = %f\\n',iter,fvalue,RelChg);\n if RelChg < tol\n break\n end\n \nend\n\nC = C'; % transpose back to be a row vector\n", "meta": {"author": "geopavlakos", "repo": "object3d", "sha": "44033b2b4fe15d41a411cba0bbff906c23e8a802", "save_path": "github-repos/MATLAB/geopavlakos-object3d", "path": "github-repos/MATLAB/geopavlakos-object3d/object3d-44033b2b4fe15d41a411cba0bbff906c23e8a802/code/estimateC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.702406848409283}} {"text": "function [output] = ols_reg(Y,X,options)\n\n% this function computes the ols coefficients of Y on X\n% Y TxN\n% X Txk (interepct at the end)\n% Y = XB + E\n\nnindex = find(sum(isnan([Y,X]),2)==0);\nindex = find(sum(isnan([Y,X]),2)>0);\nY(index,:) = [];\nX(index,:) = [];\n[N,K] = size(X);\nrobust_se_ = 0;\nL = round(N/4);\n\nif nargin > 2\n if isfield(options,'robust_se_') == 1\n robust_se_ = options.robust_se_;\n end\n if isfield(options,'L') == 1\n L = options.L;\n end\nend\n\n\nny = size(Y,2);\n\nXX = (X'*X);\niXX = XX\\eye(K);\nBols = X\\Y; % Bols = (X'*X)\\(X'*Y);\nerr = Y - X*Bols;\nse = nan(K,ny);\nSols = zeros(K*ny);\n\nif robust_se_==2 % NW Robust SE\n %-----------------------------------------------------------------------%\n Serror = (err'*err);\n nwWeights = (L+1-(1:L))./(L+1);\n for j= 1 : L\n G = (err(j+1 : N, :)'*err(1 : N-j , :));\n Serror = Serror + nwWeights(j) * (G + G');\n end\n Serror = Serror/(N-K);\n Sols = kron(diag(diag(Serror)),iXX);\n se = reshape(sqrt(diag(Sols)), K, ny);\n \nelseif robust_se_ == 1 % Hamilton (1994), Ch 10 pag 282, eq (10.5.20)\n %-----------------------------------------------------------------------%\n for vv = 1: ny % equation by equation\n u= err(:,vv); \n errs=X.*u;\n V0 = [errs'*errs] / N ; %regular weighting matrix\n for ind_i = (1:L)\n S = errs(1:N-ind_i,:)'*errs(1+ind_i:N,:) / N;\n V0 = V0 + (1 - ind_i/(L+1))*(S + S');\n end\n % D = inv((X'*X)/N);\n % varb = 1/N*D*V1*D;\n Solsj = N * iXX * V0 * iXX;\n Sols((vv-1)*K+1 : vv*K, (vv-1)*K+1 : K*vv ) = Solsj;\n end\n Serror = (err'*err)/(N-K); % not sure this is the correct Coavariance of the shocks. \n se = reshape(sqrt(diag(Sols)), K, ny);\n \n \nelseif robust_se_ == 5 % Matlab HAC function \n %-----------------------------------------------------------------------%\n if exist('hac') ==2\n % find constant\n index = find(sum(diff(X,1,1),1)~=0);\n indexC = find(sum(diff(X,1,1),1)==0);\n for vv = 1: ny\n% [EstCoeffCov0,se0,~] = hac(X(:,index),Y(:,ny),'display','off','type','HC'); \n [EstCoeffCov0,se0,~] = hac(X(:,index),Y(:,ny),'display','off','bandwidth','AR1OLS'); % remove the intercept\n se(index,vv) = se0(2:end);\n se(indexC,vv) = se0(1); %intercept\n Sols((vv-1)*K+1 : vv*K, (vv-1)*K+1 : K*vv ) = EstCoeffCov0; % order is not correct\n end\n Serror = 1/(N-K)*(err'*err);\n% output.TtestRobust = coeff./se;\n% output.pvalueRobust = tpdf(output.TtestRobust,N-K);\n else\n error('Matlab Econ Toolbox missing')\n end\nelse\n Serror = 1/(N-K)*(err'*err);\n Sols = kron(diag(diag(Serror)),iXX);\n se = reshape(sqrt(diag(Sols)), K, ny);\nend\n\nTtest = Bols./ reshape(sqrt(diag(Sols)), K, ny);\nESS = diag((X*Bols - mean(Y))'*(X*Bols - mean(Y)));\nRSS = diag(err' * err);\nTSS = diag((Y - mean(Y))' * (Y - mean(Y)));\nR2 = ones(length(ESS),1) - RSS ./ TSS;\nadjR2 = ones(length(ESS),1) - (ones(length(ESS),1) - R2)*(N-1)/(N-K);\nFtest = ESS/(K-1) ./ diag(Serror);\n\n% for v = 1 : ny\n% % output.logl(v,1) = -N/2*log(2*pi*Serror(v,v)) - RSS(v,1)/(2*Serror(v,v));\n% [output.AIC(v,1), output.SIC(v,1), output.HQIC(v,1)] = IC(output.logl(v,1), N, K);\n% end\n\noutput.beta = Bols; % OLS estimator\noutput.error = err; % (TxN) matrix of Residuals\noutput.e_ols = err; % (TxN) matrix of Residuals\noutput.Serror = Serror; % Covariance matrix of Residuals\noutput.Sigma_ols = Serror; % Covariance matrix of Residuals\noutput.Sols = Sols; % Covariance matrix of Bols\noutput.Ttest = Ttest; % t-statistics\noutput.pvalue = tpdf(Ttest,N-K); % p-value\noutput.Ftest = Ftest; % F-test\noutput.R2 = R2; % R2\noutput.adjR2 = adjR2; % Adjusted R2\noutput.yfit = X*Bols; % Fitted Values\noutput.N = N; % # of observation used\noutput.K = K; % # of regressors\noutput.nindex = nindex; % index of missing observation\noutput.index = index; % index of observation used\noutput.se = se;\noutput.XX = XX;\noutput.X = X;\noutput.Y = Y;\n\nfor v = 1 : ny\n% output.logl(v,1) = -N/2*log(2*pi*Serror(v,v)) - RSS(v,1)/(2*Serror(v,v));\n% [output.AIC(v,1), output.SIC(v,1), output.HQIC(v,1)] = IC(output, N, K);\n S = Serror(v,v); E = err(:,v);\n [output.AIC(v,1), output.SIC(v,1), output.HQIC(v,1)] = IC(S, E, N, K);\nend\n\n% if nargin > 2\n% [EstCov,se,coeff] = hac(X(:,1:end-1),Y,'display','off'); % remove the intercept\n% output.serob = se(2:end);\n% output.serob(end+1) = se(1); %intercept\n% output.TtestRobust = coeff./se;\n% output.pvalueRobust = tpdf(output.TtestRobust,N-K);\n% end\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/bvartools/ols_reg.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483232, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.7024068421625471}} {"text": "function K = covPERard(cov, hyp, x, z, i)\n\n% Stationary periodic covariance function for a stationary covariance function\n% k0 such as covMaternard, covPPard, covRQard and covSEard.\n% Stationary means that the covariance function k0(x,z) depends on the\n% data points x,z only through the squared distance\n% dxz = (x-z)'*inv(P)*(x-z) where the P matrix is diagonal with ARD parameters\n% ell_1^2,...,ell_D^2, where D is the dimension of the input space.\n% The covariance function is parameterized as:\n%\n% k(x,z) = k0(u(x),u(z)), u(x) = [sin(pi*x/p); cos(pi*x/p)]\n%\n% where the period p belongs to covPERiso and hyp0 belong to k0:\n%\n% hyp = [ log(p_1)\n% log(p_2)\n% .\n% log(p_D)\n% hyp0 ]\n%\n% The first D hyperparameters of k0 are the log lengthscales such that\n% hyp0(i) = log(ell(i)) for i=1..D.\n% Note that for k0 = covSEard and D = 1, a faster alternative is covPeriodic.\n%\n% Copyright (c) by Hannes Nickisch, 2013-10-16.\n%\n% See also COVFUNCTIONS.M.\n\nnocov = false; % default case when no cov argument is provided\nif nargin==0, cov = {@covSEard}; nocov = true; end % default case\nif isnumeric(cov) % detect old version where the cov parameter was missing\n % i <- z, z <- x, x <- hyp, hyp <- cov\n if nargin>3, i = z; end\n if nargin>2, z = x; end\n if nargin>1, x = hyp; end\n hyp = cov; cov = {@covSEard}; nocov = true;\nend\n\nif nocov && nargin<2 || ~nocov && nargin<3 % report number of parameters\n K = ['(D+',feval(cov{:}),')']; return\nend\nif nocov && nargin<3 || ~nocov && nargin<4, z = []; end % make sure, z exists\nxeqz = isempty(z); dg = strcmp(z,'diag'); % determine mode\n\n[n,D] = size(x);\np = exp(hyp(1:D));\nlell = hyp(D+(1:D));\nhyp0 = [lell; lell; hyp(2*D+1:end)];\n\nif nocov && nargin<4 || ~nocov && nargin<5\n [x,z] = u(x,z,p,dg); % apply the embedding u:IR^D->IR^2*D\n K = feval(cov{:},hyp0,x,z);\nelse\n if i<=D\n if dg % compute distance d\n di = zeros([n,1]);\n else\n if xeqz % symmetric matrix Kxx\n di = repmat(reshape(x(:,i),n, 1),[1, n])...\n -repmat(reshape(x(:,i),1, n),[n, 1]);\n else % cross covariances Kxz\n nz = size(z,1);\n di = repmat(reshape(x(:,i),n, 1),[1,nz])...\n -repmat(reshape(z(:,i),1,nz),[n, 1]);\n end\n end\n di = 2*pi*di/p(i); dD2_dlpi = -2*sin(di).*di; % derivative dD2i/dlog(p(i))\n [x,z] = u(x,z,p,dg); % apply the embedding u:IR^D->IR^2*D\n if dg % compute squared distances\n D2 = zeros(n,1);\n else\n if xeqz\n D2 = sq_dist(x(:,[i,i+D])');\n else\n D2 = sq_dist(x(:,[i,i+D])',z(:,[i,i+D])');\n end\n end\n % reconstruct derivative w.r.t. D2i from derivative w.r.t. log(ell(i))\n dK_dD2 = feval(cov{:},hyp0,x,z,i) + feval(cov{:},hyp0,x,z,i+D);\n dK_dD2 = dK_dD2./(-2*D2); dK_dD2(D2<1e-12) = 0;\n K = dK_dD2.*dD2_dlpi; % apply chain rule\n else\n [x,z] = u(x,z,p,dg); % apply the embedding u:IR^D->IR^2*D\n if i<=2*D\n K = feval(cov{:},hyp0,x,z,i-D) + feval(cov{:},hyp0,x,z,i);\n else\n K = feval(cov{:},hyp0,x,z,i);\n end\n end\nend\n\nfunction [x,z] = u(x,z,p,dg) % apply the embedding u:IR^D->IR^2*D\n x = 2*pi*x*diag(1./p); x = [sin(x), cos(x)];\n if numel(z)>0 && ~dg, z = 2*pi*z*diag(1./p); z = [sin(z), cos(z)]; end", "meta": {"author": "benfulcher", "repo": "hctsa", "sha": "919f2aed7cc8e1a3a03304c1ade573fa664c73f8", "save_path": "github-repos/MATLAB/benfulcher-hctsa", "path": "github-repos/MATLAB/benfulcher-hctsa/hctsa-919f2aed7cc8e1a3a03304c1ade573fa664c73f8/Toolboxes/gpml/cov/covPERard.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7024068396393058}} {"text": "function order = r82row_order_type ( n, a )\n\n%*****************************************************************************80\n%\n%% R82ROW_ORDER_TYPE finds if an R82ROW is (non)strictly ascending/descending.\n%\n% Discussion:\n%\n% An R82ROW is a (2,N) array of R8's.\n%\n% The dictionary or lexicographic ordering is used.\n%\n% (X1,Y1) < (X2,Y2) <=> X1 < X2 or ( X1 = X2 and Y1 < Y2).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 October 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of entries of the array.\n%\n% Input, real A(2,N), the array to be checked.\n%\n% Output, integer ORDER, order indicator:\n% -1, no discernable order;\n% 0, all entries are equal;\n% 1, ascending order;\n% 2, strictly ascending order;\n% 3, descending order;\n% 4, strictly descending order.\n%\n dim_num = 2;\n%\n% Search for the first value not equal to A(1,1).\n%\n i = 1;\n\n while ( 1 )\n\n i = i + 1;\n\n if ( n < i )\n order = 0;\n return\n end\n\n if ( ...\n a(1,1) < a(1,i) || ...\n ( a(1,1) == a(1,i) && a(2,1) < a(2,i) ) )\n\n if ( i == 2 )\n order = 2;\n else\n order = 1;\n end\n\n break\n\n elseif ( ...\n a(1,i) < a(1,1) || ...\n ( a(1,i) == a(1,1) && a(2,i) < a(2,1) ) ) \n\n if ( i == 2 )\n order = 4;\n else\n order = 3;\n end\n\n break\n\n end\n\n end\n%\n% Now we have a \"direction\". Examine subsequent entries.\n%\n while ( 1 )\n\n i = i + 1;\n if ( n < i )\n break\n end\n\n if ( order == 1 )\n\n if ( ...\n a(1,i) < a(1,i-1) || ...\n ( a(1,i) == a(1,i-1) && a(2,i) < a(2,i-1) ) )\n order = -1;\n break\n end\n\n elseif ( order == 2 )\n\n if ( ...\n a(1,i) < a(1,i-1) || ...\n ( a(1,i) == a(1,i-1) && a(2,i) < a(2,i-1) ) )\n order = -1;\n break\n elseif ( ...\n a(1,i) == a(1,i-1) && a(2,i) == a(2,i-1) )\n order = 1;\n end\n\n elseif ( order == 3 )\n\n if ( ...\n a(1,i-1) < a(1,i) || ...\n ( a(1,i-1) == a(1,i) && a(2,i-1) < a(2,i) ) )\n order = -1;\n break\n end\n\n elseif ( order == 4 )\n\n if ( ...\n a(1,i-1) < a(1,i) || ...\n ( a(1,i-1) == a(1,i) && a(2,i-1) < a(2,i) ) )\n order = -1;\n break\n elseif ( a(1,i) == a(1,i-1) && a(2,i) == a(2,i-1) )\n order = 3;\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/r8lib/r82row_order_type.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.8244619263765706, "lm_q1q2_score": 0.7024026544909223}} {"text": "function value = p32_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P32_F evaluates the integrand for problem 32.\n%\n% Dimension:\n%\n% N arbitrary.\n%\n% Region:\n%\n% 0 <= X(1:DIM_NUM) <= 1\n%\n% Integral Parameters:\n%\n% The integral depends on vectors C(1:N) and Z(1:N).\n%\n% The reference suggests choosing C at random in [0,1]\n% and then multiplying by the normalizing factor sqrt(140/N**(3/2)).\n%\n% The default value of C(1:N) is (1/2)^(1/N).\n%\n% The default value of Z(1:N) is (1/2)^(1/N).\n%\n% Integrand:\n%\n% exp ( c(1:n)*x(1:n) ) if all x(1:n) <= z(1:n)\n% 0 otherwise\n%\n% Exact Integral:\n%\n% product ( g(1:n)(x,z,a,b,c) )\n%\n% where g(i)(x,z,a,b,c) =\n%\n% 0 if z(i) <= a(i)\n% ( e^(c(i)*z(i) ) - e^(c(i)*a(i)) ) / c(i) if a(i) <= z(i) <= b(i)\n% ( e^(c(i)*b(i) ) - e^(c(i)*a(i)) ) / c(i) if b(i) <= z(i)\n% \n% with obvious modifications when c(i) = 0.\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% Alan Genz,\n% [Integral #6]\n% A Package for Testing Multiple Integration Subroutines,\n% in Numerical Integration: Recent Developments, Software\n% and Applications,\n% edited by Patrick Keast and Graeme Fairweather,\n% D Reidel, 1987, pages 337-340,\n% LC: QA299.3.N38.\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 c = [];\n c = p32_r8vec ( 'G', 'C', dim_num, c );\n\n z = [];\n z = p32_r8vec ( 'G', 'Z', dim_num, z );\n\n value(1:point_num) = 0.0;\n\n for point = 1 : point_num\n\n if ( all ( x(1:dim_num,point) <= z(1:dim_num)' ) )\n value(point) = exp ( c(1:dim_num) * x(1:dim_num,point) );\n else\n value(point) = 0.0;\n end\n\n end\n\n p32_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/p32_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.824461932846258, "lm_q1q2_score": 0.7024026538045787}} {"text": "function [ a_lu, info ] = r8ge_np_trf ( m, n, a )\n\n%*****************************************************************************80\n%\n%% R8GE_NP_TRF computes the LU factorization of a 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% R8GE_NP_TRF is a nonpivoting version of R8GE_TRF, and will fail if\n% a zero element is encountered along the diagonal.\n%\n% The factorization has the form\n% A = L * U\n% where L is lower triangular with unit diagonal elements (lower\n% trapezoidal if N < M), and U is upper triangular (upper trapezoidal\n% if M < N).\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 March 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer M, the number of rows of the matrix A. 0 <= M.\n%\n% Input, integer N, the number of columns of the matrix A. 0 <= N.\n%\n% Input, real A(M,N), the matrix to be factored.\n%\n% Output, integer INFO.\n% = 0: successful exit\n% < 0: if INFO = -K, the K-th argument had an illegal value\n% > 0: if INFO = K, U(K,K) is exactly zero. The factorization\n% has been completed, but the factor U is exactly\n% singular, and division by zero will occur if it is used\n% to solve a system of equations.\n%\n% Output, real A_LU(M,N), the factors L and U from the factorization\n% A = L*U; the unit diagonal elements of L are not stored.\n%\n info = 0;\n a_lu(1:m,1:n) = a(1:m,1:n);\n%\n% Test the input parameters.\n%\n if ( m < 0 )\n info = -1;\n return\n elseif ( n < 0 )\n info = -2;\n return\n end\n\n if ( m == 0 | n == 0 )\n return\n end\n\n for j = 1 : min ( m, n )\n%\n% Compute elements J+1:M of the J-th column.\n%\n if ( a(j,j) ~= 0.0E+00 )\n a_lu(j+1:m,j) = a_lu(j+1:m,j) / a_lu(j,j);\n elseif ( info == 0 )\n info = j;\n end\n%\n% Update the trailing submatrix.\n%\n if ( j < min ( m, n ) )\n\n for ii = j+1 : m\n a_lu(ii,j+1:n) = a_lu(ii,j+1:n) - a_lu(ii,j) * a_lu(j,j+1: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/linplus/r8ge_np_trf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7024026464554208}} {"text": "function [y,r]=smooth(x,twice)\n% SMOOTH will compute the non-linear running medians of\n% the input vector. First it smooths the data, compute\n% the residuals, smooth the residuals, and add this back\n% to the first smooth.\n%\n% Usage: y = smooth(x, OPTIONAL twice?)\n% where x is the input vector of minimum length 3\n% twice? whether to do this twice (default = 1)\n% y is the smoothed vector\n%\n% [y,r] = smooth(x, OPTIONAL twice?)\n% r is the final residuals where x = y + r\n%\n% See also: R3R, SR, R3RSR, H\n\n%\n% Huy Le, Massachusetts Institute of Technology. 1997\n%\n% See John Wilder Tukey, \"EXPLORATORY DATA ANALYSIS\".\n% Addison-Wesley Publishing Co. 1977. Chpt 7, 16.\n\nformat long e;\nxlen = length(x); x = x(:); y = x; r = x - y; batch = 1; \nif nargin<2, twice = 1; end\nif nargout<2, res = 0; end\nif ~all(isfinite(x)), error('Input must have finite values.'); end\nif xlen<3, error('Input vector must be at least 3 elements long.'); end\n% first, run the 3RSR of vector x\nxtemp1 = R3RSR(x,batch);\n% first hanning\nxtemp2 = H(xtemp1,batch);\n% second hanning\nxtemp1 = H(xtemp2,batch);\nif twice,\n % compute first residuals\n rtemp = x - xtemp1;\n % run 3RSR on first residuals\n rtemp1 = R3RSR(rtemp,batch);\n % hanning of first residuals\n rtemp2 = H(rtemp1,batch);\n % sum of smooths\n xtemp = xtemp1 + rtemp2;\nelse\n xtemp = xtemp1;\nend\n\nfor ii = 1:xlen,\n y(ii) = xtemp(ii);\n r(ii) = x(ii) - y(ii);\nend\n\nreturn\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/274-smooth/smooth/smooth.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7024026464554207}} {"text": "%DEMOPOLYGONCENTROIDS One-line description here, please.\n%\n% output = demoPolygonCentroids(input)\n%\n% Example\n% demoPolygonCentroids\n%\n% See also\n%\n \n% ------\n% Author: David Legland\n% e-mail: david.legland@inrae.fr\n% INRAE - BIA Research Unit - BIBS Platform (Nantes)\n% Created: 2022-02-16, using Matlab 9.9.0.1570001 (R2020b) Update 4\n% Copyright 2022 INRAE.\n\n\n%% Demo polygon\n\n% vertices of a \"U\"-shaped polygon\npoly = [0 0;30 0;30 20;20 20;20 11;10 11;10 20;0 20];\n\n% display the filled polygon and the open polyline\nfigure; hold on; axis equal; axis([-5 35 -5 30]);\nfillPolygon(poly, 'c');\nhPoly = drawPolygon(poly, 'linewidth', 2, 'color', 'k');\ndrawVertices(poly);\n\n\n%% Computes various centroids\n\n% computes the centroids\nvxCentroid = centroid(poly);\nlsCentroid = polylineCentroid(poly, 'closed');\npgCentroid = polygonCentroid(poly);\n\n% display the centroids\nhVxc = drawPoint(vxCentroid, 'marker', 'o', 'color', [0.8 0 0], 'linewidth', 2, 'MarkerFaceColor', 'w');\nhLsc = drawPoint(lsCentroid, 'marker', 'o', 'color', [0 0.8 0], 'linewidth', 2, 'MarkerFaceColor', 'w');\nhPgc = drawPoint(pgCentroid, 'marker', 'o', 'color', [0 0 0.8], 'linewidth', 2, 'MarkerFaceColor', 'w');\n\n% decorate graph\nlegend([hPoly hVxc hLsc hPgc], ...\n {'Polygon', 'Vertex Centroid', 'Polyline Centroid', 'Polygon Centroid'}, ...\n 'Location', 'NorthEast');\n\nprint(gcf, 'polygon_centroids.png', '-dpng');\n", "meta": {"author": "mattools", "repo": "matGeom", "sha": "1fd2c937064be1ee1f4fd09fbfdf96145ebe5271", "save_path": "github-repos/MATLAB/mattools-matGeom", "path": "github-repos/MATLAB/mattools-matGeom/matGeom-1fd2c937064be1ee1f4fd09fbfdf96145ebe5271/docs/matGeom-manual/images/polygons2d/demoPolygonCentroids.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7024026457690768}} {"text": "function out = simbin(mat1,mat2,type,mask)\n\n% Computes 106 measures of similarity and dissimilarity (distance) between\n% two binary matrices. Matrices can be any dimensions, but must have the\n% same dimensions. A mask can be used to indicate the relevant elements of\n% the matrices (needed when the measure takes into account elements present\n% in neither binary object). See further information below (including next \n% to each measure). \n%\n% IMPORTANT: naming conventions for certain measures (e.g., the 5 Sokal and\n% Sneath measures) are inconsistent across different researchers, different\n% formulas for the same 'measure' exist in the literature, and different \n% measures have similar names (e.g., Anderberg's vs. Anderberg's D). Thus, \n% you should check that the formula used below corresponds to the \n% particular measure that you wish to compute. \n%\n% Usage: out = overlap_similarity(mat1,mat2,type,mask)\n% mat1: 1st binary matrix\n% mat2: 2nd binary matrix\n% type: measure of (dis)similarity to be used\n% mask: binary mask indicating relevant matrix elements\n%\n%\n% Further Information:\n%\n% All measures are symmetric (i.e., it does not matter which matrix is mat1\n% vs. mat 2) except:\n% AD, AMPLE, BUB1, BUB2, cole, diceasym1, diceasym2,\n% digby, fleiss, forbes, GKlambda, GKtau, GK2, Ko2, LH,\n% MP, Pcs, Pmsc, Pei1, Pei2, PHI, PH, Q0, RDeprob, SS4,\n% SS5, tarantula, YQ, YQD, YY\n%\n% Computation of these measures takes into account (in some way) the \n% elements present in neither binary object (i.e., d) (which may not be \n% optimal if you want a straightforward measure of overlap):\n% AD, AMPLE, baulieu, bc, Bshape, BUB1, BUB2, CK, cole, \n% dennis, digby, disper, eyraud, faith, FD, fleiss, \n% GKlambda, GKtau, GK1, GK2, GK3, GK4, GLS, goodall, \n% gower, GW, hamann, HD, inprod, Kcam, Kpoai, LH, \n% meanman, michael, MK, MP, pattern, Pcs, Pmsc, Pei1, \n% Pei2, PHI, PH, Q0, RDeprob, Rpattern, RR, RT, scott, \n% SM, Spattern, SS1, SS3, SS4, SS5, Stau, stiles, \n% tarantula, tarwid, var, YQ, YQD, YY\n%\n% Positive monotomic relationship: bc, pattern\n% BSeuc, meanman, mirkin, var\n% BUB1, BUB2\n% DK, johnson\n% disper, MK, Stau\n% int, RR\n% hamann, inprod, SM\n% chord, hellinger\n% faith, tversky\n% \n% Negative monotomic relationship: BB with savage\n% BLWMN with dice\n% BSeuc, meanman, mirkin, and var with hamann, inprod, and SM\n% Bpattern with bc and pattern\n% Beuc with RT\n% steffensen with int and RR\n% YQ with YQD\n%\n% TAG: MEASURE NAME:\n% AMPLE Analyzing Method Patterns to Locate Errors (Dallmeier et al, 2005) (similarity)\n% AD Anderberg's D (similarity)\n% anderberg Anderberg 1973 (similarity)\n% baulieu Baulieu 1989 (dissimilarity) (also called size difference)\n% BB Braun and Blanquet 1932 (similarity)\n% bc bc (dissimilarity)\n% benini Benini 1901 (similarity)\n% Beuc Binary euclidean distance (dissimilarity)\n% BLWMN Binary Lance and Williams nonmetric (dissimilarity) (also called Sokal and Sneath nonmetric or Bray and Curtis)\n% Bpattern Browsing pattern (similarity)\n% BSeuc Binary squared euclidean distance (dissimilarity) (also called Hamming, city block, Manhattan, or Filkov)\n% Bshape Binary shape (dissimilarity)\n% BUB1 Baroni-Urbani and Buser 1976 1 (similarity)\n% BUB2 Baroni-Urbani and Buser 1976 2 (similarity)\n% chiY Chi Square with correction of Yates \n% chord Chord (dissimilarity)\n% CK Cohen's kappa (similarity)\n% cole Cole 1949 (similarity)\n% dennis Dennis (similarity)\n% dice Dice (similarity) (also called Nei and Lei's genetic coefficient, Czekanowski, or Sorenson, or Bray)\n% diceasym1 Dice asymmetric 1 (similarity)\n% diceasym2 Dice asymmetric 2 (similarity)\n% digby Digby 1983 (similarity)\n% disper Dispersion (similarity)\n% DK Driver and Kroeber 1932 (similarity) (also called Kulczynski 1927 2)\n% eyraud Eyraud 1936 (similarity)\n% fager Fager (similarity)\n% faith Faith (similarity)\n% FaMc Fager and McGowan 1963 (similarity)\n% FD Forbes 1907's D (similarity)\n% fleiss Fleiss 1975 (similarity)\n% forbes Forbes 1925 (similarity)\n% fossum Fossum (similarity) (also called Jones and Curtis)\n% gilbert Gilbert's coefficient (similarity)\n% gini Gini 1912 index (similarity)\n% GK1 Goodman and Kruskal 1954 1 (similarity)\n% GK2 Goodman and Kruskal 1954 2 (similarity)\n% GK3 Goodman and Kruskal 1954 3 (similarity)\n% GK4 Goodman and Kruskal 1954 4 (similarity)\n% GKlambda Goodman and Kruskal's lambda (similarity)\n% GKtau Goodman and Kruskal's tau (similarity)\n% goodall Goodall 1967's angular transformation of simple matching coefficient (similarity) (also called Austin and Colwell)\n% gower Gower (similarity)\n% GW Gilbert and Wells 1966 (similarity)\n% hamann Hamann 1961 (similarity)\n% HD Hawkins and Dotson 1975 (similarity)\n% hellinger Hellinger (dissimilarity)\n% inprod Inner product (similarity)\n% int Intersection of two masks (similarity)\n% jaccard Jaccard 1908 (similarity) (also called similarity ratio or Tanimioto)\n% johnson Johnson 1967 (similarity) (also called McConnaughey 1964)\n% Kcam Kuhns 1965's coefficient of arithmetic means (similarity)\n% Ko1 Koppen 1884 (similarity)\n% Ko2 Koppen 1870 (similarity)\n% Kpoai Kuhns 1965's proportion of overlap above independence (similarity)\n% kulczynski Kulczynski 1927 1 (similarity)\n% meanman Mean Manhattan (dissimilarity) (also called Canberra or Sneath total difference)\n% michael Michael 1920 (similarity)\n% mirkin Mirkin (dissimilarity)\n% MK Maron and Kuhns 1960 (similarity)\n% modgini Modified gini index (similarity)\n% mountford Mountford 1962 (similarity)\n% MP Maxwell and Pilliner 1968 (similarity)\n% ochiai Ochiai 1957 (similarity) (also called Driver and Kroeber or Otsuka)\n% pattern Pattern (dissimilarity)\n% Pcs Pearson 1905 chi-square (similarity)\n% Pei1 Peirce 1884 1 (similarity)\n% Pei2 Peirce 1884 2 (similarity)\n% PH Pearson and Heron 1913 (similarity)\n% PHI Fourfold point correlation (similarity) (also called Pearson and Heron 1913)\n% Pmsc Pearson 1905's coefficient of mean square contingency (similarity)\n% Q0 Q0 (Batagelj and Bren 1995) (dissimilarity)\n% Rcost R cost\n% RDeprob Relative decrease of error probability (similarity)\n% Rpattern Retrieval pattern (similarity)\n% RR Russell and Rao 1940 (similarity)\n% RT Rogers and Tanimoto 1960 (similarity)\n% savage Savage (dissimilarity)\n% Scost S cost\n% scott Scott 1955 (similarity)\n% simpson Simpson 1943's ecological coexistence coefficient (similarity) (also called overlap)\n% SM Sokal and Michener 1958's simple matching (similarity) (also called Rand or Kendall)\n% soergel Soergel distance\n% sorensen Sorensen 1948 (similarity)\n% sorgenfrei Sorgenfrei 1958 (similarity) (also called Fowlkes-Mallows)\n% Spattern Sneath pattern difference (dissimilarity)\n% SS1 Sokal and Sneath 1963 1 (similarity)\n% SS2 Sokal and Sneath 1963 2 (similarity)\n% SS3 Sokal and Sneath 1963 3 (similarity)\n% SS4 Sokal and Sneath 1963 4 (similarity) (also called Anderberg)\n% SS5 Sokal and Sneath 1963 5 (similarity) (also called Ochiai 2)\n% Stau Stuart's tau (similarity)\n% steffensen Steffensen 1934 (dissimilarity)\n% stiles Stiles (similarity)\n% Tcost T combined cost\n% tarantula Tarantula (Jones et al., 2002 & 2005) (similarity)\n% tarwid Tarwid 1960 (similarity)\n% tversky Tversky 1977's feature contrast model (similarity)\n% Ucost U cost\n% unigram Unigram subtuples\n% US Upholt 1977's S\n% US Upholt 1977's F \n% var Variance (dissimilarity)\n% YQ Yule 1911's Q coefficient of association (similarity)\n% YQD Yule's Q (Yule and Kendall, 1957) distance (dissimilarity)\n% YY Yule 1912's Y (or omega) coefficient of colligation (similarity)\n% \n% \n% Author: Jeffrey M. Spielberg (jspielb2@gmail.com)\n% Version: 05.06.16\n% \n% WARNING: This is a beta version. There no known bugs, but only limited \n% testing has been perfomed. This software comes with no warranty (even the\n% implied warranty of merchantability or fitness for a particular purpose).\n% Therefore, USE AT YOUR OWN RISK!!!\n%\n% Copyleft 2014-2016. Software can be modified and redistributed, but \n% modifed, redistributed versions must have the same rights\n\nmat1 = double(mat1>0);\nmat2 = double(mat2>0);\n\nif nargin==2||isempty(type)\n type = 'dice';\n mask = ones(size(mat1));\nelseif nargin<4\n mask = ones(size(mat1));\nelseif nargin==4\n mask = double(mask>0);\nend\n\nmat1 = mat1.*mask;\nmat2 = mat2.*mask;\nnmat1 = not(mat1).*mask;\nnmat2 = not(mat2).*mask;\n\na = sumn(mat1.*mat2);\nb = sumn(nmat1.*mat2);\nc = sumn(mat1.*nmat2);\nd = sumn(nmat1.*nmat2);\ntot = a+b+c+d;\nq = (a+b)*(a+c)*(b+d)*(c+d);\n\nswitch type\n case 'AD' % Anderberg's D (similarity) (measures the reduction in error probability when one item is used to predict the other) (range: 0:1)\n t1 = max(a,b)+max(c,d)+max(a,c)+max(b,d);\n t2 = max((a+c),(b+d))+max((a+d),(c+d));\n out = (t1-t2)/(2*tot);\n case 'AMPLE' % Analyzing Method Patterns to Locate Errors (Dallmeier et al, 2005) (similarity) (undefined when a+b and/or c+d are 0)\n out = abs((a/(a+b))-(c/(c+d)));\n case 'anderberg' % Anderberg 1973 (similarity)\n out = (8*a)/((8*a)+b+c);\n case 'baulieu' % Baulieu 1989 (dissimilarity) (also called size difference) (range: 0:Inf)\n out = ((b-c)^2)/(tot^2);\n case 'BB' % Braun and Blanquet 1932 (similarity) (range: 0:1)\n out = a/max((a+b),(a+c));\n case 'bc' % bc (dissimilarity)\n out = (4*b*c)/(tot^2);\n case 'benini' % Benini 1901 (similarity)\n out = (a-((a+b)*(a+c)))/(a+min(b,c)-((a+b)*(a+c)));\n case 'Beuc' % Binary euclidean distance (dissimilarity) (range: 0:Inf)\n out = sqrt(b+c);\n case 'BLWMN' % Binary Lance and Williams nonmetric (dissimilarity) (also called Sokal and Sneath nonmetric or Bray and Curtis) (range: 0:1)\n out = (b+c)/((2*a)+b+c);\n case 'Bpattern' % Browsing pattern (similarity)\n out = a-(b*c);\n case 'BSeuc' % Binary squared euclidean distance (dissimilarity) (also called Hamming, city block, Manhattan, or Filkov) (range: 0:Inf)\n out = b+c;\n case 'Bshape' % Binary shape (dissimilarity) (range: no limits)\n out = ((tot*(b+c))-((b-c)^2))/(tot^2);\n case 'BUB1' % Baroni-Urbani and Buser 1976 1 (similarity) (range: 0:1)\n out = (sqrt(a*d)+a)/(sqrt(a*d)+a+b+c);\n case 'BUB2' % Baroni-Urbani and Buser 1976 2 (similarity)\n out = (sqrt(a*d)+a-b-c)/(sqrt(a*d)+a+b+c);\n case 'chiY' % Chi Square with correction of Yates\n out = (tot*(abs((a*d)-(b*c))-(tot/2))^2)/q;\n case 'chord' % Chord (dissimilarity)\n out = sqrt(2*(1-(a/sqrt((a+b)*(a+c)))));\n case 'CK' % Cohen's kappa (similarity)\n out = (2*((a*d)-(b*c)))/(((a+b)*(b+d))+((a+c)*(c+d)));\n case 'cole' % Cole 1949 (similarity) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = ((a*d)-(b*c))/min(((a+b)*(a+c)),((b+d)*(c+d)));\n case 'dennis' % Dennis (similarity)\n out = ((a*d)-(b*c))/sqrt(tot*(a+b)*(a+c));\n case 'dice' % Dice (similarity) (also called Nei and Lei's genetic coefficient, Czekanowski, Sorenson, Bray, Upholt's F, Gower and Legendre's T, or percent positive agreement) (range: 0:1)\n out = (2*a)/((2*a)+b+c);\n case 'diceasym1' % Dice asymmetric 1 (similarity)\n out = a/(a+c);\n case 'diceasym2' % Dice asymmetric 2 (similarity)\n out = a/(a+b);\n case 'digby' % Digby 1983 (similarity) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = (((a*d)^(3/4))-((b*c)^(3/4)))/(((a*d)^(3/4))+((b*c)^(3/4)));\n case 'disper' % Dispersion (similarity) (range: -1:1)\n out = ((a*d)-(b*c))/(tot^2);\n case 'DK' % Driver and Kroeber 1932 (similarity) (also called Kulczynski 1927 2) (measures the conditional probability that both items are positive) (range: 0:1)\n out = (a/2)*((1/(a+b))+(1/(a+c)));\n case 'eyraud' % Eyraud 1936 (similarity) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = (a-((a+b)*(a+c)))/q;\n %out = ((tot^2)*((tot*a)-((a+b)*(a+c))))/q; % Alternative formula\n case 'fager' % Fager (similarity)\n out = (a/sqrt((a+b)*(a+c)))-(1/(2*sqrt(min((a+b),(a+c)))));\n %out = (a/(((a+b)*(a+c))^2))-(max(b,c)/2); % Alternative formula\n case 'faith' % Faith (similarity)\n out = (a+(0.5*d))/tot;\n case 'FaMc' % Fager and McGowan 1963 (similarity)\n out = (a/sqrt((a+b)*(a+c)))-((a+max(b,c))/2);\n case 'FD' % Forbes 1907's D (similarity) (also called Kocher and Wong)\n out = (a*tot)/((a+b)*(a+c));\n case 'fleiss' % Fleiss 1975 (similarity) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = (((a*d)-(b*c))*(((a+b)*(b+d))+((a+c)*(c+d))))/(2*q);\n case 'forbes' % Forbes 1925 (similarity) (also called Loevinger's H) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = ((tot*a)-((a+b)*(a+c)))/((tot*min((a+b),(a+c)))-((a+b)*(a+c)));\n %out = ((tot*a)-((a+b)*(a+c)))/((tot*min(b,c))-((a+b)*(a+c))); % Alternative formula\n case 'fossum' % Fossum (similarity) (also called Jones and Curtis)\n out = (tot*((a-0.5)^2))/((a+b)*(a+c));\n case 'gilbert' % Gilbert's coefficient (similarity) (undefined under certain circumstances)\n out = (a-((a+b)*(a+c)))/(a+b+c-((a+b)*(a+c)));\n case 'gini' % Gini 1912 index (similarity) (undefined under certain circumstances)\n out = (a-((a+b)*(a+c)))/sqrt((1-((a+b)^2))*(1-((a+c)^2)));\n case 'GKlambda' % Goodman and Kruskal's lambda (similarity) (measures the proportional reduction in error using one item to predict another) (range: 0:1)\n t1 = max(a,b)+max(c,d)+max(a,c)+max(b,d);\n t2 = max((a+c),(b+d))+max((a+d),(c+d));\n out = (t1-t2)/((2*tot)-t2);\n case 'GKtau' % Goodman and Kruskal's tau (similarity) (undefined when a+b and/or c+d are 0)\n out = (((((a-((a+b)*(a+c)))^2)+((b-((a+b)*(b+d)))^2))/(a+b))/(1-((a+c)^2)-((b+d)^2)))+(((((c-((a+c)*(c+d)))^2)+((d-((b+d)*(c+d)))^2))/(c+d))/(1-((a+c)^2)-((b+d)^2)));\n case 'GK1' % Goodman and Kruskal 1 1954 (similarity)\n out = ((2*min(a,d))-b-c)/((2*min(a,d))+b+c);\n case 'GK2' % Goodman and Kruskal 2 1954 (similarity)\n out = (max(a,c)+max(b,d)-max((a+b),(c+d)))/(1-max((a+b),(c+d)));\n case 'GK3' % Goodman and Kruskal 3 1954 (similarity)\n out = (a+d-max(a,d)-((b+c)/2))/(1-max(a,d)-((b+c)/2));\n case 'GK4' % Goodman and Kruskal 4 1954 (similarity)\n out = ((max(a,b)+max(c,d)+max(a,c)+max(b,d))/(2-max((a+c),(b+d))-max((a+b),(c+d))))-((max((a+c),(b+d))+max((a+b),(c+d)))/(2-max((a+c),(b+d))-max((a+b),(c+d))));\n case 'goodall' % Goodall 1967's angular transformation of simple matching coefficient (similarity) (also called Austin and Colwell)\n out = asin(sqrt((a+d)/tot))/(50*pi);\n case 'gower' % Gower (similarity) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = (a+d)/sqrt(q);\n case 'GW' % Gilbert and Wells 1966 (similarity) (undefined when a+b and/or a+c are 0)\n out = log((a*tot)/((a+b)*(a+c)));\n case 'hamann' % Hamann 1961 (similarity) (range: -1:1)\n out = ((a+d)-(b+c))/tot;\n case 'HD' % Hawkins and Dotson 1975 (similarity)\n out = 0.5*((a/(a+b+c))+(d/(b+c+d)));\n case 'hellinger' % Hellinger (dissimilarity)\n out = 2*sqrt(1-(a/sqrt((a+b)*(a+c))));\n case 'inprod' % Inner product (similarity)\n out = a+d;\n case 'int' % Intersection of two masks (similarity)\n out = a;\n case 'jaccard' % Jaccard 1908 (similarity) (also called similarity ratio or Tanimioto) (range: 0:1)\n out = a/(a+b+c);\n case 'johnson' % Johnson 1967 (similarity) (also called McConnaughey 1964)\n out = (a/(a+b))+(a/(a+c));\n case 'Kcam' % Kuhns 1965's coefficient of arithmetic means (similarity)\n out = (2*((a*d)-(b*c)))/(tot*((2*a)+b+c));\n case 'Ko1' % Koppen 1884 (similarity)\n out = a+((b+c)/2);\n case 'Ko2' % Koppen 1870 (similarity) (undefined when a+b and/or 1-a-b are 0)\n out = (((a+b)*(1-a-b))-c)/((a+b)*(1-a-b));\n case 'Kpoai' % Kuhns 1965's proportion of overlap above independence (similarity) (undefined when a+c and/or a+c are 0)\n out = ((a*d)-(b*c))/(tot*(a/((a+b)*(a+c)))*((2*a)+b+c-(((a+b)*(a+c))/tot)));\n case 'kulczynski' % Kulczynski 1927 1 (similarity) (range: 0:Inf)\n out = a/(b+c);\n case 'meanman' % Mean Manhattan (dissimilarity) (also called Canberra or Sneath total difference)\n out = (b+c)/tot;\n case 'michael' % Michael 1920 (similarity) (range: 0:1)\n out = (4*((a*d)-(b*c)))/(((a+d)^2)+((b+c)^2));\n case 'mirkin' % Mirkin (dissimilarity)\n out = 2*(b+c);\n case 'MK' % Maron and Kuhns 1960 (similarity)\n out = ((a*d)-(b*c))/tot;\n case 'modgini' % Modified gini index (similarity)\n out = (a-((a+b)*(a+c)))/(1-(abs(b-c)/2)-((a+b)*(a+c)));\n case 'mountford' % Mountford 1962 (similarity)\n out = a/((0.5*((a*b)+(a*c)))+(b*c));\n case 'MP' % Maxwell and Pilliner 1968 (similarity) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = (2*((a*d)-(b*c)))/q;\n case 'ochiai' % Ochiai 1957 (similarity) (also called Driver and Kroeber or Otsuka) (binary form of cosine similarity) (range: 0:1)\n out = a/sqrt((a+b)*(a+c));\n case 'pattern' % Pattern (dissimilarity) (range: 0:1)\n out = (b*c)/(tot^2);\n case 'Pcs' % Pearson 1905 chi-square (similarity) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = (tot*(((a*d)-(b*c))^2))/q;\n case 'Pmsc' % Pearson 1905's coefficient of mean square contingency (similarity) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n ch2 = (tot*(((a*d)-(b*c))^2))/q;\n out = sqrt(ch2/(tot+ch2));\n case 'Pei1' % Peirce 1884 1 (similarity) (undefined when a+c and/or b+d are 0)\n out = ((a*b)-(b*c))/((a+c)*(b+d));\n case 'Pei2' % Peirce 1884 2 (similarity) (undefined when a+c and/or b+d are 0)\n out = ((a*b)+(b*c))/((a*b)+(2*b*c)+(c*d));\n case 'PHI' % Fourfold point correlation (similarity) (also called Pearson and Heron 1913) (binary form of the Pearson product-moment correlation) range: 0:1) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = ((a*d)-(b*c))/sqrt(q);\n case 'PH' % Pearson and Heron 1913 (similarity) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = cos((180*sqrt(b*c))/(sqrt(a*d)+sqrt(b*c)));\n case 'Q0' % Q0 (Batagelj and Bren 1995) (dissimilarity) (range: 0:Inf) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = (b*c)/(a*d);\n case 'Rcost' % R cost\n out = log(1+(a/(a+b)))*log(1+(a/(a+c)));\n case 'RDeprob' % Relative decrease of error probability (similarity)\n out = (max(a,b)+max(c,d)-max((a+c),(b+d)))/(1-max((a+c),(b+d)));\n case 'Rpattern' % Retrieval pattern (similarity)\n out = a*d;\n case 'RR' % Russell and Rao 1940 (similarity) (range: 0:1)\n out = a/tot;\n case 'RT' % Rogers and Tanimoto 1960 (similarity) (binary dot product) (range: 0:1)\n out = (a+d)/(a+d+(2*(b+c)));\n case 'savage' % Savage (dissimilarity)\n out = 1-(a/(a+max(b,c)));\n case 'Scost' % S cost\n out = log(1+min(b,c)/(a+1))^-.5;\n case 'scott' % Scott 1955 (similarity)\n out = ((4*((a*d)-(b*c)))-((b-c)^2))/(((2*a)+b+c)+(b+c+(2*d)));\n case 'simpson' % Simpson 1943's ecological coexistence coefficient (similarity) (also called overlap) (range: 0:1)\n out = a/min((a+b),(a+c));\n case 'SM' % Sokal and Michener 1958's simple matching (similarity) (also called Rand or Kendall) (range: 0:1)\n out = (a+d)/tot;\n case 'soergel' % Soergel distance\n out = (b+c)/(b+c+d);\n case 'sorensen' % Sorensen 1948 (similarity)\n out = (4*a)/((4*a)+b+c);\n case 'sorgenfrei' % Sorgenfrei 1958 (similarity) (also called Fowlkes-Mallows)\n out = (a^2)/((a+b)*(a+c));\n case 'Spattern' % Sneath pattern difference (dissimilarity)\n out = (2*sqrt(b*c))/tot;\n case 'SS1' % Sokal and Sneath 1963 1 (similarity) (also called Gower and Legendre's S)\n out = (2*(a+d))/((2*(a+d))+b+c);\n case 'SS2' % Sokal and Sneath 1963 2 (similarity)\n out = a/(a+(2*(b+c)));\n case 'SS3' % Sokal and Sneath 1963 3 (similarity) (range: 0:Inf)\n out = (a+d)/(b+c);\n case 'SS4' % Sokal and Sneath 1963 4 (similarity) (also called Anderberg) (measures the conditional probability that both items are in the same state [present or absent]) (range: 0:1) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = ((a/(a+b))+(a/(a+c))+(d/(b+d))+(d/(c+d)))/4;\n case 'SS5' % Sokal and Sneath 1963 5 (similarity) (also called Ochiai 2) (range: 0:1) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = (a*d)/sqrt(q);\n case 'Stau' % Stuart's tau (similarity)\n out = 2*((a*d)-(b*c));\n case 'steffensen' % Steffensen 1934 (dissimilarity)\n out = (a-((a+b)*(a+c)))/2;\n case 'stiles' % Stiles (similarity) (undefined when a+b, b+d, a+c, and/or c+d are 0 and other circumstances)\n out = log10((tot*((abs((a*d)-(b*c))-(tot/2))^2))/q);\n case 'tarantula' % Tarantula (Jones et al., 2002 & 2005) (similarity) (undefined when a+b and/or c+d are 0)\n out = (a/(a+b))/((a/(a+b))+(c/(c+d)));\n case 'tarwid' % Tarwid 1960 (similarity)\n out = ((tot*a)-((a+b)*(a+c)))/((tot*a)+((a+b)*(a+c)));\n case 'Tcost' % T combined cost\n R = log(1+(a/(a+b)))*log(1+(a/(a+c)));\n S = log(1+min(b,c)/(a+1))^-.5;\n U = log(1+((min(b,c)+a)/(max(b,c)+a)));\n out = sqrt(U*S*R);\n case 'tversky' % Tversky 1977's feature contrast model (similarity)\n out = a-b-c;\n case 'Ucost' % U cost\n out = log(1+((min(b,c)+a)/(max(b,c)+a)));\n case 'unigram' % Unigram subtuples\n out = log((a*d)/(b*c))-(3.29*sqrt((1/a)+(1/b)+(1/c)+(1/d)));\n case 'UF' % Upholt 1977's F (also called Gower and Legendre's T)\n out = (2*a)/((2*a)+b+c);\n case 'US' % Upholt's S 1977\n F = (2*a)/((2*a)+b+c);\n out = (0.5*(-F+sqrt((F^2)+(8*F))))^(1/tot);\n case 'var' % Variance (dissimilarity) (range: 0:Inf)\n out = (b+c)/(4*tot);\n case 'YQ' % Yule 1911's Q coefficient of association (similarity) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = ((a*d)-(b*c))/((a*d)+(b*c));\n case 'YQD' % Yule's Q distance (dissimilarity) (range: -1:1) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = (b*c)/((a*d)+(b*c));\n case 'YY' % Yule 1912's Y (or omega) coefficient of colligation (similarity) (range: -1:1) (undefined when a+b, b+d, a+c, and/or c+d are 0)\n out = (sqrt(a*d)-sqrt(b*c))/(sqrt(a*d)+sqrt(b*c));\nend\n\nfunction out = sumn(in)\nout = sum(in(:));\n", "meta": {"author": "bahanonu", "repo": "ciatah", "sha": "f25f27660d985795ccb1012a799ab7e0d7afc596", "save_path": "github-repos/MATLAB/bahanonu-ciatah", "path": "github-repos/MATLAB/bahanonu-ciatah/ciatah-f25f27660d985795ccb1012a799ab7e0d7afc596/_external_programs/_file_exchange/simbin/simbin.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.7023995967721024}} {"text": "function [ r, info ] = r8pp_fa ( n, a )\n\n%*****************************************************************************80\n%\n%% R8PP_FA factors a R8PP matrix.\n%\n% Discussion:\n%\n% The R8PP storage format is appropriate for a symmetric positive\n% definite matrix. Only the upper triangle of the matrix is stored,\n% by successive partial columns, in an array of length (N*(N+1))/2,\n% which contains (A11,A12,A22,A13,A23,A33,A14,...,ANN) \n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 19 February 2004\n%\n% Author:\n%\n% MATLAB version by John Burkardt\n%\n% Reference:\n%\n% Dongarra, Moler, Bunch and Stewart,\n% LINPACK User's Guide,\n% SIAM, (Society for Industrial and Applied Mathematics),\n% 3600 University City Science Center,\n% Philadelphia, PA, 19104-2688.\n% ISBN 0-89871-172-X\n%\n% Parameters:\n%\n% Input, integer N, the order of the matrix.\n%\n% Input, real A((N*(N+1))/2), a R8PP matrix.\n%\n% Output, real R((N*(N+1))/2), an upper triangular matrix R, stored \n% in packed form, so that A = R'*R.\n%\n% Output, integer INFO, error flag.\n% 0, for normal return.\n% K, if the leading minor of order K is not positive definite.\n%\n info = 0;\n\n r(1:(n*(n+1))/2) = a(1:(n*(n+1))/2);\n\n jj = 0;\n\n for j = 1 : n\n\n s = 0.0E+00;\n kj = jj;\n kk = 0;\n\n for k = 1 : j-1\n\n kj = kj + 1;\n t = r(kj);\n for i = 1 : k-1\n t = t - r(kk+i) * r(jj+i);\n end\n kk = kk + k;\n t = t / r(kk);\n r(kj) = t;\n s = s + t * t;\n\n end\n\n jj = jj + j;\n s = r(jj) - s;\n\n if ( s <= 0.0E+00 )\n info = j;\n return;\n end\n\n r(jj) = sqrt ( s );\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/r8pp_fa.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7023539430138405}} {"text": "function otr = transform(itr,tmx)\n\n%\n% FUNCTION\n% otr = transform(itr,tmx)\n%\n% DESCRIPTION\n% transform 3D-tensor (Euclidean or Cartesion tensor) of any order (>0) to another coordinate system\n%\n% PARAMETERS\n% otr = output tensor, after transformation; has the same dimensions as the input tensor\n% itr = input tensor, before transformation; should be a 3-element vector, a 3x3 matrix, or a 3x3x3x... multidimensional array, each dimension containing 3 elements\n% tmx = transformation matrix, 3x3 matrix that contains the direction cosines between the old and the new coordinate system\n%\n\nne = numel(itr); % number of tensor elements\nnd = ndims(itr); % number of tensor dimensions, i.e. order of tensor\nif (ne==3), nd = 1; end % order of tensor is 1 in case of a 3x1 or 1x3 vector\n\notr = itr; % create output tensor\notr(:) = 0; % fill output tensor with zeros; this way a symbolic tensor remains symbolic\n\niie = zeros(nd,1); % initialise vector with indices of input tensor element\nioe = zeros(nd,1); % initialise vector with indices of output tensor element\ncne = cumprod(3*ones(nd,1))/3; % vector with cumulative number of elements for each dimension (divided by three)\n\nfor oe = 1:ne, % loop over all output elements\n ioe = mod(floor((oe-1)./cne),3)+1; % calculate indices of current output tensor element\n for ie = 1:ne, % loop over all input elements\n pmx = 1; % initialise product of transformation matrices\n iie = mod(floor((ie-1)./cne),3)+1; % calculate indices of current input tensor element\n for id = 1:nd, % loop over all dimensions\n pmx = pmx * tmx( ioe(id), iie(id) ); % create product of transformation matrices\n end\n otr(oe) = otr(oe) + pmx * itr(ie); % add product of transformation matrices and input tensor element to output tensor element\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/8333-transform-tensor/transform.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.7023058147954359}} {"text": "function L = gaussianNoiseExpectationLogLikelihood(noise, mu, varsigma, y)\n\n% GAUSSIANNOISEEXPECTATIONLOGLIKELIHOOD Likelihood of the data under the GAUSSIAN noise model.\n% FORMAT\n% DESC returns the likelihoods for data points under the Gaussian noise model.\n% ARG noise : the noise structure for which the likelihood is required.\n% ARG mu : input mean locations for the likelihood.\n% ARG varSigma : input variance locations for the likelihood.\n% ARG y : target locations for the likelihood.\n%\n% SEEALSO : gaussianNoiseParamInit, gaussianNoiseLogLikelihood, noiseLikelihood\n%\n% COPYRIGHT : Neil D. Lawrence, 2004, 2005\n\n\n\nN = size(y, 1);\nD = size(y, 2);\nvarsigma = varsigma + noise.sigma2;\nfor i = 1:D\n mu(:, i) = mu(:, i) + noise.bias(i);\nend\narg = (mu - y)./sqrt(varsigma);\nL = (2*pi*varsigma).^(-1/2).*exp( - .5*arg.*arg);\n", "meta": {"author": "SheffieldML", "repo": "GPmat", "sha": "4b5914a38ecbad9fb7a13a3392970bfc28c9d911", "save_path": "github-repos/MATLAB/SheffieldML-GPmat", "path": "github-repos/MATLAB/SheffieldML-GPmat/GPmat-4b5914a38ecbad9fb7a13a3392970bfc28c9d911/noise/gaussianNoiseExpectationLogLikelihood.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.7021321424143718}} {"text": "function [ mD ] = CalcDistanceMatrixCRows( mX )\n% ----------------------------------------------------------------------------------------------- %\n% [ mD ] = CalcDistanceMatrixARows( mX )\n% Calculates the distance matrix for the input data. The distance matrix\n% is a symmetric matrix where 'mD(ii, jj) = dist(mX(ii, :), mX(jj, :));'.\n% This function uses the squared Euclidean Distance for the distance\n% metric.\n% Input:\n% - mX - Data Matrix.\n% Each data sample is a row of the matrix.\n% Structure: Matrix (numVars x varDim).\n% Type: 'Single' / 'Double'.\n% Range: (-inf, inf).\n% Output:\n% - mD - Distance Matrix.\n% A symmetric matrix where 'mD(ii, jj) = dist(mX(ii,\n% :), mX(jj, :));'.\n% Structure: Matrix (numVars x numVars).\n% Type: 'Single' / 'Double'.\n% Range: [0, inf).\n% References\n% 1. A\n% Remarks:\n% 1. B\n% TODO:\n% 1. C\n% Release Notes:\n% - 1.0.000 01/01/2021 Royi Avital\tRoyiAvital@yahoo.com\n% * First release version.\n% ----------------------------------------------------------------------------------------------- %\n\nFALSE = 0;\nTRUE = 1;\n\nOFF = 0;\nON = 1;\n\nmG = mX * mX.';\nvG = diag(mG);\n\nmD = vG.' + vG - (2 * mG);\n\n\nend\n\n", "meta": {"author": "RoyiAvital", "repo": "StackExchangeCodes", "sha": "d2a934616995fa8a9f4df1ca29029402435b9e6f", "save_path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes", "path": "github-repos/MATLAB/RoyiAvital-StackExchangeCodes/StackExchangeCodes-d2a934616995fa8a9f4df1ca29029402435b9e6f/CodeReview/Q254186/CalcDistanceMatrixCRows.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.7021321358790749}} {"text": "%NS1\n% Numerical solution of 2-D instationary Navier-Stokes equations.\n% Rectangular domain; nonuniform Cartesian staggered grid.\n% Time discretization with omega-scheme.\n% Pressure-correction method.\n% Central or upwind scheme for inertia terms.\n\n% Copyright 2001 P. Wesseling\n% This program and its subprograms may be freely used, modified and distributed\n% under the GNU General Public License: http://www.gnu.org/copyleft/gpl.html\n\n% Theory is given in Chapter 6 of\n% \tPrinciples of Computational Fluid Dynamics, by P. Wesseling\n% \tSpringer-Verlag, Berlin etc., 2001. ISBN 3-540-67853-0\n% See http://dutita0.twi.tudelft.nl/nw/users/wesseling/\n\n% Theory is also given in Chapter 5 of\n%\tComputational Fluid Dynamics\n%\tLecture Notes by P. Wesseling\n%\tDepartment of Applied Mathematical Analysis, ITS, TU Delft\n% See http://ta.twi.tudelft.nl/nw/users/wesseling/\n\n% This program generates Figures and in the Lecture Notes.\n\n% Functions called: startup,problem_specification, grid_generation, draw_grid,\n%\t\t viscous_matrix, grad_and_div, initial_condition, \n%\t\t right_hand_side, inertia_matrix, errornorm, isobarplot,\n%\t\t streamlineplot, velocity_profile, relchangeplot \n\nstartup, format compact, clear all\ntime0 = clock;\nglobal geval n u0 v0 J K yu yv yseglen alpha\n% ........................................Input..............................\ngeval = 3;\t% Enter 1 for horizontal Poiseuille flow to the right\n\t\t% or 2 for vertical Poiseuille flow\n\t\t% or 3 for backward facing step\n\t\t% or 4 for driven cavity\n\t\t% or 5 for uniform flow under angle alpha without segmentation\n\t\t% or 6 for uniform flow under angle alpha with segmentation\n\t\t% or 7 for horizontal Poiseuille flow to the left\n\t\t\nproblem_specification\t% Prepare file problem_specification.m as part of input\n% User must prepare files ubd.m, vbd.m, pbd.m to specify boundary values \n\n% .................................End of input......................\n\ngrid_generation\ndraw_grid\nh = waitbar(0,'Computing...');\nviscous_matrix\t\t% Generate viscous matrices Bu, Bv and Masku, Maskv\ngrad_and_div\t\t% Generate pressure gradient matrices Pu, Pv and \n\t\t\t% divergence matrices Du, Dv\ninitial_condition\t% Generate initial u0, v0, p0 \ntic\t\t \n[Lp,Up] = lu([Du Dv]*[Pu;Pv]);\t% LU decomposition of pressure correction matrix\ntijd = toc; disp(['Pres. corr. matrix LU time = ',num2str(tijd)])\nif max(abs(sum(([Du Dv]*[Pu;Pv])'))) < 10*eps\t\t\n % Do consistency check\nend\n\nnstep = floor(tend/dt);\t% Number of time steps\n%nstep = 2;\nrelchange = zeros(nstep,1);\t% For plotting relative change per time step\nt = 0; n = 0;\nright_hand_side\t\t% Generate right-hand sides ru, rv; has to be moved\n\t\t\t% inside time loop if boundary conditions time-dependent\nu1 = u0; v1 = v0;\nfor n = 1:nstep\t\t% Time-stepping with omega scheme\n t = n*dt;\n u0 = u1; v0 = v1;\n% right_hand_side\t% Generate right-hand sides ru, rv; can be moved outside\n\t\t\t% time loop if boundary conditions not time-dependent\n\n % Navier-Stokes, predictor:\n inertia_matrix\t% Generate inertia matrices and adapt right-hand sides \n rum = (ru + rum)'; rvm = (rv + rvm)'; rum = rum(:); rvm = rvm(:);\n if n == 1, tic, end\n Cu = dt*(Bu + Cu); Cv = dt*(Bv + Cv);\n u1 = (speye(length(u0)) + omega*Cu)\\...\n (Masku*u0 + dt*(rum - Pu*p0) - (1-omega)*Cu*u0);\n v1 = (speye(length(v0)) + omega*Cv)\\...\n (Maskv*v0 + dt*(rvm - Pv*p0) - (1-omega)*Cv*v0);\n \n % End of Navier-Stokes predictor\n \n % Stokes:\n %rum = ru'; rum = rum(:); rvm = rv'; rvm = rvm(:); \n %if n == 1, tic, end \n %u1 = Bu\\(dt*(rum - Pu*p0) + Masku*u0); \n %v1 = Bv\\(dt*(rvm - Pv*p0) + Maskv*v0);\n % End of Stokes\n \n if n == 1, tijd = toc; disp(['velocity solve time = ',num2str(tijd)]), tic,end\n dp = Up\\(Lp\\(Du*u1 + Dv*v1));\tp0 = p0 + dp/dt;\n u1 = u1 - Pu*dp;\tv1 = v1 - Pv*dp;\n if n == 1, tijd = toc; disp(['press. corr. time = ',num2str(tijd)]),end\n mm = max([norm(u1,inf),norm(v1,inf)]); relchange(n) = max([norm(u1-u0,inf)...\n /mm,norm(v1-v0,inf)/mm, norm(dp,inf)/(norm(p0,inf) + 0.5*mm^2)]);\n waitbar(n/nstep)\nend\n\ndisp(['Relative change = ',num2str(relchange(end))])\ndivergence = norm(Du*u1 + Dv*v1,inf);\nif (geval==1)|(geval==2)\n errornorm\t\t% Maximum norm of error in outflow profile if exact\n\t\t\t% solution is available\nend\nclose(h)\ntic\nisobarplot\t\t% Plot of isobars and velocity vectors\nstreamlineplot \t\t% Plot of streamlines and velocity vectors\nvelocity_profile\t% Plot of velocity profiles\nrelchangeplot\t\t% Plot of relative change per time step\ntijd = toc; disp(['Plotting time = ',num2str(tijd)])\ndisp(['Total time = ',num2str(etime(clock,time0))])\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/chap6.5/ns1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.7021304655179877}} {"text": "function [H] = rotate(D);\n\n% ROTATE returns the homogenous coordinate transformation matrix\n% corresponding to a rotation around the x, y and z-axis. The direction of\n% the rotation is according to the right-hand rule.\n%\n% Use as\n% [H] = rotate(R)\n% where\n% R\t\t[rx, ry, rz] in degrees\n% H\t\tcorresponding homogenous transformation matrix\n%\n% Note that the order in which the rotations are performs matters. The\n% rotation is first done around the z-axis, then the y-axis and finally the\n% x-axis.\n\n% Copyright (C) 2000-2005, Robert Oostenveld\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\n% $Log: rotate.m,v $\n% Revision 1.1 2009/01/30 04:02:11 arno\n% *** empty log message ***\n%\n% Revision 1.5 2006/09/12 13:35:28 roboos\n% convert input rotation from degrees (according to documentation) into radians (needed for computations)\n%\n% Revision 1.4 2005/08/15 08:15:33 roboos\n% reimplemented the rotate function, which contained an error (the error is in the AIR technical reference)\n% changed all functions to be dependent on the rotate, translate and scale function\n% all functions now behave consistenly, which also means that they are not compleetly backward compatible w.r.t. the order of the rotations\n%\n% Revision 1.3 2004/05/19 09:57:07 roberto\n% added GPL copyright statement, added CVS log item\n%\n\n% convert degrees to radians\nR = D*pi/180;\n\n% get the individual angles (in radians)\nrx = R(1);\nry = R(2);\nrz = R(3);\n\n% precompute the sin/cos values of the angles\ncX = cos(rx);\ncY = cos(ry);\ncZ = cos(rz);\nsX = sin(rx);\nsY = sin(ry);\nsZ = sin(rz);\n\n% according to Roger Woods' http://bishopw.loni.ucla.edu/AIR5/homogenous.html\n% it should be this, but I cannot reproduce his rotation matrix\n% H = eye(4,4);\n% H(1,1) = cZ*cY + sZ*sX*sY;\n% H(1,2) = sZ*cY - cZ*sX*sY;\n% H(1,3) = cX*sY;\n% H(2,1) = -sZ*cX;\n% H(2,2) = cZ*cX;\n% H(2,3) = sX;\n% H(3,1) = sZ*sX*cY - cZ*sY;\n% H(3,2) = -cZ*sX*cY - sZ*sY;\n% H(3,3) = cX*cY;\n\n% instead, the following rotation matrix does work according my\n% expectations. It rotates according to the right hand rule and first\n% rotates around z, then y and then x axis\nH = [\n cZ*cY, -sZ*cY, sY, 0\n cZ*sY*sX+sZ*cX, -sZ*sY*sX+cZ*cX, -cY*sX, 0\n -cZ*sY*cX+sZ*sX, sZ*sY*cX+cZ*sX, cY*cX, 0\n 0, 0, 0, 1\n];\n\nif 0\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% The following code can be used to construct the combined rotation matrix\n% for either xyz or zyx ordering (using the Matlab symbolic math toolbox)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n syms sX sY sZ cX cY cZ\n % this is for only rotating around x\n Rx = [\n 1 0 0 0\n 0 cX -sX 0\n 0 sX cX 0\n 0 0 0 1\n ];\n % this is for only rotating around y\n Ry = [\n cY 0 sY 0\n 0 1 0 0\n -sY 0 cY 0\n 0 0 0 1\n ];\n % this is for only rotating around z\n Rz = [\n cZ -sZ 0 0\n sZ cZ 0 0\n 0 0 1 0\n 0 0 0 1\n ];\n % combine them\n Rzyx = Rz * Ry * Rx % rotate around x, y, then z\n Rxyz = Rx * Ry * Rz % rotate around z, y, then x\nend\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/plugins/dipfit2.2/private/rotate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.702110888539744}} {"text": "function [L,S,obj,err,iter] = igc(A,C,lambda,opts)\n\n% Reference: Chen, Yudong, Sujay Sanghavi, and Huan Xu. Improved graph clustering.\n% IEEE Transactions on Information Theory 60.10 (2014): 6440-6455.\n%\n% min_{L,S} ||L||_*+lambda*||C \\cdot S||_1, s.t. A=L+S, 0<=L<=1.\n%\n% ---------------------------------------------\n% Input:\n% A - d*n matrix\n% C - d*n matrix\n% lambda - >0, parameter\n% opts - Structure value in Matlab. The fields are\n% opts.tol - termination tolerance\n% opts.max_iter - maximum number of iterations\n% opts.mu - stepsize for dual variable updating in ADMM\n% opts.max_mu - maximum stepsize\n% opts.rho - rho>=1, ratio used to increase mu\n% opts.DEBUG - 0 or 1\n%\n% Output:\n% L - d*n matrix\n% S - d*n matrix\n% obj - objective function value\n% err - residual\n% iter - number of iterations\n%\n% version 1.0 - 19/06/2016\n%\n% Written by Canyi Lu (canyilu@gmail.com)\n% \n\ntol = 1e-8; \nmax_iter = 500;\nrho = 1.1;\nmu = 1e-4;\nmax_mu = 1e10;\nDEBUG = 0;\n\nif ~exist('opts', 'var')\n opts = [];\nend \nif isfield(opts, 'tol'); tol = opts.tol; end\nif isfield(opts, 'max_iter'); max_iter = opts.max_iter; end\nif isfield(opts, 'rho'); rho = opts.rho; end\nif isfield(opts, 'mu'); mu = opts.mu; end\nif isfield(opts, 'max_mu'); max_mu = opts.max_mu; end\nif isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end\n\nC = abs(C);\n[d,n] = size(A);\n\nL = zeros(d,n);\nS = L;\nZ = L;\nY1 = L;\nY2 = L;\n\niter = 0;\nfor iter = 1 : max_iter\n Lk = L;\n Sk = S;\n Zk = Z;\n % first super block {L,S}\n [L,nuclearnormL] = prox_nuclear(Z-Y2/mu,1/mu);\n S = prox_l1(-Z+A-Y1/mu,C*(lambda/mu));\n \n % second super block {Z}\n Z = project_box((-S+A+L+(Y2-Y1)/mu)/2,0,1);\n \n dY1 = Z+S-A;\n dY2 = L-Z;\n chgL = max(max(abs(Lk-L)));\n chgS = max(max(abs(Sk-S)));\n chgZ = max(max(abs(Zk-Z)));\n chg = max([chgL chgS chgZ max(abs(dY1(:))) max(abs(dY2(:)))]);\n if DEBUG\n if iter == 1 || mod(iter, 10) == 0\n obj = nuclearnormL+lambda*sum(sum(C.*abs(S)));\n err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2);\n disp(['iter ' num2str(iter) ', mu=' num2str(mu) ...\n ', obj=' num2str(obj) ', err=' num2str(err)]); \n end\n end\n \n if chg < tol\n break;\n end \n Y1 = Y1 + mu*dY1;\n Y2 = Y2 + mu*dY2;\n mu = min(rho*mu,max_mu); \nend\nobj = nuclearnormL+lambda*sum(sum(C.*abs(S)));\nerr = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2);\n\n", "meta": {"author": "canyilu", "repo": "LibADMM-toolbox", "sha": "fa9bc9458b8fbe22ac264c6008b26e7e41e70742", "save_path": "github-repos/MATLAB/canyilu-LibADMM-toolbox", "path": "github-repos/MATLAB/canyilu-LibADMM-toolbox/LibADMM-toolbox-fa9bc9458b8fbe22ac264c6008b26e7e41e70742/algorithms/igc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.7021108839417224}} {"text": "function triangulate ( prefix, animate )\n\n%*****************************************************************************80\n%\n%% TRIANGULATE triangulates a polygon using the ear slicing algorithm.\n%\n% Discussion:\n%\n% The polygon is described by a file which lists the coordinates of the\n% vertices in consecutive order during a counterclockwise traversal.\n%\n% Note that no two successive vertices can be equal, nor can the first\n% and last vertices be equal.\n%\n% Information about the polygon is stored as a structure we will call\n% a \"vertex array\".\n%\n% There is one entry in the array for each of the N vertices in the\n% polygon. The I-th entry is a structure with the following fields:\n%\n% vertex(i).index the index of the node.\n% vertex(i).next the index of the next node.\n% vertex(i).prev the index of the previous node.\n% vertex(i).x the X coordinate.\n% vertex(i).y the Y coordinate.\n% vertex(i).ear 1 if the vertex represents an \"ear\" that can\n% be sliced off.\n%\n% Usage:\n%\n% triangulate ( 'prefix', 'animate' )\n%\n% where\n%\n% * 'prefix' is the filename prefix\n% * 'animate' is 'y' if you want to see an animation of the triangulation.\n%\n% reads\n%\n% * 'prefix'_nodes.txt, the node coordinate file,\n%\n% creates\n%\n% * 'prefix'_diagonals.txt, the internal diagonals file.\n% * 'prefix'_elements.txt, the triangle file.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 January 2013\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, string PREFIX, the filename prefix.\n%\n% Input, string ANIMATE, is 'y' if the user wants to see the triangulation\n% process animated.\n%\n timestamp ( );\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGULATE\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Read a file listing the coordinates of the vertices\\n' );\n fprintf ( 1, ' of a polygon, and determine a triangulation.\\n' );\n%\n% If the user did not supply the filename prefix, request it.\n%\n if ( nargin < 1 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGULATE:\\n' );\n prefix = input ( ' Enter the filename prefix (in ''quotes''!).\\n' );\n end\n%\n% If the user did not supply the animation option, assume it is NO.\n%\n if ( nargin < 2 )\n animate = 'n';\n end\n%\n% Create filenames.\n%\n node_filename = strcat ( prefix, '_nodes.txt' );\n diagonal_filename = strcat ( prefix, '_diagonals.txt' );\n triangle_filename = strcat ( prefix, '_elements.txt' );\n%\n% Read the node coordinates.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Processing the vertex coordinate file \"%s\".\\n', node_filename )\n direction = +1;\n vertex = read_vertices ( node_filename, direction );\n\n vertex = ear_init ( vertex );\n\n area = area_poly2 ( vertex );\n%\n% If area is zero, refuse to go on.\n%\n if ( area == 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGULATE - Fatal area!\\n' );\n fprintf ( 1, ' The area is computed to be exactly zero.\\n' );\n return\n end\n%\n% If area is NEGATIVE, reverse the ordering.\n%\n if ( area < 0.0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Polygon area is negative!\\n' );\n fprintf ( 1, ' Will try reversing vertex ordering.\\n' );\n direction = -1;\n vertex = read_vertices ( node_filename, direction );\n vertex = ear_init ( vertex );\n area = area_poly2 ( vertex );\n end\n\n n = length ( vertex );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Number of vertices is %d\\n', n );\n\n print_vertices ( vertex );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Area of polygon is %g\\n', area );\n%\n% Refuse to triangulate a region in which two successive vertices are equal.\n%\n for i = 1 : n\n j = vertex(i).next;\n if ( vertex(i).x == vertex(j).x && vertex(i).y == vertex(j).y )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGULATE - Fatal error!\\n' );\n fprintf ( 1, ' Two neighbor vertices are equal.\\n' );\n fprintf ( 1, ' Vertex(%d) = Vertex(%d)\\n', i, j );\n error ( 'TRIANGULATE - Fatal error!' );\n end\n end\n%\n% Determine a reasonable scale for the plot.\n%\n xmin = vertex(1).x;\n xmax = vertex(1).x;\n ymin = vertex(1).y;\n ymax = vertex(1).y;\n for i = 2 : n\n xmin = min ( xmin, vertex(i).x );\n xmax = max ( xmax, vertex(i).x );\n ymin = min ( ymin, vertex(i).y );\n ymax = max ( ymax, vertex(i).y );\n end\n\n dx = 0.0125 * max ( xmax - xmin, ymax - ymin );\n%\n% Draw the (non-triangulated) polygon.\n%\n% You might think a single PLOT command would suffice to display\n% the vertices. However, the proper way of extracting a vector of\n% values from a structure eludes me.\n%\n figure ( 1 )\n\n clf\n\n grid on\n\n hold on\n%\n% Make the plot a little bigger than the data.\n%\n plot ( xmin - 2 * dx, ymin - 2 * dx, 'w.' );\n plot ( xmax + 2 * dx, ymin + 2 * dx, 'w.' );\n\n for i = 1 : n\n plot ( vertex(i).x, vertex(i).y, 'k.', 'MarkerSize', 25 )\n end\n\n for i = 1 : n \n text ( vertex(i).x + dx, vertex(i).y + dx, num2str ( i ) );\n end\n\n for i = 1 : n\n line ( [ vertex(i).x, vertex(vertex(i).next).x ], ...\n [ vertex(i).y, vertex(vertex(i).next).y ], ...\n 'LineWidth', 3, 'Color', 'r' )\n end\n\n xlabel ( '<-- X -->' )\n ylabel ( '<-- Y -->' )\n title ( prefix );\n axis equal\n%\n% Triangulate the polygon.\n%\n triangles = polygon_triangulate ( vertex );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Internal diagonals for triangulation:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n - 3\n fprintf ( 1, ' %2d %2d\\n', triangles(i,1:2) );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Triangles:\\n' );\n fprintf ( 1, '\\n' );\n for i = 1 : n - 2\n fprintf ( 1, ' %2d %2d %2d\\n', triangles(i,1:3) );\n end\n%\n% Draw the triangulated polygon.\n%\n figure ( 2 )\n\n clf\n\n grid on\n\n hold on\n%\n% Make the plot a little bigger than the data.\n%\n plot ( xmin - 2 * dx, ymin - 2 * dx, 'w.' );\n plot ( xmax + 2 * dx, ymin + 2 * dx, 'w.' );\n\n for i = 1 : n\n plot ( vertex(i).x, vertex(i).y, 'k.', 'MarkerSize', 25 )\n end\n\n for i = 1 : n \n text ( vertex(i).x + dx, vertex(i).y + dx, num2str ( i ) );\n end\n\n for i = 1 : n\n line ( [ vertex(i).x, vertex(vertex(i).next).x ], ...\n [ vertex(i).y, vertex(vertex(i).next).y ], 'LineWidth', 2, 'Color', 'r' )\n end\n\n for i = 1 : n - 3\n i1 = triangles(i,1);\n i2 = triangles(i,2);\n line ( [ vertex(i1).x, vertex(i2).x ], ...\n [ vertex(i1).y, vertex(i2).y ], 'LineWidth', 3, 'Color', 'b' )\n end\n\n xlabel ( '<-- X -->' )\n ylabel ( '<-- Y -->' )\n title ( sprintf ( 'Triangulation of \"%s\"', prefix ) );\n axis equal\n%\n% Optionally, animate the triangulation.\n%\n if ( animate == 'y' )\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' ANIMATION OPTION SELECTED!\\n' );\n fprintf ( 1, ' Press return to see each diagonal added.\\n' );\n\n figure ( 3 )\n\n clf\n\n grid on\n\n hold on\n%\n% Make the plot a little bigger than the data.\n%\n plot ( xmin - 2 * dx, ymin - 2 * dx, 'w.' );\n plot ( xmax + 2 * dx, ymin + 2 * dx, 'w.' );\n\n for i = 1 : n\n plot ( vertex(i).x, vertex(i).y, 'k.', 'MarkerSize', 25 )\n end\n\n for i = 1 : n \n text ( vertex(i).x + dx, vertex(i).y + dx, num2str ( i ) );\n end\n\n for i = 1 : n\n line ( [ vertex(i).x, vertex(vertex(i).next).x ], ...\n [ vertex(i).y, vertex(vertex(i).next).y ], 'LineWidth', 2, 'Color', 'r' )\n end\n\n for i = 1 : n - 3\n i1 = triangles(i,1);\n i2 = triangles(i,2);\n i3 = triangles(i,3);\n axis equal\n pause\n\n patch ( [ vertex(i1).x, vertex(i2).x, vertex(i3).x ], ...\n [ vertex(i1).y, vertex(i2).y, vertex(i3).y ], 'g' );\n\n line ( [ vertex(i1).x, vertex(i2).x ], ...\n [ vertex(i1).y, vertex(i2).y ], 'LineWidth', 3, 'Color', 'b' )\n\n axis equal\n\n end\n\n pause\n i = n - 2;\n i1 = triangles(i,1);\n i2 = triangles(i,2);\n i3 = triangles(i,3);\n line ( [ vertex(i1).x, vertex(i2).x ], ...\n [ vertex(i1).y, vertex(i2).y ], 'LineWidth', 3, 'Color', 'b' )\n\n patch ( [ vertex(i1).x, vertex(i2).x, vertex(i3).x ], ...\n [ vertex(i1).y, vertex(i2).y, vertex(i3).y ], 'g' );\n\n xlabel ( '<-- X -->' )\n ylabel ( '<-- Y -->' )\n title ( sprintf ( 'Triangulation of \"%s\"', prefix ) );\n axis equal\n\n end\n%\n% Write the diagonals to a file.\n%\n i4mat_write ( diagonal_filename, 2, n-3, triangles(1:n-3,1:2)' );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Diagonals written to \"%s\".\\n', diagonal_filename );\n%\n% Write the triangles to a file.\n%\n i4mat_write ( triangle_filename, 3, n-2, triangles(1:n-2,1:3)' );\n\n fprintf ( 1, ' Triangles written to \"%s\".\\n', triangle_filename );\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TRIANGULATE\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction area = area_poly2 ( vertex )\n\n%*****************************************************************************80\n%\n%% AREA_POLY2 computes the area of a polygon.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2011\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, vertex array VERTEX(*).\n%\n% Output, real AREA, the area of the polygon.\n%\n area = 0.0;\n\n first = 1;\n\n i = first;\n\n ip1 = vertex(i).next;\n if ( ip1 == first )\n return\n end\n\n ip2 = vertex(ip1).next;\n if ( ip2 == first )\n return\n end\n\n while ( 1 )\n\n area = area + triangle_area ( vertex(i), vertex(ip1), vertex(ip2) );\n\n i = ip1;\n ip1 = ip2;\n ip2 = vertex(ip1).next;\n\n if ( ip2 == first )\n break\n end\n\n end\n\n return\nend\nfunction value = between ( va, vb, vc )\n\n%*****************************************************************************80\n%\n%% BETWEEN is TRUE if vertex VC is between vertices VA and VB.\n%\n% Discussion:\n%\n% The points must be (numerically) collinear.\n%\n% Given that condition, we take the greater of VA.X - VB.X and VA.Y - VB.Y\n% as a \"scale\" and check where VC's value lies.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2011\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, real VA, VB, VC, the vertices.\n%\n% Output, integer VALUE, is 1 if VC is between VA and VB,\n% and 0 otherwise.\n%\n if ( ~collinear ( va, vb, vc ) )\n value = 0;\n return\n end\n\n if ( abs ( va.y - vb.y ) < abs ( va.x - vb.x ) )\n xmax = max ( va.x, vb.x );\n xmin = min ( va.x, vb.x );\n value = ( xmin <= vc.x && vc.x <= xmax );\n else\n ymax = max ( va.y, vb.y );\n ymin = min ( va.y, vb.y );\n value = ( ymin <= vc.y && vc.y <= ymax );\n end\n\n return\nend\nfunction value = collinear ( va, vb, vc )\n\n%*****************************************************************************80\n%\n%% COLLINEAR returns a measure of collinearity for three points.\n%\n% Discussion:\n%\n% In order to deal with collinear points whose coordinates are not\n% numerically exact, we compare the area of the largest square\n% that can be created by the line segment between two of the points\n% to (twice) the area of the triangle formed by the points.\n%\n% If the points are collinear, their triangle has zero area.\n% If the points are close to collinear, then the area of this triangle\n% will be small relative to the square of the longest segment.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2011\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, real VA, VB, VC, the vertices.\n%\n% Output, integer VALUE, is 1 if the points are judged to be collinear,\n% and 0 otherwise.\n%\n area = 0.5 * ( ( vb.x - va.x ) * ( vc.y - va.y ) ...\n - ( vc.x - va.x ) * ( vb.y - va.y ) );\n%\n% MATLAB's MAX function has decided to be unfriendly, and I am\n% too annoyed to try to figure out how to placate it when all\n% I want to say is M = max ( A, B, C )!\n%\n area_max = ( va.x - vb.x )^2 + ( va.y - vb.y )^2;\n area_max = max ( area_max, ( vb.x - vc.x )^2 + ( vb.y - vc.y )^2 );\n area_max = max ( area_max, ( vc.x - va.x )^2 + ( vc.y - va.y )^2 );\n\n if ( area_max <= eps )\n value = 1;\n elseif ( 2.0 * abs ( area ) <= eps * area_max )\n value = 1;\n else\n value = 0;\n end\n\n return\nend\nfunction value = diagonal ( im1, ip1, vertex )\n\n%*****************************************************************************80\n%\n%% DIAGONAL: VERTEX(IM1):VERTEX(IP1) is a proper internal diagonal.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 03 May 2014\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, integer IM1, IP1, the indices of two vertices.\n%\n% Input, vertex array VERTEX(*).\n%\n% Output, integer VALUE, the value of the test.\n%\n value = in_cone ( im1, ip1, vertex ) && ...\n in_cone ( ip1, im1, vertex ) && ...\n diagonalie ( im1, ip1, vertex );\n\n return\nend\nfunction value = diagonalie ( im1, ip1, vertex )\n\n%*****************************************************************************80\n%\n%% DIAGONALIE: VERTEX(IM1):VERTEX(IP1) is a proper diagonal.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 February 2011\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, integer IM1, IP1, the indices of two vertices.\n%\n% Input, vertex array VERTEX(*).\n%\n% Output, int VALUE, the value of the test.\n%\n first = im1;\n\n j = vertex(first).index;\n jp1 = vertex(first).next;\n\n value = 1;\n%\n% For each edge VERTEX(J):VERTEX(JP1) of the polygon:\n\n while ( 1 )\n%\n% Skip any edge that includes vertex IM1 or IP1.\n%\n if ( j == im1 || j == ip1 || jp1 == im1 || jp1 == ip1 )\n\n else\n if ( intersect ( vertex(im1), vertex(ip1), vertex(j), vertex(jp1) ) )\n value = 0;\n return\n end\n end\n\n j = jp1;\n jp1 = vertex(j).next;\n\n if ( j == vertex(first).index )\n break\n end\n\n end\n\n return\nend\nfunction vertex = ear_init ( vertex )\n\n%*****************************************************************************80\n%\n%% EAR_INIT initializes the \"earity\" of each vertex.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 February 2011\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input/output, vertex array VERTEX(*). On output, the \"ear\" field\n% of the vertex array has been initialized.\n%\n im1 = vertex(1).prev;\n i = vertex(1).index;\n ip1 = vertex(1).next;\n\n while ( 1 )\n\n vertex(i).ear = diagonal ( im1, ip1, vertex );\n\n im1 = i;\n i = ip1;\n ip1 = vertex(i).next;\n\n if ( i == vertex(1).index )\n break\n end\n\n end\n\n return\nend\nfunction value = i4_modp ( i, j )\n\n%*****************************************************************************80\n%\n%% I4_MODP returns the nonnegative remainder of I4 division.\n%\n% Discussion:\n%\n% If\n% NREM = I4_MODP ( I, J )\n% NMULT = ( I - NREM ) / J\n% then\n% I = J * NMULT + NREM\n% where NREM is always nonnegative.\n%\n% The MOD function computes a result with the same sign as the\n% quantity being divided. Thus, suppose you had an angle A,\n% and you wanted to ensure that it was between 0 and 360.\n% Then mod(A,360) would do, if A was positive, but if A\n% was negative, your result would be between -360 and 0.\n%\n% On the other hand, I4_MODP(A,360) is between 0 and 360, always.\n%\n% Example:\n%\n% I J MOD I4_MODP Factorization\n%\n% 107 50 7 7 107 = 2 * 50 + 7\n% 107 -50 7 7 107 = -2 * -50 + 7\n% -107 50 -7 43 -107 = -3 * 50 + 43\n% -107 -50 -7 43 -107 = 3 * -50 + 43\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 March 1999\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer I, the number to be divided.\n%\n% Input, integer J, the number that divides I.\n%\n% Output, integer VALUE, the nonnegative remainder when I is\n% divided by J.\n%\n if ( j == 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'I4_MODP - Fatal error!\\n' );\n fprintf ( 1, ' Illegal divisor J = %d\\n', j );\n error ( 'I4_MODP - Fatal error!' );\n end\n\n value = mod ( i, j );\n\n if ( value < 0 )\n value = value + abs ( j );\n end\n\n return\nend\nfunction value = i4_wrap ( ival, ilo, ihi )\n\n%*****************************************************************************80\n%\n%% I4_WRAP forces an integer to lie between given limits by wrapping.\n%\n% Example:\n%\n% ILO = 4, IHI = 8\n%\n% I Value\n%\n% -2 8\n% -1 4\n% 0 5\n% 1 6\n% 2 7\n% 3 8\n% 4 4\n% 5 5\n% 6 6\n% 7 7\n% 8 8\n% 9 4\n% 10 5\n% 11 6\n% 12 7\n% 13 8\n% 14 4\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 October 2006\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer IVAL, an integer value.\n%\n% Input, integer ILO, IHI, the desired bounds for the integer value.\n%\n% Output, integer I4_WRAP, a \"wrapped\" version of IVAL.\n%\n jlo = min ( ilo, ihi );\n jhi = max ( ilo, ihi );\n\n wide = jhi - jlo + 1;\n\n if ( wide == 1 )\n value = jlo;\n else\n value = jlo + i4_modp ( ival - jlo, wide );\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% 26 June 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string OUTPUT_FILENAME, the output filename.\n%\n% Input, integer M, the spatial dimension.\n%\n% Input, integer N, the number of points.\n%\n% Input, integer TABLE(M,N), the points.\n%\n\n%\n% Open the file.\n%\n output_unit = fopen ( output_filename, 'wt' );\n\n if ( output_unit < 0 )\n fprintf ( 1, '\\n' );\n fprintf ( 1, '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 value = in_cone ( im1, ip1, vertex )\n\n%*****************************************************************************80\n%\n%% IN_CONE is TRUE if the diagonal VERTEX(IM1):VERTEX(IP1) is strictly internal.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 February 2011\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, integer IM1, IP1, the indices of two vertices.\n%\n% Input, vertex array VERTEX(*).\n%\n% Output, int VALUE, the value of the test.\n%\n im2 = vertex(im1).prev;\n i = vertex(im1).next;\n\n if ( left_on ( vertex(im1), vertex(i), vertex(im2) ) )\n\n value = left ( vertex(im1), vertex(ip1), vertex(im2) ) && ...\n left ( vertex(ip1), vertex(im1), vertex(i) );\n\n else\n\n value = ~ ( left_on ( vertex(im1), vertex(ip1), vertex(i) ) && ...\n left_on ( vertex(ip1), vertex(im1), vertex(im2) ) );\n\n end\n\n return\nend\nfunction value = intersect ( va, vb, vc, vd )\n\n%*****************************************************************************80\n%\n%% INTERSECT is true if lines VA:VB and VC:VD intersect.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2011\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, vertex VA, VB, VC, VD, four vertices.\n%\n% Output, integer VALUE, the value of the test.\n%\n if ( intersect_prop ( va, vb, vc, vd ) )\n value = 1;\n elseif ( between ( va, vb, vc ) || ...\n between ( va, vb, vd ) || ...\n between ( vc, vd, va ) || ...\n between ( vc, vd, vb ) )\n value = 1;\n else\n value = 0;\n end\n\n return\nend\nfunction value = intersect_prop ( va, vb, vc, vd )\n\n%*****************************************************************************80\n%\n%% INTERSECT_PROP is TRUE if lines VA:VB and VC:VD have a proper intersection.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2011\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, vertex VA, VB, VC, VD, four vertices.\n%\n% Output, integer VALUE, the result of the test.\n%\n if ( collinear ( va, vb, vc ) || ...\n collinear ( va, vb, vd ) || ...\n collinear ( vc, vd, va ) || ...\n collinear ( vc, vd, vb ) )\n value = 0;\n else\n value = xor ( left ( va, vb, vc ), left ( va, vb, vd ) ) && ...\n xor ( left ( vc, vd, va ), left ( vc, vd, vb ) );\n end\n\n return\nend\nfunction value = left ( va, vb, vc )\n\n%*****************************************************************************80\n%\n%% LEFT is true if VC is to the left of the line VA:VB.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2011\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, vertex VA, VB, VC, three vertices.\n%\n% Output, integer VALUE, the result of the test.\n%\n value = ( 0 < triangle_area ( va, vb, vc ) );\n\n return\nend\nfunction value = left_on ( va, vb, vc )\n\n%*****************************************************************************80\n%\n%% LEFT_ON is TRUE if VC is to the left of, or on, the line VA:VB.\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% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, vertex VA, VB, VC, three vertices.\n%\n% Output, integer VALUE, the result of the test.\n%\n value = ( 0 <= triangle_area ( va, vb, vc ) );\n\n return\nend\nfunction triangles = polygon_triangulate ( vertex )\n\n%*****************************************************************************80\n%\n%% POLYGON_TRIANGULATE determines a triangulation of a polygon.\n%\n% Discussion:\n%\n% There are N-3 triangles in the triangulation.\n%\n% For the first N-2 triangles, the first edge listed is always an\n% internal diagonal.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 February 2011\n%\n% Author:\n%\n% Original C version by Joseph ORourke.\n% MATLAB version by John Burkardt.\n%\n% Reference:\n%\n% Joseph ORourke,\n% Computational Geometry in C,\n% Cambridge, 1998,\n% ISBN: 0521649765,\n% LC: QA448.D38.\n%\n% Parameters:\n%\n% Input, vertex array VERTEX(N).\n%\n% Output, integer TRIANGLES(N-2,3), the triangles of the triangulation.\n%\n n = length ( vertex );\n first = 1;\n\n triangles = zeros ( n - 2, 3 );\n triangle_num = 0;\n\n i2 = first;\n\n while ( triangle_num < n - 3 )\n%\n% If I2 is an ear, gather information necessary to carry out\n% the slicing operation and subsequent \"healing\".\n%\n if ( vertex(i2).ear )\n\n i3 = vertex(i2).next;\n i4 = vertex(i3).next;\n i1 = vertex(i2).prev;\n i0 = vertex(i1).prev;\n%\n% Make vertex I2 disappear.\n%\n vertex(i1).next = i3;\n vertex(i2).index = 0;\n vertex(i3).prev = i1;\n%\n% Update the earity of I1 and I3, because I2 disappeared.\n%\n vertex(i1).ear = diagonal ( i0, i3, vertex );\n vertex(i3).ear = diagonal ( i1, i4, vertex );\n%\n% Add the diagonal [I3, I1, I2] to the list.\n%\n triangle_num = triangle_num + 1;\n triangles(triangle_num,1) = i3;\n triangles(triangle_num,2) = i1;\n triangles(triangle_num,3) = i2;\n\n end\n%\n% Try the next vertex.\n%\n i2 = vertex(i2).next;\n\n end\n%\n% The last triangle is formed from the three remaining vertices.\n%\n i3 = vertex(i2).next;\n i1 = vertex(i2).prev;\n triangle_num = triangle_num + 1;\n triangles(triangle_num,1) = i3;\n triangles(triangle_num,2) = i1;\n triangles(triangle_num,3) = i2;\n\n return\nend\nfunction print_vertices ( vertex )\n\n%*****************************************************************************80\n%\n%% PRINT_VERTICES prints the vertex information.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 06 February 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, vertex array VERTEX(*).\n%\n n = length ( vertex );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' I IM1 IP1 X Y Earity\\n' );\n fprintf ( 1, '\\n' );\n\n for i = 1 : n\n\n if ( vertex(i).ear == -1 )\n earity = 'Unknown';\n elseif ( vertex(i).ear == 0 )\n earity = 'No';\n else\n earity = 'Yes';\n end\n\n fprintf ( 1, ' %2d %2d %2d %10f %10f %s\\n', ...\n vertex(i).index, vertex(i).prev, vertex(i).next, ...\n vertex(i).x, vertex(i).y, earity );\n\n end\n\n return\nend\nfunction vertex = read_vertices ( filename, direction )\n\n%*****************************************************************************80\n%\n%% READ_VERTICES reads vertex coordinates and initializes the vertex structure.\n%\n% Discussion:\n%\n% If the polygon was found to have negative area on the first pass,\n% we try again, reversing the vertex ordering, and hoping the user simply\n% listed the vertices in clockwise order.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 January 2013\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, string FILENAME, the name of the file to be read.\n%\n% Input, integer DIRECTION, the ordering for the vertices.\n% +1, first vertex is 1, and count up.\n% -1, first vertex is N, and count down.\n%\n% Output, vertex array VERTEX(*).\n%\n xy = load ( filename );\n\n [ n, dim ] = size ( xy );\n\n if ( direction == -1 )\n xy(1:n,1) = xy(n:-1:1,1);\n xy(1:n,2) = xy(n:-1:1,2);\n end\n \n for i = 1 : n\n vertex(i).index = i;\n vertex(i).prev = i4_wrap ( i - 1, 1, n );\n vertex(i).next = i4_wrap ( i + 1, 1, n );\n vertex(i).x = xy(i,1);\n vertex(i).y = xy(i,2);\n vertex(i).ear = -1;\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\nfunction area = triangle_area ( v1, v2, v3 )\n\n%*****************************************************************************80\n%\n%% TRIANGLE_AREA computes the signed area of a triangle.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 07 February 2011\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, vertex V1, V2, V3, three vertices.\n%\n% Output, real AREA, the signed area of the triangle.\n%\n area = 0.5 * ( ( v2.x - v1.x ) * ( v3.y - v1.y ) ...\n - ( v3.x - v1.x ) * ( v2.y - v1.y ) );\n\n return\nend\n", "meta": {"author": "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/triangulate.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.7021108793437005}} {"text": "% created: Zoya Bylinskii, Aug 2014\n% Code for computing degrees of visual angle\n\n% This code has been written to make it easier to report visual angle in\n% papers, and to ensure a standardized calculation is used.\n\n% This code can take variable input (e.g. horizontal, vertical, or diagonal\n% screen measurements in any units), and will calculate any number of \n% degrees of visual angle in pixels, as well as degrees of visual angle \n% spanned by the computer screen or an image. \n\n% The code is provided on: http://saliency.mit.edu/\n\n% Resources used: http://osdoc.cogsci.nl/miscellaneous/visual-angle/, \n% http://en.wikipedia.org/wiki/Visual_angle\n% Thank you to Lavanya Sharan and Melissa Vo for helpful discussion.\n\nfunction computeDegVisAngle_gui()\n\n% ------ INPUT ARGUMENTS: ------\n% necessary:\n% 'distance' distance to screen with units (e.g. 56 cm)\n\n% provide at least one of:\n% 'height' height of screen with units\n% 'width' width of screen with units\n% 'diagonal' diagonal of screen with units \n\n% provide at least one of:\n% 'hres' horizontal resolution of screen (provide this if also provided 'height')\n% 'vres' vertical resolution of screen (provide this if also provided 'width')\n% provide both if only provided 'diagonal'\n\n% optional:\n%'outputUnit' output units to measure screen, distance in (default: cm)\n%'numDegs' number of degres of visual angle (in pixels) to calculate (default numDegs=1)\n%'imageWidth' width of image in pixels\n%'imageHeight' height of image in pixels\n\n% NOTE: if you provide the screen diagonal and resolution, then the screen\n% height and width will be estimated under the assumption that the aspect\n% ratio of the screen dimensions matches that of the set resolution. \n% If these estimates look wrong, either:\n% (1) you measured the monitor dimensions, instead of the screen dimensions\n% (2) the screen resolution aspect ratio does not match the screen\n% dimensions\n% (3) explicitely enter the screen height and width instead of the diagonal\n\n% Common mistake: remember that the number of pixels per unit size of screen \n% or image is a linear function, but number of pixels per degree of visual \n% angle is NOT.\n\n% Remember: when writing a paper, include enough information for visual \n% angle to be calculated - providing screen resolution without screen \n% dimensions or vice versa is insufficient! Also, remember to measure the\n% screen itself, rather than the whole monitor.\n\n% units required for distance, height, width, and diagonal values\nui=inputdlg({'distance (with units)','height (with units)',...\n 'width (with units)','diagonal (with units)',...\n 'horizontal resolution','vertical resolution',...\n 'output units (optional)','number of degrees (optional)',...\n 'image width in pixels (optional)','image height in pixels (optional)'},...\n 'Visual Angle Calculator',1,...\n {'','','','','','','cm','1','',''});\n\ndist = ui{1};\nheight = ui{2};\nwidth = ui{3};\ndiagonal = ui{4};\nhres = str2num(ui{5});\nvres = str2num(ui{6});\noutputUnit = ui{7};\nnumDegs = str2num(ui{8});\nimageWidth = str2num(ui{9});\nimageHeight = str2num(ui{10});\n\ncomputeDegVisAngle_helper(dist,height,width,diagonal,hres,vres,outputUnit,numDegs,imageWidth,imageHeight);\n\n \n ", "meta": {"author": "cvzoya", "repo": "saliency", "sha": "5951cdc7c2ba73e5951d4c36bea58e8c7d41e55d", "save_path": "github-repos/MATLAB/cvzoya-saliency", "path": "github-repos/MATLAB/cvzoya-saliency/saliency-5951cdc7c2ba73e5951d4c36bea58e8c7d41e55d/computeVisualAngle/computeDegVisAngle_gui.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162774, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.7020777721969881}} {"text": "function [ x, seed ] = maxwell_sample ( a, seed )\n\n%*****************************************************************************80\n%\n%% MAXWELL_SAMPLE samples the Maxwell PDF.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 08 October 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, the parameter of the PDF.\n% 0 < A.\n%\n% Input, integer SEED, a seed for the random number generator.\n%\n% Output, real X, a sample of the PDF.\n%\n% Output, integer SEED, an updated seed for the random number generator.\n%\n a2 = 3.0;\n [ x, seed ] = chi_square_sample ( a2, seed );\n\n x = a * sqrt ( 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/prob/maxwell_sample.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311353, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.7020704396319171}} {"text": "function err = test_performance\n%TEST_PERFORMANCE compare performance of factorization/solve methods.\n% Returns the largest relative residual seen.\n%\n% Example\n% err = test_performance\n%\n% See also test_all, test_factorize, factorize, inverse, mldivide\n\n% Copyright 2009, Timothy A. Davis, University of Florida\n\nfprintf ('\\nPerformance comparisons of 5 methods:\\n') ;\nfprintf (' backslash: A\\\\b, or L\\\\b (and related) for solve times.\\n') ;\nfprintf (' linsolve: a built-in MATLAB function\\n') ;\nfprintf (' factorize1: the simple factorization object (uses LU)\\n') ;\nfprintf (' factorize: the full-featured factorization object\\n') ;\nfprintf (' inv: x=inv(A)*b, the explicit inverse (ack!)\\n') ;\nfprintf ('Run times are in seconds.\\n') ;\nfprintf ('Times relative to best times are in parentheses.\\n') ;\n\n% linsolve options:\nA_is_posdef.POSDEF = true ; % for x = A\\b where A is sym. pos. definite\nA_is_posdef.SYM = true ;\nlsolve.LT = true ; % for x = L\\b where L is lower triangular\nusolve.UT = true ; % for x = U\\b where U is upper triangular\nltsolve.LT = true ; % for x = L'b where L is lower triangular\nltsolve.TRANSA = true ;\n\nnn = [50 100 500 1000] ; % matrix sizes to test\nns = length (nn) ;\ntmax = 1 ; % minimum testing time\nerr = 0 ; % largest relative residual seen \n\nfor posdef = 0:1\n\n if (posdef)\n fprintf ('\\n------------------ For positive definite matrices:\\n') ;\n else\n fprintf ('\\n------------------ For unsymmetric matrices:\\n') ;\n end\n\n Tfactor = zeros (ns,5) ;\n Tsolve = zeros (ns,5) ;\n\n %-----------------------------------------------------------------------\n % compare factorizations times (plus a single solve)\n %-----------------------------------------------------------------------\n\n fprintf ('\\nCompare factorization times:\\n') ;\n for i = 1:ns\n n = nn (i) ;\n\n fprintf ('n %4d ', n) ;\n\n A = rand (n) ;\n if (posdef)\n A = A'*A + eye (n) ;\n end\n anorm = norm (A,1) ;\n b = rand (n,1) ;\n\n % method 1: backslash\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n x = A\\b ;\n k = k + 1 ;\n t = toc ;\n end\n Tfactor (i,1) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x\n\n if (posdef)\n\n % method 2: linsolve (pos. definite case)\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n x = linsolve (A,b, A_is_posdef) ;\n k = k + 1 ;\n t = toc ;\n end\n Tfactor (i,2) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x\n\n else\n\n % method 2: linsolve (unsymmetric case)\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n x = linsolve (A,b) ;\n k = k + 1 ;\n t = toc ;\n end\n Tfactor (i,2) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x\n\n end\n\n % method 3: factorize1 method\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n F = factorize1 (A) ;\n x = F\\b ;\n k = k + 1 ;\n t = toc ;\n end\n Tfactor (i,3) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x F\n\n % method 4: factorize method\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n F = factorize (A, posdef) ;\n x = F\\b ;\n k = k + 1 ;\n t = toc ;\n end\n Tfactor (i,4) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x F\n\n % method 5: inv method (ack!)\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n S = inv (A) ;\n x = S*b ; %#ok\n k = k + 1 ;\n t = toc ;\n end\n Tfactor (i,5) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x S\n\n tbest = min (Tfactor (i,:)) ;\n fprintf ('tbest %10.6f : backslash (%5.2f) ', tbest, ...\n Tfactor (i,1) / tbest);\n fprintf ('linsolve (%5.2f) ', Tfactor (i,2) / tbest) ;\n fprintf ('factorize1 (%5.2f) ', Tfactor (i,3) / tbest) ;\n fprintf ('factorize (%5.2f) ', Tfactor (i,4) / tbest) ;\n fprintf ('inv (%5.2f)\\n', Tfactor (i,5) / tbest) ;\n\n end\n\n %-----------------------------------------------------------------------\n % compare solve times\n %-----------------------------------------------------------------------\n\n fprintf ('\\nCompare solve times:\\n') ;\n for i = 1:ns\n n = nn (i) ;\n\n fprintf ('n %4d ', n) ;\n\n A = rand (n) ;\n if (posdef)\n A = A'*A + eye (n) ;\n end\n b = rand (n,1) ;\n anorm = norm (A,1) ;\n\n if (posdef)\n L = chol (A, 'lower') ;\n else\n [L,U,p] = lu (A,'vector') ;\n end\n\n S = inv (A) ;\n F = factorize (A) ;\n F1 = factorize1 (A) ;\n\n if (posdef)\n\n % method 1: backslash (pos. definite case)\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n x = L' \\ (L\\b) ;\n k = k + 1 ;\n t = toc ;\n end\n Tsolve (i,1) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x\n\n % method 2: linsolve (pos. definite case)\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n x = linsolve (L, linsolve (L, b, lsolve), ltsolve) ;\n k = k + 1 ;\n t = toc ;\n end\n Tsolve (i,2) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x\n\n else\n\n % method 1: backslash (unsymmetric case)\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n x = U \\ (L \\ (b (p))) ;\n k = k + 1 ;\n t = toc ;\n end\n Tsolve (i,1) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x\n\n % method 2: linsolve (unsymmetric case)\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n x = linsolve (U, linsolve (L, b (p), lsolve), usolve) ;\n k = k + 1 ;\n t = toc ;\n end\n Tsolve (i,2) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x\n\n end\n\n % method 3: factorize1 object\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n x = F1\\b ;\n k = k + 1 ;\n t = toc ;\n end\n Tsolve (i,3) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x\n\n % method 4: factorize object\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n x = F\\b ;\n k = k + 1 ;\n t = toc ;\n end\n Tsolve (i,4) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x\n\n % method 5: \"inv\" method (ack!)\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n x = S*b ; %#ok\n k = k + 1 ;\n t = toc ;\n end\n Tsolve (i,5) = t / k ;\n err = max (err, norm (A*x-b,1) / (anorm + norm (x,1))) ;\n clear x\n\n tbest = min (Tsolve (i,:)) ;\n fprintf ('tbest %10.6f : backslash (%5.2f) ', tbest, ...\n Tsolve (i,1) / tbest);\n fprintf ('linsolve (%5.2f) ', Tsolve (i,2) / tbest) ;\n fprintf ('factorize1 (%5.2f) ', Tsolve (i,3) / tbest) ;\n fprintf ('factorize (%5.2f) ', Tsolve (i,4) / tbest) ;\n fprintf ('inv (%5.2f)\\n', Tsolve (i,5) / tbest) ;\n\n clear F F1 S L U p\n\n end\n\n % determine break-even values for inv\n fprintf ('\\nBreak-even values K for inv vs the other methods\\n') ;\n fprintf ('(# of solves must exceed K for inv(A)*b to be faster):\\n') ;\n for i = 1:ns\n n = nn (i) ;\n s = zeros (4,1) ;\n for t = 1:4\n if (Tfactor (i,5) > Tfactor (i,t) && ...\n Tsolve (i,5) > Tsolve (i,t))\n % inv is always slower, for any K\n s (t) = inf ;\n elseif (Tfactor (i,5) < Tfactor (i,t) && ...\n Tsolve (i,5) < Tsolve (i,t))\n % inv is always faster, for any K\n s (t) = 1 ;\n else\n s (t) = (Tfactor (i,5) - Tfactor (i,t)) / ...\n (Tsolve (i,t) - Tsolve (i,5));\n end\n end\n\n fprintf ('n %4d # solves vs backslash %8.1f', n, max (1, s (1))) ;\n fprintf (' vs linsolve: %8.1f ', max (1, s (2))) ;\n fprintf (' vs factorize1: %8.1f ', max (1, s (3))) ;\n fprintf (' vs factorize: %8.1f\\n', max (1, s (4))) ;\n end\n\nend\n\n%---------------------------------------------------------------------------\n% compute the Schur complement, S = A-B*inv(D)*C\n%---------------------------------------------------------------------------\n\nfprintf ('\\nSchur complement, S=A-B*inv(D)*C or A-B(D\\\\C),\\n') ;\nfprintf ('where A, B, C, and D are square and unsymmetric.\\n') ;\nfprintf ('\"inverse\" means S=A-B*inverse(D)*C, which does not actually\\n') ;\nfprintf ('use the inverse, but uses the factorization object instead.\\n') ;\n\nTschur = zeros (ns,6) ;\n\nfor i = 1:ns\n n = nn (i) ;\n fprintf ('n %4d ', n) ;\n\n A = rand (n) ;\n B = rand (n) ;\n C = rand (n) ;\n D = rand (n) ;\n\n % method 1: backslash\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n S = A - B*(D\\C) ; %#ok\n k = k + 1 ;\n t = toc ;\n end\n Tschur (i,1) = t / k ;\n clear S\n\n % method 2: linsolve\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n S = A - B * linsolve (D,C) ; %#ok\n k = k + 1 ;\n t = toc ;\n end\n Tschur (i,2) = t / k ;\n clear S\n\n % method 3: factorize1 object\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n S = A - B*(factorize1(D)\\C) ; %#ok\n k = k + 1 ;\n t = toc ;\n end\n Tschur (i,3) = t / k ;\n clear F S\n\n % method 4: factorize object\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n S = A - B*(factorize(D)\\C) ; %#ok\n k = k + 1 ;\n t = toc ;\n end\n Tschur (i,4) = t / k ;\n clear F S\n\n % method 5:\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n S = A - B*inverse(D)*C ; %#ok\n k = k + 1 ;\n t = toc ;\n end\n Tschur (i,5) = t / k ;\n clear S\n\n % method 6: \"inv\" method, using the explicit inverse (ack!)\n t = 0 ;\n k = 0 ;\n tic\n while (t < tmax)\n S = A - B*inv(D)*C ; %#ok\n k = k + 1 ;\n t = toc ;\n end\n Tschur (i,6) = t / k ;\n clear S\n\n tbest = min (Tschur (i,:)) ;\n fprintf ('tbest %10.6f : backslash (%5.2f) ', tbest, ...\n Tschur (i,1) / tbest);\n fprintf ('linsolve (%5.2f) ', Tschur (i,2) / tbest) ;\n fprintf ('factorize1 (%5.2f) ', Tschur (i,3) / tbest) ;\n fprintf ('factorize (%5.2f) ', Tschur (i,4) / tbest) ;\n fprintf ('inverse (%5.2f) ', Tschur (i,5) / tbest) ;\n fprintf ('inv (%5.2f)\\n', Tschur (i,6) / tbest) ;\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/SuiteSparse/MATLAB_Tools/Factorize/Test/test_performance.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.7020704253743663}} {"text": "function y = log_normcdf( x, approx )\n\n%LOG_NORMCDF Logarithm of the cumulative normal distribution.\n% Y = LOG_NORMCDF(X) is the logarithm of the CDF of the normal\n% distribution at the point X.\n%\n% 1 / x\n% LOG_NORMCDF(X) = LOG( ------- | exp(-t^2/2) dt )\n% sqrt(2) / -Inf\n%\n% For numeric X, LOG_NORMCDF(X) is computed using the equivalent \n% expression LOG(0.5*ERFC(-X*SQRT(0.5))). When X is a CVX variable, a \n% a piecewise quadratic *approximation* is employed instead. This\n% approximation gives good results when -4 <= x <= 4, and will be\n% improved in future releases of CVX.\n%\n% For array values of X, the LOG_NORMCDF returns an array of identical\n% size with the calculation applied independently to each element.\n%\n% X must be real.\n%\n% Disciplined convex programming information:\n% LOG_NORMCDF is concave and nondecreasing in X. Therefore, when used\n% in CVX specifications, X must be concave.\n\nerror(nargchk(1,2,nargin));\nif ~isreal( x ),\n error( 'Argument must be real.' );\nend\nif nargin > 1,\n % For debugging purposes only\n y = cvx_constant(log_normcdf(cvx(x)));\nelse\n y = log(0.5*erfc(-x*sqrt(0.5)));\nend\n", "meta": {"author": "goodshawn12", "repo": "REST", "sha": "e34ce521fcb36e7813357a9720072dd111edf797", "save_path": "github-repos/MATLAB/goodshawn12-REST", "path": "github-repos/MATLAB/goodshawn12-REST/REST-e34ce521fcb36e7813357a9720072dd111edf797/dependencies/BCILAB/dependencies/cvx-1.21.b795/functions/log_normcdf.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.7020526277103326}} {"text": "function out = DN_cv(x,k)\n% DN_cv Coefficient of variation\n%\n% Coefficient of variation of order k is sigma^k / mu^k (for sigma, standard\n% deviation and mu, mean) of a data vector, x\n%\n%---INPUTS:\n%\n% x, the input data vector\n% k, the order of coefficient of variation (k = 1 is default)\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(k)\n k = 1; % Do standard CV by default\nend\n\nif (rem(k,1) ~= 0) || (k < 0)\n warning('k should probably be a positive integer');\n % Carry on with just this warning, though\nend\n\n% Compute the coefficient of variation (of order k) of the data\n\nout = (std(x))^k / (mean(x))^k;\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_cv.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7020359333355395}} {"text": "% Copyright (c) 2012-2016 Ali Akbar Eftekhari\n% See the license file\n% Coupled nonlinear PDE's\n% Buckley Leverett equation\n% dependent variables: pressure and water saturation\n% Prepared for educational purposes by ** AAE **\n% Written by Ali A. Eftekhari\n% Last checked: June 2021\n% This code works fine (two phase flow + Pc) and shows the effect of Pc\n% in the simulation of a heterogeneous 2D field.\nclc\n%% define the geometry\nNx = 100; % number of cells in x direction\nNy = 30; % number of cells in y direction\nW = 300; % [m] length of the domain in x direction\nH = 30; % [m] length of the domain in y direction\n% m = createMesh1D(Nx, W);\nm = createMesh2D(Nx, Ny, W, H); % creates a 2D mesh\n%% define the physical parametrs\nkrw0 = 1.0;\nkro0 = 0.76;\nnw = 2.4;\nno = 2.0;\nsor=0.12;\nswc=0.09;\nsws=@(sw)((sw>swc).*(sw<1-sor).*(sw-swc)/(1-sor-swc)+(sw>=1-sor).*ones(size(sw)));\nkro=@(sw)((sw>=swc).*kro0.*(1-sws(sw)).^no+(sw1-sor).*(-(1-krw0)/sor.*(1.0-sw)+1.0));\ndkrwdsw=@(sw)((sw<=1-sor).*nw.*krw0.*(1/(1-sor-swc)).*sws(sw).^(nw-1)+(sw>1-sor)*((1-krw0)/sor));\ndkrodsw=@(sw)((sw>=swc).*(-kro0*no*(1-sws(sw)).^(no-1))/(-swc-sor+1)+(sweps_p) || (error_sw>eps_sw))\n % calculate parameters\n pgrad = gradientTerm(p);\n% pcgrad=gradientTerm(pc(sw));\n sw_face = upwindMean(sw, -pgrad); % average value of water saturation\n sw_grad=gradientTerm(sw);\n sw_ave=arithmeticMean(sw);\n pcgrad=dpc(sw_ave).*sw_grad+dpcdk(sw_ave).*grad_phik;\n labdao = lo.*funceval(kro, sw_face);\n labdaw = lw.*funceval(krw, sw_face);\n dlabdaodsw = lo.*funceval(dkrodsw, sw_face);\n dlabdawdsw = lw.*funceval(dkrwdsw, sw_face);\n labda = labdao+labdaw;\n dlabdadsw = dlabdaodsw+dlabdawdsw;\n % compute [Jacobian] matrices\n Mdiffp1 = diffusionTerm(-labda);\n Mdiffp2 = diffusionTerm(-labdaw);\n% Mconvsw1 = convectionUpwindTerm(-dlabdadsw.*pgrad); % without capillary\n Mconvsw1 = convectionUpwindTerm(-dlabdawdsw.*pgrad-dlabdaodsw.*(pgrad+pcgrad)); % with capillary\n Mconvsw2 = convectionUpwindTerm(-dlabdawdsw.*pgrad);\n [Mtranssw2, RHStrans2] = transientTerm(sw_old, dt, phi);\n % Compute RHS values\n RHSpc1=divergenceTerm(labdao.*pcgrad);\n RHS1 = divergenceTerm((-dlabdawdsw.*pgrad-dlabdaodsw.*(pgrad+pcgrad)).*sw_face); % with capillary\n RHS2 = divergenceTerm(-dlabdawdsw.*sw_face.*pgrad);\n % include boundary conditions\n [Mbcp, RHSbcp] = boundaryCondition(BCp);\n [Mbcsw, RHSbcsw] = boundaryCondition(BCs);\n % Couple the equations; BC goes into the block on the main diagonal\n M = [Mdiffp1+Mbcp Mconvsw1; Mdiffp2 Mconvsw2+Mtranssw2+Mbcsw];\n RHS = [RHS1+RHSpc1+RHSbcp; RHS2+RHStrans2+RHSbcsw];\n % solve the linear system of equations\n x = M\\RHS;\n % x = agmg(M, RHS, [], 1e-10, 500, [], [p.value(:); sw.value(:)]);\n % separate the variables from the solution\n p_new = reshapeCell(m,full(x(1:(Nx+2)*(Ny+2))));\n sw_new = reshapeCell(m,full(x((Nx+2)*(Ny+2)+1:end)));\n % calculate error values\n error_p = max(abs((p_new(:)-p.value(:))./p_new(:)));\n error_sw = max(abs(sw_new(:)-sw.value(:)));\n % assign new values of p and sw\n p.value = p_new;\n sw.value = sw_new;\n end\n t=t+dt;\n p_old = p;\n sw_old = sw;\n figure(1);visualizeCells(sw); drawnow;\nend", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/Examples/Advanced/BL_capillary.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.7020089865527065}} {"text": "function [fi,ps] = VF(r,T,p)\n% VF Conversion of relative humidity to volume fraction of water vapor\n%\n% This program transfers relative humidity, absolute temperature and \n% atmospheric pressure to volume fraction of water vapor and saturation\n% vapour pressure using Goff-Gratch equation over plane surfaces of pure\n% ice. Relation is based on integration of Clausius-Clapeyron equation and\n% on experimental data. Stated range of equation validity is -100 to 0 °C.\n%\n% [fi,ps] = VF(r,T,p)\n%\n% Inputs:\n% r is the relative humidity (%). r may be a vector or a scalar\n% variable in the interval [0,100].\n%\n% T means the absolute temperature (degrees K). T must have \n% the same number of elements as r. A warning is generated\n% if any elements fall outside the range [173,273].\n%\n% p is the atmospheric pressure (kPa). p must have the same number\n% of elements as r. All elements must be non-negative.\n%\n% Results:\n% fi is the volume fraction of water vapor (%).\n%\n% ps is the saturation vapour pressure (kPa).\n%\n% Example: At an rh of 35 %, Temp = 265 °K, atmospheric pressure = 98.9 kPa\n% [fi,ps] = VF(0.35,265,98.9)\n%\n% fi =\n% 0.00108\n%\n% ps =\n% 0.305\n% \n% For citation ensue following format: Malec L. (2007). VF: Conversion\n% of relative humidity to volume fraction. A MATLAB file. [WWW document].\n% URL http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?\n% objectId=14165\n%\n% List R. J.: Smithsonian Meteorological Tables. Smithsonian Institution,\n% Washington 1984.\n%\n% Copyright. February 26, 2007.\n\n\nif any(r(:)<0) || any(r(:)>100)\n error 'Relative humidity(r) must be percent'\nend\nif any(T(:)<=0)\n error 'Temperature(T) must be positive (°K)'\nelseif any(T(:)<173) || any(T(:)>273)\n warning 'Temperature(T) fell outside the working range of this relation'\nend\nif any(p(:)<0)\n error 'Pressure(p) must be positive (kPa)'\nend\n\na1 = -9.09718;\na2 = -3.56654;\na3 = 0.876793;\n\n% Induction of ice point and saturation vapour pressure.\nTo = 273.16;\neo = 6.1071;\n\n% Saturation vapour pressure and water fraction computation.\nps = 10.^(a1 * (To ./ T - 1) + a2 * log10(To ./ T) + a3 * (1 - T / To) ...\n + log10(eo));\nps = ps / 10;\nfi = r .* ps ./ p;\n\n", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/14165-vf/VF.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.702008970504983}} {"text": "function [px, py, gx, gy] = position_7_link(z,P) \n%[px,py,gx,gy] = POSITION_7_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\nm6 = P.m(6); % Link 6 mass\nm7 = P.m(7); % Link 7 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\nl6 = P.l(6); % Link 6 length\nl7 = P.l(7); % Link 7 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\nI6 = P.I(6); % Link 6 moment of inertia about its center of mass\nI7 = P.I(7); % Link 7 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\nd6 = P.d(6); % Link 6 distance between center of mass and parent joint\nd7 = P.d(7); % Link 7 distance between center of mass and parent joint\n\nth1 = z(1,:); \nth2 = z(2,:); \nth3 = z(3,:); \nth4 = z(4,:); \nth5 = z(5,:); \nth6 = z(6,:); \nth7 = z(7,:); \n\nnTime = length(th1); \npx = zeros(7,nTime);\npy = zeros(7,nTime);\ngx = zeros(7,nTime);\ngy = zeros(7,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\npx(6,:) = l1.*cos(th1) + l2.*cos(th2) + l3.*cos(th3) + l4.*cos(th4) + l5.*cos(th5) + l6.*cos(th6);\npy(6,:) = l1.*sin(th1) + l2.*sin(th2) + l3.*sin(th3) + l4.*sin(th4) + l5.*sin(th5) + l6.*sin(th6);\ngx(6,:) = d6.*cos(th6) + l1.*cos(th1) + l2.*cos(th2) + l3.*cos(th3) + l4.*cos(th4) + l5.*cos(th5);\ngy(6,:) = d6.*sin(th6) + l1.*sin(th1) + l2.*sin(th2) + l3.*sin(th3) + l4.*sin(th4) + l5.*sin(th5);\n\npx(7,:) = l1.*cos(th1) + l2.*cos(th2) + l3.*cos(th3) + l4.*cos(th4) + l5.*cos(th5) + l6.*cos(th6) + l7.*cos(th7);\npy(7,:) = l1.*sin(th1) + l2.*sin(th2) + l3.*sin(th3) + l4.*sin(th4) + l5.*sin(th5) + l6.*sin(th6) + l7.*sin(th7);\ngx(7,:) = d7.*cos(th7) + l1.*cos(th1) + l2.*cos(th2) + l3.*cos(th3) + l4.*cos(th4) + l5.*cos(th5) + l6.*cos(th6);\ngy(7,:) = d7.*sin(th7) + l1.*sin(th1) + l2.*sin(th2) + l3.*sin(th3) + l4.*sin(th4) + l5.*sin(th5) + l6.*sin(th6);\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_7_link.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.7019516962532975}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% SABR European option pricer comparison\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Descritpion: Script to Compare European Option pricers in SABR Model\n% Author: Justin Kirkby\n% References: (1) General Valuation Framework for SABR and Stochastic Local Volatility\n% Models. SIAM J. Financial Mathematics, 2018.\n% (2) Full Fledge SABR with Markov Chains. Wimott, 2019.\n% Disclaimer: this is research code, not production code. The parameter settings etc \n% should not be expected to work as is in all cases. Determining the right parameter\n% settings will depend on your usecase. This is left up to the user. \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n[folder, name, ext] = fileparts(which( mfilename('fullpath')));\ncd(folder);\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Step 1) CHOOSE CONTRACT/GENERAL PARAMETERS\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nT = 1; % time to matruity\nr = 0.05; % interest rate\nF_0 = 1.1; % Futures price \nK = F_0*0.95; % strike\ncall = 1; % 1 = call option, else put\n\n% -----------------\n% Model Params\n% -----------------\nModParams.beta = .6;\nModParams.alpha = 0.08;\nModParams.v0 = 0.2;\nModParams.rho = 0.0;\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Reference Price (Using Obloj Asymptotic Formula with correction)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naddpath('../../Approx/SABR')\naddpath('../../Analytical/BlackScholes')\n\ntic\nIV = SABR_Hagan_Obloj_ImpliedVol( K, F_0, ModParams.v0, T, ModParams.alpha, ModParams.beta, ModParams.rho );\nprice_obloj = BSM_Greeks( 0, F_0/exp(r*T), IV, r, 0, T, K, call)\ntime_oblog=toc;\n\nprice_ref = price_obloj;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Antonov Approximation (Using Asymptotic Formula)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ntic\nprice_ant = SABR_European_AntonovApprox(F_0,K,T,call,r,ModParams)\ntime_ant = toc;\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Monte Carlo (Euler)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naddpath('../../Monte_Carlo')\naddpath('../../Monte_Carlo/European')\nM = 400;\nN_sim = 5*10^4;\n\ntic;\nSpath = Simulate_SLV_func( N_sim, M, T, F_0, 0, 0, 2, ModParams);\ndisc = exp(-r*T);\n[price_MC, stdErr] = Price_MC_European_Strikes_func(Spath, disc, call, K );\n\nprice_MC_L = price_MC - 2*stdErr; price_MC_U = price_MC + 2*stdErr;\ntime_MC = toc;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% CTMC-Double Layer Method\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\naddpath('../../PROJ/SABR/European_American_Barrier/')\naddpath('../../PROJ/SABR/Helper_Functions/')\n\n% -----------------\n% Numerical Params\n% -----------------\nM = 100; % number of time steps\ncontract_type = 1; % 1 = European, 2 = American, 3 = Down and Out Barrier\nL = 0.6*F_0; % For barrier contract, this is the barrier\n\nCTMCParams.m_0 = 26;\nCTMCParams.N = 90;\nCTMCParams.gridMult_v = 0.5;\nCTMCParams.gridMult_s = 0.05; %Grid mult param for S \nCTMCParams.gamma = 6; %Grid width param for variance grid\n\ntic\nprice_ctmc = SABR_EurBarAmer_func(call, M, T, F_0, K, r, CTMCParams, ModParams, contract_type, L)\ntime_ctmc = toc;\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% COMPARE\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfprintf('\\n---------------------------------------------\\n')\nfprintf('Method | Price | Err | CPU \\n')\nfprintf('---------------------------------------------\\n')\nfprintf('Ref (Obloj) | %.8f | | \\n', price_ref)\nfprintf('---------------------------------------------\\n')\nfprintf('Antonov | %.8f | %.2e | %.4f \\n', price_ant, abs(price_ref-price_ant), time_ant)\nfprintf('CTMC | %.8f | %.2e | %.4f \\n', price_ctmc, abs(price_ref-price_ctmc), time_ctmc)\nfprintf('MC-Euler |[%.3f,%.3f]| %.2e | %.4f \\n', price_MC_L, price_MC_U, abs(price_ref-price_MC), time_MC)\nfprintf('---------------------------------------------\\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/Comparisons/SABR/Script_Compare_European.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7017646705203902}} {"text": "function y = smoothRamp(x,alpha,order)\n%\n% y = smoothRamp(x,alpha,order)\n%\n% FUNCTION:\n%This function is a smooth version of the standard ramp function, which is:\n% ramp(x) = 0 ; (x<0)\n% ramp(x) = x ; (x>=0)\n% Smoothing is done using a polynomial transition, the degree of smoothness\n% at the transitions is set using order.\n%\n% INPUTS:\n% x = a vector of matrix of real numbers\n% alpha = smoothing parameter: -alphaalpha) = x;\n% y(else) = smooth_transition\n%\n y=x; \n c1 = x < -alpha; \n c2 = x > alpha; \nswitch order \n case 0 % No Smoothing \n y(x<0)=0; \n case 1 \n y=x; \n y(c1)=0; \n p = [1/4,1/2,1/4]; \n idx = ~c1&~c2;\n y(idx)=alpha*polyval(p,x(idx)/alpha); \n case 2 \n y=x; \n y(c1)=0; \n p = [-1/16,0,3/8,1/2,3/16]; \n idx = ~c1&~c2;\n y(idx)=alpha*polyval(p,x(idx)/alpha); \n case 3 \n y=x; \n y(c1)=0; \n p = [1/32,0,-5/32,0,15/32,1/2,5/32]; \n idx = ~c1&~c2;\n y(idx)=alpha*polyval(p,x(idx)/alpha); \n case 4 \n y=x; \n y(c1)=0; \n p = [-5/256,0,7/64,0,-35/128,0,35/64,1/2,35/256]; \n idx = ~c1&~c2;\n y(idx)=alpha*polyval(p,x(idx)/alpha); \n case 5 \n y=x; \n y(c1)=0; \n p = [7/512,0,-45/512,0,63/256,0,-105/256,0,315/512,1/2,63/512]; \n idx = ~c1&~c2;\n y(idx)=alpha*polyval(p,x(idx)/alpha); \n case 6 \n y=x; \n y(c1)=0; \n p = [-21/2048,0,77/1024,0,-495/2048,0,231/512,0,-1155/2048,0,693/1024,1/2,231/2048]; \n idx = ~c1&~c2;\n y(idx)=alpha*polyval(p,x(idx)/alpha); \n case 7 \n y=x; \n y(c1)=0; \n p = [33/4096,0,-273/4096,0,1001/4096,0,-2145/4096,0,3003/4096,0,-3003/4096,0,3003/4096,1/2,429/4096]; \n idx = ~c1&~c2;\n y(idx)=alpha*polyval(p,x(idx)/alpha); \n case 8 \n y=x; \n y(c1)=0; \n p = [-429/65536,0,495/8192,0,-4095/16384,0,5005/8192,0,-32175/32768,0,9009/8192,0,-15015/16384,0,6435/8192,1/2,6435/65536]; \n idx = ~c1&~c2;\n y(idx)=alpha*polyval(p,x(idx)/alpha); \n otherwise \n error('Order not supported');\nend \nend \n", "meta": {"author": "MatthewPeterKelly", "repo": "dscTutorials", "sha": "e1e97a9be03ec146f88bd6ddd9e06db7ee52e242", "save_path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials", "path": "github-repos/MATLAB/MatthewPeterKelly-dscTutorials/dscTutorials-e1e97a9be03ec146f88bd6ddd9e06db7ee52e242/smoothing/polynomialSmoothing/smoothRamp.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.7017646524448559}} {"text": "function pi = predlssvm(model,Xt,alpha,conftype)\n\n% Construction of bias corrected 100(1-\\alpha)% pointwise or\n% simultaneous prediction intervals\n%\n% >> pi = predlssvm({X,Y,type,gam,kernel_par,kernel,preprocess}, Xt, alpha,conftype)\n% >> pi = predlssvm(model, Xt, alpha, conftype)\n%\n% This function calculates bias corrected 100(1-\\alpha)% pointwise or\n% simultaneous prediction intervals. The procedure support homoscedastic\n% data sets as well heteroscedastic data sets. The construction of the\n% prediction intervals are based on the central limit theorem for linear\n% smoothers combined with bias correction and variance estimation.\n%\n% 1. Using the functional interface:\n%\n%\n% >> pi = predlssvm({X,Y,type,gam,kernel_par,kernel,preprocess})\n% >> pi = predlssvm({X,Y,type,gam,kernel_par,kernel,preprocess}, alpha)\n% >> pi = predlssvm({X,Y,type,gam,kernel_par,kernel,preprocess}, alpha, conftype)\n%\n%\n% Outputs\n% pi : N x 2 matrix containing the lower and upper prediction intervals\n%\n% Inputs\n% X : N x d matrix with the inputs of the training data\n% Y : N x 1 vector with the outputs of the training data\n% type : 'function estimation' ('f') or 'classifier' ('c')\n% gam : Regularization parameter\n% sig2 : Kernel parameter(s) (bandwidth in the case of the 'RBF_kernel')\n% kernel(*) : Kernel type (by default 'RBF_kernel')\n% preprocess(*) : 'preprocess'(*) or 'original'\n% alpha(*) : Significance level (by default 5%)\n% conftype(*) : Type of prediction interval 'pointwise' or 'simultaneous' (by default 'simultaneous')\n%\n% 2. Using the object oriented interface:\n%\n%\n% >> pi = predlssvm(model)\n% >> pi = predlssvm(model, alpha)\n% >> pi = predlssvm(model, alpha, conftype)\n%\n%\n% Outputs\n% pi : N x 2 matrix containing the lower and upper confidence intervals\n%\n% Inputs\n% model : Object oriented representation of the LS-SVM model\n% alpha : Significance level (by default 5%)\n% conftype : Type of prediction interval 'pointwise' or 'simultaneous' (by default 'simultaneous')\n%\n%\n% See also:\n% trainlssvm, simlssvm, cilssvm\n\n\n% Copyright (c) 2011, KULeuven-ESAT-SCD, License & help @ http://www.esat.kuleuven.be/sista/lssvmlab\n\nif iscell(model)\n model = initlssvm(model{:});\nend\n\nif nargin == 1\n error('Please specify a test set');\nelseif nargin <= 2\n alpha = 0.05;\n conftype = 'simul';\n \nelseif nargin <= 3\n conftype = 'simul';\nend\n\n\nif model.preprocess(1)=='p'\n [x,y] = postlssvm(model,model.xtrain,model.ytrain);\nelse\n x = model.xtrain; y = model.ytrain;\nend\n\n% train model\nmodel = trainlssvm(model);\n\n% smoother on test\nS = smootherlssvm(model,Xt);\n\n% bias: double smoothing with fourt order kernel RBF4\nmodelb = initlssvm(x,y,'f',[],[],'RBF4_kernel','o');\nmodelb = tunelssvm(modelb,'simplex','crossvalidatelssvm',{10,'mse'});\nmodelb = trainlssvm(modelb);\n\n% output on test Yphat\nYphat = simlssvm(modelb,Xt);\n\n% output of the smoother based on fourth order kernel on training data Yhat\nYhat = simlssvm(modelb,x);\n\nbiascorr = S*Yhat-Yphat;\n\n%1) estimate variance nonparametrically\n[sigma2,modele] = varest(model);\n% smoother on training data\nL = smootherlssvm(model);\nsigma2t = varfun(modele,L,Xt);\n\n%2) calculate var-cov matrix\nS = S*diag(sigma2)*S';\n\n%2b) find standardized absolute maxbias \ndelta = max(abs(biascorr./sqrt(diag(S))));\n\n%3) pointwise or simultaneous\nif conftype(1)=='s'\n if model.preprocess(1)=='p'\n model.xtrain = prelssvm(model,x); \n end\n z = tbform(model,alpha) + delta;\nelseif conftype(1)=='p'\n z = norminv(alpha/2);\n Yphat = Yphat - biascorr;\nelse\n error('Wrong type of confidence interval. Please choose ''pointwise'' or ''simultaneous''');\nend\n\nV = sqrt(sigma2t+diag(S));\npi = [Yphat+z*V Yphat-z*V];\n\nfunction V = varfun(modele,L,xt)\n% estimate variance op new data, given the smooth of squared residuals\n% \"modele\" and smoother matrix of the original smooth L\nV = max(simlssvm(modele,xt),0);\n% make estimate of V unbiased in homoscedastic case if regression\n% estimate is unbiased\nS = smootherlssvm(modele,xt);\nV = V./(ones(size(xt,1),1)+S*diag(L*L'-2*L));\n\nfunction [var,modele] = varest(model)\n\n% if preprocessed data, construct original data\nif model.preprocess(1)=='p'\n [x,y] = postlssvm(model,model.xtrain,model.ytrain);\nelse\n x = model.xtrain; y = model.ytrain;\nend\n\nmodel = trainlssvm(model);\n\nYh = simlssvm(model,x);\n\n% Squared normalized residuals\ne2 = (y-Yh).^2;\n\n% Make variance model\nif model.nb_data <= 200\n costfun = 'leaveoneoutlssvm'; costargs = {'mae'};\nelse\n costfun = 'crossvalidatelssvm'; costargs = {10,'mae'};\nend\nmodele = initlssvm(x,e2,'f',[],[],'RBF_kernel');\nmodele = tunelssvm(modele,'simplex',costfun,costargs);\nmodele = trainlssvm(modele);\n\n% variance model\nvar = max(simlssvm(modele,x),0);\n\n% make estimate of Var unbiased in homoscedastic case if regression\n% estimate is unbiased\nL = smootherlssvm(model);\nS = smootherlssvm(modele);\n\nvar = var./(ones(size(x,1),1)+S*diag(L*L'-L-L'));", "meta": {"author": "peterhcharlton", "repo": "RRest", "sha": "f5022e7029c5b6d6b8159b665dccc2c8f267976e", "save_path": "github-repos/MATLAB/peterhcharlton-RRest", "path": "github-repos/MATLAB/peterhcharlton-RRest/RRest-f5022e7029c5b6d6b8159b665dccc2c8f267976e/RRest_v3.0/Algorithms/extract_resp_sig/feat_based_extraction/LSSVMlabv1_8_R2009b_R2011a/predlssvm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.7017233238500609}} {"text": "function histo_gram = r8vec_histogram ( n, a, a_lo, a_hi, histo_num )\n\n%*****************************************************************************80\n%\n%% R8VEC_HISTOGRAM computes a histogram of the elements of an R8VEC.\n%\n% Discussion:\n%\n% Values between A_LO and A_HI will be histogrammed into the bins\n% 1 through HISTO_NUM. Values below A_LO are counted in bin 0,\n% and values greater than A_HI are counted in bin HISTO_NUM+1.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 09 September 2005\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of elements of A.\n%\n% Input, real A(N), the array to examine.\n%\n% Input, real A_LO, A_HI, the lowest and highest\n% values to be histogrammed. These values will also define the bins.\n%\n% Input, integer HISTO_NUM, the number of bins to use.\n%\n% Output, integer HISTO_GRAM(0:HISTO_NUM+1), contains the number of\n% entries of A in each bin.\n%\n histo_gram(1:histo_num+2) = 0;\n\n delta = ( a_hi - a_lo ) / ( 2 * histo_num );\n\n for i = 1 : n\n\n if ( a(i) < a_lo )\n\n histo_gram(1) = histo_gram(2) + 1;\n\n elseif ( a(i) <= a_hi )\n\n j = round ( ...\n ( ( a_hi - delta - a(i) ) * ( 1 ) ...\n + ( - delta + a(i) - a_lo ) * ( histo_num ) ) ...\n / ( a_hi - 2.0 * delta - a_lo ) );\n\n histo_gram(j+1) = histo_gram(j+1) + 1;\n\n elseif ( a_hi < a(i) )\n\n histo_gram(histo_num+2) = histo_gram(histo_num+2) + 1;\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/r8lib/r8vec_histogram.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7017066402536722}} {"text": "function M = Q2M(Q)\n% Generate a rotation matrix from a quaternion xi+yj+zk+w,\n% where Q = [x y z], and w = 1-x^2-y^2-z^2.\n% See: http://skal.planet-d.net/demo/matrixfaq.htm\n% _______________________________________________________________________\n% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging\n\n%\n% $Id$\n\n\nQ = Q(1:3); % Assume rigid body\nw = sqrt(1 - sum(Q.^2));\nx = Q(1); y = Q(2); z = Q(3);\nif w<1e-7,\n w = 1/sqrt(x*x+y*y+z*z);\n x = x*w;\n y = y*w;\n z = z*w;\n w = 0;\nend;\nxx = x*x; yy = y*y; zz = z*z; ww = w*w;\nxy = x*y; xz = x*z; xw = x*w;\nyz = y*z; yw = y*w; zw = z*w;\nM = [...\n(xx-yy-zz+ww) 2*(xy-zw) 2*(xz+yw) 0\n 2*(xy+zw) (-xx+yy-zz+ww) 2*(yz-xw) 0\n 2*(xz-yw) 2*(yz+xw) (-xx-yy+zz+ww) 0\n 0 0 0 1];\nreturn;\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/spm8/@nifti/private/Q2M.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9518632316144274, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.701673739897854}} {"text": "function g_nm = conjCoeffs(f_nm)\n%CONJCOEFFS Get the complex SH coefficients of a conjugate sph. function\n%\n% f_nm: (N+1)^2 coefficients of original spherical function f(\\theta,\\phi)\n%\n% g_nm: (N+1)^2 coefficients of conjugate spherical function \n% g(\\theta,\\phi) = (f(\\theta,\\phi))*\n%\n% The conversion is based on the relation Y^*_{nm} = (-1)^m Y_{n(-m)}\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Archontis Politis, 10/10/2013\n% archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% order\nN = sqrt(length(f_nm)) - 1;\n\ng_nm = zeros((N+1)^2, 1);\nfor n=0:N\n for m=-n:n\n q_g = n*(n+1)+m;\n q_f = n*(n+1)-m;\n g_nm(q_g+1) = (-1)^m * conj(f_nm(q_f+1));\n end\nend\n\n\nend\n", "meta": {"author": "polarch", "repo": "Spherical-Harmonic-Transform", "sha": "ef8a69aedbaf467e2fccb50c810564d747ce3409", "save_path": "github-repos/MATLAB/polarch-Spherical-Harmonic-Transform", "path": "github-repos/MATLAB/polarch-Spherical-Harmonic-Transform/Spherical-Harmonic-Transform-ef8a69aedbaf467e2fccb50c810564d747ce3409/conjCoeffs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404116305638, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.7016485012652427}} {"text": "%% Orientation Dependent Functions\n%\n%%\n% An orientation dependent function is a function that assigns to each\n% rotation or orientation a numerical value. An import example of a\n% rotational function is the that assignes to each crystal orientation the probability of its\n% occurence within a specimen. Other examples are the Schmidt or the Taylor\n% factor as a function of the crystal orientation.\n%\n%% Definition of a orientation dependent function\n%\n% Within MTEX a rotational function is represented by a variable of type\n% . Let us consider as an example the function\n% that takes an orientation and returns it rotational angle modulo cubic\n% crystal symmetry. In MTEX the rotational angle is computed by the command\n% . In order to turn this\n% correspondence into a |SO3Fun| we use the command @SO3FunHandle and pass\n% the angle command as an\n% .\n\n% define the crystal symmetry\ncs = crystalSymmetry('cubic');\n\n% construct the SO3Fun\nSO3F = SO3FunHandle(@(ori) angle(ori) ./ degree, cs)\n\n%% \n% Many more methods for defining orientation dependent functions are\n% discussed . \n% \n%%\n% The entire information abot the orientation dependent function is now\n% stored in the variable |SO3F|. In order to determine its value for a\n% specific orientation |ori| the function is\n% used\n\nori = orientation.rand(cs)\nSO3F.eval(ori)\n\n%% Plotting an orientation Dependent Function\n% \n% Orientation dependent functions are most of visualized by sections\n% according to the third Euler angle $\\varphi_2$\n% \n\nplotSection(SO3F)\n\n%%\n% The plot tells us for which Euler angles the the resulting rotational\n% angle is large and for which Euler angles it is low. The plot of this\n% \"angle function\" |SO3F| becomes trivial if represented in an axis angle\n% sections\n\nplotSection(SO3F,'axisAngle','upper')\nmtexColorbar\nmtexColorMap parula\n\n%%\n% as obviously, the function value is constant in each section. \n% Many more methods for visualizing orientation dependent functions are\n% discussed . \n% \n%% Computing with orientation dependent functions\n%\n% The power of representing an orientation dependent functions as a\n% variables of type @SO3Fun is that we may apply to it a\n% . In particular,\n% one can add, subtract and mutiply orientation dependent functions, plot\n% them in various projections or detect the local minima or maxima. In the\n% case of our example function the local maxima refers to the orientations\n% with maximum rotational angle in cubic symmetry. We may compute them by\n% the command \n\n[value,ori] = max(SO3F,'numLocal',10)\n\n%%\n% We observe that there are exactly six symetrically not equivalent\n% orientations that realize an orientation angle of about 62.77 degree and\n% form the vertices of the fundamental region in orienation space\n\nplot(ori.symmetrise,'axisAngle','filled','markerSize',15,'restrict2FundamentalRegion')\n\n%% Representations of Rotational Functions\n%\n% Internally MTEX represents rotational functions in different ways:\n%\n% || by a harmonic series expansion || ||\n% || as superposition of radial function || ||\n% || as superposition of fibre elements || ||\n% || as Bingham distribution || ||\n% || as sum of different components || @SO3FunComposition ||\n% || explicitely given by a formula || @SO3FunHandle ||\n%\n% All representations allow the same operations which are specified for\n% the abstact class |@SO3Fun|. In particular it is possible\n% to calculate with $SO(3)$ functions as with ordinary numbers, i.e., you\n% can add, multiply arbitrary functions, take the mean, integrate them or\n% compute gradients, see .\n%\n%% Generalizations of Rotational Functions\n%\n% || rotational vector fields || ||\n% || radial rotational functions || ||\n%\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/SO3Functions/SO3FunConcept.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.7016072029744603}} {"text": "classdef lasso\n%function [Problem] = lasso(A, b, lambda, sub_mode, smooth_lambda)\n% This file defines the lasso (least absolute shrinkage and selection operator) problem for L1 norm. \n%\n% Inputs:\n% A dictionary matrix of size dxn.\n% b observation vector of size dx1.\n% lambda l1-regularized parameter. \n% sub_mode {'prox_reg', 'subgrad_reg', 'smooth', 'const'}\n% smooth_lambda\n% Output:\n% Problem problem instance. \n%\n%\n% The problem of interest is defined as\n%\n% (1) sub_mode = 'prox_reg' for L1 regularizer solved by proximal methods\n%\n% min f(w) = 1/2 * || A * w - b ||_2^2 + lambda * || w ||_1\n%\n% (2) sub_mode = 'subgrad_reg' for L1 regularizer solved by subgrad methods\n%\n% min f(w) = 1/2 * || A * w - b ||_2^2 + lambda * || w ||_1\n%\n% (3) sub_mode = 'smooth' for smoothing \n%\n% min f(w) = 1/2 * || A * w - b ||_2^2 + smooth_lambda * || w ||_1.\n%\n% (43) sub_mode = 'const' for L1 constraint \n%\n% min f(w) = 1/2 * || A * w - b ||_2^2, s.t. || w ||_1 < r\n%\n%\n% \"w\" is the model parameter of size d vector.\n%\n%\n% This file is part of GDLibrary and SGDLibrary.\n%\n% Created by H.Kasai on Apr. 17, 2017\n% Modified by H.Kasai on Mar. 25, 2018\n% Modified by H.Kasai on Mar. 27, 2020\n% Modified by H.Kasai on Mar. 30, 2020\n\n\n properties\n name; \n dim;\n samples;\n sub_mode;\n lambda;\n d;\n n;\n A;\n b;\n AtA;\n Atb;\n L;\n prox_flag;\n sign_flag;\n idx;\n smooth_mu; % for smoothing\n smooth_type; % for smoothing\n end\n \n methods\n function obj = lasso(A, b, lambda, sub_mode, varargin) \n \n obj.A = A;\n obj.b = b;\n \n if strcmp(sub_mode, 'prox_reg')\n obj.prox_flag = true;\n elseif strcmp(sub_mode, 'subgrad_reg')\n obj.prox_flag = false; \n elseif strcmp(sub_mode, 'const')\n obj.prox_flag = true; \n elseif strcmp(sub_mode, 'smooth')\n obj.prox_flag = false;\n else\n error('Not correctly specified for sub_mode');\n end\n\n obj.sub_mode = sub_mode;\n obj.lambda = lambda;\n \n if nargin < 6\n obj.smooth_type = 'type1';\n else\n obj.smooth_type = varargin{2};\n end \n \n if nargin < 5\n obj.smooth_mu = 0.1;\n else\n obj.smooth_mu = varargin{1};\n end \n\n obj.d = size(obj.A, 2);\n obj.n = size(obj.A, 2);\n\n obj.name = 'lasso'; \n obj.dim = obj.d;\n obj.samples = obj.n;\n\n obj.AtA = obj.A'*obj.A;\n obj.Atb = obj.A'*obj.b;\n %L = max(eig(AtA));\n fprintf('Calculated Lipschitz constant (L), i.e., max(eig(AtA)), .... ')\n obj.L = eigs(obj.AtA, 1);\n fprintf('is L = %f.\\n', obj.L);\n end\n \n function v = prox(obj, w, t)\n if strcmp(obj.sub_mode, 'prox_reg')\n v = soft_thresh(w, t * obj.lambda);\n elseif strcmp(obj.sub_mode, 'const')\n %v = sign(w) .* proj_simplex(abs(w), obj.lambda, 'ineq');\n v = proj_l1_ball(w, obj.lambda);\n else\n error('Not correctly specified for sub_mode');\n end\n end \n\n function f = cost(obj, w)\n reg = obj.reg(w);\n f = 1/2 * sum((obj.A * w - obj.b).^2) + obj.lambda * reg;\n end\n\n % calculate l1 norm\n function r = reg(obj, w)\n r = norm(w,1);\n end\n\n function r = residual(obj, w)\n r = - obj.A * w + obj.b;\n end\n\n function f = cost_batch(obj, w, indices)\n error('Not implemted yet.'); \n end\n\n function g = full_grad(obj, w)\n %g = obj.A' * (obj.A * w - obj.obj.b);\n g = obj.AtA * w - obj.Atb;\n end\n\n function g = grad(obj, w, indices)\n A_partial = obj.A(:,indices);\n g = A_partial' * (A_partial * w - obj.b); \n end\n \n % for Subgradient descent\n function subg = full_subgrad(obj, w)\n subg = obj.lambda * sign(w);\n end\n \n % for Smoothing \n function smooth_g = full_smooth_grad(obj, w)\n smooth_g = zeros(obj.n, 1);\n \n if strcmp(obj.smooth_type, 'type1') % f_mu(w) = w^2/2mu for abs(w)<= mu, abs(w)-mu/2 for abs(w)> mu.\n for i = 1 : obj.n\n if abs(w(i)) <= obj.smooth_mu\n smooth_g(i) = w(i) / obj.smooth_mu;\n elseif w(i) > obj.smooth_mu\n smooth_g(i) =1;\n else\n smooth_g(i) =-1;\n end\n end\n elseif strcmp(obj.smooth_type, 'type2') % f_mu(w) = (w^2+mu^2)^(1/2)\n for i = 1 : obj.n \n smooth_g(i) = w(i)/sqrt(w(i)^2+obj.smooth_mu^2);\n end \n elseif strcmp(obj.smooth_type, 'type3') % f_mu(w) = mu log((exp(-w/mu) + exp(w/mu))/2)\n for i = 1 : obj.n \n p = exp(-w(i)/obj.smooth_mu); \n q = exp(w(i)/obj.smooth_mu);\n smooth_g(i) = (q-p)/(p+q);\n end \n %smooth_g = smooth_g;\n end\n \n smooth_g = obj.lambda * smooth_g;\n end \n\n % for Frank-Wolfe, a.k.a. Condtional Gradient\n function [s, idx, sign_flag] = LMO(obj, grad) \n [val, idx] = max( abs(grad) );\n obj.sign_flag = -1 * sign(grad(idx));\n obj.idx = idx;\n\n s = zeros(size(grad)); \n s(idx) = obj.sign_flag * obj.lambda; \n \n sign_flag = obj.sign_flag;\n end \n\n function h = hess(obj, w, indices)\n error('Not implemted yet.'); \n end\n\n function h = full_hess(obj, w)\n h = obj.AtA; \n end\n\n function hv = hess_vec(obj, w, v, indices)\n error('Not implemted yet.');\n end\n \n function step = exact_line_search(obj, w, dir, idx, sign_flag)\n As = sign_flag * obj.lambda * obj.A(:,idx); % = the i-th column of the dictionary matrix A\n As_minus_Ax = As - obj.A*w;\n step = max(0, min(1, As_minus_Ax' * (obj.b-obj.A*w) / (As_minus_Ax' * As_minus_Ax)));\n end \n\n function w_opt = calc_solution(obj, method, options_in)\n\n if nargin < 1\n method = 'ista';\n end \n\n options.max_epoch = options_in.max_epoch;\n options.w_init = options_in.w_init;\n options.verbose = options_in.verbose;\n options.tol_optgap = 1.0e-24;\n options.tol_gnorm = 1.0e-16;\n options.step_alg = 'backtracking';\n \n if ~options.verbose\n fprintf('Calclation of solution started ... ');\n end\n\n if strcmp(method, 'sd')\n [w_opt,~] = sd(obj, options);\n elseif strcmp(method, 'cg')\n [w_opt,~] = ncg(obj, options);\n elseif strcmp(method, 'newton')\n options.sub_mode = 'INEXACT'; \n options.step_alg = 'non-backtracking'; \n [w_opt,~] = newton(obj, options);\n elseif strcmp(method, 'ista')\n options.step_alg = 'fix'; \n options.step_init = 1/obj.L; \n options.sub_mode = 'FISTA'; \n [w_opt,~] = ag(obj, options); \n else \n options.step_alg = 'backtracking'; \n options.mem_size = 5;\n [w_opt,~] = lbfgs(obj, options); \n end\n \n if ~options.verbose\n fprintf('done\\n');\n end \n end\n end\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/problem/lasso.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.7015235463960001}} {"text": "%RODRIGUES Converts a rotation matrix to a rotation vector or vice versa\n%\n% dst = cv.Rodrigues(src)\n% [dst,jacobian] = cv.Rodrigues(src)\n%\n% ## Input\n% * __src__ Input rotation vector (3x1 or 1x3) or rotation matrix (3x3). Both\n% single and double-precision floating-point types are supported.\n%\n% ## Output\n% * __dst__ Output rotation matrix (3x3) or rotation vector (3x1 or 1x3),\n% respectively. Same data type as `src`.\n% * __jacobian__ Optional output Jacobian matrix, 3x9 or 9x3, which is a\n% matrix of partial derivatives of the output array components with respect\n% to the input array components. Same data type as `src`.\n%\n% The function transforms a rotation matrix in the following way:\n%\n% theta <- norm(r)\n% r <- r/theta\n% R = cos(theta) * I + (1 - cos(theta)) * r * r^T + sin(theta) * A\n% A = [0, -rz, ry; rz, 0, -rx; -ry, rx, 0]\n%\n% Inverse transformation can be also done easily, since\n%\n% sin(theta) * A = (R - R^T) / 2\n%\n% A rotation vector is a convenient and most compact representation of a\n% rotation matrix (since any rotation matrix has just 3 degrees of\n% freedom). The representation is used in the global 3D geometry\n% optimization procedures like cv.calibrateCamera, cv.stereoCalibrate, or\n% cv.solvePnP.\n%\n% See also: cv.calibrateCamera, cv.stereoCalibrate, cv.solvePnP,\n% rotationMatrixToVector, rotationVectorToMatrix\n%\n", "meta": {"author": "kyamagu", "repo": "mexopencv", "sha": "d29007b2a484d0fd92e6e941dc5fd4750014fa6a", "save_path": "github-repos/MATLAB/kyamagu-mexopencv", "path": "github-repos/MATLAB/kyamagu-mexopencv/mexopencv-d29007b2a484d0fd92e6e941dc5fd4750014fa6a/+cv/Rodrigues.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.701514023788476}} {"text": "%%*********************************************************************\n%% norm_min: matrix 2-norm minimization problem \n%%\n%% (primal) minimize || B0 + x1*B1 + ... + xm*Bm ||_2\n%%\n%% (dual) maximize - Tr B0*Q\n%% subject to Tr Bk*Q = 0, k=1,...,m\n%% sum of singular values of Q is less than one.\n%% \n%% The matrices Bk are of size p x q.\n%%\n%% The problem is equivalent to the following SDP:\n%% \n%% minimize t \n%% [0, Bk] \n%% s.t. sum_{k=1}^m xk*[ ] \n%% [Bk^*, 0] \n%% [0, i*Bk] [0, B0]\n%% + sum_{k=m+1}^{2m} xk*[ ] -t*I <= -[ ] \n%% [(i*Bk)^*, 0] [B0^*, 0]\n%%\n%% Adapted from Vandenberghe and Boyd, SIAM Review 96. \n%% see also igmres.m \n%%-------------------------------------------------------------------- \n%%\n%% [blk,Avec,C,b,X0,y0,Z0,objval,x] = norm_min(B,feas,solve); \n%%\n%% Input: B = cell array such that B{k} = B_k.\n%% feas = 1 if want feasible starting point\n%% = 0 if otherwise.\n%% solve = 0 just to initialize\n%% = 1 if want to solve the problem. \n%%\n%% SDPT3: version 3.0 \n%% Copyright (c) 1997 by\n%% K.C. Toh, M.J. Todd, R.H. Tutuncu\n%% Last modified: 2 Feb 01\n%%*********************************************************************\n\n function [blk,Avec,C,b,X0,y0,Z0,objval,x] = norm_min(B,feas,solve); \n\n if (nargin < 3); solve = 0; end; \n if (nargin < 2); feas = 0; end;\n if isempty(feas); feas = 0; end\n%%\n%% dimensions \n%%\n m = size(B,2)-1; \n [p,q] = size(B{1}); isrealB = 1; \n for k = 1:m; \n [p1,q1] = size(B{k}); \n if any([p q]-[p1 q1]); \n error('size of B_k is not the same for all k'); \n end \n isrealB = min(isrealB, isreal(B{k})); \n end\n cmp = 1-isrealB; \n%%\n%% A{k} = [0 Bk; Bk' 0], i=1,...,m+1; A{m+1} = I\n%% \n if (~cmp) \n n = p+q; \n blk{1,1} = 's'; blk{1,2} = n;\n b = [zeros(m,1); -1];\n C = -[zeros(p), B{1}; B{1}', zeros(q)]; \n A = cell(1,m+1); \n for k = 1:m\n Bk = B{k+1}; \n A{k} = [zeros(p), Bk; Bk', zeros(q)];\n end\n A{m+1} = -speye(n,n); \n Avec = svec(blk,A,ones(size(blk,1),1)); \n elseif (cmp)\n n = p+q; \n blktmp{1,1} = 's'; blktmp{1,2} = n;\n b = [zeros(2*m,1); -1];\n Ctmp{1} = -[zeros(p), B{1}; B{1}', zeros(q)]; \n A = cell(1,2*m+1); ii = sqrt(-1); \n for k = 1:m\n Bk = B{k+1};\n A{k} = [zeros(p), Bk; Bk', zeros(q)];\n A{k+m} = [zeros(p), ii*Bk; -ii*Bk', zeros(q)];\n end\n A{2*m+1} = -speye(n,n);\n [blk,Avec,C,b] = convertcmpsdp(blktmp,A,Ctmp,b); \n end \n%%\n%%\n if (feas == 1); \n if (~cmp)\n X0{1} = eye(n)/n;\n else\n X0{1} = eye(2*n)/(2*n);\n end\n y0 = 1.1*ops(C,'norm')*[zeros(length(b)-1,1); 1];\n Z0 = ops(C,'-',Atyfun(blk,Avec,[],[],y0));\n elseif (feas == 0)\n [X0,y0,Z0] = infeaspt(blk,Avec,C,b); \n end \n if (solve) \n [obj,X,y,Z] = sqlp(blk,Avec,C,b,[],X0,y0,Z0);\n objval = -mean(obj); \n if ~cmp; x = y(1:m); \n else; x = y(1:m) +sqrt(-1)*y(m+1:2*m); \n end;\n else\n objval = []; x = [];\n end\n%%*********************************************************************\n", "meta": {"author": "zarathustr", "repo": "LibQPEP", "sha": "99e5c23e746ace0bac4a86742c31db6fcf7297ba", "save_path": "github-repos/MATLAB/zarathustr-LibQPEP", "path": "github-repos/MATLAB/zarathustr-LibQPEP/LibQPEP-99e5c23e746ace0bac4a86742c31db6fcf7297ba/MATLAB/sdpt3/Examples/norm_min.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7014623102058755}} {"text": "function asa007_test02 ( )\n\n%*****************************************************************************80\n%\n%% TEST02 demonstrates the use of SYMINV.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2008\n%\n% Author:\n%\n% John Burkardt\n%\n n_max = 15;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST02:\\n' );\n fprintf ( 1, ' SYMINV computes the inverse of a positive\\n' );\n fprintf ( 1, ' definite symmetric matrix.\\n' );\n fprintf ( 1, ' A compressed storage format is used.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Here we look at the Hilbert matrix\\n' );\n fprintf ( 1, ' A(I,J) = 1 / ( I + J - 1 )\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' We expect errors to grow quickly with N.\\n' );\n\n for n = 1 : n_max\n%\n% Set A to the Hilbert matrix.\n%\n k = 0;\n for i = 1 : n\n for j = 1 : i\n k = k + 1;\n a(k) = 1.0 / ( i + j - 1 );\n end\n end\n\n [ c, nullty, ifault ] = syminv ( a, n );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Matrix order N = %d\\n', n );\n fprintf ( 1, ' Maxtrix nullity NULLTY = %d\\n', nullty );\n\n k = 0;\n for j = 1 : n\n for i = 1 : j - 1\n k = k + 1;\n cfull(i,j) = c(k);\n cfull(j,i) = c(k);\n end\n k = k + 1;\n cfull(j,j) = c(k);\n end\n\n k = 0;\n for j = 1 : n\n for i = 1 : j - 1\n k = k + 1;\n afull(i,j) = a(k);\n afull(j,i) = a(k);\n end\n k = k + 1;\n afull(j,j) = a(k);\n end\n%\n% Compute C * A - I.\n%\n b(1:n,1:n) = cfull(1:n,1:n) * afull(1:n,1:n) - eye(n);\n\n diff = sqrt ( sum ( sum ( b(1:n,1:n).^2 ) ) );\n\n fprintf ( 1, ' RMS ( C * A - I ) = %e\\n', diff );\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/asa007/asa007_test02.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7013975600969907}} {"text": "function f=evalContFrac(bFunc,aFunc,tinyVal,maxIter)\n%%EVALCONTFRAC Evaluate a continued fraction of the form\n% f=b(1)+a(1)/(b(2)+a(2)/(b(3)+a(3)/(b(4)+a(4)/...\n% Given either matrices for a finite number of a and b terms\n% of function for the a and b values such that the required\n% number of terms can be requested.\n%\n%INPUTS: bFunc This can either be a function such that bFunc(i) provides\n% b(i) in the continued fraction, or this can be a maxNX1 or\n% 1XmaxN vector of explicit b values.\n% aFunc This has to be of the same type as bFunc, either a function\n% handle or a vector to provide the a values. If a vector,\n% then it is 1X(maxN-1) or (maxN-1)X1 as it takes one fewer\n% call to the a terms than the b terms to evaluate the\n% continued fraction.\n% tinyVal An optional parameter that is less than typical values of\n% eps(b), but is not zero. This parameter is used to mitigate\n% divide-by zero errors. The default if this parameter is\n% omitted or an empty matrix is passed if 2e-100.\n% maxIter An optional parameter considering the maximum number of\n% terms to evaluate in the continued fraction. The default\n% value if omitted is 1000. This parameter is only used if\n% aFunc and bFunc are functions, not arrays. If they are\n% arrays, then the maximum number of terms used is determined\n% by the array length.\n%\n%OUTPUTS: f The value of the continued fraction. The smallest possible\n% value that this can take if b(0)=0 and all a and b are\n% non-negative is eps, due to how the function is initialized to\n% be numerically robust.\n%\n%The algorithm is the modified Lentz's method. A good description of the\n%method, demonstrating its origin is given in Chapter II and Appendix C of\n%[1]. The origin of the algorithm is [2]. However, the algorithm is harder\n%to understand outside of the context of Bessel functions when consulting\n%[2].\n%\n%An example of a continued fraction is an approximation to pi:\n% bFunc=@(i)((i==1)*0+(i~=1)*(2*(i-1)-1));\n% aFunc=@(i)(4*(i==1)+(i-1)^2*(i~=1));\n% piApprox=evalContFrac(bFunc,aFunc)\n%\n%REFERENCES:\n%[1] C.-Y. Shih, \"An investigation of a stable algorithm for the evaluation\n% of fractional order Bessel functions,\" Master's thesis, Emporia\n% State University, Emporia, KS, Nov. 1993. [Online]. Available:\n% https://esirc.emporia.edu/bitstream/handle/123456789/1773/Shih%201993.pdf\n%[2] W. J. Lentz, \"Generating Bessel functions in Mie scattering\n% calculations using continued fractions,\" Applied optics, vol. 15, no.\n% 3, pp. 668-671, Mar. 1976.\n%\n%October 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.\n%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.\n\n%The floating point precision.\nepsVal=eps();\n\nif(nargin<3)\n tinyVal=2^(-100);\nend\n\nif(isa(bFunc,'double'))\n maxN=length(bFunc);\n maxIter=maxN-1;\nelseif(nargin<4)\n maxIter=1000;\nend\n\nb0=bFunc(1);\nif(b0==0)\n f=tinyVal;\nelse\n f=b0;\nend\n\nCPrev=f;\nDPrev=0;\n\nj=1;\nwhile(jr\n % The factor 0.001 limits the step sizes of random walks \n S(i,:)=best+0.001*randn(1,d);\n end\n\n % Evaluate new solutions\n Fnew=Fun(S(i,:));\n % Update if the solution improves, or not too loud\n if (Fnew<=Fitness(i)) & (rand, is u*u'\n% p Is the expected value of y(i)^2\n%\n% zf and zi are the output and optional input state as defined in filter()\n% If zi is not specified, random numbers with the correct covariance will be used.\n% output u*u' is the state covariance matrix for filter(). Output p is the\n% mean power of the output signal y.\n\n% Copyright (C) Mike Brookes 1997\n% Version: $Id: randfilt.m 5885 2015-03-18 09:35:01Z dmb $\n%\n% VOICEBOX is a MATLAB toolbox for speech processing.\n% Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% This program is free software; you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation; either version 2 of the License, or\n% (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You can obtain a copy of the GNU General Public License from\n% http://www.gnu.org/copyleft/gpl.html or by writing to\n% Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% first normalize the denominator polynomial if necessary\n\nif pa(1)~=1\n pb=pb/pa(1); pa=pa/pa(1);\nend\n\n% check to see if we must generate zi\n\nif nargin<4 | nargout>2\n lb=length(pb);\n la=length(pa);\n\n k=max(la,lb)-1;\n l=la-1;\n ii=k+1-l:k;\n\n % form controllability matrix\n\n q=zeros(k,k);\n [z,q(:,1)]=filter(pb,pa,1);\n for i=2:k [z,q(:,i)]=filter(pb,pa,0,q(:,i-1)); end\n\n % we generate m through the step-down procedure\n s=randn(k,1);\n if l\n m=zeros(l,l);\n g=pa;\n for i=1:l\n g=(g(1)*g(1:end-1)-g(end)*g(end:-1:2))/sqrt((g(1)-g(end))*(g(1)+g(end)));\n m(i,i:l)=g;\n end\n s(ii)=triu(toeplitz(pa(1:l)))*(m\\s(ii));\n if nargout>2\n u=q;\n u(:,ii)=q(:,ii)*triu(toeplitz(pa(1:l)))/m;\n end\n else\n if nargout>2\n u=q;\n end\n end\n if nargin < 4\n if k\n zi=q*s;\n else\n zi=[];\n end\n end\nend\nif nargout>2\n if ~numel(u)\n p=pb(1).^2;\n else\n p=u(1,:)*u(1,:)'+pb(1).^2;\n end\nend\nif nargin>2 && ny>0\n [y,zf]=filter(pb,pa,randn(ny,1),zi);\nelse\n zf=zi;\n y=[];\nend", "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/randfilt.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.7013108195877163}} {"text": "function [ d2q ] = gen_DirectDynamics(q,Pcii,Icii,mcii,dq,taw)\n%% This function is used to calculate the direct 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.\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/Matlab_client/gen_DirectDynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7013108071792914}} {"text": "function sc = census(I,J)\n\n% CENSUS Census Correlation coefficient\n% CENSUS(I,J) computes the census score of matrices I and J:\n%\n% CENSUS = 1/N * ~xor( I > Io , J > Jo )\n%\n% where N = prod(size(I))\n% Io = I(central pixel)\n% Jo = J(central pixel)\n% and size(I) = size(J)\n%\n% See also PATCHCORR, ZNCC, SSD\n\n% (c) 2005 Joan Sola\n\n\nif size(I) ~= size(J)\n error ('Matrices must be the same size.')\nelse\n s = size(I); % patch size\n if any(iseven(s))\n error('Matrix sizes must be odd.')\n else\n c = (s+1)/2; % patch center\n i = I(c(1),c(2)); % central pixel\n j = J(c(1),c(2)); % central pixel\n\n V = I > i;\n W = J > j;\n\n SC = ~xor(V,W);\n sc = sum(sum(SC))/numel(I);\n end\nend\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/DetectionMatching/census.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.7013082865203994}} {"text": "function [logp, yhat, res] = tapas_rs_surprise(r, infStates, ptrans)\n% Calculates the log-probability of response speed y (in units of ms^-1) according to the surprise\n% model introduced in:\n%\n% Vossel, S.*, Mathys, C.*, Daunizeau, J., Bauer, M., Driver, J., Friston, K. J., and Stephan, K. E.\n% (2013). Spatial Attention, Precision, and Bayesian Inference: A Study of Saccadic Response Speed.\n% Cerebral Cortex.\n%\n% --------------------------------------------------------------------------------------------------\n% Copyright (C) 2012-2013 Christoph Mathys, TNU, UZH & ETHZ\n%\n% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public\n% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL\n% (either version 3 or, at your option, any later version). For further details, see the file\n% COPYING or .\n\n% Transform zetas to their native space\nze1v = exp(ptrans(1));\nze1i = exp(ptrans(2));\nze2 = exp(ptrans(3));\nze3 = exp(ptrans(4));\n\n% Initialize returned log-probabilities, predictions,\n% and residuals as NaNs so that NaN is returned for all\n% 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, responses, and inputs\nmu1hat = infStates(:,1,1);\nmu1hat(r.irr) = [];\n\ny = r.y(:,1);\ny(r.irr) = [];\n\nu = r.u(:,1);\nu(r.irr) = [];\n\n% Calculate alpha (i.e., attention)\nalpha = 1./(1-log2(mu1hat));\n\n% Calculate predicted response speed\nrs = u.*(ze1v + ze2*alpha) + (1-u).*(ze1i + ze2*(1-alpha));\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) = -1/2.*log(8*atan(1).*ze3) -(y-rs).^2./(2.*ze3);\nyhat(reg) = rs;\nres(reg) = y-rs;\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_rs_surprise.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.701308279432257}} {"text": "function w = hermite_cubic_spline_quad_rule ( nn, xn )\n\n%*****************************************************************************80\n%\n%% HERMITE_CUBIC_SPLINE_QUAD_RULE: Hermite cubic spline quadrature rule.\n%\n% Discussion:\n%\n% The integral is taken over the definition interval [X(1),X(NN)].\n%\n% Note that if the intervals are equal in size, then the derivative\n% information in DN has no effect on the integral value,\n% except for the first and last entries.\n%\n% The quadrature rule is\n%\n% Integral ( XN(1) <= X <= XN(NN) ) F(X) dX is approximately\n%\n% Sum ( 1 <= I <= NN ) W(1,I) * F(X(I)) + W(2,I) * F'(X(I))\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 28 March 2011\n%\n% Author:\n%\n% 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% Parameters:\n%\n% Input, integer NN, the number of data points.\n%\n% Input, real XN(NN), the coordinates of the data points.\n% The entries in XN must be in strictly ascending order.\n%\n% Output, real W(2,NN), the quadrature weights for F(1:NN)\n% and DN(1:NN).\n%\n w = zeros ( 2, nn );\n\n w(1,1) = 0.5 * ( xn(1,2) - xn(1,1) );\n w(1,2:nn-1) = 0.5 * ( xn(1,3:nn) - xn(1,1:nn-2) );\n w(1,nn) = 0.5 * ( xn(1,nn) - xn(1,nn-1) );\n\n w(2,1) = ( xn(1,2) - xn(1,1) ).^2 / 12.0;\n w(2,2:nn-1) = ( xn(1,3:nn) - xn(1,1:nn-2) ) ...\n .* ( xn(1,3:nn) - 2.0 * xn(1,2:nn-1) + xn(1,1:nn-2) ) / 12.0;\n w(2,nn) = - ( xn(1,nn-1) - xn(1,nn) ).^2 / 12.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/hermite_cubic/hermite_cubic_spline_quad_rule.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7012892974685367}} {"text": "%==========================================================================\n% copywrite 2011\n% iterative-Maximum ratio combining (i-MRC) detector\n% for spatial Modulation (SM) MIMO transmission technique.\n%\n% This Matlab code computes the BER of the SM for the case where the\n% channel coefficients are modeled as uncorrelated Rayleigh fading channel\n% M is the modulation order of M-QAM schemes.\n% Mt = number of transmit antennas.\n% Mr = number of receive antennas.\n% This code is written by Rajab Legnain\n%==========================================================================\nfunction simulation_of_SM_iMRC()\nclear all; clc;\nmode = 1; % mode = 1 the channel is normalized, \n % mode = 2 the channel is not normalized\nglobal M Mt hmodem bit_T\nM = 16; \nMt = 4;\nMr = 4;\nbit_SMsym = log2(M*Mt); % number of bit per spatial modulation sysmbol\nNbits = bit_SMsym*1e4; % Number of bits to be simulated.\n\nhmodem = modem.qammod('M',M, 'SymbolOrder', 'Gray','InputType', 'bit');\nhdemodem = modem.qamdemod('M', M,'SymbolOrder','Gray','OutputType','bit');\nEac = (mean(hmodem.Constellation .* conj(hmodem.Constellation))); \nSNR = 0 : 2 :24; % signal-to-noise ratio in dB\nNo= (Eac)*10.^(-SNR/10); % noise variance\n\nL_SNR=length(SNR);\nber= zeros (L_SNR,1); \nbit_R=zeros(Nbits, 1);\n\n%%\nbit_T = randi([0 1],Nbits,1);\n[mod_T ante]= SpatialMod(); % Spatial Modulation\nmod_T = mod_T.';\n\nfor ii=1:L_SNR \n for j = 1 : size(mod_T ,2)\n channel = sqrt(.5)*( randn(Mr,Mt,1) + 1i*randn(Mr,Mt,1)); \n noise = sqrt(.5)*(randn(Mr , 1) + 1i*randn(Mr , 1))* sqrt(No(ii)); \n p = diag(channel'*channel); \n switch mode\n case 1\n y = channel(:,ante(j))*(mod_T(ante(j) ,j)./sqrt(p(ante(j)))) + noise; \n z = (channel'*y)./p.^.5;\n case 2\n y = channel(:,ante(j)) * mod_T(ante(j) ,j) + noise ; \n z = (channel'*y)./p;\n end \n [~,ant_est] = max(abs(z));\n bi_ant = de2bi(ant_est - 1 , log2(Mt) ,'left-msb');\n bi_mod = demodulate(hdemodem, z(ant_est,1) );\n bit_R( (j-1)*bit_SMsym+1 : (j-1)*bit_SMsym+bit_SMsym,1) = [bi_ant.' ; bi_mod];\n \n end\n [~,ber(ii,1)] = biterr(bit_T(:,1),bit_R(:));\nend\n\nsemilogy(SNR,ber(:,1),'color',[0,0.75,0.75],'linestyle','-','LineWidth',1);\ngrid on;\nxlabel('$$SNR$$','Interpreter','latex')\nylabel('BER','Interpreter','latex')\ntitle('Bit Error Rate of SM using i-MRC detector')\nlegend([num2str(M),'-QAM'] , 'Location','NorthEast')\nend \n\n\n\nfunction [signal ant_no]= SpatialMod()\nglobal M Mt hmodem bit_T\nNt = log2(Mt);\nNobit = log2(M);\nx = reshape(bit_T,Nobit+Nt,[]);\n\nant_no = bi2de([x(1:Nt,:)].' , 'left-msb') + 1;\ndigMod = modulate(hmodem,x(Nt+1:end,:));\n\n\nsignal = zeros(Mt , length(digMod));\n\n\nfor i = 1 : length(digMod)\n signal( ant_no(i) , i) = digMod(i);\nend\n\nsignal = signal.';\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/43547-ber-performance-of-spatial-modulation-using-i-mrc-detector/simulation_of_SM_iMRC.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.7012604403977288}} {"text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Solve the following exercises:\n% A) Parabolic. with friction.\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 parabolic_with_friction()\nglobal g k m\nclose all;\ng = 9.81; %m/s^ 2. gravity at equator\n% datos de ajustados a 1000 m de https://en.wikipedia.org/wiki/Ballistic_table#/media/File:Ballistic_table_for_7.62x51_mm_NATO_(mil_and_moa).png\n% 7.62x51 mm NATO ammunition\ntheta0 = 0; %initial angle\nk = 0.0000005; % N*s/m friction coefficient\nm=9.7/1000; %mass of the bullet kg\nv=860; % m/s initial speed\n\ntheta0 = 0; %initial angle\nk = 0.0000005; % N*s/m friction coefficient\nm=0.47; %mass of the bullet kg\nv=609; % m/s initial speed\n % 914\n\n\nt0 = 0;\ntfinal = 2.2;\nx0 = 0;\ny0 = 0;\nvx0 = v*cos(theta0);\nvy0 = v*sin(theta0);\n\n[t, x] = runge_kutta(@parabolic_friction_square, [x0 y0 vx0 vy0]', [t0 tfinal], 0.01);\nx = x(:, 1:length(t)); \nplot(t, x(1,:), 'r'), hold\nplot(t, x(2,:), 'g')\nplot(t, x(3,:), 'b')\nplot(t, x(4,:), 'c')\nlegend('Position X (m) RK4', 'Position Y (m) RK4', 'Speed X (m/s) RK4', 'Speed Y (m/s) RK4')\n\nfigure, \nplot(x(1,:), x(2,:), 'r') \nxlabel('X Position (m)')\nylabel('Y Position (m)')\n\nx(2,end)\n\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Helper function to solve a constant acceleration on x axis on a ramp.\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction xd = parabolic_friction_square(t, x)\nglobal k g m\n% We must return the solution of\n% [dx1/dt; dx2/dt; dx3/dt dx4/dt]\nvx = x(3);\nvy = x(4);\n\n%forces in both axes\nsq = sqrt(vx^2+vy^2);\nxd(1) = vx;\nxd(2) = vy;\nxd(3) = -(k/m)*vx*sq;\nxd(4) = -(k/m)*vy*sq - g;\nxd = xd(:);\n\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/solution/parabolic_with_friction.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.7012447452765709}} {"text": "function err = getL2error3NE1(node,elem,exactE,Eh,markedElem)\n%% GETL2ERROR3NE1 L2 norm of the linear Nedelec edge element.\n% \n% err = getL2error3NE(node,elem,exactE,Eh,markedElem);\n%\n% Example\n% \n% node = [-1,-1,-1; 1,-1,-1; 1,1,-1; -1,1,-1; -1,-1,1; 1,-1,1; 1,1,1; -1,1,1]; \n% elem = [1,2,3,7; 1,6,2,7; 1,5,6,7; 1,8,5,7; 1,4,8,7; 1,3,4,7];\n% maxIt = 4;\n% L2Err = zeros(maxIt,1);\n% N = zeros(maxIt,1);\n% for k = 1:maxIt\n% [node,elem] = uniformbisect3(node,elem);\n% [elem2dof,edge] = dof3edge(elem);\n% pde = Maxwelldata2;\n% uI = edgeinterpolate1(pde.exactu,node,edge);\n% L2Err(k) = getL2error3NE1(node,elem,pde.exactu,uI);\n% N(k) = length(uI);\n% end\n% r = showrate(N,L2Err,1,'b-+');\n% legend('||u-u_I||',['N^{' num2str(r) '}'],'LOCATION','Best');\n%\n% Copyright (C) Long Chen. See COPYRIGHT.txt for details. \n\n%% Sort elem to ascend ordering\nelem = sort(elem,2);\n\n%% Construct Data Structure\nelem2dof = dof3edge(elem);\nNT = size(elem,1); Ndof = max(elem2dof(:)); %N = size(node,1); \n[Dlambda,volume] = gradbasis3(node,elem);\nlocEdge = [1 2; 1 3; 1 4; 2 3; 2 4; 3 4];\n\n%% Compute square of the L2 error element-wise\n[lambda,w] = quadpts3(3); % quadrature order is 3\nnQuad = size(lambda,1);\nerr = zeros(NT,1);\nfor p = 1:nQuad\n % quadrature points in the x-y-z coordinate\n pxy = lambda(p,1)*node(elem(:,1),:) ...\n + lambda(p,2)*node(elem(:,2),:) ... \n + lambda(p,3)*node(elem(:,3),:) ... \n + lambda(p,4)*node(elem(:,4),:);\n Ep = exactE(pxy);\n Ehp = zeros(NT,3);\n for k = 1:6 % for each basis\n i = locEdge(k,1); j = locEdge(k,2);\n % phi_k = lambda_iDlambda_j - lambda_jDlambda_i;\n Ehp = Ehp + repmat(Eh(elem2dof(:,k)),1,3).*...\n (lambda(p,i)*Dlambda(:,:,j)-lambda(p,j)*Dlambda(:,:,i));\n % psi_k = lambda_iDlambda_j + lambda_jDlambda_i;\n Ehp = Ehp + repmat(Eh(elem2dof(:,k)+Ndof),1,3).*...\n (lambda(p,i)*Dlambda(:,:,j)+lambda(p,j)*Dlambda(:,:,i));\n end\n err = err + w(p)*sum((Ep - Ehp).^2,2);\nend\nerr = err.*volume;\nif (nargin == 5) && ~isempty(markedElem)\n err = err(markedElem); % L2 err on some marked region\nend\nerr = sqrt(sum(err));", "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/getL2error3NE1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.7012356257167662}} {"text": "function cheby_t_poly_test ( )\n\n%*****************************************************************************80\n%\n%% CHEBY_T_POLY_TEST tests CHEBY_T_POLY.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 27 March 2012\n%\n% Author:\n%\n% John Burkardt\n%\n n_max = 12;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHEBY_T_POLY_TEST:\\n' );\n fprintf ( 1, ' CHEBY_T_POLY evaluates the Chebyshev T polynomial.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' N X Exact F T(N)(X)\\n' );\n fprintf ( 1, '\\n' );\n\n n_data = 0;\n\n while ( 1 )\n\n [ n_data, n, x, fx ] = cheby_t_poly_values ( n_data );\n\n if ( n_data == 0 )\n break\n end\n\n fx2 = cheby_t_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_t_poly_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.7011368190678934}} {"text": "% function x = cwt_iw(Wx, type, opt)\n%\n% The inverse wavelet transform of signal Wx\n%\n% Implements Eq. (4.67) of [1].\n%\n% 1. Mallat, S., Wavelet Tour of Signal Processing 3rd ed.\n%\n% Inputs:\n% Wx: wavelet transform of a signal, see help cwt_fw\n% type: wavelet used to take the wavelet transform,\n% see help cwt_fw and help wfiltfn\n% opt: options structure used for forward wavelet transform.\n%\n% Output:\n% x: the signal, as reconstructed from Wx\n%\n%---------------------------------------------------------------------------------\n% Synchrosqueezing Toolbox\n% Authors: Eugene Brevdo (http://www.math.princeton.edu/~ebrevdo/)\n%---------------------------------------------------------------------------------\nfunction x = cwt_iw(Wx, type, opt)\n if nargin<3, opt = struct(); end\n\n [na, n] = size(Wx);\n\n [N,n1,n2] = p2up(n);\n Wxp = zeros(na, N);\n\n % TODO - do we want to pad the wavelet representation here? Or not\n % cut off Wx in cwt_fw and then use that to reconstruct?\n Wxp(:, n1+1:n1+n) = Wx;\n Wx = Wxp; clear Wxp;\n\n % Following the same value in cwt_fw\n noct = log2(N)-1;\n nv = na/noct;\n as = 2^(1/nv) .^ (1:1:na);\n \n assert(mod(noct,1) == 0);\n assert(nv>0 && mod(nv,1)==0); % integer\n\n % Find the admissibility coefficient Cpsi\n Cpsi = cwt_adm(type, opt);\n\n x = zeros(1, N);\n for ai=1:na\n a = as(ai);\n Wxa = Wx(ai, :);\n\n psih = wfilth(type, N, a, opt);\n\n % Convolution theorem here\n Wxah = fft(Wxa);\n xah = Wxah .* psih;\n xa = ifftshift(ifft(xah));\n \n x = x + xa/a;\n end\n\n % Take real part and normalize by log_e(a)/Cpsi\n x = log(2^(1/nv))/Cpsi * real(x);\n\n % Keep the unpadded part\n x = x(n1+1: n1+n);\n\nend % cwt_iw\n", "meta": {"author": "HeLiangHIT", "repo": "time_frequency", "sha": "09c2abe92355ff5cd867bdb169229682e9d7af7c", "save_path": "github-repos/MATLAB/HeLiangHIT-time_frequency", "path": "github-repos/MATLAB/HeLiangHIT-time_frequency/time_frequency-09c2abe92355ff5cd867bdb169229682e9d7af7c/tf_tool_box/synchrosqueezing/synchrosqueezing/cwt_iw.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.7011368183793242}} {"text": "function fd1d_burgers_lax ( )\n\n%*****************************************************************************80\n%\n%% FD1D_BURGERS_LAX solves the nonviscous Burgers equation using Lax-Wendroff.\n%\n% Discussion:\n%\n% The non-viscous time-dependent Burgers equation is:\n%\n% du/dt + u du/dx = 0\n%\n% which can be written in conservative form as\n%\n% du/dt + 1/2 d/dx ( u^2 ) = 0 \n%\n% or\n%\n% du/dt + dF/dx = 0\n%\n% For the Burgers equation, we define \n%\n% F(x,t) = 1/2 u^2,\n% A(x,t) = dF/dx = u\n%\n% and then the Lax-Wendroff method approximates the solution \n% using the iteration:\n%\n% u(x,t+dt) = u(t) - dt dF/dx + 1/2 dt^2 d/dx A dF/dx\n%\n% which can be written:\n%\n% u(x,t+dt) = u(x,t) - dt ( F(x+dx,t) - F(x-dx,t) ) / ( 2 * dx )\n% + 1/2 dt^2/dx^2 ( A(x+dx/2,t) * ( F(x+dx,t) - F(x,t) )\n% - A(x-dx/2,t) * ( F(x,t) - F(x-dx,t) )\n%\n% where we approximate:\n%\n% A(x+dx/2,t) = 1/2 ( u(x+dx,t) + u(x,t) )\n% A(x-dx/2,t) = 1/2 ( u(x,t) + u(x-dx,t) )\n%\n% There is a stability condition that applies here, which requires that\n%\n% dt * max ( abs ( u ) ) / dx <= 1\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 21 August 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% None\n%\n timestamp ( );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD1D_BURGERS_LAX:\\n' );\n fprintf ( 1, ' MATLAB version\\n' );\n fprintf ( 1, ' Solve the non-viscous time-dependent Burgers equation,\\n' );\n fprintf ( 1, ' using the Lax-Wendroff method.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Equation to be solved:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' du/dt + u * du/dx = 0\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' for x in [ a, b ], for t in [t_init, t_last]\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' with initial conditions:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' u(x,o) = u_init\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' and boundary conditions:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' u(a,t) = u_a(t), u(b,t) = u_b(t)\\n' );\n%\n% Set and report the problem parameters.\n%\n n = 41;\n a = -1.0;\n b = +1.0;\n dx = ( b - a ) / ( n - 1 );\n step_num = 80;\n t_init = 0.0;\n t_last = 1.0;\n dt = ( t_last - t_init ) / step_num;\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' %f <= X <= %f\\n', a, b );\n fprintf ( 1, ' Number of nodes = %d\\n', n );\n fprintf ( 1, ' DX = %f\\n', dx );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' %f <= t <= %f\\n', t_init, t_last );\n fprintf ( 1, ' Number of time steps = %d\\n', step_num );\n fprintf ( 1, ' DT = %f\\n', dt );\n\n x = r8vec_even ( n, a, b );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' X:\\n' );\n fprintf ( 1, '\\n' );\n for ilo = 1 : 5 : n\n ihi = min ( ilo + 4, n );\n for i = ilo : ihi\n fprintf ( 1, ' %16f', x(i,1) );\n end\n fprintf ( 1, '\\n' );\n end\n%\n% Set the initial condition,\n% and apply boundary conditions to first and last entries.\n%\n step = 0;\n t = t_init;\n un(1:n,1) = u_init ( n, x, t );\n un(1,1) = u_a ( x(1,1), t );\n un(n,1) = u_b ( x(n,1), t );\n\n stability = ( dt / dx ) * max ( abs ( un(1:n,1) ) );\n report ( step, step_num, n, x, t, un, stability );\n\n if ( 1 )\n plot ( x, un );\n title ( sprintf ( 'Step %d, Time %f', step, t ) );\n pause\n end\n%\n% March in time.\n%\n c1 = - ( 0.5 * dt / dx );\n c2 = - ( 0.5 * dt^2 / dx^2 );\n\n for step = 1 : step_num\n\n t = ( ( step_num - step ) * t_init ...\n + ( step ) * t_last ) ...\n / ( step_num );\n\n uo(1:n,1) = un(1:n,1);\n\n un(2:n-1,1) = uo(2:n-1,1) ...\n - ( dt / dx ) * ( uo(3:n,1).^2 - uo(1:n-2,1).^2 ) ...\n + 0.5 * ( dt^2 / dx^2 ) * ( 0.5 * ( uo(3:n,1) + uo(2:n-1,1) ) ...\n .* ( uo(3:n,1).^2 - uo(2:n-1,1).^2 ) ...\n - 0.5 * ( uo(2:n-1,1) + uo(1:n-2,1) ) ...\n .* ( uo(2:n-1,1).^2 - uo(1:n-2,1).^2 ) );\n\n un(1,1) = u_a ( x(1,1), t );\n un(n,1) = u_b ( x(n,1), t );\n\n stability = ( dt / dx ) * max ( abs ( un(1:n,1) ) );\n report ( step, step_num, n, x, t, un, stability );\n\n if ( 1 )\n plot ( x, un );\n title ( sprintf ( 'Step %d, Time %f', step, t ) );\n pause\n end\n\n end\n%\n% Terminate.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'FD1D_BURGERS_LAX:\\n' );\n fprintf ( 1, ' Normal end of execution.\\n' );\n\n fprintf ( 1, '\\n' );\n timestamp ( );\n\n return\nend\nfunction a = r8vec_even ( n, alo, ahi )\n\n%*****************************************************************************80\n%\n%% R8VEC_EVEN returns N real values, evenly spaced between ALO and AHI.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 24 January 2004\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of values.\n%\n% Input, real ALO, AHI, the low and high values.\n%\n% Output, real A(N), N evenly spaced values.\n% Normally, A(1) = ALO and A(N) = AHI.\n% However, if N = 1, then A(1) = 0.5*(ALO+AHI).\n%\n if ( n == 1 )\n\n a(1,1) = 0.5 * ( alo + ahi );\n\n else\n\n a(1:n,1) = ( (n-1:-1:0) * alo + (0:n-1) * ahi ) / ( n - 1 );\n\n end\n\n return\nend\nfunction report ( step, step_num, n, x, t, u, stability )\n\n%*****************************************************************************80\n%\n%% REPORT prints or plots or saves the data at the current time step.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 August 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer STEP, the index of the current step,\n% between 0 and STEP_NUM.\n%\n% Input, integer STEP_NUM, the number of steps to take.\n%\n% Input, integer N, the number of nodes.\n%\n% Input, real X(N), the coordinates of the nodes.\n%\n% Input, real T, the current time.\n%\n% Input, real U(N), the initial values U(X,T).\n%\n% Input, real STABILITY, the stability factor, which should be \n% no greater than 1.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' STEP = %d\\n', step );\n fprintf ( 1, ' TIME = %f\\n', t );\n fprintf ( 1, ' STABILTY = %f\\n', stability )\n fprintf ( 1, '\\n' );\n for ilo = 1 : 5 : n\n ihi = min ( ilo + 4, n );\n for i = ilo : ihi\n fprintf ( 1, ' %14g', u(i) );\n end\n fprintf ( 1, '\\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\nfunction ua = u_a ( x, t )\n\n%*****************************************************************************80\n%\n%% U_A sets the boundary condition for U at A.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 August 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, T, the position and time.\n%\n% Output, real UA, the prescribed value of U(X,T).\n%\n ua = + 0.5;\n\n return\nend\nfunction ub = u_b ( x, t )\n\n%*****************************************************************************80\n%\n%% U_B sets the boundary condition for U at B.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 August 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real X, T, the position and time.\n%\n% Output, real UB, the prescribed value of U(X,T).\n%\n ub = - 0.5;\n\n return\nend\nfunction u = u_init ( n, x, t )\n\n%*****************************************************************************80\n%\n%% U_INIT sets the initial condition for U.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 18 August 2010\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer N, the number of nodes.\n%\n% Input, real X(N), the coordinates of the nodes.\n%\n% Input, real T, the current time.\n%\n% Output, real U(N), the initial values U(X,T).\n%\n ua = u_a ( x(1,1), t );\n ub = u_b ( x(n,1), t );\n\n q = 2.0 * ( ua - ub ) / pi;\n r = ( ua + ub ) / 2.0;\n%\n% S can be varied. It is the slope of the initial condition at the midpoint.\n%\n s = 1.0;\n u(1:n,1) = ( 2 * x(1:n,1) - x(n,1) - x(1,1) ) ...\n / ( x(n,1) - x(1,1) );\n\n u(1:n,1) = - q * atan ( s * u(1:n,1) ) + 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/fd1d_burgers_lax/fd1d_burgers_lax.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.7011368127487688}} {"text": "function [Y, spectrum] = slgembed(G, Gc, d, fm, varargin)\n%SLGEMBED Solves the general graph-based embedding \n%\n% $ Syntax $\n% - Y = slgembed(G, Gc, d, fm, ...)\n% - [Y, spectrum] = slgembed(G, Gc, d, fm, ...)\n%\n% $ Arguments $\n% - G: The graph to be optimized\n% - Gc: The constraint graph\n% - d: The dimension of the embedding\n% - fm: The type of formulation\n% - Y: The embedding sample coordinates\n%\n% $ Description $\n% - Y = slgembed(G, Gc, d, fm, ...) solves the general graph-based \n% embedding of dimension d. In mathematics, it is to solve the\n% following optimization problem:\n% min/max y^T M y, s.t. y^T C y = I\n% Based on different fm, the formulations of M and C are different:\n% fm is a cell array of two char string elements:\n% fm = {fg, fc}\n% fg indicates the formulation of M, fc indicates the formulation of\n% the constraint matrix C.\n% fg has the following different values:\n% - 'minW': minimization using M = W, (W is the adjmat of G)\n% - 'maxW': maximization using M = W\n% - 'minL': minimization using M = L = D - W\n% - 'maxL': maximization using M = L = D - W\n% fc has the following different values:\n% - 'I': use C = I, that is y^T * y = I\n% - 'D': use C = D, that is y^T * D * y = I (based on G)\n% - 'WC': use C = W, adjacency matrix (based on Gc)\n% - 'LC': use C = L = D - W, (based on Gc)\n% For example, if you specify fm = {'maxW', 'D'}, then the function \n% will solve the following optimization problem:\n% maximize y^T W y, s.t. y^T * D * y = I\n% You can also specify the following properties:\n% - 'inv': The parameters do to eigenvalue inverse\n% {method, ...}\n% (refer to slinvevals for details)\n% This parameter take effects only when fc = 'WC\" or\n% fc = 'LC'.\n% - 'skip': How many eigen-components to skip. default = 0.\n% (In some algorithms, it is necessary to skip\n% the first or first several eigen-components).\n%\n% - [Y, spectrum] = slgembed(G, Gc, d, fm, ...) additionally return\n% the spectrum of the embedding, the eigenvalues of the whitened\n% C^(-1/2) M C^(-1/2).\n% \n% $ Remarks $\n% - The fc can be 'WC' or 'LC' only when Gc is full matrix, in current\n% version of implementation.\n%\n% $ History $\n% - Created by Dahua Lin, on Sep 12, 2006\n%\n\n%% parse and verify input arguments\n\nif nargin < 4\n raise_lackinput('slgembed', 4);\nend\n\ngi = slgraphinfo(G, {'square'});\nn = gi.n;\nW = sladjmat(G, 'valtype', 'numeric', 'sparse', issparse(G));\n\n[fg, fc] = deal(fm{:});\n\nWc = [];\nif strcmp(fc, 'WC') || strcmp(fc, 'LC')\n if ~isempty(Gc)\n if ~isnumeric(Gc) || issparse(Gc) || ~isequal(size(Gc), [n n])\n error('sltoolbox:invalidarg', ...\n 'In current implementation, Gc must be an n x n full numeric matrix for fc = WC or GC');\n end\n Wc = Gc;\n else\n error('sltoolbox:invalidarg', ...\n 'When fc is WC or LC, Wc should be specified');\n end\nend\n\nopts.inv = {};\nopts.skip = 0;\nopts = slparseprops(opts, varargin{:});\n\nif d + opts.skip > n\n error('sltoolbox:invalidarg', ...\n 'The embedding dimension d plus the skip dimension should not exceed n');\nend\n\n\n%% main skeleton\n\nW = W + W';\nif ~isempty(Wc)\n Wc = Wc + Wc';\nend\n\n% parse formulation and decide scheme\n\nswitch fg\n case 'minW'\n Mfunc = @make_Wmat;\n optype = 'max';\n case 'maxW'\n Mfunc = @make_Wmat;\n optype = 'max';\n case 'minL'\n Mfunc = @make_Lmat;\n optype = 'min';\n case 'maxL'\n Mfunc = @make_Lmat;\n optype = 'max';\n otherwise\n error('sltoolbox:invalidarg', 'Invalid fg type: %s', fg);\nend\n\nswitch fc\n case 'I'\n whfunc = [];\n case 'D'\n whfunc = @(M) whM_by_D(M, W);\n nyfunc = @(Y, T) nY_by_S(Y, T);\n case 'WC'\n whfunc = @(M) whM_by_W(M, Wc, opts.inv);\n nyfunc = @(Y, T) nY_by_T(Y, T);\n case 'LC'\n whfunc = @(M) whM_by_L(M, Wc, opts.inv);\n nyfunc = @(Y, T) nY_by_T(Y, T);\n otherwise\n error('sltoolbox:invalidarg', 'Invalid fc type: %s', fc);\nend\n\n\n% make M\nM = Mfunc(W);\n\n% whiten M\nif ~isempty(whfunc)\n MTcell = whfunc(M);\n M = MTcell{1};\n T = MTcell{2};\n clear MTcell;\nend\n\n% optimize to solve embedding\n[Y, spectrum] = optim_embed(M, optype, d, opts.skip);\n\n% normalize the embedding to satisfy the constraint\nif ~isempty(whfunc)\n Y = nyfunc(Y, T);\nend\nY = Y';\n \n\n%% Core routines\n\nfunction M = make_Wmat(W)\n\nM = W;\n\nfunction vD = make_Dvec(W)\n\nvD = sum(W, 1)';\nif issparse(vD)\n vD = full(vD);\nend\n\nfunction L = make_Lmat(W)\n\nvD = make_Dvec(W);\nn = size(W, 1);\nif issparse(W)\n D = sparse((1:n)', (1:n)', vD, n, n, n);\n L = D - W;\nelse\n L = -W;\n dinds = (1:n)'*(n+1)-n;\n L(dinds) = L(dinds) + vD;\nend\n\nfunction MTcell = whM_by_D(M, W)\n\nvD = make_Dvec(W);\nvD(vD < eps) = eps;\ncv = 1 ./ sqrt(vD);\n\nn = size(M, 1);\nif issparse(M) \n Mw = M;\n for i = 1 : n\n Mw(:,i) = Mw(:,i) * cv(i);\n end\n for i = 1 : n\n Mw(i,:) = Mw(i,:) * cv(i);\n end\nelse\n Mw = slmulrowcols(M, cv', cv);\nend\n\nMTcell = {Mw, cv};\n\n\nfunction MTcell = whM_by_W(M, W, invparams)\n\nT = slwhiten_from_cov(W, invparams{:});\nMw = T' * M * T;\nMTcell = {Mw, T};\n\n\nfunction MTcell = whM_by_L(M, W, invparams)\n\nL = make_Lmat(W);\nMTcell = whM_by_W(M, L, invparams);\n\n\nfunction [Y, spectrum] = optim_embed(M, optype, d, dskip)\n\nswitch optype\n case 'min'\n ord = 'ascend';\n case 'max'\n ord = 'descend';\nend\n\nd0 = d + dskip;\n[spectrum, Y] = slsymeig(M, d0, ord);\nif dskip > 0\n spectrum = spectrum(dskip+1:d0);\n Y = Y(:, dskip+1:d0);\nend\n\nfunction Y = nY_by_S(Y, T)\n\nY = slmulvec(Y, T, 1);\n\nfunction Y = nY_by_T(Y, T)\n\nY = T * Y;\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/manifold/slgembed.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.701082792074365}} {"text": "function b = isposdef(a)\n% ISPOSDEF Test for positive definite matrix.\n% ISPOSDEF(A) returns 1 if A is positive definite, 0 otherwise.\n% Using chol is much more efficient than computing eigenvectors.\n\n% Written by Tom Minka\n\n[R,p] = chol(a);\nb = (p == 0);\n", "meta": {"author": "andrewssobral", "repo": "lrslibrary", "sha": "06d457349cb5f1fc56a583cd61af9f1d5150e3a1", "save_path": "github-repos/MATLAB/andrewssobral-lrslibrary", "path": "github-repos/MATLAB/andrewssobral-lrslibrary/lrslibrary-06d457349cb5f1fc56a583cd61af9f1d5150e3a1/libs/+lightspeed/isposdef.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.7010827738691556}} {"text": "function illustrate_eq_algorithm(dim,N,varargin)\n%ILLUSTRATE_EQ_ALGORITHM Illustrate the EQ partition algorithm\n%\n%Syntax\n% illustrate_eq_algorithm(dim,N,options);\n%\n%Description\n% ILLUSTRATE_EQ_ALGORITHM(dim,N) illustrates the recursive zonal equal area\n% sphere partitioning algorithm, which partitions S^dim (the unit sphere in \n% dim+1 dimensional space) into N regions of equal area and small diameter.\n%\n% The illustration consists of four subplots:\n% 1. Steps 1 and 2\n% 2. Steps 3 to 5\n% 3. Steps 6 and 7\n% 4. Lower dimensional partitions (if dim == 2 or dim == 3)\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'offset','extra') uses experimental extra\n% offsets for S^2 and S^3. If dim > 3, extra offsets are not used.\n% For more detail on partition options, see HELP PARTITION_OPTIONS.\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,options) also recognizes a number of\n% illustration options, which are specified as name, value pairs.\n% Any number of pairs can be used, in any order.\n%\n% The following illustration options are used.\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'fontsize',size)\n% Font size used in titles (numeric, default 16).\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'title','long')\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'title','short')\n% Use long or short titles (default 'short').\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'proj','stereo')\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'proj','eqarea')\n% Use stereographic or equal area projection (default 'stereo').\n%\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'points','show')\n% ILLUSTRATE_EQ_ALGORITHM(dim,N,'points','hide')\n% Show or hide center points (default 'show').\n%\n% See examples below.\n% For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS.\n%\n%Notes\n% The step numbers refer to the following steps of the the recursive zonal\n% equal area sphere partitioning algorithm, which partition the sphere into \n% zones.\n%\n% 1. Determine the colatitudes of the North and South polar caps.\n% 2. Determine an ideal collar angle.\n% 3. Use the angle between the North and South polar caps and the ideal collar\n% angle to determine an ideal number of collars.\n% 4. Use a rounding procedure to determine the actual number of collars,\n% given the ideal number of collars.\n% 5. Create a list containing the ideal number of regions in each collar.\n% 6. Use a rounding procedure to create a list containing the actual number of\n% regions in each collar, given the list containing the ideal number of\n% regions.\n% 7. Create a list containing the colatitude of the top of each zone,\n% given the list containing the actual number of regions in each collar,\n% and the colatitudes of the polar caps.\n%\n%Examples\n% > illustrate_eq_algorithm(3,99)\n% > illustrate_eq_algorithm(3,99,'offset','extra','proj','eqarea')\n% > illustrate_eq_algorithm(3,99,'proj','eqarea','points','hide')\n%\n%See also\n% PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, SUBPLOT\n\n% Copyright 2004-2005 Paul Leopardi for the University of New South Wales.\n% $Revision 1.10 $ $Date 2005-06-01 $\n% Documentation files renamed\n% $Revision 1.00 $ $Date 2005-02-13 $\n%\n% For licensing, see COPYING.\n% For references, see AUTHORS.\n% For revision history, see CHANGELOG.\n\npdefault.extra_offset = false;\n\npopt = partition_options(pdefault, varargin{:});\n\ngdefault.fontsize = 16;\ngdefault.show_title = true;\ngdefault.long_title = false;\ngdefault.stereo = false;\ngdefault.show_points = true;\n\ngopt = illustration_options(gdefault, varargin{:});\nopt_args = option_arguments(popt,gopt);\n\nsubplot(2,2,1);axis off\nillustrate_steps_1_2(dim,N,opt_args);\n\nsubplot(2,2,2);axis off\nillustrate_steps_3_5(dim,N,opt_args);\n\nsubplot(2,2,3);axis off\nillustrate_steps_6_7(dim,N,opt_args);\n\nsubplot(2,2,4);axis off\ncla\n\ngopt.fontsize = 32;\nswitch dim\ncase 2\n opt_args = option_arguments(popt,gopt);\n project_s2_partition(N,opt_args{:});\ncase 3\n opt_args = option_arguments(popt,gopt);\n [s,m] = eq_caps(dim,N);\n max_collar = min(4,size(m,2)-2);\n for k = 1:max_collar\n subn = 9+2*k-mod(k-1,2);\n subplot(4,4,subn);axis off\n project_s2_partition(m(1+k),opt_args{:});\n end\nend\n%\n% end function\n\nfunction illustrate_steps_1_2(dim,N,varargin)\n% Illustrate steps 1 and 2 of the EQ partition of S^dim into N regions;\n%\n% illustrate_steps_1_2(dim,N,options);\n\ngdefault.fontsize = 14;\ngdefault.show_title = true;\ngdefault.long_title = false;\n\ngopt = illustration_options(gdefault, varargin{:});\nh = [0:1/90:1];\n% Plot a circle to represent dth coordinate of S^d\nPhi = h*2*pi;\nplot(sin(Phi),cos(Phi),'k','LineWidth',1)\naxis equal;axis off;hold on\n\nc_polar = polar_colat(dim,N);\n\nk = [-1:1/20:1];\nj = ones(size(k));\n\n% Plot the bounding parallels of the polar caps\nplot(sin(c_polar)*k, cos(c_polar)*j,'r','LineWidth',2)\nplot(sin(c_polar)*k,-cos(c_polar)*j,'r','LineWidth',2)\n\n% Plot the North-South axis\nplot(zeros(size(j)),k,'b','LineWidth',1)\n% Plot the polar angle\nplot(sin(c_polar)*h,cos(c_polar)*h,'b','LineWidth',2)\n\ntext(0.05,2/3,'\\theta_c','Fontsize',gopt.fontsize);\n\n% Plot the ideal collar angle\nDelta_I = ideal_collar_angle(dim,N);\ntheta = c_polar + Delta_I;\nplot(sin(theta)*h,cos(theta)*h,'b','LineWidth',2)\n\nmid = c_polar + Delta_I/2;\ntext(sin(mid)*2/3,cos(mid)*2/3,'\\Delta_I','Fontsize',gopt.fontsize);\n\n% Plot an arc to indicate angles\ntheta = h*(c_polar + Delta_I);\nplot(sin(theta)/5,cos(theta)/5,'b','LineWidth',1)\n\ntext(-0.9,-0.1,sprintf('V(\\\\theta_c) = V_R \\n = \\\\sigma(S^{%d})/%d',dim,N),...\n 'Fontsize',gopt.fontsize);\n\ncaption_angle = min(mid + 2*Delta_I,pi-c_polar);\ntext(sin(caption_angle)/3,cos(caption_angle)/3,sprintf('\\\\Delta_I = V_R^{1/%d}',dim),...\n 'Fontsize',gopt.fontsize);\n\nif gopt.show_title\n title_str = sprintf('EQ(%d,%d) Steps 1 to 2\\n',dim,N);\n title(title_str,'Fontsize',gopt.fontsize);\nend\n\nhold off\n%\n% end function\n\nfunction illustrate_steps_3_5(dim,N,varargin)\n% Illustrate steps 3 to 5 of the EQ partition of S^dim into N regions;\n%\n% illustrate_steps_3_5(dim,N,options);\n\ngdefault.fontsize = 14;\ngdefault.show_title = true;\ngdefault.long_title = false;\n\ngopt = illustration_options(gdefault, varargin{:});\n\nh = [0:1/90:1];\nPhi = h*2*pi;\nplot(sin(Phi),cos(Phi),'k','LineWidth',1)\naxis equal;axis off;hold on\n\nc_polar = polar_colat(dim,N);\nn_collars = num_collars(N,c_polar,ideal_collar_angle(dim,N));\nr_regions = ideal_region_list(dim,N,c_polar,n_collars);\ns_cap = cap_colats(dim,N,c_polar,r_regions);\n\nk = [-1:1/20:1];\nj = ones(size(k));\nplot(sin(c_polar)*k, cos(c_polar)*j,'r','LineWidth',2);\n\nplot(zeros(size(j)),k,'b','LineWidth',1)\n\nfor collar_n = 0:n_collars\n zone_n = 1+collar_n;\n theta = s_cap(zone_n);\n plot(sin(theta)*h,cos(theta)*h,'b','LineWidth',2);\n theta_str = sprintf('\\\\theta_{F,%d}',zone_n);\n text(sin(theta)*1.1,cos(theta)*1.1,theta_str,'Fontsize',gopt.fontsize);\n if collar_n ~= 0\n plot(sin(theta)*k, cos(theta)*j,'r','LineWidth',2);\n theta_p = s_cap(collar_n);\n arc = theta_p + (theta-theta_p)*h;\n plot(sin(arc)/5,cos(arc)/5,'b','LineWidth',1);\n mid = (theta_p + theta)/2;\n text(sin(mid)/2,cos(mid)/2,'\\Delta_F','Fontsize',gopt.fontsize);\n y_str = sprintf('y_{%d} = %3.1f...',collar_n,r_regions(zone_n));\n text(-sin(mid)+1/20,cos(mid)+(mid-pi)/30,y_str,'Fontsize',gopt.fontsize);\n end\nend\nif gopt.show_title\n title_str = sprintf('EQ(%d,%d) Steps 3 to 5\\n',dim,N);\n title(title_str,'Fontsize',gopt.fontsize);\nend\nhold off\n%\n% end function\n\nfunction illustrate_steps_6_7(dim,N,varargin)\n% Illustrate steps 6 to 7 of the EQ partition of S^dim into N regions;\n%\n% illustrate_steps_6_7(dim,N,options);\n\ngdefault.fontsize = 14;\ngdefault.show_title = true;\ngdefault.long_title = false;\n\ngopt = illustration_options(gdefault, varargin{:});\n\nh = [0:1/90:1];\nPhi = h*2*pi;\nplot(sin(Phi),cos(Phi),'k','LineWidth',1)\naxis equal;axis off;hold on\n\nc_polar = polar_colat(dim,N);\nn_collars = num_collars(N,c_polar,ideal_collar_angle(dim,N));\nr_regions = ideal_region_list(dim,N,c_polar,n_collars);\nn_regions = round_to_naturals(N,r_regions);\ns_cap = cap_colats(dim,N,c_polar,n_regions);\n\nk = [-1:1/20:1];\nj = ones(size(k));\nplot(sin(c_polar)*k, cos(c_polar)*j,'r','LineWidth',2);\n\nplot(zeros(size(j)),k,'b','LineWidth',1)\n\nfor collar_n = 0:n_collars\n zone_n = 1+collar_n;\n theta = s_cap(zone_n);\n plot(sin(theta)*h,cos(theta)*h,'b','LineWidth',2);\n theta_str = sprintf('\\\\theta_{%d}',zone_n);\n text(sin(theta)*1.1,cos(theta)*1.1,theta_str,'Fontsize',gopt.fontsize);\n if collar_n ~= 0\n plot(sin(theta)*k, cos(theta)*j,'r','LineWidth',2);\n theta_p = s_cap(collar_n);\n arc = theta_p + (theta-theta_p)*h;\n plot(sin(arc)/5,cos(arc)/5,'b','LineWidth',1);\n mid = (theta_p + theta)/2;\n Delta_str = sprintf('\\\\Delta_{%i}',collar_n);\n text(sin(mid)/2,cos(mid)/2,Delta_str,'Fontsize',gopt.fontsize);\n m_str = sprintf('m_{%d} =%3.0f',collar_n,n_regions(zone_n));\n text(-sin(mid)+1/20,cos(mid)+(mid-pi)/30,m_str,'Fontsize',gopt.fontsize);\n end\nend\nif gopt.show_title\n title_str = sprintf('EQ(%d,%d) Steps 6 to 7\\n',dim,N);\n title(title_str,'Fontsize',gopt.fontsize);\nend\nhold off\n%\n% end function\n\nfunction arg = option_arguments(popt,gopt)\n\nk = 1;\nif isfield(popt,'extra_offset')\n arg{k} = 'offset';\n if popt.extra_offset\n arg{k+1} = 'extra';\n else\n arg{k+1} = 'normal';\n end\n k = k+2;\nend\n\nif isfield(gopt,'fontsize')\n arg{k} = 'fontsize';\n arg{k+1} = gopt.fontsize;\n k = k+2;\nend\n\nif isfield(gopt,'stereo')\n arg{k} = 'proj';\n if gopt.stereo\n arg{k+1} = 'stereo';\n else\n arg{k+1} = 'eqarea';\n end\n k = k+2;\nend \n\nif isfield(gopt,'show_title')\n arg{k} = 'title';\n if gopt.show_title\n if isfield(gopt,'long_title')\n if gopt.long_title\n arg{k+1} = 'long';\n else\n arg{k+1} = 'short';\n end\n else\n arg{k+1} = 'show';\n end\n else\n arg{k+1} = 'none';\n end\n k = k+2;\nelseif isfield(gopt,'long_title')\n arg{k} = 'title';\n if gopt.long_title\n arg{k+1} = 'long';\n else\n arg{k+1} = 'short';\n end\n k = k+2;\nend\n\n\nif isfield(gopt,'show_points')\n arg{k} = 'points';\n if gopt.show_points\n arg{k+1} = 'show';\n else\n arg{k+1} = 'hide';\n end\n k = k+2;\nend\n\nif isfield(gopt,'show_surfaces')\n arg{k} = 'surf';\n if gopt.show_surfaces\n arg{k+1} = 'show';\n else\n arg{k+1} = 'hide';\n end\n k = k+2;\nend \n\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/eq_sphere_partitions/eq_partitions/illustrate_eq_algorithm.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.701024944110419}} {"text": "%% Kernel Average Misorientation (KAM)\n%\n%%\n% The kernel average misorientation (KAM) is a measure of local grain\n% misorientation that is usually derived from EBSD data. For formaly\n% defining the KAM we denote by $o_{i,j}$ the orientations at pixel\n% position $(i,j)$ and by $N(i,j)$ the set of all neighboring pixels. Then\n% the kernel average misorientation $\\mathrm{kam}_{i,j}$ at pixel position\n% $(i,j)$ is defined as\n% \n% $$\\mathrm{KAM}_{i,j} = \\frac{1}{|N(i,j)|}\\sum_{(k,l) \\in N(i,j)} \\omega(o_{i,j}, o_{k,l}) $$\n% \n% Here $\\lvert N(i,j) \\rvert$ denotes the number of all neighboring pixels\n% taking into account and $\\omega(o_{i,j}, o_{k,l})$ the disorientation\n% angle between the orientation $o_{ij}$ in the center and the neighbouring\n% orientation $(o_{k,l})$. The specific choice of the set $N(i,j)$ of\n% neighboring pixels is crucial for the compution of the KAM. Most commonly\n% the following additional constrains are made\n%\n% * consider neighbors up to order $n$, e.g. $n=1,2,3,\\ldots$\n% * consider only neighbors belonging to the same grain\n% * consider only neighbors with a misorientation angle smaller than a\n% threshold angle $\\delta$\n% \n% In the case of sqaure and hexagonal grids the order of neighbors is\n% illustrated below\n\nplotSquareNeighbours; nextAxis; plotHexNeighbours\n\n%% A Deformed Ferrite Specimen\n%\n% Let us demonstrate the computation of the KAM at the example of a\n% deformed Ferrite specimen. Lets import the data first and reconstruct the\n% grain structure\n\nmtexdata ferrite\n\n[grains,ebsd.grainId] = calcGrains(ebsd('indexed'));\n% remove one-three pixel grains\nebsd(grains(grains.grainSize <= 3)) = [];\n[grains,ebsd.grainId] = calcGrains(ebsd('indexed'));\n\ngrains = smooth(grains,5);\n\nplot(ebsd('indexed'),ebsd('indexed').orientations)\nhold on\nplot(grains.boundary,'lineWidth',1.5)\nhold off\n\n%%\n% Although MTEX allows the computation of the KAM from arbitrarily sampled\n% EBSD maps the algorithms are much faster an memory efficient if the maps\n% are measured on regular hexagonal or rectangular grid - as it is standard\n% in most applications. The command makes\n% MTEX aware of such an underlying regular measurement grid.\n\nebsd = ebsd.gridify;\n\n%%\n%\n% The kernel average misorientation is computed by the command\n% . As all MTEX commands it return the mean\n% disorientation angle in radiant. Hence, dividing by the constant |degree|\n% gives the result in degree.\n\nkam = ebsd.KAM / degree;\n\n% lets plot it\nplot(ebsd,kam,'micronbar','off')\ncaxis([0,15])\nmtexColorbar\nmtexColorMap LaboTeX\nhold on\nplot(grains.boundary,'lineWidth',1.5)\nhold off\n\n%%\n% When computed with default parameters in MTEX neighbors up to order 1 are\n% considered and no threshold angle $\\delta$ is applied. If grains have\n% been reconstructed and the property |ebsd.grainId| has been set (as we\n% did above) only misorientations within the same grain are considered. As\n% a consequence the resulting KAM map is dominated by the orientation\n% gradients at the subgrain boundaries.\n%\n% Specifying a reasonable small theshold angle $\\delta=2.5^{\\circ}$ the\n% subgrain boundaries can be effectively removed from the KAM.\n\nplot(ebsd,ebsd.KAM('threshold',2.5*degree) ./ degree,'micronbar','off')\ncaxis([0,2])\nmtexColorbar\nmtexColorMap LaboTeX\nhold on\nplot(grains.boundary,'lineWidth',1.5)\nhold off\n\n%%\n% Unfortunately, the remaining KAM becomes very sensitve to measurement\n% errors and is often very noisy. The noise can be reduced by considering\n% heigher order neighbors\n\nplot(ebsd,ebsd.KAM('threshold',2.5*degree,'order',5) ./ degree,'micronbar','off')\ncaxis([0,2])\nmtexColorbar\nmtexColorMap LaboTeX\nhold on\nplot(grains.boundary,'lineWidth',1.5)\nhold off\n\n%% \n% Although this reduced noise it also smoothes away local dislocation\n% structures. A much more effective way to reduce the effect of measurement\n% errors to the kernel average misorientation is to denoise the EBSD map\n% first and compute than the KAM from the first order neighbors. \n\n% chose a denoising filter\nF = halfQuadraticFilter;\nF.alpha = 0.5;\n\n% denoise the orientation map\nebsdS = smooth(ebsd,F,'fill',grains);\n\n% plot the first order KAM\nplot(ebsdS,ebsdS.KAM('threshold',2.5*degree) ./ degree,'micronbar','off')\ncaxis([0,2])\nmtexColorbar\nmtexColorMap LaboTeX\nhold on\nplot(grains.boundary,'lineWidth',1.5)\nhold off\n\n%%\n% We observe that the KAM is not longer related to subgrain boundaries and\n% nicely revalves local dislocation structures of the deformed material.\n%\n%% Some helper functions\n%\n% The functions below where only used to generate the neighborhood pictures\n% of the first paragraph\n\nfunction plotSquareNeighbours\n\nN = [4 3 2 3 4;...\n 3 2 1 2 3;...\n 2 1 0 1 2;...\n 3 2 1 2 3;...\n 4 3 2 3 4];\n\ncs = crystalSymmetry;\nebsd = EBSDsquare(rotation.nan(5,5),N,0:4,{cs,cs,cs,cs,cs},[10 10]);\nplot(ebsd,'EdgeColor','black','micronbar','off','figSize','small')\nlegend off\n\ntext(ebsd,N)\n\nend\n\nfunction plotHexNeighbours\n\nN = [3 2 2 2 3;...\n 2 1 1 2 3;...\n 2 1 0 1 2;...\n 2 1 1 2 3;...\n 3 2 2 2 3;...\n 3 3 3 3 4];\n\ncs = crystalSymmetry;\nebsd = EBSDhex(rotation.nan(6,5),N,0:4,{cs,cs,cs,cs,cs},10,1,1);\nplot(ebsd,'edgecolor','k','micronbar','off','figSize','small')\nlegend off\ntext(ebsd,N)\naxis off\n\nend\n\n\n\n", "meta": {"author": "mtex-toolbox", "repo": "mtex", "sha": "f0ce46a720935e9ae8106ef919340534bca1adcb", "save_path": "github-repos/MATLAB/mtex-toolbox-mtex", "path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/doc/EBSDAnalysis/EBSDKAM.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.700825825122523}} {"text": "function [idx, theta, rho] = PolarCoordinatesGrid(y, r, nDivs)\n% PolarCoordinatesGrid - Calculate index of grid cell and \n% polar coordinates for a given objective vector\n%\n% [idx, theta, rho] = PolarCoordinatesGrid(y, r, nDivs)\n%\n% Input:\n% y - individual's objectives\n% r - reference point\n% nDivs - number of divisions in each right angle\n%\n% Output:\n% idx - index of grid cell where individual resides\n% theta - polar angles\n% rho - radius\n\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% This function is written by Roman Denysiuk\n\n%% calculate polar coordinates\n\n% determine dimensionality\nm = numel(r);\n\n% calculate radius\nrho = norm(y-r);\n\n% calculate angles\ntheta = zeros(m-1,1);\n\nfor i = 0:m-2\n \n u = (y(m-i) - r(m-i))/rho;\n \n for j = 0:i-1\n u = u/cos(theta(j+1));\n end\n \n u = min( max(u, -1), 1); % ensure feasibility\n \n theta(i+1) = asin(u);\n \n theta(i+1) = min( max(theta(i+1), eps), pi/2-eps);\nend\n\n%% calculate grid index based on polar coordinates\n\n% calculate grid coordinates (integer values)\nG = ceil(2*nDivs*theta/pi);\n\n% calculate index of pop member using grid coordinates\n% formula: idx=G(1)*ndiv^0+(G(2)-1)*ndiv^1+(G(3)-1)*ndiv^2 ...\n\nidx = G(1);\nfor i = 2:numel(G)\n idx = idx + (G(i)-1)*power(nDivs, i-1);\nend\n\nend", "meta": {"author": "BIMK", "repo": "PlatEMO", "sha": "c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5", "save_path": "github-repos/MATLAB/BIMK-PlatEMO", "path": "github-repos/MATLAB/BIMK-PlatEMO/PlatEMO-c5b5b7c37a9bb42689a5ac2a0d638d9c4f5693d5/PlatEMO/Algorithms/Multi-objective optimization/MOEA-PC/PolarCoordinatesGrid.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940925, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.7008133395636837}} {"text": "function sparse_grid_monomial_test ( rule, dim_num, level_max, degree_max )\n\n%*****************************************************************************80\n%\n%% SPARSE_GRID_MONOMIAL_TEST tests monomial exactness of the sparse grid rules.\n%\n% Discussion:\n%\n% This test is going to check EVERY monomial of total degree DEGREE_MAX\n% or less. Even for a moderately high dimension of DIM_NUM = 10, you\n% do NOT want to use a large value of DEGREE_MAX, since there are\n%\n% 1 monomials of total degree 0,\n% DIM_NUM monomials of total degree 1,\n% DIM_NUM^2 monomials of total degree 2,\n% DIM_NUM^3 monomials of total degree 3, and so on.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 July 2008\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, integer RULE, the index of the rule.\n% 1, \"CC\", Clenshaw Curtis Closed Fully Nested rule.\n% 2, \"F1\", Fejer 1 Open Fully Nested rule.\n% 3, \"F2\", Fejer 2 Open Fully Nested rule.\n% 4, \"GP\", Gauss Patterson Open Fully Nested rule.\n% 5, \"GL\", Gauss Legendre Open Weakly Nested rule.\n% 6, \"GH\", Gauss Hermite Open Weakly Nested rule.\n% 7, \"LG\", Gauss Laguerre Open Non Nested rule.\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Input, integer LEVEL_MAX, the level.\n%\n% Input, integer DEGREE_MAX, the maximum monomial total\n% degree to check.\n%\n level_min = max ( 0, level_max + 1 - dim_num );\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'SPARSE_GRID_MONOMIAL_TEST\\n' );\n fprintf ( 1, ' Check the exactness of a sparse grid quadrature rule,\\n' );\n fprintf ( 1, ' applied to all monomials of orders 0 to DEGREE_MAX.\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' For cases where the dimension is greater than 1,\\n' );\n fprintf ( 1, ' many sparse grid of this level have accuracy through\\n' );\n fprintf ( 1, ' monomials of total degree %d\\n', 2 * level_max + 1 );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Spatial dimension DIM_NUM = %d\\n', dim_num );\n fprintf ( 1, ' LEVEL_MIN = %d\\n', level_min );\n fprintf ( 1, ' LEVEL_MAX = %d\\n', level_max );\n fprintf ( 1, ' 1D quadrature index RULE = %d\\n', rule );\n fprintf ( 1, ' Check up to DEGREE_MAX = %d\\n', degree_max );\n%\n% Determine the number of points in the rule.\n%\n point_num = levels_index_size ( dim_num, level_max, rule );\n\n fprintf ( 1, ' Unique points in the grid = %d\\n', point_num );\n%\n% Compute the weights and points.\n%\n [ grid_weight, grid_point ] = sparse_grid ( dim_num, level_max, rule, ...\n point_num );\n%\n% Compare exact and estimated values of the integrals of various monomials.\n%\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Error Total Monomial\\n' );\n fprintf ( 1, ' Degree Exponents\\n' );\n fprintf ( 1, '\\n' );\n\n for degree = 0 : degree_max\n\n expon = [];\n more = 0;\n h = 0;\n t = 0;\n\n while ( 1 )\n\n [ expon, more, h, t ] = comp_next ( degree, dim_num, expon, more, h, t );\n\n quad_error = monomial_quadrature ( dim_num, expon, point_num, ...\n grid_weight, grid_point, rule );\n\n fprintf ( 1, ' %14e %2d ', quad_error, degree );\n for dim = 1 : dim_num\n fprintf ( 1, '%2d', expon(dim) );\n end\n fprintf ( 1, '\\n' );\n\n if ( ~more )\n break\n end\n\n end\n\n if ( 1 < dim_num )\n fprintf ( 1, '\\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/sandia_sparse/sparse_grid_monomial_test.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.700770302567266}} {"text": "% The OxyGEN proyect by Profoty.xyz\n% Together against the Covid-19\n% V4.0 rev.17/03/2020\n% \n% Website/blog: oxygen.protofy.xyz\n% Contact: oxygen@protofy.xyz\n\n\n%GEOMETRICAL PARAMETERS\n\n%Length from the bearing to the hinge\nl0 = 27.3;\n\n%Length of the vertical wall that supports the hinge\nh0 = 6.5;\n\n%Lenght of the vertical support of the bearing\nhb = 5.0;\n\n%Bearing radius\nbr = 1.1;\n\n%Array of different max and min positions of the bearing\nh1a = [6.5, 8.5, 10.5, 12.5];\nh2a = [20.5, 20.5, 20.5, 20.5];\n\n%Number of cycles per cam turn (1 to 3).\nnc = 1;\n\n%Minimum radius of the camshaft\nrmin = 5;\n\n\n%BREATHING CYCLE PARAMETERS\n\n%Duration of the inhale cycle / duration of the whole cycle\nlambda1 = 0.500;\nlambda2 = 0.060;\n\n%Soft transition between inhale and exhale cycles\ndpsi21 = 0.12;\ndpsi12 = 0.15;\n\n%Adjust parameters of the inhale curve\nga1 = pi;\ngb1 = 1.2;\nff1 = 20;\nsp1 = 1;\n\n%Adjust parametes of the exhale curve\nga2 = 9;\ngb2 = .5;\nff2 = 20;\n\n\n%GENERATION OF THE CURVES AND THE CAMSHAFT\n\n%Generation of the geometry\n\nl = sqrt(l0^2+hb^2);\n\n\nfor i = 1:numel(h1a);\n \n ymin(i) = h1a(i);\n ymax(i) = h2a(i);\n \n alphamin(i) = acos((h0 - h1a(i)) / l);\n alphamax(i) = acos((h0 - h2a(i)) / l);\n \n xmin(i) = l*sin(alphamin(i)); \n xmax(i) = l*sin(alphamax(i));\n \n d(i) = sqrt((xmin(i)-xmax(i))^2 + (ymin(i)-ymax(i))^2);\n \n alphatan(i) = (alphamin(i) + alphamax(i)) / 2;\n \n xtan(i) = l*sin(alphatan(i)); \n ytan(i) = h0 - l*cos(alphatan(i));\n \n xsup(i) = xtan(i) + (d(i)/2)*cos(alphatan(i));\n xinf(i) = xtan(i) - (d(i)/2)*cos(alphatan(i));\n \n ysup(i) = ytan(i) + (d(i)/2)*sin(alphatan(i));\n yinf(i) = ytan(i) - (d(i)/2)*sin(alphatan(i));\n \n xcam(i) = xtan(i) + (d(i)/2 + rmin + br)*cos(alphatan(i));\n ycam(i) = ytan(i) + (d(i)/2 + rmin + br)*sin(alphatan(i));\n \nend;\n\n\n%Time increment\ndt = 0.01;\n\n%time coordinate during the whole cycle\ntheta = 0:dt:2*pi;\n\n%Generation of the soft transition between inhale and exhale curves\npsi1 = [];\npsi2 = [];\n\nfor i = 1:numel(theta);\n \n if theta(i) < (lambda2-dpsi21/2)*2*pi;\n psi1(i) = 0;\n \n elseif theta(i) < (lambda2+dpsi21/2)*2*pi;\n psi1(i) = 0.5 + 0.5*cos((theta(i)-(lambda2+dpsi21/2)*2*pi)/(2*dpsi21));\n \n else theta(i) < (lambda1-dpsi12/2)*2*pi;\n psi1(i) = 1;\n \n end;\n \n psi2(i) = 1 - psi1(i);\n \nend; \n\n\n%Generation of the complete breathing cycle rho(theta)\n\nrho = [];\nrho1 = [];\nrho2 = [];\nrho2next = [];\n\nrhomin = 1000;\nrhomax = 0;\n\nfor i = 1:numel(theta);\n \n %Inhale curve\n rho1(i) = ff1*normpdf(sp1*theta(i), ga1, gb1);\n rho1next(i) = ff1*normpdf(sp1*theta(i)+sp1*2*pi, ga1, gb1);\n \n %Exhale curve\n rho2(i) = ff2*gampdf(theta(i), ga2, gb2);\n rho2next(i) = ff2*gampdf(theta(i)+2*pi, ga2, gb2);\n \n \n rho(i) = rho1(i);\n \n \n %Capturing min and max in order to generate the normalized curve\n if rho(i) > rhomax\n rhomax = rho(i);\n end;\n \n if rho(i) < rhomin\n rhomin = rho(i);\n end;\n\nend;\n\n\n%Generation of a normalised curve and camshaft\n\nrhonorm = [];\nrhocam = [];\n\nfor i = 1:numel(theta);\n \n rhonorm(i) = (rho(i)-rhomin)/(rhomax-rhomin);\n \n for n = 1:numel(d)\n \n rhocam(n,i) = rmin + rhonorm(i)*d(n);\n \n end;\n \nend;\n\n\n%Generation of the first derivate of the camshaft geometry to analize and\n%validate the design\n\ndrho = [];\ndrhonorm = [];\ndrhocam = [];\n\na = rmin;\nb = 1/dt;\n\nfor i = 1 : numel(rho)-1;\n \n drho(i) = b*(rho(i+1)-rho(i));\n drhonorm(i) = b*(rhonorm(i+1)-rhonorm(i));\n drhocam(i) = b*(rhocam(i+1)-rhocam(i)) + a;\n \nend;\n\ndrho(numel(rho)) = b*(rho(1)-rho(numel(rho)));\ndrhonorm(numel(rhonorm)) = b*(rhonorm(1)-rhonorm(numel(rhonorm)));\ndrhocam(numel(rhocam)) = b*(rhocam(1)-rhocam(numel(rhocam))) + a;\n\n\n%X and Y coordinates during two cycles (for 2-cycle camshaft plot)\n\ntheta2 = [theta/2, (2*pi+theta)/2];\n\nrhocam2 = [rhocam, rhocam];\ndrhocam2 = [drho, drho];\n\n\n%X and Y coordinates during three cycles (for 3-cycle camshaft plot)\n\ntheta3 = [theta/3, (2*pi+theta)/3, (4*pi+theta)/3];\n\nrhocam3 = [rhocam, rhocam, rhocam];\ndrhocam3 = [drho, drho, drho];\n\n\n\n%GENERATION OF THE PLOTS\n\n%Trying to print it out in real size (FAIL)\n%set(gcf,'PaperUnits','centimeters'); \n%set(gcf,'PaperSize',[42 29.7]);\n\n\nfpos = figure('Name', 'Dimensions', 'Units', 'centimeters', 'NumberTitle', 'off');\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 28, 20]);\nfpos = gcf;\nhold on\n\nxlim([-5 35]);\nylim([0 30]);\n\nfor i = 1:numel(xmin)\n \n plot([0, xmin(i)], [h0, ymin(i)], '-x') \n plot([0, xmax(i)], [h0, ymax(i)], '-x')\n \n plot([0, xtan(i)], [h0, ytan(i)], '--xb')\n \n plot([xsup(i), xinf(i)], [ysup(i), yinf(i)], '--xr')\n scatter(xcam(1), ycam(1))\n\nend;\n\nhold off\n\n\n\n\n%Plot of the breathing cycle interpolation by curves\n\nfcycle = figure('Name', 'Breath Cycle curves', 'Units', 'centimeters', 'NumberTitle', 'off');\n\nhold on\nplot(theta, psi1, '-k')\nplot(theta, psi2, '-k')\nplot(theta, rho1, '-g')\nplot(theta, rho1next, '-g')\nplot(theta, rho2, '-g')\nplot(theta, rho2next, '-g')\n%plot(theta, drho, '-r')\nplot(theta, rho, '-b')\nhold off\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of the normalized breathing cycle and first derivate\n\n\nfnorm = figure('Name', 'Normalized Breath Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n\nhold on\n%plot(theta, drhonorm, '-r')\nplot(theta, rhonorm, '-b')\nhold off\n\nset(gcf,'PaperUnits','centimeters', 'PaperSize', [42/2 27.9/2]);\nset(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\nfcam3 = gcf;\n\n\n%Plot of a 1-cycle camshaft\n\nfor n = 1:numel(d)\n\n fcam1 = figure('Name', '1-Cycle Camshaft', 'Units', 'centimeters', 'NumberTitle', 'off');\n %hold on\n \n %polarplot(theta, drhocam, '-r')\n polar(theta, rhocam(n,:), '-b')\n\n \n %rlim([0 25]);\n hold off\n\n set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n fcam3 = gcf;\n \nend\n\n\n% %Plot of a 2-cycle camshaft\n% \n% fcam2 = figure('Name', '2-Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n% \n% %hold on;\n% %polar(theta, drhocam2, '-r')\n% polar(theta2, rhocam2, '-b')\n% %hold off;\n% \n% set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n% set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n% fcam3 = gcf;\n% \n% \n% %Plot of a 3-cycle camshaft\n% \n% fcam3 = figure('Name', '3-Cycle', 'Units', 'centimeters', 'NumberTitle', 'off');\n% \n% %hold on;\n% %polar(theta,drhocam3)\n% polar(theta3, rhocam3)\n% %hold off;\n% \n% set(gcf,'PaperUnits','centimeters', 'PaperSize', [42 27.9]);\n% set(gcf, 'units', 'centimeters', 'position', [0, 0, 27.9, 27.9]);\n% fcam3 = gcf;\n\n% The OxyGEN proyect by Profoty.xyz\n% Together against the Covid-19\n% V4.0 rev.17/03/2020\n% \n% Website/blog: oxygen.protofy.xyz\n% Contact: oxygen@protofy.xyz", "meta": {"author": "ProtofyTeam", "repo": "OxyGEN", "sha": "8a2870695e01928c07af2cc73ed86e5e53d8f726", "save_path": "github-repos/MATLAB/ProtofyTeam-OxyGEN", "path": "github-repos/MATLAB/ProtofyTeam-OxyGEN/OxyGEN-8a2870695e01928c07af2cc73ed86e5e53d8f726/Matlab Files/V6/Respirador_V6_1_1.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.7007702995995778}} {"text": "\n\n% Demonstrate posthoc model comparison for spm_mlm_bayes\n\nclear all\nclose all\n\nN=100;\nd=10;\np=5;\n\n\nx=randn(N,p);\nW=randn(p,d);\nW(4:5,:)=0;\ne=2*randn(N,d);\n\ny=x*W+e;\nverbose=1;\n\n% Input-specific shrinkage \nmlm = spm_mlm_bayes (y,x,'input',verbose);\n\nfigure\nimagesc(mlm.wmean);\ncolormap gray\ncolorbar\nylabel('Inputs');\nxlabel('Outputs');\ntitle('Bayes Regression Coefficients');\n\nfigure\nimagesc(mlm.wml);\ncolorbar\nylabel('Inputs');\nxlabel('Outputs');\ncolormap(gray);\ntitle('ML Regression Coefficients');\n\ndisp(' ');\ndisp('Posthoc questions:');\ndisp(' ');\ndisp('Is regression coefficient 1,1 non zero ?');\ncon=zeros(p,d);\ncon(1,1)=1;\ncon_vec=con(:)';\ndisp('Log Evidence in favour of this hypothesis:');\nlogbf = spm_mlm_posthoc (mlm,con_vec)\n\ndisp('Is regression coefficient 4,6 non zero ?');\ncon=zeros(p,d);\ncon(4,6)=1;\ncon_vec=con(:)';\ndisp('Log Evidence in favour of this hypothesis:');\nlogbf = spm_mlm_posthoc (mlm,con_vec)\n\ndisp('Are regression coefficients 1,1 2,1 and 3,1 non zero ?');\nw=zeros(p,d);\nw(1,1)=1;w(2,1)=1;w(3,1)=1;\ncon_vec1 = spm_mlm_makecon (mlm,w);\ndisp('Log Evidence in favour of this hypothesis:');\nlogbf = spm_mlm_posthoc (mlm,con_vec1)\n\n\n\ndisp('If we define w1 = regression coefficients 1,1 2,1 and 3,1');\ndisp('and w2 = regression coefficients 1,2 2,2 and 3,2');\ndisp('Is w1 different to w2 ?');\nw=zeros(p,d);\nw(1,2)=1;w(2,2)=1;w(3,2)=1;\ncon_vec2 = spm_mlm_makecon (mlm,w);\ncon_vec_diff=con_vec2-con_vec1;\ndisp('Log Evidence in favour of this hypothesis:');\nlogbf = spm_mlm_posthoc (mlm,con_vec_diff)\n", "meta": {"author": "spm", "repo": "spm12", "sha": "3085dac00ac804adb190a7e82c6ef11866c8af02", "save_path": "github-repos/MATLAB/spm-spm12", "path": "github-repos/MATLAB/spm-spm12/spm12-3085dac00ac804adb190a7e82c6ef11866c8af02/toolbox/mlm/demo_mlm_posthoc.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.700770297002342}} {"text": "function he_plot ( a, b, index, filename )\n\n%*****************************************************************************80\n%\n%% HE_PLOT plots HE(i,x).\n%\n% Discussion:\n%\n% He(i,x) represents the probabilist's Hermite polynomial.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 02 February 2014\n%\n% Author:\n%\n% John Burkardt\n%\n% Parameters:\n%\n% Input, real A, B, the plotting range.\n%\n% Input, integer INDEX(*), the orders of 1 or more Hermite functions\n% to be plotted together.\n%\n% Input, string FILENAME, the name into which the graphics information is\n% to be stored. Note that the PNG format will be used.\n%\n m = 501;\n x = linspace ( a, b, m );\n x = x';\n index_num = length ( index );\n\n clf\n hold on\n for i = 1 : index_num\n n = index(i);\n y = he_polynomial_value ( m, n, x );\n plot ( x, y(:,n+1), 'LineWidth', 2 );\n end\n grid on\n xlabel ( '<--- X --->', 'Fontsize', 16 )\n ylabel ( '<--- He(i,x) --->', 'Fontsize', 16 )\n title ( 'Hermite polynomials He(n,x)', 'Fontsize', 24 )\n hold off\n print ( '-dpng', 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/hermite_polynomial/he_plot.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7007688684136525}} {"text": "function geometry_test2069 ( )\n\n%*****************************************************************************80\n%\n%% TEST2069 tests TRIANGLE_CONTAINS_LINE_PAR_3D.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 12 February 2007\n%\n% Author:\n%\n% John Burkardt\n%\n dim_num = 3;\n\n p0 = [ 3.0, 0.0, -7.0 ];\n pd = [ 2.0, 1.0, 5.0 ];\n t = [ ...\n 8.0, 4.0, 2.0; ...\n 9.0, 0.0, 5.0; ...\n 2.0, 1.0, 2.0 ]';\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'TEST2069\\n' );\n fprintf ( 1, ' TRIANGLE_CONTAINS_LINE_PAR_3D determines whether\\n' );\n fprintf ( 1, ' a triangle \"contains\" a parametric line in 3D.\\n' );\n\n r8mat_transpose_print ( dim_num, 3, t, ' Triangle vertices:' );\n\n norm = sqrt ( sum ( pd(1:dim_num).^2 ) );\n pd(1:dim_num) = pd(1:dim_num) / norm;\n\n r8vec_print ( dim_num, p0, ' Parametric base point P0:' );\n r8vec_print ( dim_num, pd, ' Parametric direction PD:' );\n\n [ inside, pint ] = triangle_contains_line_par_3d ( t, p0, pd );\n\n if ( inside )\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The triangle contains the line.\\n' );\n r8vec_print ( dim_num, pint, ' Intersection point:' );\n else\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The triangle does not contain the line.\\n' );\n r8vec_print ( dim_num, pint, ' The intersection point:' );\n end\n\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' Expected answer:\\n' );\n fprintf ( 1, '\\n' );\n fprintf ( 1, ' The triangle contains the line, and\\n' );\n fprintf ( 1, ' the intersection point is at:\\n' );\n fprintf ( 1, ' ( 7, 2, 3 ).\\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/geometry/geometry_test2069.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7007688610815888}} {"text": "function out = DT_IsSeasonal(y)\n% DT_IsSeasonal A simple test of seasonality.\n%\n% Fits a 'sin1' model to the time series using fit function from the Curve Fitting\n% Toolbox. The output is binary: 1 if the goodness of fit, R^2, exceeds 0.3 and\n% the amplitude of the fitted periodic component exceeds 0.5, and 0 otherwise.\n%\n%---INPUTS:\n% y, the input time series\n%\n%---OUTPUT: Binary: 1 (= seasonal), 0 (= non-seasonal)\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%% Preliminaries\n%-------------------------------------------------------------------------------\n% Check a curve-fitting toolbox license is available:\nBF_CheckToolbox('curve_fitting_toolbox');\n\n% Make sure the input time series, y, is a column vector\nif size(y,2) > size(y,1)\n y = y';\nend\nN = length(y); % length of input time series\nr = (1:N)'; % range over which to fit\n\n%-------------------------------------------------------------------------------\n%% Fit a sinusoidal model using the Curve-Fitting Toolbox\n%-------------------------------------------------------------------------------\n[cfun,gof] = fit(r,y,'sin1'); % fits the following form: a1*sin(b1*x+c1)\n\n%-------------------------------------------------------------------------------\n%% Two conditions for determining whether time series contains periodicities:\n%-------------------------------------------------------------------------------\n% Condition 1: fit is ok\nth_fit = 0.3; % r2 > th_fit\n\n% Condition 2: amplitude is not too small\nth_ampl = 0.5; % a1 > th_ampl\n\nif gof.rsquare > th_fit && abs(cfun.a1 > th_ampl)\n out = 1; % test thinks the time series has strong periodicities\nelse\n out = 0; % test thinks the time series doesn't have any strong periodicities\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/DT_IsSeasonal.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.7007272863623649}} {"text": "function coords = gsp_lle(G, dim, param)\n%GSP_LLE Local Linear Embedding\n% Usage: coords = gsp_lle(G, dim);\n% coords = gsp_lle(G, dim, param);\n%\n% Input parameters\n% G : Graph\n% dim : Dimensionality of the embedding\n% param : Structure of optional parameters\n%\n% Output parameters\n% coords : Coordinates of the embedding\n%\n% This function uses the weight matrix of a graph G, in order to compute\n% a *dim* -dimensional embedding (output coordinates). The algorithm used\n% is Locally Linear Embedding (LLE). Warning, this function might not\n% work if the graph is not connected.\n%\n% *param* is a structure with optional parameters:\n%\n% * *param.tol* : Tolerance for the spectral gap (default 1e-6).\n% * *param.kernel* : The kernel used to create the graph weight matrix:\n% + 'exp' : exponential kernel ($e^(frac{-d_{ij}}{sigma^2})$)\n% + '1/x' : inverse of x kernel ($frac{1}{sigma+d_{ij}}$)\n% + '1/x^2' : inverse of x^2 kernel ($frac{1}{(sigma+d_{ij})^2}$)\n% + 'resistance' : Resistance distance.\n% * *param.k* : Max number of nearest neighbors. If not defined, the\n%\n% number of neighbors varies from node to node since the algorithm\n% considers all the columns $j$ of the weight matrix that have non\n% zero values on the line $i$ as the neighbors of $i$.\n%\n% References: saul2000introduction\n%\n% See also: gsp_update_coordinates gsp_isomap gsp_laplacian_eigenmaps\n%\n% Demo: gsp_demo_graph_embedding\n\n% Authors : Dion O. E. Tzamarias\n% Date : 20/11/2015\n\n%% TODO Fix bug param.k\n%%\n\nif nargin<3\n param = struct;\nend\n\n\nif ~isfield(param,'tol'), param.tol = 1e-6; end\nif ~isfield(param,'kernel'), param.kernel = 'exp'; end\n\n\n% Handling default parameters\n\nW = zeros(G.N,G.N);\n\n% if ~isfield(param,'k')\n [D] = gsp_weight2distance(G);\n [rows, cols ] = find(D);\n idx = cell(cols(end),1);\n for jj=1:cols(end)\n idx{jj} = rows(cols==jj).';\n end\n% else\n% [D,idx] = gsp_weight2distance(G, param.kernel, param.k);\n% end\nD = D.^2; % D contains the squared distances\nfor ii=1:length(D)\n \n % C = 0.5*(repmat(sum(D(idx{ii},idx{ii}),2),1,length(idx{ii}))/length(idx{ii})...\n % + repmat(sum(D(idx{ii},idx{ii}),2).',length(idx{ii}),1)/length(idx{ii}) ...\n % - D(idx{ii},idx{ii}) - repmat(sum(sum(D(idx{ii},idx{ii}),1)),...\n % length(idx{ii}),length(idx{ii}))/length(idx{ii}).^2);\n C = 0.5*(bsxfun(@plus,sum(D(idx{ii},idx{ii}),2),sum(D(...\n idx{ii},idx{ii}),1))/length(idx{ii})-bsxfun(@plus,...\n D(idx{ii},idx{ii}),sum(sum(D(idx{ii},idx{ii}),1))...\n /length(idx{ii}).^2));\n \n if abs(det(C))< param.tol % C is singular\n C = C + (param.tol*trace(C)) / length(idx{ii})...\n * eye(size(C));\n end\n% if abs(det(C))< param.tol*1e-3\n% warning('C is singular')\n% end\n \n W(ii,idx{ii}) = C\\ones(length(idx{ii}),1);\n W(ii,:) = W(ii,:)./sum(W(ii,:));\nend\n\nM = (eye(G.N,G.N) - W)' * (eye(G.N,G.N) - W);\nM = sparse(M);\n\n% Compute first dim eigenvectors of M\noptions.disp = 0;\noptions.isreal = 1;\noptions.issym = 1;\n% only need bottom (no_dims + 1) eigenvectors\ntol = param.tol;\n[coords, e] = eigs(M, dim + 1, tol, options);\ne = diag(e);\n\nif nnz(e 1\n disp('Multiple zero eigenvalues')\nend\n\n[~ , ind] = sort(e, 'ascend');\ncoords = coords(:,ind);\ncoords = coords(:,2:end);\nend\n\n\n% The input parameter type refers to the type of the problem:\n% * 'weight_matrix' : Solve problem using the weight matrix of the graph G\n% Use the pairwise distance equation in order to reconstruct data from\n% neighbours.\n% * 'coords' : Slove the problem using the coordinates. This is the\n% typical LLE aproach.\n\n\n\n% switch lower(type)\n% case 'coords'\n% for ii=1:G.N\n%\n% k_near_indx = knnsearch(G.coords,G.coords(ii,:),'k',n_neighbor+1);\n% k_nearest = G.coords(k_near_indx(2:end),:);\n%\n% C = (repmat(G.coords(ii,:),n_neighbor,1) - k_nearest)* ...\n% (repmat(G.coords(ii,:),n_neighbor,1) - k_nearest)' ;\n%\n% if abs(det(C))=qs(i2) & 1-ye)./mean(1-ye);\n fps(i2+1)=mean(crit>=qs(i2) & ye)./(mean(ye));\nend\n\nif (mean(1-ye)==0)||(mean(ye)==0) \n warning('z vector has no different values, function will return 0');\n a=0;\nelse\n a=sum([diff(fps).*mean([tps(1:end-1);tps(2:end)],1)]); \nend\n\nend\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/external/dmlt/external/gpstuff/diag/aucs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.7007272635501707}} {"text": "function value = p31_exact ( dim_num )\n\n%*****************************************************************************80\n%\n%% P31_EXACT returns the exact integral for problem 31.\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% Kenneth Hanson,\n% Quasi-Monte Carlo: halftoning in high dimensions?\n% in Computatinal Imaging,\n% Edited by CA Bouman and RL Stevenson,\n% Proceedings SPIE,\n% Volume 5016, 2003, pages 161-172.\n%\n% Parameters:\n%\n% Input, integer DIM_NUM, the spatial dimension.\n%\n% Output, real VALUE, the exact value of the integral.\n%\n\n%\n% Get the limits of integration.\n%\n [ a, b ] = p31_lim ( dim_num );\n%\n% Get the coefficient vector C.\n%\n c = [];\n c = p31_r8vec ( 'G', 'C', dim_num, c );\n%\n% Get the location of Z.\n%\n z = [];\n z = p31_r8vec ( 'G', 'Z', dim_num, z );\n%\n% The value of the DIM_NUM dimensional integral is separable\n% into the product of integrals over each dimension.\n%\n% Each of these 1 dimensional integrals, in turn, is\n% easily computed, depending on where Z(I) lies with\n% respect to the limits of integration A(I) and B(I).\n%\n value = 1.0;\n\n for i = 1 : dim_num\n%\n% Z < A < B\n%\n% | X - Z | = X - Z from A to B.\n%\n if ( z(i) < a(i) )\n\n value = value * ...\n ( exp ( - c(i) * ( a(i) - z(i) ) ) ...\n - exp ( - c(i) * ( b(i) - z(i) ) ) ) / c(i);\n%\n% A < Z < B\n%\n% | X - Z | = Z - X from B to Z, \n% = X - Z from Z to A.\n%\n elseif ( z(i) < b(i) )\n\n value = value * ( 2.0 ...\n - exp ( - c(i) * ( z(i) - a(i) ) ) ...\n - exp ( - c(i) * ( b(i) - z(i) ) ) ) / c(i);\n%\n% A < B < Z\n%\n% | X - Z | = Z - X from A to B.\n%\n else\n\n value = value * ...\n ( exp ( - c(i) * ( z(i) - b(i) ) ) ...\n - exp ( - c(i) * ( z(i) - a(i) ) ) ) / c(i);\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/quadrature_test/p31_exact.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156293, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7006465579932756}} {"text": "function cvx_optpnt = complex_lorentz( sx, dim )\n\n%COMPLEX_LORENTZ Complex second-order cone.\n% COMPLEX_LORENTZ(N), where N is a positive integer, creates a column\n% variable of length N and a scalar variable, and constrains them\n% to lie in a second-order cone. That is, given the declaration\n% variable x(n) complex\n% variable y\n% the constraint\n% {x,y} == complex_lorentz(n)\n% is equivalent to\n% norm(x,2) <= y\n% The inequality form is more natural, and preferred in most cases. But\n% in fact, the COMPLEX_LORENTZ set form is used by CVX itself to convert\n% complex NORM()-based constraints to solvable form.\n%\n% COMPLEX_LORENTZ(SX,DIM), where SX is a valid size vector and DIM is a\n% positive integer, creates an array variable of size SX and an array\n% variable of size SY (see below) and applies the second-order cone\n% constraint along dimension DIM. That is, given the declarations\n% sy = sx; sy(min(dim,length(sx)+1))=1;\n% variable x(sx) complex\n% variable y(sy)\n% the constraint\n% {x,y} == complex_lorentz(sx,dim)\n% is equivalent to\n% norms(x,2,dim) <= y\n% Again, the inequality form is preferred, but CVX uses the set form\n% internally. DIM is optional; if it is omitted, the first non-singleton\n% dimension is used.\n%\n% LORENTZ(SX,DIM,CPLX) creates real second-order cones if CPLX is FALSE,\n% and complex second-order cones if CPLX is TRUE. The latter case is\n% equivalent to COMPLEX_LORENTZ(SX,DIM).\n%\n% Disciplined convex programming information:\n% LORENTZ is a cvx set specification. See the user guide for\n% details on how to use sets.\n\nnarginchk(1,2);\nif nargin == 1,\n cvx_optpnt = lorentz( sx, [], true );\nelse\n cvx_optpnt = lorentz( sx, dim, true );\nend\n\n% Copyright 2005-2016 CVX Research, Inc.\n% See the file LICENSE.txt for full copyright information.\n% The command 'cvx_where' will show where this file is located.\n", "meta": {"author": "cvxr", "repo": "CVX", "sha": "a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd", "save_path": "github-repos/MATLAB/cvxr-CVX", "path": "github-repos/MATLAB/cvxr-CVX/CVX-a7b46e7840c3ccf3f35df374d2ff3da4eaafc3cd/sets/complex_lorentz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7006465499967728}} {"text": "function value = p13_f ( dim_num, point_num, x )\n\n%*****************************************************************************80\n%\n%% P13_F evaluates the integrand for problem 13.\n%\n% Dimension:\n%\n% DIM_NUM arbitrary.\n%\n% Region:\n%\n% 0 <= X(1:DIM_NUM) <= 1\n%\n% Integrand:\n%\n% product ( 1 <= i <= dim_num ) t(n(i))(2*x(i)-1)\n%\n% where T(N)(X) is the Chebyshev polynomial of order N,\n% and N(I) = mod ( i, 4 ) + 1.\n%\n% Exact Integral:\n%\n% 0\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% Paul Bratley, Bennett Fox, Harald Niederreiter,\n% Implementation and Tests of Low-Discrepancy Sequences,\n% ACM Transactions on Modeling and Computer Simulation,\n% Volume 2, Number 3, July 1992, pages 195-213.\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 value(1:point_num) = 1.0;\n\n for point = 1 : point_num\n\n for dim = 1 : dim_num\n\n t = 2.0 * x(dim,point) - 1.0;\n k = mod ( dim, 4 );\n\n if ( k == 1 )\n factor = t;\n elseif ( k == 2 )\n factor = 2.0 * t - 1.0;\n elseif ( k == 3 )\n factor = ( 4.0 * t - 3.0 ) * t;\n elseif ( k == 4 )\n factor = ( 8.0 * t - 8.0 * t + 1.0 );\n end\n\n value(point) = value(point) * factor;\n\n end\n\n end\n\n p13_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/p13_f.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.7006465493862252}} {"text": "function jed = ymd_to_jed_gregorian ( y, m, d )\n\n%*****************************************************************************80\n%\n%% YMD_TO_JED_GREGORIAN converts a Gregorian YMD date to a JED.\n%\n% Licensing:\n%\n% This code is distributed under the GNU LGPL license.\n%\n% Modified:\n%\n% 20 April 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, the YMD date.\n%\n% Output, real JED, the corresponding JED.\n%\n\n%\n% Check the date.\n%\n [ y, m, d, ierror ] = ymd_check_gregorian ( y, m, d );\n\n if ( ierror ~= 0 )\n jed = -1.0;\n return\n end\n%\n% Account for the missing year 0 by moving negative years up one.\n%\n y2 = y_common_to_astronomical ( y );\n%\n% Convert the calendar date to a computational date.\n%\n y_prime = y2 + 4716 - floor ( ( 14 - m ) / 12 );\n m_prime = mod ( m + 9, 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 j2 = floor ( ( 153 * m_prime + 2 ) / 5 );\n\n g = floor ( ( y_prime + 184 ) / 100 );\n\n g = floor ( 3 * g / 4 ) - 38;\n\n jed = j1 + j2 + d_prime - 1401 - g - 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/calpak/ymd_to_jed_gregorian.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.700623181579221}} {"text": "function xdot = dto_rhs (t, x, u)\n\n% first-order equations of motion\n\n% required by dto_trap.m\n\n% input\n\n% t = current time\n\n% x = current state vector\n\n% x(1) = r, x(2) = u, x(3) = v\n\n% u = current control vector\n\n% output\n\n% xdot = rhs equations of motion\n\n% xdot(1) = r dot, xdot(2) = u dot, xdot(3) = v dot\n\n% Orbital Mechanics with MATLAB\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nglobal acc beta\n\n% current control variable\n\ntheta = u(1);\n\n% current thrust acceleration\n\naccm = acc / (1.0 - beta * t);\n\n% evaluate equations of motion at current conditions\n\nxdot(1) = x(2);\n\nxdot(2) = (x(3) * x(3) - 1.0 / x(1)) / x(1) + accm * sin(theta);\n\nxdot(3) = -x(2) * x(3) / x(1) + accm * cos(theta);\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/38936-aerospace-trajectory-optimization-using-direct-transcription-and-collocation/dto_rhs.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.7004715166796048}} {"text": "function LLF = cauchy_log(parameters,data)\n%---------------------------------------------------\n% PURPOSE: \n% Log Likelihood function of the Cauchy-Lorentz Distribution, \n% to estimate the location and scale parameters of a data set \n%---------------------------------------------------\n% USAGE: \n% LLF = cauchy_log(x, data)\n%\n% INPUTS: \n% parameters: a vector of parameters of the form [m; s] \n% data: the data set\n% \n% OUTPUTS:\n% LLF: The log-likelihood function\n%---------------------------------------------------\n% Author:\n% Alexandros Gabrielsen, a.gabrielsen@city.ac.uk\n% Date: 06/2010\n%---------------------------------------------------\n[a,b]=size(parameters);\nif b>a\n parameters=parameters';\nend\nn=length(data);\nLLF = -n*log(pi) +n*log(parameters(2)) - sum(log(parameters(2)^2 + (data-parameters(1)).^2));\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/29051-distributions/cauchy_log.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.700471512933466}} {"text": "function test_tutorial_connectivity20130308\n\n% MEM 7gb\n% WALLTIME 00:10:00\n% DEPENDENCY\n\n% Simulated data with directed connections\n% We will first simulate some data with a known connectivity structure built in. This way we know what to expect in terms of connectivity. To simulate data we use ft_connectivitysimulation. We will use an order 2 multivariate autoregressive model. The necessary ingredients are a set of NxN coefficient matrices, one matrix for each time lag. These coefficients need to be stored in the cfg.param field. Next to the coefficients we have to specify the NxN covariance matrix of the innovation noise. This matrix needs to be stored in the cfg.noisecov field. The model we are going to use to simulate the data is as follows:\n% \n% x(t) = 0.8*x(t-1) - 0.5*x(t-2)\n% y(t) = 0.9*y(t-1) + 0.5*z(t-1) - 0.8*y(t-2)\n% z(t) = 0.5*z(t-1) + 0.4*x(t-1) - 0.2*z(t-2)\n\ncfg = [];\ncfg.ntrials = 500;\ncfg.triallength = 1;\ncfg.fsample = 200;\ncfg.nsignal = 3;\ncfg.method = 'ar';\n\ncfg.params(:,:,1) = [ 0.8 0 0 ; \n 0 0.9 0.5 ;\n 0.4 0 0.5];\n \ncfg.params(:,:,2) = [-0.5 0 0 ; \n 0 -0.8 0 ; \n 0 0 -0.2];\n \ncfg.noisecov = [ 0.3 0 0 ;\n 0 1 0 ;\n 0 0 0.2];\n\ndata = ft_connectivitysimulation(cfg);\n\n% The simulated data consists of 3 channels in 500 trials. You can easily visualize the data for example in the first trial using\n% \nfigure\nplot(data.time{1}, data.trial{1}) \nlegend(data.label)\nxlabel('time (s)')\n\n\n% or browse through the complete data using\n% \ncfg = [];\ncfg.viewmode = 'vertical'; % you can also specify 'butterfly' \nft_databrowser(cfg, data);\n\n% \n% \n% Computation of the multivariate autoregressive model\n% To be able to compute spectrally resolved Granger causality, or other frequency-domain directional measures of connectivity, we have to fit an autoregressive model to the data. This is done using the ft_mvaranalysis function.\n% \n% For the actual computation of the autoregressive coefficients FieldTrip makes use of an implementation from third party toolboxes. At present ft_mvaranalysis supports the biosig and bsmart toolboxes for these computations.\n% \n% In this tutorial we will use the bsmart toolbox. The relevant functions have been included in the FieldTrip release in the fieldtrip/external/bsmart directory.\n% \ncfg = [];\ncfg.order = 5;\ncfg.toolbox = 'bsmart';\nmdata = ft_mvaranalysis(cfg, data);\n\n% mdata = \n% dimord: 'chan_chan_lag'\n% label: {3x1 cell}\n% coeffs: [3x3x5 double]\n% noisecov: [3x3 double]\n% dof: 500\n% fsampleorig: 200\n% cfg: [1x1 struct]\n% \n% The resulting variable mdata contains a description of the data in terms of a multivariate autoregressive model. For each time-lag up to the model order (which is 5 in this case), a 3\u001a3 matrix of coefficients is outputted. The noisecov-field contains covariance matrix of the model's residuals.\n% \n% Exercise 1\n% Compare the parameters specified for the simulation with the estimated coefficients and discuss.\n% \n% Computation of the spectral transfer function\n% From the autoregressive coefficients it is now possible to compute the spectral transfer matrix, for which we use ft_freqanalysis.\n% \ncfg = [];\ncfg.method = 'mvar';\nmfreq = ft_freqanalysis(cfg, mdata);\n \n% mfreq = \n% label: {3x1 cell}\n% freq: [1x101 double]\n% dimord: 'chan_chan_freq'\n% transfer: [3x3x101 double]\n% noisecov: [3x3 double]\n% crsspctrm: [3x3x101 double]\n% dof: 500\n% cfg: [1x1 struct]\n% \n% The resulting mfreq data structure contains the pairwise transfer function between the 3 channels for 101 frequencies.\n% \n% It is also possible to compute the spectral transfer function using non-parametric spectral factorization of the cross-spectral density matrix. For this, we need a Fourier decomposition of the data. This is done in the following section.\n% \n% \n% Non-parametric computation of the cross-spectral density matrix\n% Some connectivity metrics can be computed from a non-parametric spectral estimate (i.e. after the application of the FFT-algorithm and conjugate multiplication to get cross-spectral densities), such as coherence, phase-locking value and phase slope index. The following part computes the fourier-representation of the data using ft_freqanalysis. It is not necessary to compute the cross-spectral density at this stage, because the function used in the next step, ft_connectivityanalysis, contains functionality to compute the cross-spectral density from the fourier coefficients.\n% \ncfg = [];\ncfg.method = 'mtmfft';\ncfg.taper = 'dpss';\ncfg.output = 'fourier';\ncfg.tapsmofrq = 2;\nfreq = ft_freqanalysis(cfg, data);\n\n% freq = \n% label: {3x1 cell}\n% dimord: 'rpttap_chan_freq'\n% freq: [1x101 double]\n% fourierspctrm: [1500x3x101 double]\n% cumsumcnt: [500x1 double]\n% cumtapcnt: [500x1 double]\n% cfg: [1x1 struct]\n% The resulting freq structure contains the spectral estimate for 3 tapers in each of the 500 trials (hence 1500 estimates), for each of the 3 channels and for 101 frequencies.\n% \n% \n% Computation and inspection of the connectivity measures\n% The actual computation of the connectivity metric is done by ft_connectivityanalysis. This function is transparent to the type of input data, i.e. provided the input data allows the requested metric to be computed, the metric will be calculated. Here, we provide an example for the computation and visualization of the coherence coefficient.\n% \ncfg = [];\ncfg.method = 'coh';\ncoh = ft_connectivityanalysis(cfg, freq);\ncohm = ft_connectivityanalysis(cfg, mfreq);\n% Subsequently, the data can be visualized using ft_connectivityplot.\n% \ncfg = [];\ncfg.parameter = 'cohspctrm';\ncfg.zlim = [0 1];\nft_connectivityplot(cfg, coh, cohm);\n\n% \n% The coherence measure is a symmetric measure, which means that it does not provide information regarding the direction of information flow between any pair of signals. In order to analyze directionality in interactions, measures based on the concept of granger causality can be computed. These measures are based on an estimate of the spectral transfer matrix, which can be computed in a straightforward way from the multivariate autoregressive model fitted to the data.\n% \ncfg = [];\ncfg.method = 'granger';\ngranger = ft_connectivityanalysis(cfg, mfreq);\n\ncfg = [];\ncfg.parameter = 'grangerspctrm';\ncfg.zlim = [0 1];\nft_connectivityplot(cfg, granger);\n\n\n% Instead of plotting it with ft_connectivityplot, you can use the following low-level MATLAB plotting code which gives a better understanding of the numerical representation of the results.\n% \nfigure\nfor row=1:3\nfor col=1:3\n subplot(3,3,(row-1)*3+col);\n plot(granger.freq, squeeze(granger.grangerspctrm(row,col,:)))\n ylim([0 1])\nend\nend\n\n% \n% Exercise 2\n% Discuss the differences between the granger causality spectra, and the coherence spectra.\n% Exercise 3\n% Compute the following connectivity measures from the mfreq data, and visualize and discuss the results: partial directed coherence (pdc), directed transfer function (dtf), phase slope index (psi)\n% \n% Simulated data with common pick-up and different noise levels\n% this is under progress\n% \n% When working with electrophysiological data (EEG/MEG/LFP) the signals that are picked up by the individual channels invariably consist of instantaneous mixtures of the underlying source signals. This mixing can severely affect the outcome of connectivity analysis, and thus affects the interpretation. We will demonstrate this by simulating data in 2 channels, where each of the channels consists of a weighted combination of temporally white noise unique to each of the channels, and a common input of a band-limited signal (filtered between 15 and 25 Hz). We will compute connectivity between these channels, and show that the common input can give rise to spurious estimates of connectivity.\n% \n% % create some instantaneously mixed data\n% \n% define some variables locally\nnTrials = 100;\nnSamples = 1000;\nfsample = 1000;\n\n% mixing matrix\nmixing = [0.8 0.2 0;\n 0 0.2 0.8];\n\ndata = [];\ndata.trial = cell(1,nTrials);\ndata.time = cell(1,nTrials);\nfor k = 1:nTrials\n dat = randn(3, nSamples);\n dat(2,:) = ft_preproc_bandpassfilter(dat(2,:), 1000, [15 25]);\n dat = 0.2.*(dat-repmat(mean(dat,2),[1 nSamples]))./repmat(std(dat,[],2),[1 nSamples]);\n data.trial{k} = mixing * dat;\n data.time{k} = (0:nSamples-1)./fsample;\nend\ndata.label = {'chan1' 'chan2'}';\n\nfigure;plot(dat'+repmat([0 1 2],[nSamples 1]));\ntitle('original ''sources''');\n\nfigure;plot((mixing*dat)'+repmat([0 1],[nSamples 1])); \naxis([0 1000 -1 2]);\nset(findobj(gcf,'color',[0 0.5 0]), 'color', [1 0 0]);\ntitle('mixed ''sources''');\n \n\n% do spectral analysis\ncfg = [];\ncfg.method = 'mtmfft';\ncfg.output = 'fourier';\ncfg.foilim = [0 200];\ncfg.tapsmofrq = 5;\nfreq = ft_freqanalysis(cfg, data);\nfd = ft_freqdescriptives(cfg, freq);\n\nfigure;plot(fd.freq, fd.powspctrm);\nset(findobj(gcf,'color',[0 0.5 0]), 'color', [1 0 0]);\ntitle('powerpectrum');\n\n% \n% compute connectivity\ncfg = [];\ncfg.method = 'granger';\ng = ft_connectivityanalysis(cfg, freq);\ncfg.method = 'coh';\nc = ft_connectivityanalysis(cfg, freq);\n% visualize the results\ncfg = [];\ncfg.parameter = 'grangerspctrm';\nft_connectivityplot(cfg, g);\ncfg.parameter = 'cohspctrm';\nft_connectivityplot(cfg, c);\n\n\n% Exercise 4\n% Simulate new data using the following mixing matrix:\n% [0.9 0.1 0;0 0.2 0.8] \n% and recompute the connectivity measures. Discuss what you see.\n% \n% Exercise 5\n% Play a bit with the parameters in the mixing matrix and see what is the effect on the estimated connectivity.\n% Exercise 6\n% Simulate new data where the 2 mixed signals are created from 4 underlying sources, and where two of these sources are common input to both signals, and where these two sources are temporally shifted copies of one another.\n% Hint: the mixing matrix could look like this:\n% \n% [a b c 0; 0 d e f];\n% and the trials could be created like this:\n% \n% for k = 1:nTrials\n% dat = randn(4, nSamples+10);\n% dat(2,:) = ft_preproc_bandpassfilter(dat(2,:), 1000, [15 25]);\n% dat(3,1:(nSamples)) = dat(2,11:(nSamples+10)); \n% dat = dat(:,1:1000);\n% dat = 0.2.*(dat-repmat(mean(dat,2),[1 nSamples]))./repmat(std(dat,[],2),[1 nSamples]);\n% data.trial{k} = mixing * dat;\n% data.time{k} = (0:nSamples-1)./fsample;\n% end\n% Compute connectivity between the signals and discuss what you observe. In particular, also compute measures of directed interaction.\n% \n% \n% Connectivity between MEG virtual channel and EMG\n% The previous two examples were using simulated data, either with a clear directed connectivity structure, or with a trivial pick-up of a common source in two channels. We will now continue with connectivity analysis on real MEG data. The dataset is the same as the one used in the Analysis of corticomuscular coherence tutorial.\n% \n% In short, the dataset consists of combined MEG and EMG recordings while the subject lifted his right hand. The coherence tutorial introduction contains a more elaborate description of the experiment and the dataset and a detailed analysis can be found in the corresponding paper 1). Due to the long distance between the EMG and the MEG, there is no volume conduction and hence no common pick-up. Hence this dataset lends itself well for connectivity analysis. But rather than doing an analysis between the EMG and one of the MEG channels (as in the original study), we will extract the cortical activity using a beamformer virtual channel.\n% \n% \n% Compute the spatial filter for the region of interest\n% We start with determining the motor cortex as region of interest. At the end of the coherence tutorial it is demonstrated how to make a 3-D reconstruction of the cortico-muscolar coherence (CMC) using the DICS algorithm. That source reconstruction serves as starting point for this analysis.\n% \n% You can download the result from the DICS reconstruction from the FieldTrip ftp server (source.mat)\n% \n% We will first determine the position on which the cortico-muscular coherence is the largest.\n% \n\ncd(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/connectivity'));\nload source\n\n[maxval, maxindx] = max(source.avg.coh);\nmaxpos = source.pos(maxindx,:);\n\n% maxpos = \n% 4 -3 12\n% The cortical position is expressed in individual subject head-coordinates and in centimeter. Relative to the center of the head (in between the ears) the position is 4 cm towards the nose, -3 towards the left side (i.e., 3 cm towards the right!) and 12 cm towards the vertex.\n% \n% The ft_sourceanalysis methods are usually applied to the whole brain using a regular 3-D grid or using a triangulated cortical sheet. You can also just specify the location of a single or multiple points of interest with cfg.sourcemodel.pos and the LCMV beamformer will simply be performed at the location of interest.\n% \n% The LCMV beamformer spatial filter for the location of interest will pass the activity at that location with unit-gain, while optimally suppressing all other noise and other source contributions to the MEG data. The LCMV implementation in FieldTrip requires the data covariance matrix to be computed with ft_timelockanalysis.\n% \n% Rather than doing all the preprocessing again, you can download the preprocessed data from the FieldTrip ftp server (data.mat)\n% \nload data\n% \n%% compute the beamformer filter\ncfg = [];\ncfg.covariance = 'yes';\ncfg.channel = 'MEG';\ncfg.vartrllength = 2;\ncfg.covariancewindow = 'all';\ntimelock = ft_timelockanalysis(cfg, data);\n\ncfg = [];\ncfg.method = 'lcmv';\ncfg.hdmfile = 'SubjectCMC.hdm';\ncfg.sourcemodel.pos = maxpos;\ncfg.keepfilter = 'yes';\nsource = ft_sourceanalysis(cfg, timelock);\n% The source reconstruction contains the estimated power and the source-level time-series of the averaged ERF, but here we are not interested in those. The cfg.keepfilter option results in the spatial filter being kept in the output source structure. That spatial can be used to reconstruct the single-trial time series as a virtual channel by multiplying it with the original MEG data.\n% \n% \n% Extract the virtual channel time-series\n%% construct the 3-D virtual channel at the location of interest\nbeamformer = source.avg.filter{1};\n\nchansel = ft_channelselection('MEG', data.label); % find the names\nchansel = match_str(data.label, chansel); % find the indices\n\nsourcedata = [];\nsourcedata.label = {'x', 'y', 'z'};\nsourcedata.time = data.time;\nfor i=1:length(data.trial)\n sourcedata.trial{i} = beamformer * data.trial{i}(chansel,:);\nend\n% The LCMV spatial filter is computed here without applying any time-domain filters. Consequently, it will have to suppress all noise in the data in all frequency bands. The spatial filter derived from the broadband data allows us to compute a broadband source level time-series.\n% If you would know that the subsequent analysis would be limited to a specific frequency range in the data (e.g. everything above 30 Hz), you could first apply a filter using ft_preprocessing (e.g. cfg.hpfilter=yes and cfg.hpfreq=30) prior to computing the covariance and the spatial filter.\n% \n% The sourcedata structure resembles the raw-data output of ft_preprocessing and consequently can be used in any follow-up function. You can for example visualize the single-trial virtual channel time-series using ft_databrowser:\n% \ncfg = [];\ncfg.viewmode = 'vertical'; % you can also specify 'butterfly'\nft_databrowser(cfg, sourcedata);\n\n% \n% Notice that the reconstruction contains three channels, for the x-, the y- and the z-component of the equivalent current dipole source at the location of interest.\n% \n% \n% Project along the strongest dipole direction\n% The interpretation of connectivity is facilitated if we can compute it between two plain channels rather than between one channel versus a triplet of channels. Therefore we will project the time-series along the dipole direction that explains most variance. This projection is equivalent to determining the largest (temporal) eigenvector and can be computationally performed using the singular value decomposition (svd).\n% \n%% construct a single virtual channel in the maximum power orientation\ntimeseries = cat(2, sourcedata.trial{:});\n\n[u, s, v] = svd(timeseries, 'econ');\n\n% whos u s v\n% Name Size Bytes Class Attributes\n% \n% s 3x3 72 double \n% u 3x3 72 double \n% v 196800x3 4723200 double \n% Matrix u contains the spatial decomposition, matrix v the temporal and on the diagonal of matrix s you can find the eigenvalues. See \"help svd\" for more details.\n% \n% We now recompute the virtual channel time-series, but now only for the dipole direction that has the most power.\n% \n% this is equal to the first column of matrix V, apart from the scaling with s(1,1)\ntimeseriesmaxproj = u(:,1)' * timeseries;\nvirtualchanneldata = [];\nvirtualchanneldata.label = {'cortex'};\nvirtualchanneldata.time = data.time;\nfor i=1:length(data.trial)\n virtualchanneldata.trial{i} = u(:,1)' * beamformer * data.trial{i}(chansel,:);\nend\n% Rather than using a sourcemodel in the beamformer that consists of all three (x, y, z) directions, you can also have the beamformer compute the filter for only the optimal source orientation. This is implemented using the cfg.lcmv.fixedori='yes' option.\n% Recompute the spatial filter for the optimal source orientation and using that spatial filter (a 1\u001a151 vector) recompute the time-series.\n% \n% Investigate and describe the difference between the two time-series. What is the difference between the two dipole orientations?\n% \n% Note that one orientation is represented in the SVD matrix \"u\" and the other is in the source.avg.ori field.\n% \n% \n% Combine the virtual channel with the EMG\n% The raw data structure containing one (virtual) channel can be combined with the two EMG channels from the original preprocessed data.\n% \n%% select the two EMG channels\ncfg = [];\ncfg.channel = 'EMG';\nemgdata = ft_selectdata(cfg, data);\n\n%% combine the virtual channel with the two EMG channels\ncfg = [];\ncombineddata = ft_appenddata(cfg, virtualchanneldata, emgdata);\n\n% save combineddata combineddata\n% \n% Compute the connectivity\n% The resulting combined data structure has three channels: the activity from the cortex, the left EMG and the right EMG. We can now continue with regular channel-level connectivity analysis.\n% \n%% compute the spectral decomposition\ncfg = [];\ncfg.output = 'fourier';\ncfg.method = 'mtmfft';\ncfg.foilim = [5 100];\ncfg.tapsmofrq = 5;\ncfg.keeptrials = 'yes';\ncfg.channel = {'cortex' 'EMGlft' 'EMGrgt'};\nfreq = ft_freqanalysis(cfg, combineddata);\n\ncfg = [];\ncfg.method = 'coh';\ncoherence = ft_connectivityanalysis(cfg, freq);\n% This computes the spectral decomposition and the coherence spectrum between all channel pairs, which can be plotted with\n% \ncfg = [];\ncfg.zlim = [0 0.2];\nfigure\nft_connectivityplot(cfg, coherence);\ntitle('coherence')\n\n% \n% To look in more detail into the numerical representation of the coherence results, you can use\n% \nfigure\nplot(coherence.freq, squeeze(coherence.cohspctrm(1,2,:)))\ntitle(sprintf('connectivity between %s and %s', coherence.label{1}, coherence.label{2}));\nxlabel('freq (Hz)')\nylabel('coherence')\n\n% \n% The spectrum reveals coherence peaks at 10 and 20 Hz (remember that the initial DICS localizer was done at beta). Furthermore, there is a broader plateau of coherence in the gamma range from 40-50 Hz.\n% \n% The spectral decomposition was performed with mutitapering and 5 Hz spectral smoothing (i.e. 5Hz in both directions). Recompute the spectral decomposition and the coherence with a hanning taper. Recompute it with mutitapering and 10 Hz smoothing. Plot the three coherence spectra and look at the differences.\n% Rather than looking at undirected coherence, the virtual channel level data can now also easily be submitted to directed connectivity measures. Compute the spectrally resolved granger connectivity and try to assess whether the directionality is from cortex to EMG or vice versa.\n% \n% Summary and further reading\n% This tutorial demonstrates how to compute connectivity measures between two time series. If you want to learn how to make a distributed representation of connectivity throughout the whole brain, you may want to continue with the corticomuscular coherence tutorial.\n% \n% This tutorial was last tested by Robert with revision 6026 of FieldTrip (~20120611) on a 64-bit Mac OS X machine using MATLAB 2011b.\n", "meta": {"author": "fieldtrip", "repo": "fieldtrip", "sha": "c2039be598a02d86b39aae76bfa7aaa720f9801c", "save_path": "github-repos/MATLAB/fieldtrip-fieldtrip", "path": "github-repos/MATLAB/fieldtrip-fieldtrip/fieldtrip-c2039be598a02d86b39aae76bfa7aaa720f9801c/test/test_tutorial_connectivity20130308.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.7004663359733442}} {"text": "function sinogram = myRadon(image,thetas)\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% radon transformation -> schlegel & bille 9.1.1\n% written by Mark Bangert\n% m.bangert@dkfz.de 2011\n\nnumOfAngularProjections = length(thetas);\nnumOfParallelProjections = size(image,1);\n\nsinogram = zeros(numOfParallelProjections,numOfAngularProjections);\n\n% loop over the number of angles\nfor i = 1:length(thetas)\n \n % rotate image\n tmpImage = imrotate(image,-thetas(i),'bilinear','crop');\n \n % fill sinogram\n sinogram(:,i) = sum(tmpImage,2);\n \n % visualization on the fly\n imagesc(sinogram);\n drawnow\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/34608-ct-reconstruction-package/ctRecontruction/myRadon.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.700390365328945}} {"text": "function K = covPeriodic(hyp, x, z, i)\n\n% Stationary covariance function for a smooth periodic function, with period p \n% in 1d (see covPERiso and covPERard for multivariate data):\n%\n% k(x,z) = sf^2 * exp( -2*sin^2( pi*||x-z||/p )/ell^2 )\n%\n% where the hyperparameters are:\n%\n% hyp = [ log(ell)\n% log(p)\n% log(sf) ]\n%\n% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2011-01-05.\n%\n% See also COVFUNCTIONS.M.\n\nif nargin<2, K = '3'; 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\n[n,D] = size(x);\nif D>1, error('Covariance is defined for 1d data only.'), end\nell = exp(hyp(1));\np = exp(hyp(2));\nsf2 = exp(2*hyp(3));\n\n% precompute distances\nif dg % vector kxx\n K = zeros(size(x,1),1);\nelse\n if xeqz % symmetric matrix Kxx\n K = sqrt(sq_dist(x'));\n else % cross covariances Kxz\n K = sqrt(sq_dist(x',z'));\n end\nend\n\nK = pi*K/p;\nif nargin<4 % covariances\n K = sin(K)/ell; K = K.*K; K = sf2*exp(-2*K);\nelse % derivatives\n if i==1\n K = sin(K)/ell; K = K.*K; K = 4*sf2*exp(-2*K).*K;\n elseif i==2\n R = sin(K)/ell; K = 4*sf2/ell*exp(-2*R.*R).*R.*cos(K).*K;\n elseif i==3\n K = sin(K)/ell; K = K.*K; K = 2*sf2*exp(-2*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/covPeriodic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.7003456885849206}} {"text": "function [MHz] = radps2MHz(radps)\n% Convert frequency from radians per second to megahertz.\n% Chad A. Greene 2012\nMHz = radps/(2*pi)/1000000;", "meta": {"author": "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/radps2MHz.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.7003456801962649}} {"text": "function [af, sf] = farras\n\n% Farras nearly symmetric filters for orthogonal\n% 2-channel perfect reconstruction filter bank\n%\n% USAGE:\n% [af, sf] = farras\n% OUTPUT:\n% af - analysis filters\n% sf - synthesis filters\n% REFERENCE:\n% A. F. Abdelnour and I. W. Selesnick. \n% \"Nearly symmetric orthogonal wavelet bases\",\n% Proc. IEEE Int. Conf. Acoust., Speech,\n% Signal Processing (ICASSP), May 2001.\n% See afb, dwt.\n%\n% WAVELET SOFTWARE AT POLYTECHNIC UNIVERSITY, BROOKLYN, NY\n% http://taco.poly.edu/WaveletSoftware/\n\naf = [\n 0 -0.01122679215254\n 0 0.01122679215254\n -0.08838834764832 0.08838834764832\n 0.08838834764832 0.08838834764832\n 0.69587998903400 -0.69587998903400\n 0.69587998903400 0.69587998903400\n 0.08838834764832 -0.08838834764832\n -0.08838834764832 -0.08838834764832\n 0.01122679215254 0\n 0.01122679215254 0\n];\n \nsf = af(end:-1:1, :);\n\n", "meta": {"author": "thomaskuestner", "repo": "CS_MoCo_LAB", "sha": "a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b", "save_path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB", "path": "github-repos/MATLAB/thomaskuestner-CS_MoCo_LAB/CS_MoCo_LAB-a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b/reconstruction/matlab/CS_LAB_matlab/utils/utils_Proximal/Denoising/WaveletFunctions/farras.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.7003181485570801}} {"text": "function gammaAB = diffCoherence(k, r_A, r_B, a_nm, b_nm, G_mtx)\n%DIFFCOHERENCE Computes diffuse field coherence of two directional patterns\n%\n% Does that. For more details see\n%\n% Politis, A., 2016. \n% Diffuse-field coherence of sensors with arbitrary directional responses. arXiv preprint arXiv:1608.07713.\n%\n% Inputs:\n% k: vector of wavenumbers to compute coherence at\n% r_A: [x y z] vector of location of first sensor/beamformer\n% r_B: [x y z] vector of location of second sensor/beamformer\n% a_nm: SHD beamweights of the first directional pattern\n% b_nm: SHD beamweights of the second directional pattern\n% G_mtx: (optional) pre-computed matrix of Gaunt coefficients used\n% in the derivation. If not passed then they are computed here,\n% but that can be very slow for high orders.\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% DIFFCOHERENCE.M - 7/06/2015\n% Archontis Politis, archontis.politis@aalto.fi\n%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n% get the vector connecting the two patterns\nr_AB = r_B-r_A;\n[phi_r, elev_r, d] = cart2sph(r_AB(1),r_AB(2),r_AB(3));\ntheta_r = pi/2-elev_r;\n\norderA = sqrt(length(a_nm)) -1;\norderB = sqrt(length(b_nm)) -1;\norderC = orderA+orderB;\nminOrder = min(orderA, orderB);\n\n% convert second pattern to its conjugate for coherence between complex\n% patterns (doesn't do anything if the patterns are real)\nb_nm = conjCoeffs(b_nm);\n\n% denominator of the coherence function\ndenAB = sqrt((a_nm'*a_nm) * (b_nm'*b_nm));\n\nif d==0\n % numerator of the coherence function\n numAB = dot(a_nm(1:(minOrder+1)^2), b_nm(1:(minOrder+1)^2));\n numAB = numAB*ones(size(k));\n \nelse\n % get coefficients of the product function\n if nargin<6\n c_nm = sphMultiplication(a_nm, b_nm);\n else\n c_nm = sphMultiplication(a_nm, b_nm, G_mtx);\n end\n \n % numerator of the coherence function\n y_nm_r = getSH(orderC, [phi_r theta_r], 'complex')';\n kd = k*d;\n imag_n = 1i.^(0:orderC).';\n bessel_n = zeros(orderC+1,length(kd));\n for no=0:orderC, bessel_n(no+1,:) = sph_besselj(no, kd).'; end\n imag_bessel_n = (imag_n*ones(1,length(kd))).*bessel_n;\n imag_bessel_nm = replicatePerOrder(imag_bessel_n);\n planewave_nm = 4*pi*(y_nm_r*ones(1,length(kd))).*imag_bessel_nm;\n numAB = zeros(size(k));\n for kk=1:length(kd)\n numAB(kk) = planewave_nm(:,kk)' * c_nm;\n end\nend\n \n% coherence\ngammaAB = numAB/denAB;\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/diffCoherence.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894548800271, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.7003181238252003}} {"text": "function [ fe, next, ierr ] = chfev ( x1, x2, f1, f2, d1, d2, ne, xe )\n\n%*****************************************************************************80\n%\n%% CHFEV evaluates a cubic polynomial given in Hermite form.\n%\n% Discussion:\n%\n% This routine evaluates a cubic polynomial given in Hermite form at an\n% array of points. While designed for use by SPLINE_PCHIP_VAL, it may\n% be useful directly as an evaluator for a piecewise cubic\n% Hermite function in applications, such as graphing, where\n% the interval is known in advance.\n%\n% The cubic polynomial is determined by function values\n% F1, F2 and derivatives D1, D2 on the interval [X1,X2].\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% David Kahaner, Cleve Moler, Steven Nash,\n% Numerical Methods and Software,\n% Prentice Hall, 1988.\n%\n% Parameters:\n%\n% Input, real X1, X2, the endpoints of the interval of\n% definition of the cubic. X1 and X2 must be distinct.\n%\n% Input, real F1, F2, the values of the function at X1 and\n% X2, respectively.\n%\n% Input, real D1, D2, the derivative values at X1 and\n% X2, respectively.\n%\n% Input, integer NE, the number of evaluation points.\n%\n% Input, real XE(NE), the points at which the function is to\n% be evaluated. If any of the XE are outside the interval\n% [X1,X2], a warning error is returned in NEXT.\n%\n% Output, real FE(NE), the value of the cubic function\n% at the points XE.\n%\n% Output, integer NEXT(2), indicates the number of extrapolation points:\n% NEXT(1) = number of evaluation points to the left of interval.\n% NEXT(2) = number of evaluation points to the right of interval.\n%\n% Output, integer IERR, error flag.\n% 0, no errors.\n% -1, NE < 1.\n% -2, X1 == X2.\n%\n if ( ne < 1 )\n ierr = -1;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHFEV - Fatal error!\\n' );\n fprintf ( 1, ' Number of evaluation points is less than 1.\\n' );\n fprintf ( 1, ' NE = %d\\n', ne );\n error ( 'CHFEV - Fatal error!' )\n end\n\n h = x2 - x1;\n\n if ( h == 0.0 )\n ierr = -2;\n fprintf ( 1, '\\n' );\n fprintf ( 1, 'CHFEV - Fatal error!\\n' );\n fprintf ( 1, ' The interval [X1,X2] is of zero length.\\n' );\n error ( 'CHFEV - Fatal error!' )\n end\n%\n% Initialize.\n%\n ierr = 0;\n next(1) = 0;\n next(2) = 0;\n xmi = min ( 0.0, h );\n xma = max ( 0.0, h );\n%\n% Compute cubic coefficients expanded about X1.\n%\n delta = ( f2 - f1 ) / h;\n del1 = ( d1 - delta ) / h;\n del2 = ( d2 - delta ) / h;\n c2 = -( del1 + del1 + del2 );\n c3 = ( del1 + del2 ) / h;\n%\n% Evaluation loop.\n%\n for i = 1 : ne\n\n x = xe(i) - x1;\n fe(i) = f1 + x * ( d1 + x * ( c2 + x * c3 ) );\n%\n% Count the extrapolation points.\n%\n if ( x < xmi )\n next(1) = next(1) + 1\n end\n\n if ( xma < x )\n next(2) = next(2) + 1\n end\n\n end\n\n return\nend\n", "meta": {"author": "johannesgerer", "repo": "jburkardt-m", "sha": "1726deb4a34dd08a49c26359d44ef47253f006c1", "save_path": "github-repos/MATLAB/johannesgerer-jburkardt-m", "path": "github-repos/MATLAB/johannesgerer-jburkardt-m/jburkardt-m-1726deb4a34dd08a49c26359d44ef47253f006c1/spline/chfev.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.8128673246376008, "lm_q1q2_score": 0.7003162478139021}} {"text": "function [W, b] = initializeOneLayerParams(layerSize, inputSize)\n%% Initialize Parameters Randomly Based on Layer Sizes\nr = sqrt(6) / sqrt(layerSize+inputSize+1);\nW = rand(layerSize, inputSize) * 2 * r - r;\nb = zeros(layerSize, 1);\nend\n", "meta": {"author": "zellyn", "repo": "deeplearning-class-2011", "sha": "d44b6c8695baa0d80b9fea21538f877e6d2eaddb", "save_path": "github-repos/MATLAB/zellyn-deeplearning-class-2011", "path": "github-repos/MATLAB/zellyn-deeplearning-class-2011/deeplearning-class-2011-d44b6c8695baa0d80b9fea21538f877e6d2eaddb/ufldl/dist_belief/initializeOneLayerParams.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.7003094612179175}} {"text": "%ZSAD Sum of absolute differences\n%\n% M = ZSAD(I1, I2) is the zero-mean sum of absolute differences between the \n% two equally sized image patches I1 and I2. The result M is a scalar that\n% indicates image similarity, a value of 0 indicates identical pixel patterns\n% and is increasingly positive as image dissimilarity increases.\n%\n% Notes::\n% - The ZSAD similarity measure is invariant to changes in image brightness\n% offset.\n%\n% See also SAD, SSD, NCC, ISIMILARITY.\n\n\n\n% Copyright (C) 1993-2011, by Peter I. Corke\n%\n% This file is part of The Machine Vision Toolbox for Matlab (MVTB).\n% \n% MVTB 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% MVTB 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 MVTB. If not, see .\n\nfunction m = zssd(w1, w2)\n\n\tw1 = w1 - mean(w1(:));\n\tw2 = w2 - mean(w2(:));\n\n\tm = abs(w1-w2);\n m = sum(m(:));\n", "meta": {"author": "petercorke", "repo": "machinevision-toolbox-matlab", "sha": "2d791168c19c5e56acef74d22eafd227b4b58e42", "save_path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab", "path": "github-repos/MATLAB/petercorke-machinevision-toolbox-matlab/machinevision-toolbox-matlab-2d791168c19c5e56acef74d22eafd227b4b58e42/zsad.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.7003030480906768}} {"text": "% Chapter 7 - Differential Equations.\n% Program_7c - Solving Simple Differential Equations.\n% Copyright Birkhauser 2013. Stephen Lynch.\n\n% Chemical kinetics (Example 8).\n% Note that INLINE will be removed in future releases.\n% deqn=inline('.00713*(4-c(1))^2*(1-c(1)/2)','t','c');\nk=0.00713;\ndeqn = @(t,c) [k*(4-c)^2*(1-c/2)]; \n[t,ca]=ode45(deqn,[0 400],0);\nplot(t,ca(:,1))\naxis([0 400 0 3])\nfsize=15;\nset(gca,'XTick',0:100:400,'FontSize',fsize)\nset(gca,'YTick',0:1:3,'FontSize',fsize)\nxlabel('t','FontSize',fsize)\nylabel('c(t)','FontSize',fsize)\nhold off\n\n% End of Program_7c.", "meta": {"author": "Sable", "repo": "mcbench-benchmarks", "sha": "ba13b2f0296ef49491b95e3f984c7c41fccdb6d8", "save_path": "github-repos/MATLAB/Sable-mcbench-benchmarks", "path": "github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/2374-dynamical-systems-with-applications-using-matlab/MATLAB files 20013a/Program_7c.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.7003030376742582}} {"text": "function [upsilonvp, upsilon] = lfmvpComputeUpsilonMatrix(gamma, sigma2, t1, t2, mode)\n\n% LFMVPCOMPUTEUPSILONMATRIX Upsilon matrix vel. pos. with t1, t2 limits\n% FORMAT\n% DESC computes a portion of the LFM 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% SEEALSO : lfmComputeUpsilonMatrix.F, lfmComputeH3.m\n%\n% COPYRIGHT : Mauricio A. Alvarez, 2010\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 if nargout > 1\n upsilon = lfmComputeUpsilonMatrix(gamma, sigma2, t1, t2);\n upsilonvp = -gamma*upsilon + (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2);\n else\n upsilonvp = -gamma*lfmComputeUpsilonMatrix(gamma, sigma2, t1, t2) ...\n + (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2);\n end\nelse\n if nargout > 1\n upsilon = lfmComputeUpsilonMatrix(gamma, sigma2, t1, t2);\n upsilonvp = gamma*upsilon - (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2) ...\n + (2/(sqrt(pi)*sigma))*exp(-gamma*t1)*(exp(-(t2.^2)/sigma2)).';\n else\n upsilonvp = gamma*lfmComputeUpsilonMatrix(gamma, sigma2, t1, t2) ...\n - (2/(sqrt(pi)*sigma))*exp(-(timeGrid.^2)./sigma2) ...\n + (2/(sqrt(pi)*sigma))*exp(-gamma*t1)*(exp(-(t2.^2)/sigma2)).';\n end\nend\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/lfmvpComputeUpsilonMatrix.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.70030303276376}} {"text": "function [m_CO2, y_CO2] = DuanSun(T, p, m_salt)\n% This function solves the Duan-Sun model to calculate the solubility of\n% CO2 in water and in the brine and the mole fraction of CO2 in the gas phase\n% T is the temperature in [K]\n% p is the pressure in [Pa]\n% m is the salt molality in [mol/kg]\n% Copyright (c) 2012-2016 Ali Akbar Eftekhari\n% See the license file\n% R = 0.08314467; % [bar.L/(mol.K)]\n% Written by Ali A. Eftekhari at TU Delft\n\nP = p/1e5; % convert Pa to bar\n% Constants (Table 2):\n% constants for the calculation of chemical potential of CO2 in the liquid phase\nc_mu_CO2_L = [28.9447706, -0.0354581768, -4770.67077, 1.02782768e-5, ...\n\t\t 33.8126098, 9.04037140e-3, -1.14934031e-3, -0.307405726, ...\n\t\t -0.0907301486, 9.32713393e-4, 0.0];\n% Constants for the calculation of second and third order interaction parameters\nc_lambda_CO2_Na = [-0.411370585, 6.07632013e-4, 97.5347708, 0.0, 0.0, ...\n\t\t\t\t 0.0, 0.0, -0.0237622469, 0.0170656236, 0.0, 1.41335834e-5];\nc_zeta_CO2_NaCl = [3.36389723e-4, -1.98298980e-5, 0.0, 0.0, 0.0, ...\n\t\t\t\t 0.0, 0.0, 2.12220830e-3, -5.24873303e-3, 0.0, 0.0];\n\n% using the above constants (Eq. 7)\npar = @(c)(c(1)+c(2)*T+c(3)/T+c(4)*T^2+c(5)/(630-T)+c(6)*P+ ...\n\t\t c(7)*P*log(T)+c(8)*P/T+c(9)*P/(630-T)+ ...\n\t\t c(10)*P^2/(630-T)^2+c(11)*T*log(P));\n\nmu_CO2_L = par(c_mu_CO2_L);\nlambda_CO2_Na = par(c_lambda_CO2_Na);\nzeta_CO2_NaCl = par(c_zeta_CO2_NaCl);\n\n% activity coefficient of CO2 (Eq. 5)\nm_Na = m_salt;\nm_Cl = m_salt;\nlog_gama_CO2 = 2*lambda_CO2_Na*m_Na+zeta_CO2_NaCl*m_Na*m_Cl;\n\n\n% calculation of the fugacity of CO2 using the equation of Duan\na = [8.99288497e-2, -4.94783127e-1, 4.77922245e-2, 1.03808883e-2, ...\n -2.82516861e-2, 9.49887563e-2, 5.20600880e-4, -2.93540971e-4, ...\n -1.77265112e-3, -2.51101973e-5, 8.93353441e-5, 7.88998563e-5, ...\n -1.66727022e-2, 1.39800000, 2.96000000e-2];\n% CO2 critical properties\nTc = 304.25; % [K]\nPc = 7.39e6; % [Pa]\nVc = 8.314467*Tc/Pc;\nTr = T/Tc;\nPr = P*1.0e5/Pc;\nZ = @(Vr)(1+(a(1)+a(2)/Tr^2+a(3)/Tr^3)/Vr + ...\n (a(4)+a(5)/Tr^2+a(6)/Tr^3)/Vr^2 + (a(7)+a(8)/Tr^2+a(9)/Tr^3)/Vr^4 ...\n + (a(10)+a(11)/Tr^2+a(12)/Tr^3)/Vr^5 + ...\n a(13)/(Tr^3*Vr^2)*(a(14)+a(15)/Vr^2)*exp(-a(15)/Vr^2));\nVr_guess = (8.314*T*0.9/(P*1.0e5))/Vc;\nF = @(Vr)(Z(Vr)/Vr-Pr/Tr);\nVr = fzero(F, Vr_guess);\n\n% fugacity coefficient of pure CO2\nZ_num = Z(Vr);\nlog_phi_CO2 = Z_num - 1.0 - log(Z_num) + (a(1)+a(2)/Tr^2+a(3)/Tr^3)/Vr + ...\n\t\t\t(a(4)+a(5)/Tr^2+a(6)/Tr^3)/(2.0*Vr^2) + ...\n\t\t\t(a(7)+a(8)/Tr^2+a(9)/Tr^3)/(4.0*Vr^4) + ...\n\t\t\t(a(10)+a(11)/Tr^2+a(12)/Tr^3)/(5.0*Vr^5) + ...\n\t\t\ta(13)/(2.0*Tr^3*a(15))*(a(14)+1.0-(a(14)+1.0+a(15)/Vr^2)*exp(-a(15)/Vr^2));\n\n% pure water vapor pressure\nc = [-38.640844, 5.8948420, 59.876516, 26.654627, 10.637097];\nPcw = 220.85; % [bar]\nTcw = 647.29; % [K]\nt = (T-Tcw)/Tcw;\nP_water = Pcw*T/Tcw*(1+c(1)*(-t)^1.9+c(2)*t+c(3)*t^2+c(4)*t^3+c(5)*t^4);\ny_CO2 = (P-P_water)/P;\n\nlog_coef = mu_CO2_L - log_phi_CO2 + log_gama_CO2;\nm_CO2 = y_CO2*P/exp(log_coef);\n", "meta": {"author": "simulkade", "repo": "FVTool", "sha": "49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6", "save_path": "github-repos/MATLAB/simulkade-FVTool", "path": "github-repos/MATLAB/simulkade-FVTool/FVTool-49f5cb9ee8a5ff0befebd9fa71a99feae7c724d6/PhysicalProperties/DuanSun.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.7003030309780272}} {"text": "function mappedX = hlle(X, no_dims, k, eig_impl)\n%HLLE Runs the Hessian LLE algorithm\n%\n% mappedX = hlle(X, no_dims, k, eig_impl)\n%\n% Runs the Hessian LLE algorithm on dataset X to reduce its dimensionality\n% to no_dims. The variable k specifies the number of nearest negihbors that\n% is used.\n%\n%\n\n% This file is part of the Matlab Toolbox for Dimensionality Reduction.\n% The toolbox can be obtained from http://homepage.tudelft.nl/19j49\n% You are free to use, change, or redistribute this code in any way you\n% want for non-commercial purposes. However, it is appreciated if you \n% maintain the name of the original author.\n%\n% (C) Laurens van der Maaten, Delft University of Technology\n\n\n if ~exist('no_dims', 'var')\n no_dims = 2;\n end\n if ~exist('k', 'var')\n k = 12;\n end\n if ~exist('eig_impl', 'var')\n eig_impl = 'Matlab';\n end\n\n % Compute nearest neighbors\n if ischar(k)\n warning('Adaptive neighborhood selection often leads to problems in Hessian LLE.');\n end\n disp('Finding nearest neighbors...');\n [D, nind] = find_nn(X, k);\n max_k = size(nind, 2);\n \n % Size of original data\n n = size(X, 1);\n \n % Extra term count for quadratic form\n dp = no_dims * (no_dims + 1) / 2;\n W = sparse([], [], [], dp * n, n, dp * n * max_k);\n\n % For all datapoints\n disp('Building Hessian estimator for neighboring points...');\n for i=1:n\n % Center datapoints by substracting their mean\n tmp_ind = nind(i,:);\n tmp_ind = tmp_ind(tmp_ind ~= 0);\n kt = length(tmp_ind);\n thisx = X(tmp_ind,:);\n thisx = (thisx - repmat(mean(thisx, 1), kt, 1))';\n\n % Compute local coordinates (using SVD)\n [U, D, Vpr] = svd(thisx);\n if size(Vpr, 2) < no_dims\n no_dims = size(Vpr, 2);\n dp = no_dims * (no_dims + 1) / 2;\n warning(['Target dimensionality reduced to ' num2str(no_dims) '...']);\n end\n V = Vpr(:,1:no_dims);\n\t\t% Basically, the above is applying PCA to the neighborhood of Xi. The PCA mapping that is found\n\t\t% (and that is contained in V) is an approximation for the tangent space at Xi.\n\n % Build Hessian estimator\n clear Yi; clear Pii;\n ct = 0;\n for mm=1:no_dims\n startp = V(:,mm);\n for nn=1:length(mm:no_dims)\n indles = mm:no_dims;\n Yi(:,ct+nn) = startp .* (V(:,indles(nn)));\n end\n ct = ct + length(mm:no_dims);\n end\n Yi = [repmat(1, kt, 1) V Yi];\n\t\t \n % Gram-Schmidt orthogonalization (works different from Matlab QR function)\n [Yt, Orig] = mgs(Yi);\n Pii = Yt(:,no_dims + 2:end)';\n \n % Double check weights sum to 1\n for j=1:dp\n if sum(Pii(j,:)) > 0.0001\n tpp = Pii(j,:) ./ sum(Pii(j,:)); \n else\n tpp = Pii(j,:);\n end\n \n % Fill weight matrix\n W((i - 1) * dp + j, tmp_ind) = tpp;\n end\n end\n\n % The weight matrix W is now entirely filled, perform eigenanalysis of W\n disp('Computing HLLE embedding (eigenanalysis)...');\n\n % Make sparse matrix that is inproduct of W\n G = W' * W;\n\tG(isnan(G)) = 0;\n G = sparse(G);\n \n % Clear some memory\n clear X thisx W D nind U D Vpr;\n\n % Perform eigendecomposition\n tol = 0;\n if strcmp(eig_impl, 'JDQR')\n options.Disp = 0;\n options.LSolver = 'bicgstab';\n [mappedX, eigenvals] = jdqr(G, no_dims + 1, tol, options);\n else\n options.disp = 0;\n options.issym = 1;\n options.isreal = 1;\n [mappedX, eigenvals] = eigs(G, no_dims + 1, tol, options);\n end\n \n % Sort eigenvalues and eigenvectors\n [eigenvals, ind] = sort(diag(eigenvals), 'ascend');\n if size(mappedX, 2) < no_dims + 1, no_dims = size(mappedX, 2) - 1; end\n mappedX = mappedX(:,ind(2:no_dims + 1)); \n \n % Extract nonzero coordinates\n mappedX = mappedX(:,1:no_dims)' * sqrt(n);\n mappedX = mappedX';\n\n", "meta": {"author": "tobyma2020", "repo": "cluster", "sha": "c9c3706523859f8c34f9741be94fb2dd89fa4cc0", "save_path": "github-repos/MATLAB/tobyma2020-cluster", "path": "github-repos/MATLAB/tobyma2020-cluster/cluster-c9c3706523859f8c34f9741be94fb2dd89fa4cc0/dr/drtoolbox/techniques/hlle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.7001959519791165}} {"text": "function [xform, fiterr] = affineSolve(A,B);\n% Solve the equation coordsA = xform * coordsB for the xform.\n%\n% Usage: [xform, fiterr] = affineSolve(coordsA,coordsB);\n%\n% Problem: You have coordinates of the same points in two \n% coordinate spaces, A and B. You want to find a 4x4 affine\n% transform matrix that optimally maps between these points.\n%\n% Sub-problem: Simply dividing coordsA / coordsB returns a \n% 3x3 xform, not a 4x4 affine.\n%\n% Solution: use this. It uses singular value decomposition to \n% find the rotation, scales (and skews, if the points are not\n% really matching), and subtraction to find the translations, \n% and builds a 4x4 affine xform which minimizes the error\n% in the above equation.\n%\n% coordsA and coordsB should be 3xN coordinate matrices with the\n% same number of columns. Each column of coordsA should reflect\n% the (row, column, slice) of a point in coordinate space A (the\n% NEW coordinate space being xformed to), and each column in coordsB\n% should be the (row, column, slice) of the SAME POINT in coordinate\n% space B (the OLD coordinate space being xformed from).\n%\n% The optional output argument fiterr is the root mean squared error\n% between coordsA and coordsB given the best set of rotations and \n% tanslations. It is a measure of the goodness-of-fit of the xform\n% (since, if the points don't really correspond, not all equations\n% can be perfectly solved).\n% \n% ras, 10/2005.\nif nargin<2, help(mfilename); error('Not enough args.'); end\n\n% size + number checks:\nif ~isnumeric(A) | ~isnumeric(B), error('Need numeric args.'); end\nif size(A,2)~=size(B,2)\n error('Coords should have same # of columns.');\nend\nif size(A,1)<3 | size(B,1)<3, \n error('Coords need to be specified in 3 dimensions.')\nend\n\n% just curious: does just doing / division work better?\nn = size(A, 2);\nxform = [A; ones(1, n)] / [B; ones(1, n)];\n\n% % express points relative to center of all points:\n% nPoints = size(A,2);\n% centeredA = A - repmat(mean(A,2),[1 nPoints]);\n% centeredB = B - repmat(mean(B,2),[1 nPoints]);\n% \n% % solve for rotation + scales (& skews, if points are bad):\n% H = zeros(3,3);\n% for i = 1:nPoints\n% H = H + (centeredB(:,i) * centeredA(:,i)');\n% end\n% [U S V] = svd(H);\n% rot = V*(U');\n% \n% % solve for translation\n% rotatedB = rot * B;\n% trans = mean(A,2) - mean(rotatedB,2);\n% \n% % build 4x4 affine xform matrix\n% xform = [rot trans; 0 0 0 1];\n% \n% % force skew to equal 0\n% [trans rot scale skew] = affineDecompose(xform);\n% skew = [0 0 0];\n% xform = affineBuild(trans,rot,scale,skew);\n% \n% % return error of fit if requested\n% if nargout > 1\n% \txB = xform * [B; ones(1, size(B, 2))];\n% \txB = xB(1:3,:);\n% \tfiterr = mean(abs(A - xB).^2);\n% end\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/RSVista/mrMethods/coords/affineSolve.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.7001445122559792}} {"text": "function omega = maxAngle(oR,varargin)\n% get the maximum angle of the fundamental region\n%\n% Syntax\n% omega = maxAngle(oR) % maximum angle in the orientation region\n% omega = maxAngle(oR,v) % maximum angle about axis v \n%\n% Description\n% It is important that v is within the fundamental sector\n%\n% Input\n% oR - @orientationRegion\n% v - @vector3d\n%\n\n\nif nargin>1 && isa(varargin{1},'vector3d')\n\n % ignore restrictions on the rotational axis\n %N = oR.N(oR.N.angle < pi<1e-3);\n N = oR.N;\n \n % project v to the fundamental sector\n dcs = properGroup(disjoint(oR.CS1,oR.CS2));\n if oR.antipodal, dcs = dcs.Laue; end\n h = varargin{1};\n h = reshape(project2FundamentalRegion(h,dcs),size(h));\n \n if isempty(N)\n omega = repmat(pi,size(h));\n else\n \n d = dot_outer(N.axis, normalize(h));\n dtan = repmat(-tan(N(:).angle./2),1,size(d,2));\n d(abs(d)<1e-2)=0;\n d = dtan .* d;\n \n %d = dot_outer(-tan(N.angle/2) .* N.axis, normalize(varargin{1}));\n \n d = 2*acot(d);\n d(d<0) = pi;\n \n omega = min(d,[],1);\n omega = reshape(omega,size(h));\n omega(omega<1e-4) = 0;\n end\n\nelseif isempty(oR.V) || check_option(varargin,'complete')\n\n omega = pi;\n\nelse\n \n omega = max(angle(oR.V,'noSymmetry'));\n \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/geometry/@orientationRegion/maxAngle.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.7001445037770386}} {"text": "function [xo]=groupthresh(xi,lambda,varargin)\n%GROUPTHRESH Group thresholding\n% Usage: xo=groupthresh(xi,lambda);\n%\n% `groupthresh(x,lambda)` performs group thresholding on *x*, with\n% threshold *lambda*. *x* must be a two-dimensional array, the first\n% dimension labelling groups, and the second one labelling members. This\n% means that the groups are the row vectors of the input (the vectors\n% along the 2nd dimension).\n%\n% Several types of grouping behaviour are available:\n%\n% * `groupthresh(x,lambda,'group')` shrinks all coefficients within a given\n% group according to the value of the $l^2$ norm of the group in\n% comparison to the threshold *lambda*. This is the default.\n%\n% * `groupthresh(x,lambda,'elite')` shrinks all coefficients within a\n% given group according to the value of the $l^1$ norm of the\n% group in comparison to the threshold value *lambda*.\n%\n% `groupthresh(x,lambda,dim)` chooses groups along dimension\n% *dim*. The default value is $dim=2$.\n%\n% `groupthresh` accepts all the flags of |thresh| to choose the\n% thresholding type within each group and the output type (full / sparse\n% matrix). Please see the help of |thresh| for the available\n% options. Default is to use soft thresholding and full matrix output.\n% \n% See also: thresh\n%\n% Demos: demo_audioshrink\n%\n% References: Kowalski08sparsity kowalski2009mixed yu2008audio\n\n% AUTHOR : Kai Siedenburg, Bruno Torresani.\n% REFERENCE: OK\n \n\nif nargin<2\n error('Too few input parameters.');k\nend;\n\nif (prod(size(lambda))~=1 || ~isnumeric(lambda))\n error('lambda must be a scalar.');\nend;\n\n% Define initial value for flags and key/value pairs.\ndefinput.import={'thresh','groupthresh'};\ndefinput.importdefaults={'soft'};\ndefinput.keyvals.dim=2;\n\n[flags,keyvals,dim]=ltfatarghelper({'dim'},definput,varargin);\n\n% kv.dim (the time or frequency selector) is handled by assert_sigreshape_pre\n[xi,L,NbMembers,NbGroups,dim,permutedsize,order]=assert_sigreshape_pre(xi,[],dim,'GROUPTHRESH');\n\nif flags.do_sparse\n xo = sparse(size(xi));\nelse\n xo = zeros(size(xi));\nend;\n\nif flags.do_group\n \n groupnorm = sqrt(sum(abs(xi).^2));\n w = thresh(groupnorm, lambda, flags.iofun,flags.outclass)./groupnorm;\n \n % Clean w for NaN. NaN appears if the input has a group with norm\n % exactly 0.\n w(isnan(w)) = 0;\n \n xo = bsxfun(@times,xi,w);\n\nend\n\nif flags.do_elite \n for ii=1:NbGroups,\n y = sort(abs(xi(:,ii)),'descend');\n rhs = cumsum(y);\n rhs = rhs .* lambda ./ (1 + lambda * (1:NbMembers)');\n M_ii = find(diff(sign(y-rhs)));\n if (M_ii~=0)\n tau_ii = lambda * norm(y(1:M_ii),1)/(1+lambda*M_ii);\n else\n tau_ii = 0;\n end \n \n % FIXME: The following line does not work for sparse matrices.\n xo(:,ii) = thresh(xi(:,ii),tau_ii,flags.iofun,flags.outclass);\n end\nend;\n\nxo=assert_sigreshape_post(xo,dim,permutedsize,order);\n\n", "meta": {"author": "ltfat", "repo": "ltfat", "sha": "4496a06ad8dddb85cd2e007216b765dc996ef327", "save_path": "github-repos/MATLAB/ltfat-ltfat", "path": "github-repos/MATLAB/ltfat-ltfat/ltfat-4496a06ad8dddb85cd2e007216b765dc996ef327/sigproc/groupthresh.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7905303236047048, "lm_q1q2_score": 0.7001185355920034}} {"text": "% 1D Simple Bar \n% clear memory\nclear all\n \n% E: modulus of elasticity\n% A: area of cross section\n% L: length of bar\nE=30e6; A=1; L=[30 30 30]; \n \n% numberElements: number of elements\nnumberElements=3; \n% numberNodes: number of nodes\nnumberNodes=4;\n% generation of coordinates and connectivities\nelementNodes=[1 2;2 3;3 4];\nnodeCoordinates=[0 30 60 90];\n% for structure:\n % displacements: displacement vector\n % force : force vector\n % stiffness: stiffness matrix\nforce=zeros(numberNodes,1);\nstiffness=zeros(numberNodes,numberNodes); \n% applied load at node 2\nforce(2)=3000.0;\n \n% computation of the system stiffness matrix\nfor e=1:numberElements; \n % elementDof: element degrees of freedom (Dof)\n elementDof=elementNodes(e,:) ;\n k(e)=E*A/L(e) ;\n stiffness(elementDof,elementDof)=...\n stiffness(elementDof,elementDof)+k(e)*[1 -1;-1 1];\nend\n% boundary conditions and solution\n% prescribed dofs\nprescribedDof=[1;4];\n% solution\nGDof=numberNodes;\ndisplacements=solution(GDof,prescribedDof,stiffness,force);\n% output displacements/reactions\noutputDisplacementsReactions(displacements,stiffness, ...\n numberNodes,prescribedDof,force)\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/FEM/BarSimple/problem1dSimple.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.7000804543196036}} {"text": "\nfunction c = gamvbcost(x,logx,apost,bpost,aprior,bprior)\n% function c = gamvbcost(x,logx,apost,bpost,aprior,bprior)\n%\n% Calculates c = -KL(q||p) = - \n% where the expectation <.> is taken over q(X). This is used for\n% calculating the lower bound of the marginal loglikelihood in VB\n% models.\n%\n% Let X be a Gamma distributed variable:\n% p(X) = G(aprior,bprior)\n% q(X) = G(apost,bpost)\n% = x\n% = logx\n\n% Cost from prior\nc = aprior*log(bprior) - gammaln(aprior) + (aprior-1)*logx - bprior*x;\n% Cost from q-posterior\nc = c + gamentropy(apost,bpost);\n", "meta": {"author": "jluttine", "repo": "matlab", "sha": "63406c7782b0869948f06e1dbc594460c165d24e", "save_path": "github-repos/MATLAB/jluttine-matlab", "path": "github-repos/MATLAB/jluttine-matlab/matlab-63406c7782b0869948f06e1dbc594460c165d24e/gppca/gamvbcost.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632996617212, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.7000804531856486}} {"text": "function dz = rocketDynamics(z,u)\n% dz = rocketDynamics(z,u)\n%\n% The basic dynamics and drag coefficient data are from the paper:\n%\n% \"Drag-law Effects in the Goddard Problem\"\n% P. Tsiotras, H. Kelley, H.Kelley 1991\n%\n% INPUTS:\n% z = [3,n] = [h; v; m] = state vector\n% u = [1,n] = [T] = control = thrust\n%\n\nh = z(1,:); %Height\nv = z(2,:); %Velocity\nm = z(3,:); %Mass\nT = u; %Thrust\n\n%%%% Density of air:\n% altitude = [0, 1e4, 2e4, 3e4, 4e4]; %(m) %height above the ground\n% density = [1.23, 0.41, 0.089, 0.018, 0.004]; %(kg/m^3) density of air\ndensity = 1.474085291*(0.9998541833.^h); %Data fit off of wolfram alpha\n\n%%%% Drag coefficient, calculated from paper:\nA1 = 0.0095;\nA2 = 25;\nA3 = 0.953;\nA4 = 0.036;\nspeedOfSound = 280; %(m/s) %At 10 km altitude\nmach = v/speedOfSound;\nCd = A1*atan(A2*(mach-A3))+A4;\n\n%%%% Compute the drag:\nArea = pi*3.66; %(m^2) cross-sectional area (SpaceX F9 Falcon)\nD = 0.5*Cd.*Area.*density.*v.^2;\n\n%%%% Compute gravity from inverse-square law:\nrEarth = 6.3674447e6; %(m) radius of earth\nmEarth = 5.9721986e24; %(kg) mass of earth\nG = 6.67e-11; %(Nm^2/kg^2) gravitational constant\ng = G*mEarth./((h+rEarth).^2);\n\n%%%% Complete the calculation:\nc = 4500; %(m/s) rocket exhaust velocity - chemical rocket\ndh = v; %vertical velocity\ndv = (T-D)./m - g; %vertical acceleration\ndm = -T/c; %mass rate\n\ndz = [dh;dv;dm];\n\nend", "meta": {"author": "MatthewPeterKelly", "repo": "OptimTraj", "sha": "c97b57fda511dacc6a6187f683428f0f3a1965f2", "save_path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj", "path": "github-repos/MATLAB/MatthewPeterKelly-OptimTraj/OptimTraj-c97b57fda511dacc6a6187f683428f0f3a1965f2/demo/goddardRocket/rocketDynamics.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.700080448639167}} {"text": "function [ bic ] = ml_gmm_bic(Data,Priors,Mu,Sigma,cov_type)\n%ML_GMM_BIC Bayesian Information criterion\n%\n% input ------------------------------------------------------------------\n%\n% o Data: D x N array representing N datapoints of D dimensions.\n%\n% o Priors: 1 x K array representing the prior probabilities of the\n% K GMM components.\n% o Mu: D x K array representing the centers of the K GMM components.\n%\n% o Sigma: D x D x K array representing the covariance matrices of the\n% K GMM components.\n%\n% o cov_type: string, covariance type = 'full','diag' or 'iso'\n%\n% output -----------------------------------------------------------------\n%\n% o bic : (1 x 1)\n%\n%\n\n\n\n\n[D,N] = size(Data);\nK = length(Priors);\nnum_param = K-1 + K * D;\n\nif strcmp(cov_type,'full') == true\n num_param = num_param + K * ( D * ( D - 1)/2 );\nelseif strcmp(cov_type,'diag') == true\n num_param = num_param + K * D;\nelseif strcmp(cov_type,'iso') == true\n num_param = num_param + K * 1;\nelse\n error(['no such covariance type: ' cov_type ' only full | diag | isot ']); \nend\n \n\n% compute the loglikelihood of the data given the model\n% loglik: (N x 1) \n\nloglik = ml_LogLikelihood_gmm(Data,Priors,Mu,Sigma);\nbic = - 2 * loglik + num_param * log(N);\n\nend\n\n", "meta": {"author": "epfl-lasa", "repo": "ML_toolbox", "sha": "61cc1245a2abe0c86a737d7b48bd645b28ffebee", "save_path": "github-repos/MATLAB/epfl-lasa-ML_toolbox", "path": "github-repos/MATLAB/epfl-lasa-ML_toolbox/ML_toolbox-61cc1245a2abe0c86a737d7b48bd645b28ffebee/methods/toolboxes/gmmbox/ml_gmm_functions/ml_gmm_bic.m", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.7000804414432358}}